id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
72728706_6
class JsonArrayConverter implements Converter<String,JsonArray> { @Override public JsonArray from(String databaseObject) { return databaseObject==null?null:new JsonArray(databaseObject); } @Override public String to(JsonArray userObject); @Override public Class<String> fromType(); @Ove...
JsonArray from = converter.from(null); Assert.assertNull(from); } }
72736755_0
class DefaultEventSerializer implements EventSerializer { @Override public String serialize(final Event event) { return getXML(event); } public static String getXML(final Event event); private static Marshaller getMarshaller(); private synchronized static JAXBContext getContext(); } ...
final Event event = buildEvent(); final EventSerializer serializer = new DefaultEventSerializer(); final String xml = serializer.serialize(event); System.out.println(xml); final String expectedXML = "<Event xmlns=\"event-logging:3\">\n" + " <EventDetail>\n" +...
72737456_1
class Configuration { public List<Pipeline> getEffectiveOutputPipelines() { final Map<String, Pipeline> pipelineMap = pipelines.stream() .collect(Collectors.toMap(Pipeline::getPipelineName, Function.identity())); final List<Pipeline> effectivePipelines = pipelines.stream() ...
//pipe1 (no output) Pipeline pipe1 = new Pipeline( "pipe1", null, null, false, null, Arrays.asList("T1.1", "T1.2")); //pipe1 <- pipe2 (no output) Pipeline pipe2 = new Pipeline( ...
72737874_48
class DockerServiceImpl implements DockerService { @Override public SwarmInspectResponse getSwarm() { return getOrNullAction(makeBaseUrl().path("swarm"), SwarmInspectResponse.class); } @SuppressWarnings("unchecked") public DockerServiceImpl(Builder b); private URI createUri(); public...
SwarmInspectResponse swarm = service.getSwarm(); Assert.assertNotNull(swarm); } }
72795142_10
class AdminUserDetailsService implements IAdminUserDetailsService { @Override public List<UserDetails> getAllAdmins() { List<UserDetails> userList = new ArrayList<>(); Set<Entry<Object, Object>> entries = users.entrySet(); for (Entry<Object, Object> entry : entries) { String...
Entry<Object, Object> entry = new SimpleEntry<>(USERNAME, USERDATA); Set<Entry<Object, Object>> set = new HashSet<>(); set.add(entry); Mockito.when(users.entrySet()).thenReturn(set); List<UserDetails> admins = adminDetailsServiceToTest.getAllAdmins(); Assert.assertTrue(a...
72805051_3
class TransformGestureDetector implements MultiPointerGestureDetector.Listener { @Override public void onGestureUpdate(MultiPointerGestureDetector detector) { if (mListener != null) { mListener.onGestureUpdate(this); } } public TransformGestureDetector(MultiPointerGestureDetector multiPointerGe...
mGestureDetector.onGestureUpdate(mMultiPointerGestureDetector); verify(mListener).onGestureUpdate(mGestureDetector); } }
72815283_3
class BmcPropertyAccessor { Accessor<Boolean> asBoolean() { return new Accessor<Boolean>() { @Override public Boolean get(BmcProperties property) { // overridden properties only use the new property names, no need to check for clashes String overridde...
assertThat( propertyAccessor.asBoolean().get(BmcProperties.IN_MEMORY_READ_BUFFER), is(false)); this.configuration.setBoolean(BmcProperties.IN_MEMORY_READ_BUFFER.getPropertyName(), true); assertThat(propertyAccessor.asBoolean().get(BmcProperties.IN_MEMORY_READ_BUFFER), is(true)); ...
72836592_0
class CaEhcache extends BasicCa<K, V> { public CaEhcache(String name, Cache<K, V> ca) { super(name, CaType.Local); this.ca = ca; } public CaEhcache(String name, Cache<K, V> ca); @Override protected CaValue<K, V> doRead(K key); @Override protected boolean doWrite(CaValue<K, V> val...
@SuppressWarnings("resource") CaEhcache<String, String> ca = new CaEhcache<String, String>(NAME, cacheManager.getCache(NAME, String.class, String.class)); String key = "key1"; CaValue<String, String> val = ca.read(key); LOG.info(val.toString()); Assert.assertEquals(null,...
72846258_12
class Gavtc extends Gav { public static List<Gavtc> ofPattern(String gavtcPattern) { StringTokenizer st = new StringTokenizer(gavtcPattern, ":"); if (!st.hasMoreTokens()) { throw new IllegalStateException( String.format("Cannot parse [%s] to a " + Gav.class.getName()...
Assert.assertEquals(Arrays.asList(Gavtc.of("g:a:v:pom"), Gavtc.of("g:a:v:jar")), Gavtc.ofPattern("g:a:v:[pom,jar]")); Assert.assertEquals(Arrays.asList(Gavtc.of("g:a:v:pom")), Gavtc.ofPattern("g:a:v:[pom]")); Assert.assertEquals(Arrays.asList(Gavtc.of("g:a:v:pom")), Gavtc.ofPatte...
72847871_5
class AppClient { public App getApp() { return app; } } class AppClientTest { @Test public void appMessage() {
Assert.assertEquals("Hello World!", new AppClient().getApp().getMessage()); } }
72868257_10
class AppServerConfig implements ServerConfig { @Override public @Nullable List<@NotNull PostServerStartupHook> postServerStartupHooks() { PostServerStartupHook eurekaStartupHook = guiceValues.eurekaServerHooks.eurekaStartupHook; return (eurekaStartupHook == null) ? null : Collections.singleton...
"true", "false" }) @Test public void postServerStartupHooks_works_as_expected(boolean eurekaStartupHookIsNull) { // given PostServerStartupHook eurekaStartupHook = (eurekaStartupHookIsNull) ? null : mock(PostServerStartupHook.class); Whitebox.setInternalState( ...
72889410_70
class MethodHash implements Comparable<MethodHash> { @Override public boolean equals(Object o) { if (o instanceof MethodHash) { return isSameHash((MethodHash) o); } return false; } public MethodHash(); public MethodHash(String methodName, String methodSig, boo...
byte[] hash2 = ClassHash.stringToHash(s); Assert.assertTrue(Arrays.equals(hash, hash2)); } }
72967236_3
class BlurLayout extends FrameLayout { public void setBlurRadius(int blurRadius) { this.mBlurRadius = blurRadius; // This field is now bad (it's pre-blurred with blurRadius so will need to be re-made) this.mLockedBitmap = null; invalidate(); } public BlurLayout(Context c...
blurLayout.setBlurRadius(TEST_INT); assertEquals(TEST_INT, blurLayout.getBlurRadius()); } }
73006755_9
class StreamResourceSupport { static ResourceOptions buildResourceOptions(NakadiClient client, StreamConfiguration sc) { ResourceOptions options = ResourceSupport // breaks with api definition https://github.com/zalando-incubator/nakadi-java/issues/98 .options(APPLICATION_JSON) .tokenProv...
assertNull( StreamResourceSupport.buildResourceOptions(client, new StreamConfiguration().eventTypeName("et")).scope() ); assertNull( StreamResourceSupport.buildResourceOptions(client, new StreamConfiguration().subscriptionId("sub1")).scope() ); assertNull( ...
73013368_14
class ViewManager implements Observer<LifecycleEvent> { @MainThread void finish(@NonNull ContentViewContract view) { final Dual<NavigationDetails, Boolean> removedViewMetadata = removeViewFromStack(view); if (removedViewMetadata == null) { LogUtil.logViewWarning(TAG, "Tried to remove non-existing vie...
final MockView secondView = spy(new MockView() { @Override public void onDestroy() { super.onDestroy(); viewManager.finish(this); } }); assertFinishFromOnDestroyDoesNoting(secondView); } }
73056727_27
class Program { public void compile() throws IOException { final String[] lines = new TextOf(this.input).asString().split("\n"); final ANTLRErrorListener errors = new BaseErrorListener() { // @checkstyle ParameterNumberCheck (10 lines) @Override public void synta...
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Program program = new Program( new InputOf( new JoinedText( "\n", "object car as Serializable:", " Integer @vin", " String n...
73085073_1
class IOTimeoutAction { void execute() throws IOException { if( timeout > 0 ) { long timeSpentWaiting = 0; long currentTS = System.currentTimeMillis(); while( !condition() ) { try { Thread.sleep(...
final long initialTS = System.currentTimeMillis(); IOTimeoutAction action = new IOTimeoutAction(300) { @Override public boolean condition() throws IOException { return System.currentTimeMillis() - initialTS > 500; } }; ...
73097094_5
class DefaultXvfbController implements XvfbController { @Override public Map<String, String> configureEnvironment(Map<String, String> environment) { environment.put(ENV_DISPLAY, display); return environment; } public DefaultXvfbController(ProcessMonitor<?, ?> xvfbMonitor, String displ...
XvfbController ctrl = new DefaultXvfbController(EasyMock.createMock(ProcessMonitor.class), ":123", EasyMock.createMock(DisplayReadinessChecker.class), EasyMock.createMock(Screenshooter.class), EasyMock.createMock(Sleeper.class), EasyMock.createMock...
73103312_7
class Zone extends ZoneType { @Override public int getLowerBoundbydbmIndex(int index) { return _matrix[dbmIndexToMatrixIndex(index)][0]; } public Zone(int[] timers, int[][] matrix); public Zone(State initialState); private Zone(); @Override public int getUpperBoundbyTransitionIndex(int timer); @Overrid...
int expected2 = -2; int expected3 = -3; int expected6 = -6; int expected7 = -7; int actual2 = zone1.getLowerBoundbydbmIndex(1); int actual3 = zone1.getLowerBoundbydbmIndex(2); int actual6 = zone1.getLowerBoundbydbmIndex(3); int actual7 = zone1.getLowerBoundbydbmIndex(4); assertEquals(expected2, act...
73185566_1
class EventStoreEsjcEventRepository implements EventRepository<T> { @Override public EventReadResult<T> read(final String streamId, final int version, final int maxEvents) { return readInternal(toEsStreamId(streamId), version, maxEvents, false); } public EventStoreEsjcEventRepository( ...
when(eventStore.readStreamEventsForward(any(), anyInt(), anyInt(), anyBoolean())) .thenReturn(wrapFuture(new StreamEventsSlice( SliceReadStatus.StreamNotFound, "stream", 0, ReadDirection.Forward, ...
73209796_0
class MainViewModel { @NonNull public Observable<List<Language>> getObservableSupportedLanguages() { return mDataModel.getObservableSupportedLanguages(); } public MainViewModel(@NonNull final IDataModel dataModel, @NonNull final ISchedulerProvider schedulerProvider); ...
Language de = new Language("German", LanguageCode.DE); Language en = new Language("English", LanguageCode.EN); List<Language> languages = Arrays.asList(de, en); Observable<List<Language>> mockObservable = Observable.just(languages); //Observable<Language> mockObservable = Observ...
73236117_13
class MongoHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { try { Document result = db.runCommand(PING); int ok = 0; if (result.containsKey("ok") && result.get("ok") instanceof Number) { ok = result.get("ok", Num...
Fongo fongo = new Fongo("fake-mongo"); MongoHealthCheck check = new MongoHealthCheck(fongo.getDatabase("fake-mongo-db")); assertTrue(check.check().isHealthy()); } }
73270880_0
class TelegramSettingsBean extends RememberState { public TelegramSettings toSettings() { TelegramSettings settings = new TelegramSettings(); settings.setBotToken(botToken); settings.setPaused(paused); settings.setUseProxy(useProxy); settings.setProxyServer(proxyServer); settings.setProxyPort...
TelegramSettingsBean bean = new TelegramSettingsBean(new TelegramSettings()); bean.setBotToken("123123"); bean.setPaused(true); bean.setUseProxy(true); bean.setProxyServer("localhost"); bean.setProxyPort("345"); bean.setProxyUsername("user"); bean.setProxyPassword("123"); TelegramSe...
73282380_0
class BeerController { @RequestMapping(method = RequestMethod.POST, value = "/beer", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public String gimmeABeer(@RequestBody Person person) { ResponseEntity<Response> response = this.restTemplate.exchange( ...
// OK assertEquals(this.controller.gimmeABeer(new Person("marcin", 25)), "THERE YOU GO"); // NOT_OK assertEquals(this.controller.gimmeABeer(new Person("marcin", 10)), "GET LOST"); } }
73314646_0
class MagicalRemoteDataSource implements MagicalDataSource { @Override public Observable<FluxWeed> getFluxWeed() { return Observable.just(new FluxWeed()) .delay(randomizer.randomInRange(2, 5), TimeUnit.SECONDS); } @Inject public MagicalRemoteDataSource(Randomizer randomizer); ...
//TODO Create a TestObserver TestObserver<Object> testObserver = TestObserver.create(); //TODO subscribe to getFluxWeed() magicalDataSource.getFluxWeed().subscribe(testObserver); //TODO tell observer to wait for terminal event testObserver.awaitTerminalEvent(); /...
73380577_1
class BarAppListener { @RabbitListener(queues = {BarApp.XEBICON_BARAPP_LISTENER}) public void receiveOrder(Map<String, Object> msg) { logger.debug("Receiving message [{}]", msg); if (shopService.isShopOpen().orElse(false) && ofNullable(msg.get("type")).orElse("").equals("BUY")) { s...
// Given Map<String, Object> buyOrderMsg = createBuyOrderMsg(ProductType.margaux, 1L); when(shopService.isShopOpen()).thenReturn(ofNullable(TRUE)); // When barAppListener.receiveOrder(buyOrderMsg); // Then Mockito.verify(shopService, times(1)).processBuyOrder(an...
73419103_13
class RequestParser { public static <V extends Message> void handleBody( String fieldPath, V.Builder builder, String body) throws InvalidProtocolBufferException { // * maps all body fields to the top-level proto // IDENT maps all body fields to nested proto ...
NestedType nestedType = NestedType.newBuilder().setF1("abc").build(); TestRequest expected = TestRequest.newBuilder().setNt(nestedType).build(); // Output nested json only String json = JsonFormat.printer().print(nestedType); TestRequest.Builder deserialized = TestRequest.newBu...
73420810_10
class ProblemReportDB { public static List<ProblemReport> getFavoriteProblemReports() { // Simulate a long running process. try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return database.subList(0, database.size() ...
List<ProblemReport> reports = getFavoriteProblemReports(); assertNotNull(reports); assertFalse(reports.isEmpty()); assertEquals(2, reports.size()); } }
73430564_1
class NomadJson { public static Job readJobSpec(String jobSpec) throws IOException { return OBJECT_MAPPER.readValue(jobSpec, JobSpec.class).job; } public static String asJobSpec(Job job); public static String serialize(Object value); public static T deserialize(String json, Class<T> clazz)...
String jobSpec = IOUtils.toString(getClass().getResourceAsStream("job.json"), UTF_8); final Job job = NomadJson.readJobSpec(jobSpec); assertThat(job.getId(), is("Job-ID")); assertThat(job.getUnmappedProperties().get("Unknown Job String"), is((Object) "Hi")); final HashMap<Strin...
73473909_3
class SphericalView extends RelativeLayout { public float getDefaultRotationSensibility() { return defaultRotationSensibility; } public SphericalView(Context context); public SphericalView(Context context, AttributeSet attrs); public SphericalView(Context context, AttributeSet attrs, in...
AttributeSet attributeSet = Robolectric.buildAttributeSet().addAttribute(R.attr.rotationSensibility, "0.1").build(); SphericalView subject = new SphericalView(RuntimeEnvironment.application, attributeSet); assertThat(subject.getDefaultRotationSensibility()).isEqualTo(0.1f); } }
73478000_13
class ExportFilterManager { public static ExportFilter instantiateExportFilterByExtension( Class<?> forClass, String identifier) throws Exception { for (Class c = forClass; c != null; c = c.getSuperclass()) if (EXPORT_FILTER_EXTENSIONS.containsKey(c)) { HashMap<Strin...
PluginManager.registerClass(TrivialGraphFormatExport.class); ByteArrayOutputStream result = new ByteArrayOutputStream(); OutputStreamWriter out = new OutputStreamWriter(result); ExportFilterManager.instantiateExportFilterByExtension(Structure.class, "tgf") .exportGraph(...
73620856_36
class RxFirebaseRemote { @NonNull public static Completable fetch(@NonNull final FirebaseRemoteConfig config, @NonNull final long cacheLifeTime) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(Complet...
TestObserver fetchTestObserver = RxFirebaseRemote .fetch(firebaseConfig, ANY_TIME) .test(); testOnFailureListener.getValue().onFailure(EXCEPTION); verify(firebaseConfig).fetch(eq(ANY_TIME)); fetchTestObserver.assertError(EXCEPTION) .assertNotComplet...
73690083_19
class ClusterManagerImpl implements ClusterManager { public long getNumberOfNodes() throws DockerException, InterruptedException { return streamReadyNodes().count(); } public ClusterManagerImpl(); public Info getClusterInfo(); private Stream<Node> streamReadyNodes(); public long getN...
long numberOfNodes = clusterManager.getNumberOfNodes("org.hobbit.workergroup=system"); assertEquals(0, numberOfNodes); } }
73711911_46
class Tiling2048 implements Serializable { public int addressSpecial(State2048 state) { int[] values = state.getValues(); int address = 0; for (int i = 0; i < numSegments; ++i) { address *= 2; address += state.hasValue(values, maxSegment - i) ? 1 : 0; } if (address > 0) address -= 1; for (int i =...
Tiling2048 tiling2048 = Tiling2048.createWithRandomWeights(3, 15, new int[] { 7, 8, 9, 10, 15, 16 }, 16, 0, 0, new RandomDataGenerator(new MersenneTwister(123))); Assert.assertEquals(0, tiling2048.addressSpecial(new State2048( new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }))); Assert.as...
73733927_1
class JPASessionUtil { @SuppressWarnings("WeakerAccess") public static synchronized EntityManager getEntityManager(String persistenceUnitName) { persistenceUnits.putIfAbsent(persistenceUnitName, Persistence.createEntityManagerFactory(persistenceUnitName)); return persistenceUnit...
public void nonexistentEntityManagerName() { JPASessionUtil.getEntityManager("nonexistent"); fail("We shouldn't be able to acquire an EntityManager here"); } }
73840074_1
class AuditAggregator { public boolean addRecord(String sourceTopic, int partition, long offset, JSONObject record) { // dot . is reserved delimiter for graphite naming String topicName = record.getString(AuditMsgField.TOPICNAME.getName()); String hostName = record.getString(AuditMsgField.HOSTNAME.getNam...
long timeBucketIntervalInSec = 60; int reportFreqMsgCount = 10; short reportFreqIntervalSec = 2; AuditAggregator agg = new AuditAggregator(timeBucketIntervalInSec, reportFreqMsgCount, reportFreqIntervalSec); int partition = 0; long offset = 1024; long nowInMs = System.currentTimeMillis(); ...
73899453_155
class JavaBeanSerializeUtil { public static JavaBeanDescriptor serialize(Object obj) { return serialize(obj, JavaBeanAccessor.FIELD); } private JavaBeanSerializeUtil(); public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor); private static JavaBeanDescriptor cr...
JavaBeanDescriptor descriptor = new JavaBeanDescriptor(); JavaBeanDescriptor result = JavaBeanSerializeUtil.serialize(descriptor); Assert.assertTrue(descriptor == result); Map map = new HashMap(); map.put("first", descriptor); result = JavaBeanSerializeUtil.serialize(map...
73930305_59
class WorkspacePackageRepository extends GeneralFSPackageRepository { protected PackageSource lookupPackageSource(PackageID pkgID) { Path path = this.generatePath(pkgID); return new WorkspacePackageSource(pkgID, path); } public WorkspacePackageRepository(String programDirRoot, WorkspaceDo...
Path filePath = RES_DIR.resolve("source").resolve("multipackages").resolve("sample").resolve("main.bal"); Pair pair = compileAndGetWorkspacePackageRepo(filePath); Names names = pair.getNames(); WorkspacePackageRepository workspacePackageRepository = pair.getWorkspacePackageRepository(); ...
73963835_3
class XForwardedRemoteAddressResolver implements RemoteAddressResolver { @Override public InetSocketAddress resolve(ServerWebExchange exchange) { List<String> xForwardedValues = extractXForwardedValues(exchange); Collections.reverse(xForwardedValues); if (!xForwardedValues.isEmpty()) { int index = Math.min(...
ServerWebExchange exchange = buildExchange(oneTwoThreeBuilder()); InetSocketAddress address = trustOne.resolve(exchange); assertThat(address.getHostName()).isEqualTo("0.0.0.3"); } }
74145628_185
class AVLTreeNode { public int height() { // TODO... return -3; } public AVLTreeNode(int key); public boolean validAVL(); public boolean find(int key); public AVLTreeNode insert(int key); public void dot(StringBuilder sb); private int dotNode(StringBuilder sb, int idx...
Random r = new Random(); int h1 = r.nextInt(Integer.MAX_VALUE); int h2 = r.nextInt(Integer.MAX_VALUE); setField(node().withHeight(h1), "right"); setField(node().withHeight(h2), "left"); Assert.assertEquals(Math.max(h1, h2) + 1, test.height()); } }
74149803_1
class SchemaBuilder3 extends JFrame { public void createSchema(){ pcName = schemaNameField.getText(); if(pcName == null || pcName.length() == 0){ JOptionPane.showMessageDialog(null, "Please fill out Schema Name Field"); return; } String descr = descrField.ge...
createSchema(); createTables(1); assertErrorOnSubmit(); } }
74164375_9
class ModuleDetailPresenter implements Presenter { @Override public void loadModule() { if (null == mModule) { mModuleDetailView.showMissingModule(); } else { mModuleDetailView.showModule(mModule); } } public ModuleDetailPresenter(@Nullable Module modul...
mModuleDetailPresenter = new ModuleDetailPresenter(null, mModuleDetailView); mModuleDetailPresenter.loadModule(); verify(mModuleDetailView).showMissingModule(); } }
74169930_2
class ArticlesServer implements ArticlesDataSource { @Override public Single<ArticleResource> requestArticle(@NonNull final String id) { final Retrofit retrofit = new Retrofit.Builder() .baseUrl(mBaseUrl) .addConverterFactory(HALConverterFactory.create(ArticleResource.cl...
// Given there is a web server with some prepared responses final String articleId = "bnl-vkn-20161117-7352758"; final HttpUrl baseUrl = prepareAndStartServerToReturnJsonFromFile(mServer, "article(ws.blendle.com_item_" + articleId + ").json"); // When I make a request ...
74169960_32
class ClusterSummary { public List<Task> tasksForInstance(ContainerInstance instance) { String arn = instance.getArn(); if (instancesByInstanceArn.containsKey(arn)) { return tasksByInstanceArn.getOrDefault(arn, Collections.emptyList()); } else { throw new IndexOutOfBoundsException( ...
ClusterSummary summary = new ClusterSummary(snapshot); assertThatThrownBy(() -> summary.tasksForInstance(instance("i-1"))).hasMessageContaining("i-1"); } }
74189838_2
class ApiGenMojo extends AbstractMojo { @Override public void execute() { try { sourceDirectory = makeAbsolute(sourceDirectory); outputDirectory = makeAbsolute(outputDirectory); if ( ! sourceDirectory.exists() ) return; getLog().debug("Running ApiGen\n\ts...
File basedir = resources.getBasedir("posts"); MavenExecutionResult result = mavenRuntime .forProject(basedir) .execute("clean", "test"); result.assertErrorFreeLog(); } }
74192763_1
class RequestListener implements com.bumptech.glide.request.RequestListener { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) { WebImageView view = null; if (target instanceof WebImageViewTarget) { view = ((WebI...
verify(mEventEmitter, never()).receiveEvent(anyInt(), anyString(), any(WritableMap.class)); WebImageViewTarget target = new WebImageViewTarget(mImageView); mViewManager.mRequestListener.onLoadFailed(new GlideException("some error"), null, target, true); WritableMap expectedEvent = new...
74278300_0
class DrDecryption { public static String decrypt(String input) { if (input == null) { return null; } try { return doDecrypt(input); } catch (GeneralSecurityException | RuntimeException ex) { Timber.e(ex, "Unable to decrypt: %s", input); return null; } } private sta...
assertEquals( "https://drtesty-lh.akamaihd.net/i/drtestytext_0@668184/master.m3u8?subtestbyteje", DrDecryption.decrypt("01000000c09b2fd5b4ffcb615af5555f571928bdad01cb1b0157af52c08a3673fae605f37c0e0a486f68f322d11e2df22fecb3d99fd30fb404021ba932076a2031401d527679ce066da7f71020a3f756cd8f123cdbf94fc3201...
74327735_1
class RegexIntentDetector implements IntentDetector<IConversationIntent> { @Override public Optional<IConversationIntent> detectIntent(String text, String languageCode, String sessionId) { for (Map.Entry<String, Pattern> entry : intentRegexMap.entrySet()) { final Matcher matcher = entry.ge...
System.out.println("detectIntent"); String sessionId = "0"; Map<String,String> intentMap = new HashMap(); intentMap.put("DUCK", "duck"); intentMap.put("GOOSE", "goose"); intentMap.put("YES", RegexIntentDetector.YES); intentMap.put("NO", RegexIntentDetecto...
74351531_0
class UserService { public void register(User user) throws UserExistException{ User u = this.getUserByUserName(user.getUserName()); if(u != null){ throw new UserExistException("用户名已经存在"); }else{ user.setCredit(100); user.setUserType(1); userDao.save(user); } } public voi...
User user = new User(); user.setUserName("tom"); user.setPassword("1234"); doAnswer(new Answer<User>() { public User answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); User user = (User) args[0]; if (user != null) { user.setUserId(1); } return user; ...
74385593_4
class HiveSchemaConverter { public static TypeInfo convertPrimitiveMaybeLogical(Schema schema) { if (schema.name() == null) { return convertPrimitive(schema); } if (Decimal.LOGICAL_NAME.equals(schema.name())) { String scale = schema.parameters().get(Decimal.SCALE_FIELD); String precisi...
Map<String, String> props = new HashMap<>(); String someScale = "2"; String validPrecision = String.valueOf(HiveSchemaConverter.HIVE_DECIMAL_PRECISION_MAX); props.put(Decimal.SCALE_FIELD, someScale); props.put(HiveSchemaConverter.CONNECT_AVRO_DECIMAL_PRECISION_PROP, validPrecision); //without a...
74387321_8
class S3SinkConnectorConfig extends StorageSinkConnectorConfig { @Override public Object get(String key) { ComposableConfig config = propertyToConfig.get(key); if (config == null) { throw new ConfigException(String.format("Unknown configuration '%s'", key)); } return config == this ? super.ge...
properties.put(AvroDataConfig.ENHANCED_AVRO_SCHEMA_SUPPORT_CONFIG, "true"); properties.put(AvroDataConfig.CONNECT_META_DATA_CONFIG, "false"); connectorConfig = new S3SinkConnectorConfig(properties); assertEquals(true, connectorConfig.get(AvroDataConfig.ENHANCED_AVRO_SCHEMA_SUPPORT_CONFIG)); assertEq...
74401462_32
class Linker { public static Set<BaggageBuffersDeclaration> link(BBC.Settings settings) throws CompileException { return link(settings.files, FileUtils.splitBagPath(settings.bagPath)); } private Linker(List<String> bagPath); public static Set<BaggageBuffersDeclaration> link(List<String> inpu...
File dir = Files.createTempDir(); dir.deleteOnExit(); File f1 = new File(dir, "bagpathimport"); File f2 = createFile(); write(f1, "package edu.brown.cs;\nbag MyBag1 {bool test = 0;}"); write(f2, "import \"%s\";\nbag MyBag2 {MyBag1 test = 0;}", f1.getName...
74409326_16
class EntityTag { @Override public String toString() { StringBuilder b = new StringBuilder(); if (weak) { b.append("W/"); } appendQuoted(b, value); //b.append('"').append(value.replaceAll("\"", "\\\\\"")).append('"'); return b.toString(); } public EntityTag(final String value); ...
assertEquals(new EntityTag( "Hello \"World\"", true).toString(), "W/\"Hello \\\"World\\\"\""); } }
74491626_10
class NamedEntityGraph extends AbstractEntityGraph { @Override public int hashCode() { return Objects.hash(name, getEntityGraphType(), isOptional()); } public NamedEntityGraph(EntityGraphType type, boolean optional, String name); public NamedEntityGraph(EntityGraphType type, String name); public Na...
final EntityGraph optionalGraph = new NamedEntityGraph(EntityGraphType.LOAD, true, "graph"); final EntityGraph requiredGraph = new NamedEntityGraph(EntityGraphType.LOAD, false, "graph"); assertNotEquals(optionalGraph, requiredGraph); assertNotEquals(optionalGraph.hashCode(), requiredGraph.hashCode()); ...
74616657_0
class HalyardQueryJoinOptimizer extends QueryJoinOptimizer { @Override public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { final Set<String> parallelSplitBounds = new HashSet<>(); tupleExpr.visit(new AbstractQueryModelVisitor<IncompatibleOperationException>() { ...
final TupleExpr expr = new SPARQLParser().parseQuery("select * where {?a ?b ?c, \"1\".}", "http://baseuri/").getTupleExpr(); new HalyardQueryJoinOptimizer(new HalyardEvaluationStatistics(null, null)).optimize(expr, null, null); expr.visit(new AbstractQueryModelVisitor<RuntimeException>(){ ...
74617406_2
class Recipe { public static Recipe readFromStream(InputStream stream) { if (stream == null) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String id = null; String title = null; StringBuilder descBuilder = new StringBuilder(); try { ...
InputStream stream = RecipeTest.class.getResourceAsStream("/recipes/mixed.txt"); Recipe recipe = Recipe.readFromStream(stream); assertNotNull(recipe); assertEquals("punch", recipe.id); assertEquals("Punch", recipe.title); assertEquals("Juice of 3 lemons\n" + "1 orange\n" + "1 pin...
74704643_1
class GraphQlExecutorImpl implements GraphQlExecutor { @Override public Object executeRequest(Map requestBody) { val query = (String) requestBody.get("query"); val operationName = (String) requestBody.get("operationName"); val variables = getVariablesFromRequest(requestBody); va...
// Given val request = new LinkedHashMap<String, Object>(); request.put("query", "dummy"); request.put("operationName", "dummy"); request.put("variables", 1234); // When val exception = assertThatThrownBy(() -> graphQlExecutor.executeRequest(request)); /...
74740415_4
class BallotCipherService { public AuthenticatedBallot encryptBallotThenWrapForAuthentication(String plainText, int ballotIndex) { Cipher ballotKeyCipher = ciphersProvider.getBallotKeyCipher(); Cipher ballotCipher = ciphersProvider.getBallotCipher(); // Generate a random symmetric key, re...
initBallotCiphersProviderMock(); StringBuilder sb = new StringBuilder(); sb.append("GE;6699:9903"); sb.append("370001;0;37000101;p=DEP"); sb.append(Strings.repeat(";1001", 545)); AuthenticatedBallot authenticatedBallot = ballotCipherService.encryptBallotThenWrapForAuthe...
74843923_59
class AppRequestHandler implements RequestHandler { @Override public Response handle(Request request) { final AppRequest appRequest = appRequestFactory.create(request); final Optional<AppResponse> primedResponseOpt = primingContext.getResponse(appRequest); if(!primedResponseOpt.isPres...
appRequestHandler.handle(request); verify(callHistory).add(exchange); } }
74857438_8
class HoodUtil { public static String obfuscateAndShorten(@Nullable String original, int maxCharLengthLeftOrRight, char obfuscationChar) { if (original == null || original.trim().length() <= 1) { return original; } if (maxCharLengthL...
assertEquals("h***o", HoodUtil.obfuscateAndShorten("hello", 1, '*')); assertEquals("he***lo", HoodUtil.obfuscateAndShorten("hello", 2, '*')); assertEquals("he***lo", HoodUtil.obfuscateAndShorten("hello", 3, '*')); assertEquals("he***lo", HoodUtil.obfuscateAndShorten("hello", 4, '*')); ...
74877759_0
class ServiceHelperSupport { public JSONObject get(String id) { if (getKey == null) getKey = getKey() + ".get"; return carousel.get(getKey, id); } public JSONArray fill(JSONArray array, String[] names); protected abstract String getKey(); @Inject private Thread th...
while (Calendar.getInstance().get(Calendar.SECOND) > 55) thread.sleep(5, TimeUnit.Second); mockHelper.reset(); mockHelper.mock("/service-helper"); mockCarousel.reset(); mockCarousel.register("key", "{\"code\":0,\"data\":{\"id 1\":{\"id\":\"new id\",\"name\":\"carouse...
74907921_191
class DataQuality extends Types { public static int columns(Row row) { return row.width(); } public static boolean hascolumn(Row row, String column); public static boolean inrange(double value, double lower, double upper); public static int strlen(String str); public static boolean isnull(Object objec...
Row row = new Row("a", 1).add("b", 2).add("c", 3); Assert.assertEquals(3, DataQuality.columns(row)); row = new Row("a", 1); Assert.assertEquals(1, DataQuality.columns(row)); row = new Row(); Assert.assertEquals(0, DataQuality.columns(row)); } }
74950506_2
class ClassIntrospector { public static Collection<ResourceMethodInfoDTO> getResourceMethodInfos( Class<?> clazz, Bus bus) { final Class<?> realClass = unwrap(clazz, bus); ClassResourceInfo classResourceInfo = ResourceUtils.createClassResourceInfo( realClass...
Bus bus = BusFactory.getDefaultBus(true); ResourceMethodInfoDTO[] resourceMethodInfoDTOS = ClassIntrospector.getResourceMethodInfos( PlainResourceSeveralOperations.class, bus ).toArray( new ResourceMethodInfoDTO[0] ); assertEq...
74971299_45
class PatternFilter extends AbstractFilter { @Override public <T extends Object> PrismPropertyValue<T> apply(PrismPropertyValue<T> propertyValue) { Validate.notNull(propertyValue, "Node must not be null."); String value = getStringValue(propertyValue); if (StringUtils.isEmpty(value)) { ...
List<Object> parameters = createBadParameters2(); filter.setParameters(parameters); PrismPropertyValue<String> value = new PrismPropertyValue<String>(input); value = filter.apply(value); AssertJUnit.assertEquals(expected, value.getValue()); } }
74972240_0
class RxMqtt { @NonNull @CheckReturnValue public static Maybe<IMqttToken> connect(@NonNull final MqttAndroidClient client) { return connect(client, new MqttConnectOptions(), null); } @NonNull public static MqttAndroidClient client( @NonNull final Context context, @N...
final MqttAndroidClient client = RxMqtt.client(RuntimeEnvironment.application, url); TestObserver observer = RxMqtt.connect(client).doOnNext(new Consumer<IMqttToken>() { @Override public void accept(IMqttToken token) throws Exception { System.out.println(token); ...
74999474_10
class TypeSafeConfWrapper implements ParsecConfig { @Override public List<Integer> getIntList(String path) { try { return configDelegate.getIntList(path); } catch (ConfigException e) { throw new RuntimeException(e); } } public TypeSafeConfWrapper(Config...
int[] expected = new int[] { 1, 2, 3, 4, 5, 6 }; ParsecConfig confWrapper = getConfig(); List<Integer> numberList = confWrapper.getIntList("numberList"); int idx = 0; for (int value : numberList) { assertEquals(value, expected[idx++]); } confWrapper.ge...
75065038_2
class CollectionUtils { public static <T> T get(T[] data, int index) { int len = data.length; if (index > len - 1) { index = len - 1; } return data[index]; } public static T last(List<T> data); public static String strings(List<T> data, String split); p...
int[] ints = new int[]{1, 2, 3, 4}; Assert.assertTrue(4 == CollectionUtils.get(ints, 7)); Assert.assertTrue(1 == CollectionUtils.get(ints, 0)); Assert.assertFalse(4 == CollectionUtils.get(ints, 1)); } }
75085823_10
class GitConfigStore implements ConfigStore { @Override public Future<Void> close() { return vertx.executeBlocking(promise -> { git.close(); promise.complete(); }); } public GitConfigStore(Vertx vertx, JsonObject configuration); private Git initializeGit(); @Override public Future<Bu...
git.close(); remote = "acme"; FileUtils.deleteQuietly(root); git = connect(bareRoot, root); Async async = tc.async(); add(git, root, new File("src/test/resources/files/a.json"), null); branch = "dev"; add(git, root, new File("src/test/resources/files/regular.json"), null); push(git);...
75118280_10
class RecordPersister extends SourcePersister implements RecordProvider<BarCode> { @Nonnull @Override public RecordState getRecordState(@Nonnull BarCode barCode) { return sourceFileReader.getRecordState(barCode, expirationUnit, expirationDuration); } @Inject public RecordPersister(FileSys...
when(fileSystem.getRecordState(TimeUnit.DAYS, 1L, SourcePersister.pathForBarcode(simple))) .thenReturn(RecordState.STALE); assertThat(sourcePersister.getRecordState(simple)).isEqualTo(RecordState.STALE); } }
75133570_25
class TravelerGroupController extends Controller { public void subscribe(@Nonnull String groupId, @Nonnull User user) { final Key<Account> accountKey = Key.create(user.getUserId()); final Key<TravelerGroupEntity> groupKey = Key.create(groupId); Map<Key<Object>, Object> fetched = ofy().load().keys(accoun...
TravelerGroupEntity group = endpoint.insert("Adventure", TEST_IMG, user); endpoint.subscribe(group.getWebsafeId(), user); TravelerGroupEntity adventure = ofy().load().entity(group).now(); assertTrue(adventure.getPostCount() == 1L); } }
75164823_194
class IndexFile { public void selectPhyOffset(final List<Long> phyOffsets, final String key, final int maxNum, final long begin, final long end, boolean lock) { if (this.mappedFile.hold()) { int keyHash = indexKeyHashMethod(key); int slotPos = keyHash % this.hashSlotNum; ...
IndexFile indexFile = new IndexFile("200", HASH_SLOT_NUM, INDEX_NUM, 0, 0); for (long i = 0; i < (INDEX_NUM - 1); i++) { boolean putResult = indexFile.putKey(Long.toString(i), i, System.currentTimeMillis()); assertThat(putResult).isTrue(); } // put over index fi...
75169335_1
class PrettyFormatter { public static String formatMillisToYearsDaysHours(long millis) { long days = TimeUnit.MILLISECONDS.toDays(millis); millis -= TimeUnit.DAYS.toMillis(days); final long hours = TimeUnit.MILLISECONDS.toHours(millis); millis -= TimeUnit.HOURS.toMillis(hours); ...
long millis = TimeUnit.MINUTES.toMillis(1); Assert.assertEquals("1 minute", PrettyFormatter.formatMillisToYearsDaysHours(millis)); millis += TimeUnit.MINUTES.toMillis(1); Assert.assertEquals("2 minutes", PrettyFormatter.formatMillisToYearsDaysHours(millis)); millis += TimeUnit...
75215830_74
class CustomNginxStorageBackend implements StorageBackend { @Override public URI store(JsonOutputObject outputObject) throws StorageException { URI serviceUri = getServiceUri(outputObject.getJobId()); try (PipeStream inputStream = createJsonInputStream(outputObject)) { return store(...
URI localUri = null; try { setStorageUri("http://127.0.0.1:12345"); MarkupResult markup = createMarkupResult(); localUri = URI.create(markup.getMarkupUri()); _nginxStorageService.store(markup); fail("Expected exception not thrown"); } ...
75269665_3
class Calculator { public double add(double firstOperand, double secondOperand) { return firstOperand + secondOperand; } public double sub(double firstOperand, double secondOperand); public double div(double firstOperand, double secondOperand); public double mul(double firstOperand, double...
double resultAdd = mCalculator.add(-1d, -17d); assertThat(resultAdd, is(equalTo(-18d))); } }
75277003_45
class TbChangeOriginatorNode extends TbAbstractTransformNode { @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { this.config = TbNodeUtils.convert(configuration, TbChangeOriginatorNodeConfiguration.class); validateConfig(config); setCo...
init(); AssetId assetId = new AssetId(Uuids.timeBased()); CustomerId customerId = new CustomerId(Uuids.timeBased()); Asset asset = new Asset(); asset.setCustomerId(customerId); RuleChainId ruleChainId = new RuleChainId(Uuids.timeBased()); RuleNodeId ruleNodeId = ...
75368166_21
class PersistenceManager { public boolean createDirectoryStructure(String directoryPath) { File directory = new File(directoryPath); if (directory.exists()) { throw new IllegalArgumentException("\"" + directoryPath + "\" already exists."); } return directory.mkdirs(); } } class PersistenceManagerTest ...
final String path = "directoryPath"; File fileMock = createMock(File.class); PersistenceManager tested = new PersistenceManager(); expectNew(File.class, path).andReturn(fileMock); expect(fileMock.exists()).andReturn(false); expect(fileMock.mkdirs()).andReturn(true); replay(fileMock, File.class); as...
75383441_0
class MainPresenter extends MainContract.PresenterViewOperations { @Override void onContinue(final String firstName, final String lastName) { onView(new ViewAction<MainContract.ViewOperations>() { @Override public void onAction(MainContract.ViewOperations view) { ...
presenter.onContinue(null, null); verify(view, times(1)).showFirstNameError(); verify(view, times(1)).showLastNameError(); } }
75386501_1
class JsonObjectLoader { public JsonObject loadOptions(String filename) { return loadOptions(defaultRootPath, filename); } @SneakyThrows public T loadOptions(String filename, Class<T> optionClazz); @SneakyThrows(IOException.class) public JsonObject loadOptions(String defaultRootPath, String filename); ...
JsonObject jsonObject = my(JsonObjectLoader.class).loadOptions("VertxOptions.json"); Assert.assertNotNull(jsonObject); Assert.assertTrue(jsonObject.getBoolean("clustered")); VertxOptions vertxOptions = my(JsonObjectLoader.class).loadOptions("VertxOptions.json", VertxOptions.class); Assert.assertNo...
75608943_0
class SmurfAssembler { public static SmurfR toRepresentation(Smurf smurf) { return new SmurfR(smurf.getId(), smurf.getName(), smurf.getCreationDate()); } } class SmurfAssemblerTest { @Test public void canAssembleASmurfRFromASmurfEntity() throws Exception {
LocalDate now = LocalDate.now(); Smurf smurf = SmurfTestBuilder.aDefaultSmurf().withCreationDate(now).build(); SmurfR smurfR = SmurfAssembler.toRepresentation(smurf); SmurfR expectedSmurfR = SmurfRTestBuilder.aSmurfR() .withName(SmurfTestBuilder.NAME) .wi...
75626745_2
class ProviderFactory { public static UserInfoProvider getOpenIdProvider(String providerType) { UserInfoProvider openIdProvider; String s = providerType.toUpperCase(); if (s.equals("AZURE")) { openIdProvider = new AzureAD(); } else { openIdProvider = new UserInfoProvider(); } return openId...
UserInfoProvider openIdProvider = ProviderFactory.getOpenIdProvider(""); assertTrue(openIdProvider.getClass() == UserInfoProvider.class); } }
75643631_20
class BadgeShape { public Rect draw(@NonNull Canvas canvas, @NonNull Rect bounds, @NonNull Paint paint, int layoutDirection) { float width = bounds.width() * scale; float height = bounds.height() * scale; if (width < height * aspectRatio) { height = width / aspectRatio; ...
region.set(0, 0, 48, 48); TestBadgeShape badgeShape = new TestBadgeShape(1, 1, 0); Rect rect = badgeShape.draw(canvas, region, paint, 0); badgeShape.assertRegion(rect); badgeShape.assertRegion(region); } }
75661534_33
class AwsHttpServletRequest implements HttpServletRequest { protected List<HeaderValue> parseHeaderValue(String headerValue) { return parseHeaderValue(headerValue, HEADER_VALUE_SEPARATOR, HEADER_QUALIFIER_SEPARATOR); } AwsHttpServletRequest(Context lambdaContext); public AwsHttpServletRespo...
AwsHttpServletRequest context = new AwsProxyHttpServletRequest(null,null,null); String value = Base64.getUrlEncoder().encodeToString("a".getBytes()); List<AwsHttpServletRequest.HeaderValue> result = context.parseHeaderValue(value); assertTrue(result.size() > 0); assertEquals("Y...
75718771_0
class Computation extends IntentService { @Override protected void onHandleIntent(Intent intent) { Intent resultIntent = new Intent(RESULT_INTENT_ACTION); Integer result = new Computer().compute(); resultIntent.putExtra(RESULT_VALUE_INTENT_EXTRA_KEY, result); sendBroadcast(resul...
final List<Intent> receivedIntents = new ArrayList<>(); BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { receivedIntents.add(intent); } }; IntentFilter fi...
75735839_5
class AnnotationUtils extends CommonUtils { public String convertSpecialCharacters(String input) { String returnInput = input; if (null != input && input.contains(":")) { List<String> inputList = getListFromSpaceSeparatedTerms(input); for (String replacement : inputList) { if (replacement.contains(...
String input = "http://www.emaple.com/ferd/lgg/"; String output = annotationUtils.convertSpecialCharacters(input); LOG.info(input); LOG.info(output); assertEquals(output, "(\"http://www.emaple.com/ferd/lgg/\")"); input = "trt:ttttt"; output = annotationUtils.convertSpecialCharacters(input); LOG.info(input); L...
75753179_0
class OrikaAutoConfiguration { @ConditionalOnMissingBean @Bean public MapperFactoryBuilder<?, ?> orikaMapperFactoryBuilder() { DefaultMapperFactory.Builder orikaMapperFactoryBuilder = new DefaultMapperFactory.Builder(); if (orikaProperties.getUseBuiltinConverters() != null) { or...
assertThat(orikaMapperFactoryBuilder) .isPresent() .hasValueSatisfying(value -> assertThat(value) .hasFieldOrPropertyWithValue("useBuiltinConverters", true) .hasFieldOrPropertyWithValue("useAutoMapping", ...
75873961_0
class CloneHelper { public static <T> T cloneObject(T source) { T cloned = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream ous = new ObjectOutputStream(baos); ous.writeObject(source); ous.close(); ...
AdrConfigurationServiceMock config = new AdrConfigurationServiceMock(null); AdrIconDescriptor sourceIcon = config.getDefaultIcon(); AdrIconDescriptor cloned = CloneHelper.cloneObject(sourceIcon); cloned.setComponentId(cloned.getComponentId() + 10341); assertNotEquals(sourceIcon,c...
75879612_1
class AnnotationMerger { public void merge() { mergeByCategory(); } public AnnotationMerger(HpoDisease d1, HpoDisease d2, Ontology honto); public void printToShell(); private void outputByCategory(); private void outputCategory(HpoCategory hcat); private void printTerms(List<Term...
assertNotNull(CCAIDCMS_OMIM); AnnotationMerger merger = new AnnotationMerger(CCAIDCMS_OMIM,CCAIDCMS_ORPHA,ontology); merger.merge(); } }
75939912_4
class EnvironmentVariables { public static List<String> configurationNames() { return configurationNames(System.getenv().keySet()); } public static Optional<String> getValue(String configuration, String key); public static Optional<JsonObject> getConfiguration(String configurationName); st...
Map<String, String> entries = new HashMap<>(); entries.put("firehose.sampleservice.uri", "http://sample-service:8080/sample-service/resources/metrics"); entries.put("another.sampleservice.uri", "http://another:8080/another/resources/metrics"); entries.put("firehose.another.uri", "http://...
75974381_3
class SingleWeaver { public static boolean methodAnnotatedWithRxLogSingle(ProceedingJoinPoint joinPoint) { return ((MethodSignature) joinPoint.getSignature()).getReturnType() == Single.class; } public Object weaveAroundJoinPoint(ProceedingJoinPoint joinPoint, Logger logger); private SingleWeaver singleWe...
final boolean result = singleWeaver.methodAnnotatedWithRxLogSingle(proceedingJoinPoint); assertThat(result).isTrue(); } }
75985902_3
class HasherFactory { public static Hasher createHasher(String hasherType) { Hasher hasher; switch (hasherType) { case "MD5": hasher = new MD5Hasher(); break; case "SHA1": hasher = new SHA1Hasher(); break; ...
Hasher hasher = HasherFactory.createHasher("CRC32b"); assertThat(hasher.getClass().getTypeName(), is(CRC32Hasher.class.getTypeName())); } }
75990052_9
class UrlUtils { public static boolean isInternalErrorURL(final String url) { return "data:text/html;charset=utf-8;base64,".equals(url); } public static String normalize(@NonNull String input); public static boolean isUrl(String url); public static boolean isValidSearchQueryUrl(String url)...
assertTrue(UrlUtils.isInternalErrorURL("data:text/html;charset=utf-8;base64,")); assertFalse(UrlUtils.isInternalErrorURL("http://www.mozilla.org")); assertFalse(UrlUtils.isInternalErrorURL("https://www.mozilla.org/en-us/about")); assertFalse(UrlUtils.isInternalErrorURL("www.mozilla.org"...
76003412_48
class EfFindFilesInDirByPattern extends EvaluationFunction { @Override public ValueEvaluation evaluate() { try { checkContractCompliance(); boolean errorIfDirNull = true; List<ValueParam> paramErrorIfDirNull = valueParams.getParams(PARAM_ERROR_IF_DIR_NULL); ...
EvaluationFunction evFunction = engine.buildEvaluationFunction(FUNCTION_NAME) .withValueParam(PARAM_DIR, ValueType.FILE, new ValueEvaluation(PSP_DIR_FILE)) .withValueParamByReference(PARAM_DIR, ValueType.FILE, PSP_VAR); //TODO: to by melo byt v ramci kontroly kotraktu, tj...
76028699_0
class ApiBaseResponse extends GenericErrorContainer implements ApiResponse { @Override public String getVersion() { return version; } public ApiBaseResponse(); @Override public String getSid(); @Override public void setSid(String sid); @Override public void insertData(String key, Object obj); @O...
String result = apiBaseResponse.getVersion(); assertEquals("1.0.0", result); } }
76093141_6
class AlipayRunner { public String tradePrecreate(long seckillId) { Seckill seckill = redisService.getSeckill(seckillId); Goods goods = goodsMapper.selectById(seckill.getGoodsId()); // 需保证商户系统端不能重复,建议通过数据库sequence生成, String outTradeNo = "tradeprecreate" + System.currentTimeMillis() ...
assertTrue(StringUtils.isNotBlank(alipayRunner.tradePrecreate(1001L))); } }
76099157_7
class Substitutor { public String replace(final String source) { if (source == null) { return null; } final StringBuilder builder = new StringBuilder(source); if (substitute(builder, 0, source.length(), null) <= 0) { return source; } return re...
assertEquals("pref-bar-suff", new Substitutor(singletonMap("foo", "bar")).replace("pref-${foo}-suff")); } }
76112580_1
class FluxController { @GetMapping("/status") @ResponseStatus(HttpStatus.CREATED) public Mono<String> status() { return Mono.just("Status"); } @GetMapping("/inject") public Mono<String> inject(); @GetMapping("/path/{param}") public Mono<String> pathParam(@PathVariable("param") String parameter); @GetMapping(...
this.webTestClient.get().uri("/complex/status").exchange().expectStatus().isCreated().expectBody(String.class) .value((body) -> assertEquals(body, "Status")); } }
76160515_0
class Option implements TraversableOnce<A>, Serializable, Equals, Function0<A>, Monad<A> { public static <A> Option<A> of(A value) { return value == null ? Option.none() : new Option<>(value); } private Option(); private Option(A value); @SuppressWarnings("unchecked") public static Opti...
assertEquals(Option.of(0), Option.of(0)); } }
76169459_0
class SQLiteOperator { public SaveOperation<T> save(final @NonNull T... objectsToInsert) { final SQLiteDAO generated = getGeneratedDAO(null); final SQLiteDAO<T>[] generatedObjects = new SQLiteDAO[objectsToInsert.length]; for (int i = 0; i < objectsToInsert.length; i++) { generat...
SQLiteOperator<TestTable> operator = SQLiteOperator.from(getContext(), TestTable.class); final TestTable table = new TestTable(); table.testString = "123"; table.testList = Arrays.asList("1", "2", "3"); table.testBoolean = true; table.unique = 1; table.testSeriali...
76177416_22
class StringToDurationConverter implements Converter<String, Duration> { @Override public Duration convert(String source) { try { if (ISO8601.matcher(source).matches()) { return Duration.parse(source); } Matcher matcher = SIMPLE.matcher(source); ...
assertThat(convert("10")).isEqualTo(Duration.ofMillis(10)); assertThat(convert("+10")).isEqualTo(Duration.ofMillis(10)); assertThat(convert("-10")).isEqualTo(Duration.ofMillis(-10)); } }
76198055_1
class ContributorsPresenter extends MvpBasePresenter<ContributorsView> { public void loadContributors(String owner, String repo, boolean pullToRefresh) { if (isViewAttached()) { getView().showProgress(pullToRefresh); } subscription = appRepository.contributors(owner...
ContributorsPresenter contributorsPresenter = new ContributorsPresenter(appRepository); contributorsPresenter.attachView(contributorsView); when(githubApi.contributors(OWNER, REPO)).thenReturn( Observable.just(Response.success(new ArrayList<>()))); contributorsPresenter.loa...