id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
117452304_11
class Position extends Point { @Override public Position clone() { return new Position(x, y, angle); } public Position(double x, double y, double angle); public Position(double x, double y); public Position(Point point, double angle); public Position(Point point); public P...
Position p1 = new Position(Math.random(), Math.random(), Math.random()); assertNotSame(p1, p1.clone()); assertEquals(p1, p1.clone()); } }
117474465_9
class RepoMVPPresenter extends BasePresenter<RepoMVPView> implements RepoPresenter { @Override public void getRepo(@NonNull String owner, @NonNull String repo) { checkViewAttached(); getMvpView().showMessageView(false); getMvpView().showProgress(true); getDataManager().getRepo(...
String owner = TestDataFactory.repoDataFactory.createOwner().login; String repoName = TestDataFactory.repoDataFactory.createRepoName(); stubDataManagerGetRepo(owner, repoName, Single.error(new RuntimeException(""))); repoPresenter.getRepo(owner, repoName); testScheduler.triggerA...
117598163_0
class PulsarClientLRUCache extends LRUMap<K, V> { @Override public void clear() { this.values().parallelStream().forEach(closable -> { releaseResources(closable); }); super.clear(); } public PulsarClientLRUCache(int maxSize); public PulsarClientLRUCache(int max...
PulsarClientLRUCache<String, Producer> cache = new PulsarClientLRUCache<String, Producer>(26); for (Character i='A'; i<='Z'; i++) { cache.put(i.toString(), mockedPulsarProducer); } // Make sure we only have all the items in the cache assertEquals(26, cache.size()); ...
117711019_4
class BylineImpl implements Byline { @Override public boolean isEmpty() { final Image image = getImage(); if (StringUtils.isBlank(name)) { // Name is missing, but required return true; } else if (occupations == null || occupations.isEmpty()) { ...
ctx.currentResource("/content/without-name"); Byline byline = ctx.request().adaptTo(Byline.class); assertTrue(byline.isEmpty()); } }
117965972_5
class TSDBConnection implements Connection4TSDB { @Override public boolean isSupported() { String versionJson = version(); if (StringUtils.isBlank(versionJson)) { throw new RuntimeException("Cannot get the version!"); } String version = JSON.parseObject(versionJson)....
Assert.assertTrue(new TSDBConnection(TSDB_ADDRESS).isSupported()); } }
117978265_8
class OverrideDubboConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplication...
Properties properties = ConfigUtils.getProperties(); Assert.assertEquals("dubbo-demo-application", properties.get("dubbo.application.name")); Assert.assertEquals("dubbo-demo-module", properties.get("dubbo.module.name")); Assert.assertEquals("zookeeper://192.168.99.100:32770", propertie...
118104847_0
class EasyPermissions { public static boolean hasPermissions(@NonNull Context context, @Size(min = 1) @NonNull String... perms) { // Always return true for SDK < M, let the system deal with the permissions if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {...
Application app = RuntimeEnvironment.application; String[] perms = new String[]{ Manifest.permission.READ_SMS, Manifest.permission.ACCESS_FINE_LOCATION }; // Wes should not have permissions before any are granted assertFalse(EasyPermissions.hasPe...
118151375_4
class SupplyChainCredentialValidator implements CredentialValidator { @Override public AppraisalStatus validatePlatformCredentialAttributes( final PlatformCredential platformCredential, final DeviceInfoReport deviceInfoReport, final EndorsementCredential endorsementCredentia...
DeviceInfoReport deviceInfoReport = buildReport( new HardwareInfo(PLATFORM_MANUFACTURER, PLATFORM_MODEL, PLATFORM_VERSION, DeviceInfoReport.NOT_SPECIFIED, TEST_SERIAL_NUMBER, TEST_SERIAL_NUMBER)); deviceInfoReport = PowerMockito.spy(device...
118198720_1
class TraitToPropertyMap { String traitsToDataFormat(final boolean onlyFromProperty) { boolean isArray = false; boolean isBig = false; boolean isSmall = false; boolean isInteger = false; boolean probablyJson = false; Enum<CdmDataFormat> baseType = CdmDataFormat.Unknown; final CdmTraitCol...
final CdmTypeAttributeDefinition cdmAttribute = new CdmTypeAttributeDefinition( new ResolveContext(new CdmCorpusDefinition()), "SomeAttribute"); cdmAttribute.getAppliedTraits().add("is.dataFormat.someRandomDataFormat"); final TraitToPropertyMap traitToPropertyMap = new TraitT...
118261543_81
class WishlistDtoFromRecordBuilder extends DtoFromRecordBuilder<WishlistDataDto> { public WishlistDataDto build(CSVRecord csvRecord) throws ImportException { try { return new WishlistDataDto( formatLong(getId(csvRecord)), formatInteger(csvRecord.get("movi...
doReturn(true).when(csvRecord).isMapped("id"); doReturn("12").when(csvRecord).get("id"); doReturn("24").when(csvRecord).get("movie_id"); doReturn("a good title").when(csvRecord).get("title"); doReturn("overview").when(csvRecord).get("overview"); doReturn("2015").when(csvR...
118323013_0
class MainViewModel extends ActorViewModel { @Command(MSG_SEARCH_FOR_CITY_RESULT) void onSearchForCityResult(Optional<City> foundCity) { foundCity.map(this::addNewFavoriteCityAndSaveToPreferences) .defaultIfEmpty(false) .whenNot(Boolean::booleanValue) .th...
boolean[] result = {false}; viewModel.searchCityInProgress .subscribeOn(scheduler) .observeOn(scheduler) .subscribe(status -> result[0] = status); scheduler.triggerActions(); viewModel.searchForCity.onNext(true); scheduler.trigger...
118375319_0
class IcyHttpDataSourceFactory extends OkHttpDataSource.BaseFactory { @Override protected IcyHttpDataSource createDataSourceInternal(@NonNull HttpDataSource.RequestProperties defaultRequestProperties) { return new IcyHttpDataSource.Builder(callFactory) .setUserAgent(userAgent) ...
// Arrange OkHttpClient client = new OkHttpClient.Builder().build(); IcyHttpDataSourceFactory factory = new IcyHttpDataSourceFactory.Builder(client) .setUserAgent(Constants.TEST_USER_AGENT) .setIcyHeadersListener(TEST_ICY_HEADERS_LISTENER) .setIcyM...
118421344_71
class HurlStack extends BaseHttpStack { @SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET...
TestRequest.Options request = new TestRequest.Options(); assertEquals(request.getMethod(), Method.OPTIONS); HurlStack.setConnectionParametersForRequest(mMockConnection, request); assertEquals("OPTIONS", mMockConnection.getRequestMethod()); assertFalse(mMockConnection.getDoOutput...
118477931_0
class Value { public boolean cmp(Value o) { if (o == null) { return false; } if (rlp != null && o.rlp != null) { return Arrays.equals(rlp, o.rlp); } else { return Arrays.equals(this.encode(), o.encode()); } // return DeepEquals.de...
Value val1 = new Value("hello"); Value val2 = new Value("world"); assertFalse("Expected values not to be equal", val1.cmp(val2)); Value val3 = new Value("hello"); Value val4 = new Value("hello"); assertTrue("Expected values to be equal", val3.cmp(val4)); Value...
118497841_326
class DockerCredentialHelper { public Credential retrieve() throws IOException, CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException { boolean isWindows = systemProperties.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); String lowerCas...
systemProperties.setProperty("os.name", "WINdows"); List<String> command = Arrays.asList(Paths.get("/foo/bar.CmD").toString(), "get"); Mockito.when(processBuilderFactory.apply(command)).thenReturn(processBuilder); DockerCredentialHelper credentialHelper = new DockerCredentialHelper( ...
118602757_0
class TextStyleBuilder { void applyStyle(@NonNull TextView textView) { for (Map.Entry<TextStyle, Object> entry : values.entrySet()) { switch (entry.getKey()) { case SIZE: { final float size = (float) entry.getValue(); applyTextSize(textVie...
final MockTextStyleBuilder builder = new MockTextStyleBuilder(); final TextView textView = Mockito.mock(TextView.class); builder.applyStyle(textView); Assert.assertFalse(builder.textColorApplied); Assert.assertFalse(builder.textSizeApplied); Assert.assertFalse(builder.g...
118738606_4
class XCLLongLongMap extends AbstractMarshallable { public void putAll(XCLLongLongMap map) { if (put == null) put = this::put; map.forEach(put); } public static XCLLongLongMap withExpectedSize(int expectedSize); public abstract long put(long key, long value); public abstract long g...
map.put(1, 1); map.put(2, 2); XCLLongLongMap map2 = XCLLongLongMap.withExpectedSize(16); map2.put(0, 0); map2.put(1, 11); map2.putAll(map); assertEquals("!cash.xcl.util.KolobokeXCLLongLongMap {\n" + " ? 2: 2,\n" + " ? 1: 1,\n" + ...
118781792_9
class ShoveGestureDetector extends ProgressiveGesture<ShoveGestureDetector.OnShoveGestureListener> { boolean isAngleAcceptable() { MultiFingerDistancesObject distancesObject = pointersDistanceMap.get(new PointerDistancePair(pointerIdList.get(0), pointerIdList.get(1))); // Takes values from 0 to 180 ...
gestureDetector.pointerIdList.add(0); gestureDetector.pointerIdList.add(1); gestureDetector.pointersDistanceMap.put( new PointerDistancePair(0, 1), new MultiFingerDistancesObject(300, 0, 275, 15) ); assertTrue(gestureDetector.isAngleAcceptable()); gestureDetector.pointerIdList.clear...
118787197_1
class MyEnrichAndReformatFn extends DoFn<String, String> { public long _calculateTimestamp(long offset) { return this.startTimestamp + offset; } public MyEnrichAndReformatFn(); public MyEnrichAndReformatFn(long arg0); @ProcessElement public void processElement(@Element String element, Outp...
long offset = 789; long timestampExpected = BEAM_2_14_RELEASE + offset; long timestampCalculated = myEnrichAndReformatFn._calculateTimestamp(offset); assertThat("timestampCalculated", timestampCalculated, is(equalTo(timestampExpected))); } }
118799500_3
class ResourceMapNamespaces { public static boolean isResourceMap(String namespace) { boolean is = false; if(namespace != null && !namespace.trim().equals("")) { getNamespaces(); if(resourceMapNamespaces != null && resourceMapNamespaces.contains(namespace)) { is = true; } ...
assertTrue(NAMESPACE1+"should be a namespace of the resource map document ", ResourceMapNamespaces.isResourceMap(NAMESPACE1)); assertTrue(NAMESPACE2+"should be a namespace of the resource map document ", ResourceMapNamespaces.isResourceMap(NAMESPACE2)); assertTrue(NAMESPACE3+"should NOT be a namespace of...
118824988_0
class Player { public List<PlayedWord> getPlayedWords() { return playedWords; } protected Player(); public Player(String username, String macAddr, Team team); public void setScore(); public String getUsername(); public String getMacAddr(); public Team getTeam(); public int getScore(); @Autowired pr...
Player player = players.findByUsername("brendan").get(0); assertTrue(player.getPlayedWords().size() == 0); player.getPlayedWords().add(new PlayedWord("cool", 100, false, false, player)); assertTrue(player.getPlayedWords().size() == 1); } }
118963036_1
class ParamProvider implements AutoCloseable { public abstract Iterator<Object[]> iterator()public abstract Iterator<Object[]> iterator(); public abstract Iterator<Object[]> iterator()public ParamProvider(ParamGenerator... paramGenerators); public abstract Iterator<Object[]> iterator()public static Suggested sugges...
ParamProvider prov = new ParamProvider.AllPermutations( ParamGenerator.of(1, 2, 3), ParamGenerator.of(true, false) ); Iterator<Object[]> iter = prov.iterator(); List<List<Object>> all = new ArrayList<>(); while (iter.hasNext()) all.add(Arrays.asList(iter.next())); Assert.assertEquals...
118998719_2
class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator...
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); ...
119147365_6
class Timepoint implements Parcelable, Comparable<Timepoint> { public void add(TYPE type, int value) { if (type == MINUTE) value *= 60; if (type == HOUR) value *= 3600; value += toSeconds(); switch (type) { case SECOND: second = (value % 3600) % 60; ...
HashSet<Timepoint> timepoints = new HashSet<>(4); timepoints.add(new Timepoint(12, 0, 0)); timepoints.add(new Timepoint(12, 0, 0)); timepoints.add(new Timepoint(12, 0, 0)); timepoints.add(new Timepoint(12, 0, 0)); Assert.assertEquals(timepoints.size(), 1); } }
119281902_3
class GeoJsonReader { public Geometry read(String string) { try { JSONObject json = new JSONObject(string); String type = json.getString(TYPE); switch (type) { case "Feature": return createFeature(json); case "FeatureCollection": Geometry[] features = createFeatures(json.getJSONArra...
Geometry g = read("{" + " \"type\": \"Feature\"," + " \"properties\": {\"a\": 3, \"b\": \"blub\", \"c\": null, \"d\": [1,2], \"e\": {\"hi\":\"ho\"}}," + " \"geometry\": {" + " \"type\": \"Point\"," + " \"coordinates\": [5,5]" + " }" + "}"); assertTrue(g.getUserData() instanceof...
119369247_14
class LiteCycle implements LifecycleObserver { public static <T> LiteObserverFactory<T> with(T item) { return new LiteObserverFactory<>(item); } public static LiteObserverFactory<T> defer(Callable<T> itemInitializer); } class LiteCycleTest { @Test public void observeWithNoParameterThenR...
Object subject = LiteCycle.with(0) .forLifeCycle(new MockLifeCycleOwner()) .observe(BehaviorSubject.<Integer>create()); assertTrue(subject instanceof BehaviorSubject); } }
119531923_16
class TimeUtil { public static String convertMillisToMinSecFormat(long millis) { long ms = millis % 1000; long s = (millis / 1000) % 60; long m = ((millis / 1000) / 60) % 60; if (s > 0 && m <= 0) { return String.format("%d sec %d ms", s, ms); } else if (s > 0 || ...
assertThat(TimeUtil.convertMillisToMinSecFormat(100), equalTo("100 ms")); assertThat(TimeUtil.convertMillisToMinSecFormat(1010), equalTo("1 sec 10 ms")); assertThat(TimeUtil.convertMillisToMinSecFormat(60010), equalTo("1 min 0 sec 10 ms")); } }
119633513_2
class ThumbnailAdapter extends RecyclerView.Adapter<ThumbnailViewHolder> { @Override public int getItemCount() { if (cursor == null) { return 0; } else { return cursor.getCount(); } } public ThumbnailAdapter(EventBus eventBus); public void setCurso...
assertEquals(0, adapter.getItemCount()); } }
119644903_0
class PinnedPubKeyTrustManager implements X509TrustManager { public static SSLContext pinSha256SSLContext(final Stream<String> sha256Pins) { return sslContext(pinSha256TrustManager(sha256Pins)); } public PinnedPubKeyTrustManager(final String algorithm, final Iterable<byte[]> pinnedPubKeys); ...
// todo: make these not rely on remote server, stand up local TLS server with hard-coded certs? assertEquals("pinnedpubkey authentication failed, server pin (SHA-256): t62CeU2tQiqkexU74Gxa2eg7fRbEgoChTociMee9wno=", testPin("moparisthebest.com", 443, "bla").getCause().getMessage()); ...
119702819_35
class DeadLetterConfig extends AbstractConfig { @Override public boolean validate() { log.info("Validating DeadLetterConfig..."); if (deadLetterExchange != null && deadLetterExchange.validate()) { log.info("DeadLetterConfig configuration validated successfully for deadLetterExchange '{}'", deadLetter...
deadLetterConfig = DeadLetterConfig.builder() .deadLetterExchange(null) .queuePostfix(".dlq") .build(); assertFalse(deadLetterConfig.validate()); } }
119727871_28
class PatternOptionBuilder { public static Options parsePattern(String pattern) { char opt = ' '; boolean required = false; Class<?> type = null; Options options = new Options(); for (int i = 0; i < pattern.length(); i++) { char ch = pattern.charAt(...
Options options = PatternOptionBuilder.parsePattern("abc"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, new String[] { "-abc" }); assertTrue(line.hasOption('a')); assertNull("value a", line.getOptionObject('a')); assertTrue(line...
119737924_5
class User implements Parcelable { public void setEmail(String mail) throws InvalidEmailException { this.email = mail; } public User(String username, String email, String phoneNumber); public User(String username, String email, String phoneNumber, float rating); public User(String Usern...
User newUser = new User("HelloWorld"); newUser.setEmail("myEmail@gmail.com"); assertTrue(newUser.getEmail().equals("myEmail@gmail.com")); } }
119819447_306
class MethodVisitor { @Deprecated public void visitMethodInsn( final int opcode, final String owner, final String name, final String descriptor) { int opcodeAndSource = opcode | (api < Opcodes.ASM5 ? Opcodes.SOURCE_DEPRECATED : 0); visitMethodInsn(opcodeAndSource, owner, name, descriptor, opcode == O...
StringWriter log = new StringWriter(); LogMethodVisitor logMethodVisitor = new LogMethodVisitor(log); MethodVisitor methodVisitor = new MethodVisitor4Override(logMethodVisitor, log); methodVisitor.visitMethodInsn(0, "C", "m", "()V", false); assertEquals("LogMethodVisitor:m4()V;MethodVisitor4:m()V;...
120003293_2
class RetryStrategy implements Function<Flowable<Throwable>, Flowable<?>> { public static Builder always() { return new Builder(t -> true); } RetryStrategy(Builder builder); @Override public Flowable<?> apply(Flowable<Throwable> errors); private Flowable<Duration> getCappedDelays(); private Flowabl...
AtomicInteger retries = new AtomicInteger(); TestScheduler scheduler = new TestScheduler(); TestSubscriber<Integer> test = errorSource(10) .doOnSubscribe(d -> retries.incrementAndGet()) .retryWhen( RetryStrategy.always() .withBackoffSchedul...
120074273_7
class ColuTransferInstructionsParser { public List<Integer> retrieveOutputIndexesFromScript(byte []scriptBytes) throws ParseException { List<Integer> indexes = new ArrayList<>(); if (!isValidColuScript(scriptBytes)) { return indexes; } int offset = OPCODE_OFFSET; ...
// Transaction 811ce060b88cec67e5066f7bb75cd8acef43c3f24c0787fb1fe426510d4fe38b contains the invalid script byte[] script = Hex.decode("6a 07 43 43 02 15 00 21 64"); // this may not crash but result in no output being found. // Or am I interpreting wrongly the fact that the CC blockexplo...
120152712_6
class XMLDSigVerifier { public XMLDsigVerificationResult VerifyXMLDSig(InputStream fileStream) { XMLDsigVerificationResult result = new XMLDsigVerificationResult(); try { //Signature will also be validated in this call, if it fails an exception is thrown //No poi...
InputStream EntryToken = new FileInputStream("src/test/ts/EntryToken-future-cert-self-signed.tsml"); XMLDsigVerificationResult result = new XMLDSigVerifier().VerifyXMLDSig(EntryToken); assert(!result.isValid); assert(result.failureReason.contains("NotBefore")); // save travis from misrep...
120272671_0
class OrderRepository implements OrderDataSource { @Nullable public OrderList getAllCachedOrderHistory() { return cachedOrderList; } private OrderRepository(@NonNull final BlockchainSource blockchainSource, @NonNull final EventLogger eventLogger, @NonNull final OrderDataSource.Remote remoteData, @NonNull...
assertNull(orderRepository.getAllCachedOrderHistory()); } }
120274146_0
class StringUtil { public boolean isValidPassword(String password) { Pattern p = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}$"); Matcher m = p.matcher(password); if (m.find()) return true; return false; } StringUtil stringUtil; } class S...
//given String validPassword = "As1asd1sdas21"; String invalidPassword = "asd123"; //when and then assertTrue(stringUtil.isValidPassword(validPassword)); assertFalse(stringUtil.isValidPassword(invalidPassword)); } }
120363922_2
class FeignContext extends NamedContextFactory<FeignClientSpecification> { @Nullable public <T> T getInstanceWithoutAncestors(String name, Class<T> type) { try { return BeanFactoryUtils.beanOfType(getContext(name), type); } catch (BeansException ex) { return null; } } public FeignContext(); @Null...
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.refresh(); FeignContext feignContext = new FeignContext(); feignContext.setApplicationContext(parent); feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class))); Logger.Level lev...
120471283_161
class RoleStore { public List<Role> findAll() { List<Role> result = new ArrayList<>(); try (Connection connect = CON.getConnect(); Statement st = connect.createStatement(); ResultSet rstSet = st.executeQuery(QUERIES.getProperty("findAllRoles"))) { while (rstSet...
testStore.add(new Role("test")); testStore.add(new Role("test2")); assertTrue(testStore.findAll().containsAll(asList(new Role("test"), new Role("test2")))); } }
120487379_34
class TypesBuilder { public List<Builder> build(Domain domain, DomainTypeResolver domainTypeResolver) { final List<Type> domainTypes = domain.getTypes(); List<TypeHandlerResult> result = new ArrayList<>(); if (CollectionUtils.isNotEmpty(domainTypes)) { for (Type type : domainTypes) { resul...
Map<Class<? extends ArrayItem>, String> arrayItems = new HashMap<>(); arrayItems.put(ObjectArrayItem.class, "Object"); arrayItems.put(AnyArrayItem.class, "Object"); arrayItems.put(StringArrayItem.class, "String"); arrayItems.put(IntegerArrayItem.class, "Integer"); arrayItems.put(NumberArrayItem...
120606464_2
class AsynchronousTimeoutBean { @Asynchronous public Future<Boolean> timeout(boolean shouldTimeout) { Boolean timedOut = false; if (shouldTimeout) { try { // Simulate a long running query Thread.sleep(AWAIT); } catch (InterruptedE...
Future<Boolean> future = asynchronousTimeoutBean.timeout(true); try { future.get(); } catch (TimeoutException toe) { return; } catch (ExecutionException ex) { if (ex.getCause() instanceof TimeoutException) { return; } ...
120684055_76
class CalypsoPo extends MatchingSe { public PoRevision getRevision() { return this.revision; } public CalypsoPo(SeResponse selectionResponse, String extraInfo); public byte[] getDfName(); public byte[] getApplicationSerialNumber(); public byte[] getAtr(); public boolean isModific...
Assert.assertEquals(getPoApplicationByte((byte) 0x01).getRevision(), PoRevision.REV2_4); Assert.assertEquals(getPoApplicationByte((byte) 0x04).getRevision(), PoRevision.REV2_4); Assert.assertEquals(getPoApplicationByte((byte) 0x06).getRevision(), PoRevision.REV2_4); Assert.assertEqual...
120756407_1
class CompositeBuffer implements Buffer { public static CompositeBuffer newBuffer() { return BuffersBuffer.create(); } public static CompositeBuffer newBuffer(final MemoryManager memoryManager); public static CompositeBuffer newBuffer(final MemoryManager memoryManager, final Buffer... buffers)...
final byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; final List<Buffer> bufferList = new ArrayList<>(); for (byte b : bytes) { final Buffer buffer = mm.allocate(1); buffer.put(0, b); bufferList.add(buffer); } final Buffer[] buff...
120761297_9
class UserMapper implements Function<UserRaw, User> { @Override public User apply(UserRaw userRaw) { return User.builder() .login(notNullOrEmpty(userRaw.login())) .id(userRaw.id()) .avatarUrl(notNullOrEmpty(userRaw.avatarUrl())) .url(notNu...
UserRaw userRaw = UserDataTestUtils.userRawTestBuilder() .starredUrl("www.google.com") .build(); User user = userMapper.apply(userRaw); assertThat(user.starredUrl()).isEqualTo("www.google.com"); } }
120778005_2
class LiveDataResponseBodyConverterFactory extends Converter.Factory { @Nullable @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (type instanceof ParameterizedT...
Type responseType = new TypeToken<String>() {}.getType(); Converter<ResponseBody, ?> converter = factory .responseBodyConverter(responseType, NO_ANNOTATIONS, retrofit); assertThat(converter).isInstanceOf(StringConverterFactory.StringResponseBodyConverter.class); } }
120780458_0
class Library { public Collection<Book> getFirstAvailableBooks(final String keyword) { return new GetFirstAvailableBooks(emf, keyword).transact(); } public static final Library library(); public synchronized Library init(KieContext kcontext); synchronized Library init(); public Loan at...
final Collection<Book> books = LIBRARY.getFirstAvailableBooks("Time Machine"); assertThat(books, is(not(emptyCollectionOf(Book.class)))); } }
120905144_6
class ProcFSUtils { protected static List<ProcSmaps> parseSmaps(String output) { String[] lines = output.split("\n"); List<ProcSmaps> res = new ArrayList<>(); ProcSmaps.Builder builder = null; for (String line : lines) { line = line.trim(); Matcher address ...
String output = "7f1ada0ca000-7f1ada19c000 rw-p 00000000 00:00 0 \n" + "Size: 840 kB\n" + "Rss: 836 kB\n" + "Pss: 836 kB\n" + "Shared_Clean: 0 kB\n" + "Shared_Dirty: 0...
120961330_12
class Resources { public static Set<String> getResourceReferences(Collection<? extends Message> resources) { final ImmutableSet.Builder<String> refs = ImmutableSet.builder(); for (Message r : resources) { if (r instanceof ClusterLoadAssignment || r instanceof RouteConfiguration) { // Endpoints...
String clusterServiceName = "clusterWithServiceName0"; io.envoyproxy.envoy.config.cluster.v3.Cluster clusterWithServiceName = io.envoyproxy.envoy.config.cluster.v3.Cluster .newBuilder() .setName(V3_CLUSTER_NAME) .setEdsClusterConfig( io.envoyproxy.envoy.config.cluster.v3.Clus...
120970441_39
class BigQuerySchemaUtils { public static Schema beamSchemaToBigQueryClientSchema( org.apache.beam.sdk.schemas.Schema tableSchema) { ArrayList<Field> bqFields = new ArrayList<>(tableSchema.getFieldCount()); for (org.apache.beam.sdk.schemas.Schema.Field f : tableSchema.getFields()) { bqFields.add...
assertThat(BigQuerySchemaUtils.beamSchemaToBigQueryClientSchema(ALL_BEAM_SCHEMA), is(ALL_BQ_SCHEMA)); } }
121075789_4
class App { public String greet(String name) { return Util.join("Hello ", name); } public boolean store(String name); } class AppTest { @Test public void testGreet() {
App app = new App(); assertEquals(app.greet("world"), "Hello world"); } }
121110666_1
class CalendarUtil { public static List<Date> getMonthDates(int year, int month) { // long curTime = System.currentTimeMillis(); LocalDate localDate = new LocalDate(year, month, 1); List<Date> dates = new ArrayList<>(); while (localDate.getMonthOfYear() <= month && localDate.getYear(...
List<Date> dates = CalendarUtil.getMonthDates(2018, 7); assertEquals(42, dates.size()); } }
121151622_4
class ExpandableList extends Node implements List<INode> { protected boolean isChild(INode node) { INode parent = node.getParent(); while (parent != null) { if (parent == this) { return true; } parent = parent.getParent(); } return...
INode node1 = new Node(); INode node2 = new Node(); node1.insert(node2); Node node3 = new Node(); node2.insert(node3); ExpandableList list = new ExpandableList(); assertFalse(list.isChild(node3)); list.insert(node1); assertTrue(list.isChild(node3))...
121153885_0
class McuMgrResponse { public static int getExpectedLength(@NotNull McuMgrScheme scheme, @NotNull byte[] bytes) throws IOException { if (scheme.isCoap()) { throw new UnsupportedOperationException("Method not implemented for CoAP"); } else { if (bytes.length < Mcu...
final byte[] data = {(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x79, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0xBF, (byte) 0x66, (byte) 0x69, (byte) 0x6D, (byte) 0x61, (byte) 0x67, (byte) 0x65, (byte) 0x73, (byte) 0x9F, (byte) 0xBF, (byte) 0x64, (byte) 0x73,...
121218280_1
class QRTone { public static double computeRms(float[] signal) { double sum = 0; for (double aSignal : signal) { sum += aSignal * aSignal; } return Math.sqrt(sum / signal.length); } public QRTone(Configuration configuration); public int getMaximumWindowLen...
double sampleRate = 44100; double powerRMS = Math.pow(10, -26.0 / 20.0); // -26 dBFS float signalFrequency = 1000; double powerPeak = powerRMS * Math.sqrt(2); float[] audio = new float[4410]; for (int s = 0; s < audio.length; s++) { double t = s * (1 / sample...
121236494_125
class WildcardMatcher { public abstract boolean matches(CharSequence s)public abstract boolean matches(CharSequence s); public abstract boolean matches(CharSequence s)public static WildcardMatcher caseSensitiveMatcher(String matcher); public abstract boolean matches(CharSequence s)public static WildcardMatcher matchA...
final WildcardMatcher matcher = buildMatcher("*foo*"); assertSoftly(softly -> { // no allocations necessary softly.assertThat(matcher.matches("foo", "BAR")).isTrue(); softly.assertThat(matcher.matches("BAR", "foo")).isTrue(); softly.assertThat(matcher.matc...
121247108_26
class QuickSort { public static List<Integer> sort(List<Integer> sourceDatas) { switch (sourceDatas.size()) { case 0: // Base Case return new ArrayList<>(); case 1: // Base Case return sourceDatas; default: int pivot = sour...
int[] array = { 3, 2, 4, 1 }; QuickSort.sort(array, 0, array.length - 1); assertThat(array, equalTo(new int[] { 1, 2, 3, 4 })); } }
121312281_8
class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profile...
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))...
121320887_3
class CursorPoint { public CursorPoint getCursorPointScaledBy(double scaleFactor) { return (new CursorPoint((int) (this.x * scaleFactor), (int) (this.y * scaleFactor), (int) (delay * scaleFactor))); } public CursorPoint(int x, int y, int delay); public double getDistanceFromOrigin(); public double getThetaFr...
CursorPoint a = new CursorPoint(0, 0, 0); CursorPoint b = new CursorPoint(100, 0, 0); CursorPoint c = new CursorPoint(100, 200, 0); CursorPoint d = new CursorPoint(-400, -300, 0); CursorPoint e = a.getCursorPointScaledBy(1.1); CursorPoint f = b.getCursorPointScaledBy(0.95); CursorPoint g = c.getCursorPoin...
121349361_3
class HelloHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) { String who = "World"; if ( request.getPathParameters() != null ) { String name ...
input.withPathParamters(Collections.emptyMap()); APIGatewayProxyResponseEvent res = handler.handleRequest(input, null); assertNotNull(res); assertEquals("Hello World!", res.getBody()); } }
121391917_16
class JsonSchemaPreProcessor implements RecordPreProcessor { @Override public CompletionStage<Envelope> preProcess(Envelope envelope) { try { var rawValue = envelope.getRawValue(); final JsonNode event; final String eventType; if (rawValue instanceof Clo...
var processor = getProcessor(); assertThatThrownBy(() -> preProcess(processor, (String) null)) .hasMessageContaining("/eventType is null"); } }
121405227_0
class FixLengthDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.readableBytes() >= length){ ByteBuf byt = in.readBytes(length) ; out.add(byt) ; } } publ...
ByteBuf buf = Unpooled.buffer(); for (int i = 0; i < 9; i++) { buf.writeByte(i); } ByteBuf duplicate = buf.duplicate(); EmbeddedChannel channel = new EmbeddedChannel(new FixLengthDecoder(3)); channel.writeInbound(buf.retain()); channel.finish(); ...
121473558_6
class VertexMetadata { public Iterable<String> toIterable(CSVRecord record) { return () -> new Iterator<String>() { int index = 0; @Override public boolean hasNext() { return index <= lastColumnIndex; } @Override publ...
String columnHeaders = "\"_id\",\"_labels\",\"address\",\"name\",\"index\",\"txid\",\"_start\",\"_end\",\"_type\",\"strength\",\"timestamp\""; VertexMetadata vertexMetadata = createVertexMetadata(columnHeaders); CSVRecord record = CSVUtils.firstRecord("\"1\",\":Person\",\"address\",\"name\",\"1...
121514433_0
class MethodRemovalRule implements ComparingValidationRule { @Override public void methodRemoved(final ValidationContext ctx, final MethodDescriptor current) { // TODO(staffan): Take things like lifecycle into account here. Removing methods from a GA // service is a no-no but removing it from a experimenta...
final DescriptorSet current = DescriptorSetUtils.buildDescriptorSet( "a.proto", "syntax = 'proto3';\n" + "service Derp {\n" + " rpc GetDerp (HerpDerp) returns (HerpDerp);\n" + "}\n" + "message HerpDerp {}" ); final DescriptorSet candidate = DescriptorSetUtils...
121984024_10
class DictionaryPresenter { void search(String word) { boolean isLatinAlphabet; if (word.isEmpty()) { return; } word = word.toLowerCase(Locale.ROOT); if (SpellChecker.ALPHABET_LATIN.indexOf(word.charAt(0)) >= 0) { isLatinAlphabet = true; } ...
List<SozlikDbModel> list = new ArrayList<>(); list.add(new SozlikDbModel()); when(sozlikDaoMock.getTranslation(SOME_WORD)).thenReturn(null); when(spellCheckerMock.check(SOME_WORD, true)).thenReturn(list); dictionaryPresenter.search(SOME_WORD); verify(dictionaryViewMock...
122105687_1
class Manifest { Optional<String> fetch(final String assetName) { log.fine(() -> String.format("Fetching asset '%s'", assetName)); Optional<String> rv; try { final Map<String, String> values = getValues(); rv = Optional.ofNullable(values.get(assetName)).map(a -> a.r...
final Manifest manifest = new Manifest(objectMapper, new ClassPathResource("broken.json")); assertThat(manifest.fetch("app.js")).isEmpty(); } }
122146857_2
class FeaturesConfigReader extends AbstractConfigReader { public static FieldFeatureExtractorFactory loadFactory(FeaturesConfigReader.FeatureDesc featureDesc){ ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class<? extends FieldFeatureExtractorFactory> cls = (Class<? extends...
FeaturesConfigReader fcReader = new FeaturesConfigReader(loader,"ltr_features.conf"); assertEquals(FieldFeatureTFExtractorFactory.class, FeaturesConfigReader.loadFactory(fcReader.getFeatureDesc("TF in title")).getClass()); assertEquals(FieldFeatureTFExtractorFactory.class, FeaturesConfigReader.loadFactory(f...
122194961_3
class NarayanaConfiguration { @Bean @ConditionalOnMissingBean public JtaTransactionManager transactionManager(UserTransaction userTransaction, TransactionManager transactionManager, TransactionSynchronizationRegistry transactionSynchronizationRegistry) { JtaTransactionManage...
JtaTransactionManager jtaTransactionManager = this.configuration.transactionManager( this.mockUserTransaction, this.mockTransactionManager, this.mockTransactionSynchronizationRegistry); assertThat(jtaTransactionManager.getUserTransaction()).isEqualTo(this.mockUserTransaction); as...
122369264_51
class ComposerProviderHandler implements Handler { @Nonnull @Override public Response handle(@Nonnull final Context context) throws Exception { Response response = context.proceed(); if (!Boolean.parseBoolean(context.getRequest().getAttributes().get(DO_NOT_REWRITE, String.class))) { if (response.ge...
when(response.getPayload()).thenReturn(null); Response output = underTest.handle(context); assertThat(output, is(response)); verifyNoMoreInteractions(composerJsonProcessor); } }
122426223_23
class TransactionApiImpl implements TransactionApi { @Override public List<String> getPendingTransactionList(String branchId) { return branchGroup.getUnconfirmedTxs(BranchId.of(branchId)) .stream().map(tx -> tx.getHash().toString()).collect(Collectors.toList()); } @Autowired pu...
assertThat(txApi.getPendingTransactionList(yggdrashBranch)).isNotNull(); } }
122426901_387
class BlockchainConfig { public void updateChain(Chain chain, int minPrunableLifetime, int maxPrunableLifetime) { Objects.requireNonNull(chain, "Chain cannot be null"); setFields(chain, minPrunableLifetime, maxPrunableLifetime); Map<Integer, BlockchainProperties> blockchainProperties = cha...
Chain emptyChain = new Chain(UUID.randomUUID(), new ArrayList<>(), "Empty", "Empty chain", "EMP", "EM", "EMP", "", List.of()); assertThrows(IllegalArgumentException.class, () -> blockchainConfig.updateChain(emptyChain)); } }
122429896_1
class AkkaEngineProvider implements ReactiveStreamsEngine { public static AkkaEngine provider() { AkkaEngine engine = null; // Double checked locking to initialize the weak reference the first time this method // is invoked. if (cachedEngine == null) { synchronized (mutex) { if (cached...
AkkaEngine engine = AkkaEngineProvider.provider(); ActorSystem system = ((ActorMaterializer) engine.materializer).system(); Flow.Publisher<Done> publisher = Source.tick( Duration.create(100, TimeUnit.MILLISECONDS), Duration.create(100, TimeUnit.MILLISECONDS), Don...
122461562_1
class ImageBuilder { public TargetPlatformSpec prepare(TargetPlatformSpec inputSpec) { try { List<Path> platformArtifacts = install(Arrays.asList(inputSpec.getDependencies()),TargetPlatformSpec.platformPath(targetBase)); Path specArtifact = Files.createDirectories(TargetPlatformSpec...
FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); // Create test inputs: Path inputs = Files.createDirectories(fs.getPath("/").resolve("INPUTS")); Path p1 = Files.write(inputs.resolve("DATA1"),"data1".getBytes(StandardCharsets.UTF_8)); Path p2 = Files.write(inputs.resolv...
122467588_2
class NameRepository { public Single<String> getName() { return Single.create( emitter -> { Gson gson = new Gson(); emitter.onSuccess(gson.fromJson(fileReader.readFile(), User.class).name); }); } public NameRepository(FileReader fileReader); @Mock FileReader fileReade...
TestObserver<String> observer = nameRepository.getName().test(); observer.assertValue("Sasha"); } }
122494549_0
class Server implements Instance, Communicatable { @Override public void start() { try { this.starting = true; Message message = Message.create() .setType("START_SERVER") .set("name", getName()) .set("id", getId()) ...
mockStatic(HashUtil.class); when(HashUtil.getHashes(any(File.class))).thenReturn(null); when(coreFileManager.getServerGlobalDirectory()).thenReturn(new File("core/templates/server/Global/")); doAnswer(invocation -> { Message message = invocation.getArgument(0); ge...
122514469_8
class FloatParser implements ConfigurationParser { @Override public Float parseValue(String value, Class targetType) { if(value == null) throw new ConfigurationParserException("Could not parse 'null' to float"); return Float.parseFloat(value); } @Override public Set<Class> getResponsib...
parser.parseValue(null, Float.class); fail(); } }
122529106_2
class OwnerFieldClass { public ExecutableElement getSetter(String propertyName) throws UnableToCompleteException { if (ambiguousSetters != null && ambiguousSetters.contains(propertyName)) { logger.die( "Ambiguous setter requested: " + AptUtil.asQualifiedNameable(rawType).getQualifiedName() ...
TypeElement typeElement = elements.getTypeElement(ChildClass.class.getName()); OwnerFieldClass cut = new OwnerFieldClass(typeElement.asType(), mockLogger, mockContext); ExecutableElement setter = cut.getSetter("text"); assertNotNull(setter); verifyNoMoreInteractions(mockLogger, mockContext); } ...
122577034_11
class InterProcessReadWriteLock { public InterProcessMutex writeLock() { return writeMutex; } public InterProcessReadWriteLock(CuratorFramework client, String basePath); public InterProcessReadWriteLock(CuratorFramework client, String basePath, byte[] lockData); public InterProc...
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final byte[] nodeData = new byte[] { 1, 2, 3, 4 }; InterProcessReadWriteLock lock = new InterProcessReadWriteLock(cli...
122583771_0
class ChirpTimelineEntity extends PersistentEntity<ChirpTimelineCommand, ChirpTimelineEvent, NotUsed> { private Persist addChirp(AddChirp cmd, CommandContext<Done> ctx) { return ctx.thenPersist(new ChirpAdded(cmd.chirp), evt -> { ctx.reply(Done.getInstance()); topic.publish(cmd.chir...
ChirpTopicStub topic = new ChirpTopicStub(); PersistentEntityTestDriver<ChirpTimelineCommand, ChirpTimelineEvent, NotUsed> driver = new PersistentEntityTestDriver<>(system, new ChirpTimelineEntity(topic), "user-1"); Chirp chirp = new Chirp("user-1", "Hello, world"); Per...
122638182_96
class PlanParser { public PerfPlan parseResource(Resource resource) { requireNonNull(resource); URI uri = resource.getUri(); String source = read(resource); ServiceLoader<cucumber.perf.salad.PlanParser> services =ServiceLoader.load(cucumber.perf.salad.PlanParser.class); Iter...
PlanParser p = new PlanParser(UUID::randomUUID); URI uri = URI.create("src/test/java/resources/test.plan"); Resource r = new UriResource(Paths.get(uri.getPath())); PerfPlan pp = p.parseResource(r); assertEquals("simulation 1", pp.getSaladPlan().getPlan().getChildren().get(0).getName()); } }
122711080_76
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...
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...
122751554_12
class MatcherContext { public Set<Person> getRemainingReceivers() { return IntStream.range(0, satisfiedReceivers.length) .filter(i -> !satisfiedReceivers[i]) .mapToObj(receivers::get) .collect(Collectors.toUnmodifiableSet()); } public MatcherContext(final List<...
assertEquals(Set.of(PERSON_1, PERSON_2, PERSON_3), target.getRemainingReceivers()); } }
122753171_110
class DefaultHttp2FrameReader implements Http2FrameReader, Http2FrameSizePolicy, Configuration { @Override public void readFrame( final ChannelHandlerContext ctx, final ByteBuf input, final Http2FrameListener listener) throws Http2Exception { if (readError) { input.skipBytes(input.readableByt...
final int streamId = 1; final ByteBuf input = Unpooled.buffer(); try { final Http2Headers headers = new DefaultHttp2Headers().authority("foo").method("get").path("/").scheme("https"); final Http2Flags flags = new Http2Flags().endOfHeaders(true).endOfStream(true); writeHeaderFram...
122852176_0
class DatabaseFourObject implements ModelDAO { public boolean createStudent(Student student) throws SQLException, FileNotFoundException, IOException { state = isUserAvailable(student.getChatId()); if (state) { students = connect(); students.store(student); students.commit(); } return state; } p...
assertTrue(database.createStudent(new Student(Long.parseLong("9998"), "0000", "0000"))); } }
122918493_34
class ServiceProviderInterfaceRecommender implements ConfigDef.Recommender { @Override public boolean visible(String name, Map<String, Object> connectorConfigs) { return true; } public ServiceProviderInterfaceRecommender(Class<T> clazz); @Override public List<Object> validValues(String name, Map<Strin...
ServiceProviderInterfaceRecommender<RequestExecutor> recommender = new ServiceProviderInterfaceRecommender<>(RequestExecutor.class); assertThat(recommender.visible("test", Collections.emptyMap()), equalTo(true)); } }
122954189_6
class DefaultCaseValidator extends Validator { @Override public void validate(UastNode node) { is(UastNode.Kind.DEFAULT_CASE); hasKeyword("default"); noChild(UastNode.Kind.CONDITION); // FIXME go 'select' nodes are feeding default cases and should be removed // hasAncestor(UastNode.Kind.SWITCH)...
UastNode caseNode = node(Sets.newHashSet(UastNode.Kind.DEFAULT_CASE, UastNode.Kind.CASE), keyword("case"), token(":")); UastNode node = node(UastNode.Kind.SWITCH, caseNode); Validator.ValidationException exception = assertThrows(Validator.ValidationException.class, () -> validate(node)); as...
122966748_12
class DateUtils { public static Date getDateBeforePeriod(String perStr, Date curDate) { Period pr = getPeriod(perStr); DateTime dt = new DateTime(curDate); return dt.minus(pr).toDate(); } public static Period getPeriod( String perStr ); public static Date getDateAfte...
DateTime dt = new DateTime(2015, 1, 1, 1, 1); Date expected = dt.minusHours(1).minusMinutes(5).toDate(); Date result = DateUtils.getDateBeforePeriod("1s5d", dt.toDate()); Assert.assertEquals(expected, result); //Ingilizce result = DateUtils.getD...
123178569_1
class Library { public boolean someLibraryMethod() { return true; } } class LibraryTest { @Test public void testSomeLibraryMethod() {
Library classUnderTest = new Library(); assertTrue(classUnderTest.someLibraryMethod(), "someLibraryMethod should return 'true'"); } }
123189523_1
class MagnetInstanceManager implements InstanceManager { @Override public <T> @Nullable InstanceFactory<T> getFilteredInstanceFactory( Class<T> type, String classifier, FactoryFilter factoryFilter ) { Range range = getOptionalRange(type, classifier); if (range == null) { ...
// when InstanceFactory<Type1> factory = instManager.getFilteredInstanceFactory( Type1.class, CLASSIFIER_LOCAL, factoryFilter); // then assertThat(factory).isNotNull(); } }
123284439_19
class RecordApi extends BaseProvider implements RecordProvider { @Override public void checkRecordExists(String id) throws OaiPmhException { ResponseEntity<String> response = getResponseForRecord(id); if (response == null) { throw new IdDoesNotExistException("Record with id '" + id ...
Mockito.doThrow(new IdDoesNotExistException("INCORRECT/ID")).when(recordApi).checkRecordExists("INCORRECT/ID"); recordApi.checkRecordExists("INCORRECT/ID"); fail(); // should not reach this code } }
123335926_5
class Utils { public static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo) { SymbolInfo symbolInfo = pExchangeInfo.getSymbolInfo(pSymbol); String tickSize = symbolInfo.getSymbolFilter(FilterType.LOT_SIZE).getStepSize(); return roundToTickSize(pQuantity, tickSize); } p...
ExchangeInfo ex = new ExchangeInfo(); List<SymbolInfo> symbols = new ArrayList<>(); SymbolInfo si = new SymbolInfo(); si.setSymbol("NEOETH"); symbols.add(si); ex.setSymbols(symbols); SymbolFilter lotFilter = new SymbolFilter(); lotFilter.setFilterType(FilterType.LOT_SIZE); lotFilter.setStepSize(...
123340956_1
class User implements Serializable { public String getUsername() { return username; } public User(String username); public void setUsername(String username); public void listenToMessages(MessageReceivedObserver observer); public void receiveMessage(Message message); @Override pub...
assertEquals("john", john.getUsername()); } }
123415889_0
class ResteasyEmbeddedServletInitializer implements BeanFactoryPostProcessor { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { logger.debug("Post process bean factory has been called"); findJaxrsApplications(beanFactory); // This is ...
Map<String, ServletRegistrationBean> servletRegistrationBeans = applicationContext.getBeansOfType(ServletRegistrationBean.class); Assert.assertNotNull(servletRegistrationBeans); // Although there are 5 sample JAX-RS Application classes, one of them is not annotated with the Application...
123463973_5
class PlayerViewModel extends BaseViewModel { public void volumeDown(){ audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND); setCurrentVolumeVolume(); } @Inject public PlayerViewModel(VideoRepository videoRepository, AudioManager audioManager); public v...
Observer observer = mock(Observer.class); viewModel.getVolumeValue().observeForever(observer); currentVolume = 5; viewModel.volumeDown(); verify(observer, times(2)).onChanged(any()); assertTrue(viewModel.getVolumeValue().getValue() == 4); } }
123532715_1
class DockerPluginUtils { public static String resolveValue(String value) throws DockerPluginException { int startIndex; if ((startIndex = value.indexOf("$env{")) >= 0) { int endIndex = value.indexOf("}", startIndex); if (endIndex > 0) { String varName = valu...
Map<String, String> env = new HashMap<>(); env.put("DOCKER_USERNAME", "anuruddhal"); setEnv(env); try { Assert.assertEquals(DockerPluginUtils.resolveValue("$env{DOCKER_USERNAME}"), "anuruddhal"); } catch (DockerPluginException e) { Assert.fail("Unable to r...
123532974_6
class KubernetesUtils { public static void copyFileOrDirectory(String source, String destination) throws KubernetesPluginException { File src = new File(source); File dst = new File(destination); try { // if source is file if (Files.isRegularFile(Paths.get(source))) ...
File testFile = tempDirectory.resolve("copy.txt").toFile(); Assert.assertTrue(testFile.createNewFile()); Path destinationDir = Files.createTempDirectory("copy-test-"); KubernetesUtils.copyFileOrDirectory(testFile.getAbsolutePath(), destinationDir.toString()); // assert ...
123618046_11
class Config { public AsyncClient getAsyncClient() { if (!asyncClientIsReady()) { buildAsyncClient(); } return asyncClient.get(); } public Config(); private void setDefaults(); public Config httpClient(HttpClient httpClient); public Config httpClient(Clien...
assertSame(config.getAsyncClient(), config.getAsyncClient()); } }
123664565_0
class RxBackoff { public static RxBackoff fixed(long interval, int maxRetryCount) { return new RxBackoff(new Backoff.Builder() .setAlgorithm(new FixedIntervalAlgorithm(interval, TimeUnit.MILLISECONDS)) .setMaxRetryCount(maxRetryCount) .build()); } public RxBackoff(@NonNull Backoff b...
final AtomicInteger count = new AtomicInteger(0); final TestScheduler scheduler = new TestScheduler(); final RxBackoff backoff = new RxBackoff( new Backoff.Builder() .setAlgorithm(new FixedIntervalAlgorithm()) .setMaxRetryCount(5) .build(), scheduler); ...
123681471_114
class RuleParser { public static KnowledgeBase parse(final InputStream stream, final String encoding, final ParserConfiguration parserConfiguration) throws ParsingException { JavaCCParser parser = new JavaCCParser(stream, encoding); parser.setParserConfiguration(parserConfiguration); return doParse(parser); ...
String input = "@base <http://example.org/> . " + " q(?X, !Y), r(?X, d) :- ~p(?X,c), p(?X,?Z) . "; ArrayList<Statement> statements = new ArrayList<>(RuleParser.parse(input).getStatements()); assertEquals(Arrays.asList(rule2), statements); } }
123712995_12
class TweeterApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { this.jdbcTemplate.execute("CREATE TABLE tweets (\n" + // " uuid VARCHAR(36) PRIMARY KEY,\n" + // " text VARCHAR(255),\n" + // " username VARCHAR(128),\n...
SpringApplication.run(Hajiboot2TweeterApplication.class); String output = capture.toString(); assertThat(output).contains("Number of tweets: 2"); assertThat(output).containsPattern( "Tweet\\{uuid=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}, text='Demo1', username='making', createdAt=[0-9]{4...