id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
111042175_0
class RecommendationVerticle extends AbstractVerticle { static String parseContainerIdFromHostname(String hostname) { return hostname.replaceAll("recommendation-v\\d+-", ""); } @Override public void start(); private void logging(RoutingContext ctx); private void timeout(RoutingContext ctx)...
assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommendation-v1-abcdef"), equalTo("abcdef")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommendation-v2-abcdef"), equalTo("abcdef")); assertThat(RecommendationVerticle.parseContainerIdFromHostname("recommen...
111090962_7
class TextAndPosition { public List<Integer> match(String toMatch) { // For now, we do case-insensitive search... toMatch = toMatch.toLowerCase(); ArrayList<Integer> result= new ArrayList<>(); if (toMatch.length() == 0) return result; int found = 0; ...
List<Integer> res = textAndPosition.match("ghi"); assertEquals(Arrays.asList(11), res); } }
111096014_345
class PartitionSpecCreatingDiffListener implements DiffListener { @Override public void onNewPartition(String partitionName, Partition partition) { addPartition(partition); } public PartitionSpecCreatingDiffListener(Configuration conf); @Override public void onDiffStart(TableAndMetadata source, Option...
Partition partition1 = new Partition(Lists.newArrayList("val1", "val2"), DB, TABLE, 1, 1, null, null); Partition partition2 = new Partition(Lists.newArrayList("val11", "val22"), DB, TABLE, 1, 1, null, null); listener.onDiffStart(source, replica); listener.onNewPartition("p1", partition1); listener.o...
111391133_89
class ContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, String> attachments = setCallChainContextMap(invocation); if (attachments != null) { attachments = new HashMap<String, String>(attachments); ...
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInv...
111433118_3
class GoogleAssistantAutoConfiguration { @Bean @ConditionalOnMissingBean(WebhookController.class) public WebhookController webhookController(SpeechRequestDispatcher dispatcher) { return new WebhookController(dispatcher); } private final ApplicationContextRunner contextRunner; } class GoogleAssistantAutoConfi...
this.contextRunner.withUserConfiguration(GoogleConfiguration.class) .run( context -> { SpeechRequestDispatcher dispatcher = context.getBean(SpeechRequestDispatcher.class); assertThat(context).hasSingleBean(WebhookController.class); assertThat(context.getBean(WebhookController.class)) ...
111445552_5
class DecoderUtil { public static String getUtf8FromByteBuffer(final ByteBuffer bb) { bb.rewind(); byte[] bytes; if (bb.hasArray()) { bytes = bb.array(); } else { bytes = new byte[bb.remaining()]; bb.get(bytes); ...
String testString = "asdlkfjajo3wjaf3o8ajlfija3lfijaslijfl83auj"; byte[] encodedBytes = testString.getBytes(StandardCharsets.UTF_8); ByteBuffer bb = ByteBuffer.wrap(encodedBytes); String decodedString = DecoderUtil.getUtf8FromByteBuffer(bb); Assert.assertEquals(testStrin...
111517878_42
class ShortString implements EncodableData { public static ShortString parse(ByteBuf buf) { int size = buf.readUnsignedByte(); byte[] data = new byte[size]; buf.readBytes(data); return new ShortString(size, data); } @SuppressFBWarnings("EI_EXPOSE_REP2") public ShortString...
ByteBuf buf = Unpooled.buffer(DEFAULT_DATA_STRING.length() + 1); DEFAULT_TEST_OBJECT.write(buf); ShortString parsedObject = ShortString.parse(buf); Assert.assertEquals(parsedObject, DEFAULT_TEST_OBJECT, "Encoding and decoding should match to same object"); } }
111669949_29
class DefaultUserDetails implements UserDetails { @Override public boolean equals(Object obj) { return ObjectEquals.of(this) .equals(obj, (orgin, other) -> Objects.equals(orgin.getUsername(), other.getUsername())); } private List<String> authorities(); @Override public Coll...
UserDetails obj = DefaultUserDetails.builder() .username("jittagornp") .build(); boolean output = userDetails.equals(obj); boolean expected = true; assertThat(output).isEqualTo(expected); } }
111690131_4
class Loan { public static Loan createTermLoan(double commitment, int riskTaking, Date maturity){ return new Loan(null, commitment, 0.00, riskTaking, maturity, null); } private Loan(CapitalStrategy capitalStrategy, double commitment, double outstanding, int riskTaking, Date maturity, Date expiry)...
Loan termLoan = Loan.createTermLoan(2.0, 1, Date.from(Instant.now())); assertNotNull(termLoan); System.out.println("Test term loan"); } }
111698811_1
class Utils { public static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder) { boolean showHigherResolutions = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.s...
List<VideoStream> result = Utils.getSortedStreamVideosList(MediaFormat.MPEG_4, true, videoStreamsTestList, videoOnlyStreamsTestList, true); List<String> expected = Arrays.asList("144p", "240p", "360p", "480p", "720p", "720p60", "1080p", "1080p60", "1440p60", "2160p", "2160p60"); //for (VideoStr...
111825535_9
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"); ...
111854037_474
class DefaultAudioSink implements AudioSink { @Override @SuppressWarnings("ReferenceEquality") public boolean handleBuffer(ByteBuffer buffer, long presentationTimeUs) throws InitializationException, WriteException { Assertions.checkArgument(inputBuffer == null || buffer == inputBuffer); if (pendin...
configureDefaultAudioSink( CHANNEL_COUNT_STEREO, /* trimStartFrames= */ TRIM_100_MS_FRAME_COUNT, /* trimEndFrames= */ TRIM_10_MS_FRAME_COUNT); defaultAudioSink.handleBuffer(createDefaultSilenceBuffer(), /* presentationTimeUs= */ 0); assertThat(arrayAudioBufferSink.output) .h...
112094343_36
class RadioBrowser { public List<Station> listStationsBy(@NonNull final Paging paging, @NonNull final SearchMode searchMode, @NonNull final String searchTerm, final ListParameter...listParam) { ...
List<Station> stations = browser .listStationsBy(SearchMode.BYNAME, "pop") .limit(256) .collect(Collectors.toList()); assertThat(stations, notNullValue()); assertThat(stations, is(not(Collections.emptyList()))); } }
112101025_42
class RecordManager extends AbstractTransactionManager { public RecordManager( String fileName ) { this( fileName, DEFAULT_PAGE_SIZE ); } public RecordManager( String fileName ); public RecordManager( String fileName, int pageSize ); private void runReclaimer(); private boolean ...
assertEquals( 1, recordManager.getNbManagedTrees() ); Set<String> managedBTrees = recordManager.getManagedTrees(); assertEquals( 1, managedBTrees.size() ); assertTrue( managedBTrees.contains( "test" ) ); BTree<Long, String> btree1 = recordManager.getManagedTree( "test" ); ...
112128651_0
class RouterFunctions { public static <T extends ServerResponse> RouterFunction<T> route(RequestPredicate predicate, HandlerFunction<T> handlerFunction) { Assert.notNull(predicate, "'predicate' must not be null"); Assert.notNull(handlerFunction, "'handlerFunction' must not be null"); return new DefaultRout...
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().build(); RouterFunction<ServerResponse> routerFunction1 = request -> Mono.empty(); RouterFunction<ServerResponse> routerFunction2 = request -> Mono.just(handlerFunction); RouterFunction<ServerResponse> result = routerFunction1.and...
112199510_3
class ProductServiceImpl implements ProductService { @Override public ProductInfo save(ProductInfo productInfo) { return repository.save(productInfo); } @Override public ProductInfo findOne(String productId); @Override public List<ProductInfo> findUpAll(); @Override public Page<Product...
ProductInfo productInfo = new ProductInfo(); productInfo.setProductId("123457"); productInfo.setProductName("皮皮虾"); productInfo.setProductPrice(new BigDecimal(3.2)); productInfo.setProductStock(100); productInfo.setProductDescription("很好吃的虾"); productInfo.setProdu...
112254161_6
class Bme680 implements AutoCloseable { private int concatBytes(final int msb, final int lsb, final boolean isSigned) { if (isSigned) { return (msb << 8) | (lsb & 0xff); // keep the sign of msb but not of lsb } else { return ((msb & 0xff) << 8) | (lsb & 0xff); } ...
byte msb = -12; // 244 byte lsb = 12; int i = concatBytes(msb, lsb, true); // should be 'true' according to c-driver assertThat(i, CoreMatchers.equalTo(-3060)); } }
112291646_1
class AzureWebappPlugin implements Plugin<Project> { public void apply(Project project) { AzureWebAppExtension azureWebAppExtension = new AzureWebAppExtension(project); project.getExtensions().add(WEBAPP_EXTENSION_NAME, azureWebAppExtension); project.getTasks().create(DeployTask.TASK_NAME, ...
Project project = ProjectBuilder.builder().build(); project.getPluginManager().apply("lenala.azure.azurewebapp"); assertTrue(project.getTasks().findByPath("azureWebappDeploy") instanceof DeployTask); } }
112424920_1
class PhoneUtil { public static String hiddenMiddlePhoneNum(String phoneNumber) throws IOException { if (!isPhoneNumber(phoneNumber)) { throw new IOException("phoneNumber invalid"); } return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } @SuppressLint...
String hiddenPhoneNumber = PhoneUtil.hiddenMiddlePhoneNum("1363442986"); Assert.assertEquals("", "136****986", hiddenPhoneNumber); } }
112428883_0
class CustomerServiceProxy { public Mono<Optional<GetCustomerResponse>> findCustomerById(String customerId) { Mono<ClientResponse> response = client .get() .uri(customerServiceUrl + "/customers/{customerId}", customerId) .exchange(); return response.flatMap(resp -> { ...
JSONObject json = new JSONObject(); json.put("customerId", 101); json.put("name", "Fred"); json.put("creditLimit", "12.34"); String expectedResponse = json.toString(); stubFor(get(urlEqualTo("/customers/101")) .willReturn(aResponse() .withStatus(200) ...
112444990_135
class ParametersConverter { public CameraParametersDecorator toPlatformParameters(Parameters parameters, CameraParametersDecorator output) { for (Parameters.Type storedType : parameters.storedTypes()) { applyParameter( ...
// Given Parameters input = new Parameters(); // When CameraParametersDecorator result = testee.toPlatformParameters( input, outputParameters ); // Then assertSame( result, outputParameters ...
112465036_7
class LoggingCallAdapterFactory extends CallAdapter.Factory { @Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { CallAdapter<?, ?> delegate = retrofit.nextCallAdapter(this, returnType, annotations); return new LoggingCallAdapter<>(delegate, logger); } ...
MockWebServer server = new MockWebServer(); final AtomicReference<Throwable> failureRef = new AtomicReference<>(); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")) .addCallAdapterFactory( new LoggingCallAdapterFactory(new LoggingCallAdapterFactory.Logger() { ...
112628388_4
class ConverterUtils { public static Object convertValueToType(Class<?> fieldType, String formattedValue, String columnName, int rowNum) { Object value = null; if (fieldType == String.class) { value = String.valueOf(formattedValue); } else if (fieldType == LocalDateTime.class) {...
assertEquals("Hello", convertValueToType(String.class, "Hello", "A", 1)); assertEquals("HELLO", convertValueToType(String.class, "HELLO", "A", 1)); assertEquals("1.0", convertValueToType(String.class, "1.0", "A", 1)); assertEquals("2019-01-01", convertValueToType(String.class, "2019-01-0...
112785414_2
class ProduceMediaTypeExpression extends AbstractMediaTypeExpression { public final boolean match(List<MediaType> acceptedMediaTypes) { boolean match = matchMediaType(acceptedMediaTypes); return (!isNegated() ? match : !match); } ProduceMediaTypeExpression(String expression); ProduceMediaTypeExpression(Me...
ProduceMediaTypeExpression expression = createExpression( MediaType.APPLICATION_JSON_VALUE); Assert.assertTrue(expression.match( Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON))); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertFalse(expression.match(A...
112941183_81
class UtilAll { public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); // format: "pid@hostname" try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { ...
assertThat(UtilAll.getPid()).isGreaterThan(0); } }
112945272_3
class ChecksumHelper { protected byte[] validateAndStripChecksum(byte[] source) { // retrieve checksum int lastIndexOf = Bytes.lastIndexOf(source, (byte) SEPARATOR); if (lastIndexOf < 0) { throw new RuntimeException("no checksum was found on source: " + new String(source)); } long checkSum = Long.parseLo...
ChecksumHelper checksumHelper = new ChecksumHelper(); byte[] withChecksum = "foobarbaz#444082092".getBytes(); log.debug("withChecksum: " + new String(withChecksum)); assertNotNull(withChecksum); checksumHelper.validateAndStripChecksum(withChecksum); fail("should have thrown an exception by now"); } }
112975556_9
class ExtrasHandler { int remainingExtras() { return extras.size(); } ExtrasHandler(List<IndRecord> indRecords, Random random); void formExtras(List<HhRecord> hhRecs); List<Person> getPersonsFromExtras(RelationshipStatus relStatus, Sex sex, AgeRange ageRange, int count); List<Per...
Assert.assertNotNull(extrasHandler); Assert.assertEquals("Number of extras", extrasHandler.remainingExtras(), 145); } }
113003835_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...
113079801_0
class Sh1106 implements Closeable { public void setContrast(int level) throws IOException, IllegalArgumentException { if (mI2cDevice == null) { throw new IllegalStateException("I2C Device not open"); } if (level < 0 || level > 255) { throw new IllegalArgumentExceptio...
mockStatic(BitmapHelper.class); mockStatic(Bitmap.class); Sh1106 sh1106 = new Sh1106(mI2c); int[] validValues = {0, 66, 255}; for (int validValue : validValues) { sh1106.setContrast(validValue); Mockito.verify(mI2c).writeRegByte(0x00, (byte) 0x81); ...
113164027_59
class MultiplicationServiceImpl implements MultiplicationService { @Transactional @Override public boolean checkAttempt(final MultiplicationResultAttempt attempt) { // Check if the user already exists for that alias Optional<User> user = userRepository.findByAlias(attempt.getUser().getAlias...
// given Multiplication multiplication = new Multiplication(50, 60); User user = new User("john_doe"); MultiplicationResultAttempt attempt = new MultiplicationResultAttempt( user, multiplication, 3010, false); MultiplicationSolvedEvent event = new MultiplicationSo...
113194597_6
class Commands { public final static void main(String[] args) throws Exception { logger.debug(format("CM Client has been called with command line '%s'.", getArgsLogString(args))); CommandLine commandLine = new DefaultParser().parse(Helpers.getStandardParameters(true), args, true); if((co...
Commands.main(new String[] {"--help", "-t", "SOLMAN", "is-change-in-development"}); String help = IOUtils.toString(result.toByteArray(), "UTF-8"); assertThat(help, Matchers.containsString("usage: <CMD> [COMMON_OPTIONS] is-change-in-development")); } }
113222463_311
class YamlDocGenerator { public String generate(String schemaName) { return generate(schemaName, schema); } public YamlDocGenerator(Map<String, Object> schema); private static String toStructureName(String reference); private static String getSimpleName(String reference); private static String toLoc...
Map<String, Object> schema = generateSchema(ReferencingObject.class); YamlDocGenerator generator = new YamlDocGenerator(schema); String markdown = generator.generate("start"); assertThat( markdown, containsString( String.join( "\n", "### Start"...
113356740_1
class QueryResponseToProto { public static <T extends Message> T buildMessage(T message, Map<String, Object> fields) { @SuppressWarnings("unchecked") T populatedMessage = (T) buildMessage(message.toBuilder(), fields); return populatedMessage; } private QueryResponseToProto(); @SuppressWarnings("...
ProtoTruth.assertThat( QueryResponseToProto.buildMessage( TestProto.Proto1.getDefaultInstance(), ImmutableMap.of( "id", "abc", "intField", 123, "testProto", ...
113375834_1255
class ExtraColumnsMetaDataProvider implements MetaDataProvider { @Override public Object getValue(String key) { Object value = null; if (myExtraColumns.containsKey(key)) { value = myExtraColumns.get(key); } else { value = myOriginal.ge...
EasyMockSupport support = new EasyMockSupport(); MetaDataProvider original = createProvider(support); Map<String, Object> extras = createExtraColumns(); support.replayAll(); ExtraColumnsMetaDataProvider provider = new ExtraColumnsMetaDataProvider(original, extras); as...
113380752_0
class RegistryServiceImpl implements RegistryService { @Override public API add(API api) { api.setId(UUID.randomUUID().toString()); jpaTemplate.tx( TransactionType.Required, entityManager -> { entityManager.persist(mapTo(api)); ...
API api = new API(); api.setContext("/simple"); api.setDescription("Simple API"); api.setName("Simple"); registryService.add(api); ClientDataSource dataSource = getDataSource(); try (Connection connection = dataSource.getConnection()) { try (Statemen...
113416930_1
class ThrowErrorTree extends PriorityTree { @Override protected void log(int priority, String tag, @NotNull String message, Throwable t) { if (skipLog(priority, tag, message, t)) { return; } if (t != null) { throw new LogPriorityExceededError(priority, getPriori...
ThrowErrorTree tree = new ThrowErrorTree(); Throwable testThrowable = new Throwable("test"); try { tree.log(Log.INFO, "tag", "message", testThrowable); fail("Expected LogPriorityExceededError"); } catch (LogPriorityExceededError e) { assertEquals(testT...
113425021_115
class Hasher { public Hasher putDouble(double d) { hasher.putDouble(d); return this; } public static Hasher of(HashFunction function); public HashCode hash(); public Hasher put(Hashable hashable); public Hasher putAll(Iterable<? extends Hashable> hashables); public Hasher putBoolean(boolean b); public Has...
assertThat(Hasher.of(HASH_FUNCTION).putDouble(0.0).putDouble(1.0).hash()) .isEqualTo(HASH_FUNCTION.newHasher().putDouble(0.0).putDouble(1.0).hash()); } }
113508911_0
class CertificateManager { public boolean hasNoCertificates() { return (certs == null || certs.length == 0); } CertificateManager(KeyStoreLoader loader); public void setPasswordRequestListener(KeyStoreEntryPasswordRequestListener passwordRequestListener); public void setKeyStoreRequestListe...
boolean hasNoCertificates = manager.hasNoCertificates(); assertFalse(hasNoCertificates); } }
113563925_18
class ScheduledActionHelpers { public static ScheduledAction getNextScheduledPayment(final @Nonnull LocalDate startOfTerm, final @Nonnull LocalDate fromDate, final @Nonnull LocalDate endOfTerm, ...
final LocalDate roughEndDate = ScheduledActionHelpers.getRoughEndDate(testCase.initialDisbursementDate, testCase.caseParameters); testCase.expectedResultContents.stream() .filter(x -> x.getAction() == Action.ACCEPT_PAYMENT) .forEach(expectedResultContents -> { final ScheduledAction nextSc...
113564534_1
class ContactPointUtils { public static void process(final Cluster.Builder clusterBuilder, final String contactPoints) { final String[] splitContactPoints = contactPoints.split(","); for (final String contactPoint : splitContactPoints) { if (contactPoint.contains(":")) { final String[] address ...
final String contactPoints = "127.0.0.1:1234,127.0.0.2:2345,127.0.0.3:3456"; final Cluster.Builder clusterBuilder = Cluster.builder(); ContactPointUtils.process(clusterBuilder, contactPoints); final List<InetSocketAddress> addedClusterPoints = clusterBuilder.getContactPoints(); Assert.assertTrue(a...
113585452_0
class PahoRxMqttCallback implements RxMqttCallback, MqttCallbackExtended { public static PahoRxMqttCallback create( Consumer<Throwable> onConnectionLost, BiConsumer<Boolean, String> onConnectComplete) { return create( onConnectionLost, onConnectComplete, token -> { /* NOP */ }...
PahoRxMqttCallback rxMqttCallback = spy(PahoRxMqttCallback.create(cause -> {}, (recon, uri) -> {}, t -> {})); PahoRxMqttException exception = new PahoRxMqttException( new MqttException(MqttException.REASON_CODE_CONNECTION_LOST)); ArgumentCaptor<Throwable> onConnectionLostCauseArgumentCaptor = Argu...
113597154_117
class MatchingServiceHealthCheckResource { @GET public Response performMatchingServiceHealthCheck() { final AggregatedMatchingServicesHealthCheckResult result = matchingServiceHealthCheckHandler.handle(); final Response.ResponseBuilder response = result.isHealthy() ? Response.ok() : Response.s...
final String failureDescription = "some-error-description"; AggregatedMatchingServicesHealthCheckResult result = new AggregatedMatchingServicesHealthCheckResult(); result.addResult(unhealthy(aMatchingServiceHealthCheckDetails().withDetails(failureDescription).build())); when(handler.hand...
113597875_26
class AsyncListenableFuture extends FiberAsync<V, ExecutionException> { public static <V> V get(ListenableFuture<V> future) throws ExecutionException, InterruptedException, SuspendExecution { if (Fiber.isCurrentFiber() && !future.isDone()) return new AsyncListenableFuture<>(future).run(); ...
final SettableFuture<String> fut = SettableFuture.create(); final Fiber<String> fiber = new Fiber<>(scheduler, new SuspendableCallable<String>() { @Override public String run() throws SuspendExecution, InterruptedException { try { String res =...
113689042_2
class GameBoard { public boolean addObstacle(Obstacle o) { return verifyObstacle(o) ? obstacles.add(o) : false; } public GameBoard(); public GameBoard(int map); private void initializeGameMap(int map); public boolean verifyObstacle(Obstacle o); public boolean addObstacle(MovingO...
assertTrue(board.addObstacle(new Obstacle(5, 10, 0, 0))); assertTrue(board.addObstacle(new Obstacle(25, 25, BOARD_SIZE - 25, BOARD_SIZE - 25))); verifyTaken(0, 0); verifyTaken(4, 9); verifyTaken(BOARD_SIZE - 25, BOARD_SIZE - 25); verifyTaken(BOARD_SIZE - 1, BOARD_SIZE -...
113726044_0
class Wordpath { public Vertex combine(int from, int length) { this.connect(from, length); if (wordnet.isNotContains(from, length)) { return wordnet.put(from, length); } else { return wordnet.getVertex(from, length); } } public Wordpath(Wordnet word...
String line = "我的中国心"; Wordpath wordPath = new Wordpath(new Wordnet(line.toCharArray())); wordPath.combine(0, 2); wordPath.combine(2, 3); Assert.assertEquals("我的 | 中国心", wordPath.toString()); } }
113899964_1
class LifoBlockingLimiter implements Limiter<ContextT> { @Override public Optional<Listener> acquire(ContextT context) { return tryAcquire(context).map(delegate -> new Listener() { @Override public void onSuccess() { delegate.onSuccess(); unblock(...
// Acquire all 4 available tokens List<Optional<Limiter.Listener>> listeners = acquireN(blockingLimiter, 4); // Schedule one to release in 250 msec Executors.newSingleThreadScheduledExecutor().schedule(() -> listeners.get(0).get().onSuccess(), 250, TimeUnit.MILLISECONDS); // Ne...
114149111_1
class VirtualMetric extends AbstractMetric<V> { @Override public ImmutableList<MetricPoint<V>> getTimestampedValues() { return getTimestampedValues(Instant.now()); } VirtualMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, ...
assertThat(metric.getTimestampedValues(Instant.ofEpochMilli(1337))) .containsExactly( MetricPoint.create( metric, ImmutableList.of("label_value1"), Instant.ofEpochMilli(1337), "value1"), MetricPoint.create( metric, ImmutableList.of("label_value2"), Ins...
114157177_36
class StrictMetricsEvaluator { public boolean eval(DataFile file) { // TODO: detect the case where a column is missing from the file using file's max field id. return visitor().eval(file); } public StrictMetricsEvaluator(Schema schema, Expression unbound); private MetricsEvalVisitor visitor(); pr...
boolean shouldRead = new StrictMetricsEvaluator(SCHEMA, notNull("all_nulls")).eval(FILE); Assert.assertFalse("Should not match: no non-null value in all null column", shouldRead); shouldRead = new StrictMetricsEvaluator(SCHEMA, notNull("some_nulls")).eval(FILE); Assert.assertFalse("Should not match: co...
114263933_47
class SPPDecoder implements MALDecoder { @Override public UOctet decodeUOctet() throws MALException { return new UOctet((short) (read() & 0xFF)); } public SPPDecoder(final InputStream inputStream, final Map properties); @Override public Boolean decodeBoolean(); @Override public Boolean decodeNullableBoolean...
newBuffer(new byte[]{}); try { decoder.decodeUOctet(); fail("Expected exception, but none thrown."); } catch (MALException ex) { assertEquals(SPPDecoder.INSUFFICIENT_DATA, ex.getMessage()); } } }
114273718_0
class RequestSignature implements HttpRequestInterceptor { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { try { this.messageSigner.sign(new Request(request)); } catch (GeneralSecurityException e) { throw new HttpException("Can't sign HTTP request...
HttpMessageSigner httpSignature = HttpMessageSigner.builder() .algorithm(Algorithm.RSA_SHA256) .keyMap(HashKeyMap.INSTANCE) .addHeaderToSign(HttpMessageSigner.REQUEST_TARGET) .addHeaderToSign("Date") .addHeaderToSign("Content-Length") .addHeaderToSign("Digest") .keyId("myKeyId").build(); ...
114312965_12
class HMSClient implements AutoCloseable { public Set<String> getAllTables(@NotNull String dbName, @Nullable String filter) throws TException { if (filter == null || filter.isEmpty()) { return new HashSet<>(client.get_all_tables(dbName)); } return client.get_all_tables(dbName) .stream() ...
try { client.createTable(TEST_TABLE); assertThat(client.getAllTables(TEST_DATABASE, null), contains(TEST_TABLE_NAME)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { client.dropTable(TEST_DATABASE, TEST_TABLE_NAME); } } }
114408926_0
class ScreenshotFileProvider { String cleanseTag(@NonNull String tag) { final String originalTag = tag; tag = tag.toLowerCase().replaceAll(" ", "_").replaceAll("[^A-Za-z0-9_]", ""); if (!originalTag.equals(tag)) { log("Cleansed Tag: [" + originalTag + "] -> [" + tag + "]"); ...
String cleansed = new ScreenshotFileProviderNoOp().cleanseTag("a b c * $ ! d"); assertThat(cleansed).isEqualTo("a_b_c____d"); } }
114418594_45
class Part4Backpressure { @Complexity(EASY) public static Flux<String> dropElementsOnBackpressure(Flux<String> upstream) { // TODO: apply backpressure to drop elements on downstream overwhelming // HINT: Flux#onBackpressureDrop throw new RuntimeException("Not implemented"); } ...
DirectProcessor<String> processor = DirectProcessor.create(); StepVerifier .create(dropElementsOnBackpressure(processor), 0) .expectSubscription() .then(() -> processor.onNext("")) .then(() -> processor.onNext("")) .thenRequ...
114489910_12
class OrderServiceImpl implements OrderService { @Override @Transactional(readOnly = true) public IngredientType getIngredientTypeByIngredientId(Long ingredientId) { return ingredientDAO.findById(ingredientId).orElseThrow(RuntimeException::new).getIngredientType(); } @Override @Transaction...
// given IngredientType ingredientType = new IngredientType(); Long ingredientId = 42L; Ingredient ingredient = new Ingredient(); ingredient.setId(ingredientId); ingredient.setIngredientType(ingredientType); when(ingredientDAO.findById(ingredientId)).thenReturn(O...
114520717_207
class Listener4Assist implements ListenerAssist { public synchronized void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause) { Listener4Model model = modelHandler.removeOrCreate(task, task.getInfo()); if (assistExtend != null ...
when(handler.removeOrCreate(task, info)).thenReturn(model); assist.taskEnd(task, EndCause.COMPLETED, null); verify(callback).taskEnd(eq(task), eq(EndCause.COMPLETED), nullable(Exception.class), any(Listener4Assist.Listener4Model.class)); } }
114649434_8
class CRC16 { public static int MCRF4XX(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0xFFFF, data, offset, length, true, true, 0x0000); } private CRC16(); public static int CCITT_Kermit(@NonNull final byte[] data, final int offset, final int length); public static int ...
final byte[] data = new byte[] { 'A' }; assertEquals(0x5C0A, CRC16.MCRF4XX(data, 0, 1)); } }
114670580_2
class RemoteAccessOpHandler { <K, V, U> void onTableAccessReqMsg(final long opId, final TableAccessReqMsg msg) { final String origEvalId = msg.getOrigId(); final OpType opType = msg.getOpType(); final boolean replyRequired = msg.getReplyRequired(); final String tableId = msg.getTableId(); final ...
final long origOpId = 0; doAnswer(invocation -> { final Object[] arguments = invocation.getArguments(); final String origId = (String) arguments[0]; final String destId = (String) arguments[1]; final long opId = (long) arguments[2]; assertEquals("The origin ID should be kept same...
114688767_69
class PathBidirRef extends Path { @Override public Path extract() { if (sptEntry == null || edgeTo == null) return this; if (sptEntry.adjNode != edgeTo.adjNode) throw new IllegalStateException("Locations of the 'to'- and 'from'-Edge has to be the same." + toString() + "...
Graph g = createGraph(); g.edge(1, 2, 10, false); g.edge(2, 3, 20, false); EdgeExplorer explorer = g.createEdgeExplorer(carOutEdges); EdgeIterator iter = explorer.setBaseNode(1); iter.next(); PathBidirRef pw = new PathBidirRef(g, new FastestWeighting(carEncoder));...
114698912_0
class TopicFilter implements Predicate<String> { @Override public boolean test(String topicName) { int tc = 0; int fc = 0; while(true) { // begin of path part if( filter.charAt(fc) == '+') { fc++; // eat + // matches one path part, skip all up to / or end in topic while( (tc < ...
TopicFilter tf = new TopicFilter("aaa/ccc/bbb"); assertTrue( tf.test("aaa/ccc/bbb") ); assertFalse( tf.test("aaa/c/bbb") ); assertFalse( tf.test("aaa/ccccc/bbb") ); assertFalse( tf.test("aaa/ccccc/ccc") ); } }
114886091_6
class SignupFormValidator implements Validator { @Override public void validate(Object target, Errors errors) { SignupForm form = (SignupForm) target; validateUniqueEmail(form, errors); validateUniquePhone(form, errors); validateValidPhone(form, errors); validatePassword...
validator.validate(form, errors); verifyZeroInteractions(errors); } }
114928169_21
class MsTeamsNotificationConfig { public boolean hasCustomContent() { return customContent; } @SuppressWarnings("unchecked") public MsTeamsNotificationConfig(Element e); public MsTeamsNotificationConfig(String token, Boolean enabled, BuildState states, boolea...
assertTrue(msteamsnotificationCustomContent.hasCustomContent()); } }
115041372_2
class Casa { public int getGastoTotal() { int gasto = 0; Iterator<ComponenteElectrico> iterador = estufas.iterator(); while (iterador.hasNext()){ ComponenteElectrico estufa = iterador.next(); gasto = gasto + estufa.getConsumo(); } iterador = cerco...
Casa casa = new Casa(); ComponenteElectrico estufaDelBanio = new ComponenteElectrico("estufa"); estufaDelBanio.ambientes = 1; estufaDelBanio.precioKw = 10; estufaDelBanio.calorias = 1000; casa.estufas.add(estufaDelBanio); ComponenteElectrico losaComedor = new ...
115077083_1378
class OrchestrationStatusValidator { public void validateOrchestrationStatus(BuildingBlockExecution execution) { try { execution.setVariable(ORCHESTRATION_STATUS_VALIDATION_RESULT, null); String buildingBlockFlowName = execution.getFlowToBeCalled(); BuildingBlockDetail b...
String flowToBeCalled = "UnassignServiceInstanceBB"; execution.setVariable("flowToBeCalled", flowToBeCalled); execution.setVariable("aLaCarte", true); BuildingBlockDetail buildingBlockDetail = getBuildingBlockDetail("UnassignServiceInstanceBB", ResourceType.SERVICE, Orc...
115260386_8
class CourseDAOMemory implements CourseDAO { @Override public void save(Course course) { delete(course.getId()); course.setId(nextId()); courseList.add(course); } public CourseDAOMemory(); @Override public Course find(int courseId); @Override public void delete(int co...
Course course = new Course("TEST", "TEST", 1, 1); daoMemory.save(course); List<Course> all = daoMemory.findAll(); assertTrue(all.contains(course)); } }
115411826_3
class NodeTable { public synchronized Node addNode(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); if (nodes.contains(e)) { nodes.forEach(nodeEntry -> { if (nodeEntry.equals(e)) { nodeEntry.touch(); } }); return null; } NodeEntry lastSeen = buckets[...
for (int i = 0; i < KademliaOptions.BUCKET_SIZE; i++) { TimeUnit.MILLISECONDS.sleep(10); addNode(new Node(ids.get(i), ips[i], 18888, 18888)); } Node lastSeen = nodeTable.addNode(new Node(ids.get(16), ips[16], 18888, 18888)); Assert.assertTrue(null != lastSeen); Assert.assertEquals(ips[15...
115451647_15
class NativeRiJargon2Backend implements Jargon2Backend { @Override public boolean verifyEncoded(String encodedHash, int threads, byte[] secret, byte[] ad, byte[] password, Map<String, Object> options) { if (encodedHash == null) { throw new Jargon2BackendException("Encoded hash cannot be nul...
backend.verifyEncoded("$argon2i$v=19$m=65536,t=2,p=xxx$xxx$xxx", -1, null, null, password, null); } }
115516500_316
class DnsNameResolver extends InetNameResolver { @Override public void close() { if (ch.isOpen()) { ch.close(); } } public DnsNameResolver( EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory, final DnsCache res...
final String overriddenIP = "12.34.12.34"; final TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() { @Override public Set<ResourceRecord> getRecords(QuestionRecord question) throws DnsException { ResourceRecordModifier rm = new ResourceRecordModifier(...
115558016_1
class FindBookListsByAuthorInteractor implements FindBookListByAuthor { @Override public List<BookOutputData> getBooks(BookListByAuthorInputData bookListByAuthorInputData) { Optional<List<Book>> books = bookGateway.findByAuthor(bookListByAuthorInputData.getAuthor()); if (!books.isPresent()) { throw ...
BookListByAuthorInputData bookListByAuthorInputData = BookListByAuthorInputData.builder() .author(ROBERT_C_MARTIN) .build(); Optional<List<Book>> books = Optional.of(Collections.singletonList(cleanArchitectureBook)); when(bookGateway.findByAuthor(any(String.class))).thenReturn(books); ...
115569790_68
class JSPackagerClient implements ReconnectingWebSocket.MessageCallback { @Override public void onMessage(String text) { try { JSONObject message = new JSONObject(text); int version = message.optInt("version"); String method = message.optString("method"); Object id = message.opt("id");...
RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage(ByteString.EMPTY); verify(handler, never()).onNotification(any()); verify(handler, never()).onRequest(any(), any(Re...
115604783_56
class SwicoBillInformation { public void setVatRate(BigDecimal vatRate) { this.vatRate = vatRate; } public String getInvoiceNumber(); public void setInvoiceNumber(String invoiceNumber); public LocalDate getInvoiceDate(); public void setInvoiceDate(LocalDate invoiceDate); public Str...
SwicoBillInformation billInformation = new SwicoBillInformation(); billInformation.setVatRate(BigDecimal.valueOf(7.7)); assertEquals(7.7, billInformation.getVatRate().doubleValue()); } }
115777140_0
class DataUtils { public static String eval(String statement, JsonObject data) { for (String key : data.getMap().keySet()) { DataItem dataItem = new DataItem(data.getJsonObject(key)); statement = eval(statement, dataItem); } return statement; } public stat...
DataItem dataItem = new DataItem() .setID("SHELVED_LIST") .setType(DataItem.Type.STRING) .setValue("100"); JsonObject data = new JsonObject().put(dataItem.getID(), dataItem.json()); String shelvedList = DataUtils.eval("${data.SHELVED_LIST}", data...
115838569_1
class KarmaPlugin implements PluginProvider { @Override public String process(MessageUpdate update, String locale) { StringBuilder response = new StringBuilder(); try { if (canProcess(update.getMessage().getText()) && !update.isEdited()) { List<String> itens = Arrays...
karmaPlugin.process(getSimpleMessage("test--"), "en_US"); Assertions.assertEquals(0, karmaRepository.get("test")); } }
115869675_6
class ProductController { @RequestMapping(method = RequestMethod.GET) public Iterable<Product> getProducts(@RequestParam("category") long categoryId) { return productService.findProductsByCategoryId(categoryId); } @RequestMapping(path = "/{productId}", method = RequestMethod.GET) public Produc...
long categoryId = 1; List<Product> products = TestDataFactory.getProductList(5, categoryId); when(productService.findProductsByCategoryId(categoryId)).thenReturn(products); assertThat(productController.getProducts(categoryId)).isEqualTo(products); } }
115956753_2
class CdcChange { public String toTelegraf(String json) { return json == null ? null : toTelegraf(json.getBytes()); } public String toTelegraf(byte[] json); private String getTimeInS(JsonNode payload); private String getId(JsonNode afterNode); private String toUpdate(JsonNode beforeNod...
assertThat(cdcChange.toTelegraf("" + "{\n" + " \"before\": null,\n" + " \"after\": {\n" + " \"id\": 57,\n" + " \"name\": \"Florida dragons\"\n" + " },\n" + " \"source\": {\n" + ...
116011653_544
class OrderOtherServiceImpl implements OrderOtherService { @Override public Response getOrderPrice(String orderId, HttpHeaders headers) { Order order = orderOtherRepository.findById(UUID.fromString(orderId)); if (order == null) { return new Response<>(0, orderNotFound, "-1.0"); ...
Order order = new Order(); Mockito.when(orderOtherRepository.findById(Mockito.any(UUID.class))).thenReturn(order); Response result = orderOtherServiceImpl.getOrderPrice(UUID.randomUUID().toString(), headers); Assert.assertEquals(new Response<>(1, "Success", order.getPrice()), result); ...
116057862_2
class FluxWithSingle extends Flux<F> implements CorePublisherWithSingle<F, S> { public final @NotNull CompletableFuture<S> subscribeSingleFuture() { final SingleFutureSubscriber<F, S> singleFutureSubscriber = new SingleFutureSubscriber<>(this); final CompletableFuture<S> future = singleFutureSubscr...
final CountDownLatch cancelLatch = new CountDownLatch(1); final CountDownLatch completeLatch = new CountDownLatch(1); final Flux<? extends CharSequence> flux = Flux.<CharSequence>create(emitter -> { emitter.next(new StringBuilder("single")); emitter.next("next0"); ...
116109319_16
class HypergeometricDistribution extends AbstractDiscreteDistribution { @Override public double probability(int x) { final double logProbability = logProbability(x); return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); } public HypergeometricDistribution(i...
final int n = 11; // population final int m = 4; // successes in population final int s = 0; // number of trials final HypergeometricDistribution dist = new HypergeometricDistribution(n, m, 0); for (int i = 1; i <= n; i++) { final double p = dist.probability(i); ...
116160086_20
class UserPrincipalImpl implements UserPrincipal { public Long getCustomLongAttribute(String attributeName) { long attribute = 0; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optLong(attributeName); } return...
assertEquals(new Long(1L), userPrincipalImpl.getCustomLongAttribute("long")); assertEquals(new Long(0L), userPrincipalImpl.getCustomLongAttribute("nonExistentCustomAttribute")); } }
116163042_0
class Name implements Supplier<String> { public static Name of(String name) { return new Name(name); } private Name(String value); @Override public String get(); @Override public boolean equals(Object o); @Override public int hashCode(); @Override public String toString(); } cl...
assertThrows(NullPointerException.class, () -> { Name.of(null); }); } }
116228237_17
class Certificate { private static boolean verify(String body, String signature, PublicKey publicKey) { try { Signature sign = Signature.getInstance("SHA1WithRSA"); sign.initVerify(publicKey); sign.update(body.getBytes("UTF-8")); return sign.verify(Base64.dec...
fail("Not yet implemented"); } }
116309308_53
class KoofrClient { public boolean fileExists(String path) throws IOException, InvalidTokenException { String url; try { url = getUriBuilder() .setPath(API_PATH_PREFIX + "/mounts/primary/files/info") .setParameter("path", path) .build() ...
server.enqueue(new MockResponse().setResponseCode(500).setBody("Internal error")); Exception caughtExc = null; try { client.fileExists("/path/to/file"); } catch (Exception exc) { caughtExc = exc; } Assert.assertNotNull(caughtExc); Assert.assertEquals( "Got error code: ...
116324279_0
class Util { public static int compare(@Nullable String s1, @Nullable String s2) { if (s1 == s2) { return 0; } else if ((s1 == null) && (s2 != null)) { return -1; } else if ((s1 != null) && (s2 == null)) { return 1; } return s1.compareTo(s...
assertTrue(Util.compare("foo", "bar") > 1); assertTrue(Util.compare("bar", "foo") < 1); assertEquals(0, Util.compare("foo", "foo")); assertEquals(-1, Util.compare(null, "foo")); assertEquals(1, Util.compare("foo", null)); assertEquals(0, Util.compare(null, null)); } ...
116500263_0
class ForecastUtil { public static Set<WeatherForecastPerDay> calculateWeatherForDays(WeatherForecastDbHelper.WeatherForecastRecord weatherForecastRecord) { Set<WeatherForecastPerDay> result = new HashSet<>(); Calendar forecastCalendar = Calendar.getInstance(); int initialYearForTheList = f...
//given createDetailedWeatherForecastForDayWithNegativeTemperatures(); //when Set<ForecastUtil.WeatherForecastPerDay> result = ForecastUtil.calculateWeatherForDays(weatherForecastRecord); //then assertEquals(1, result.size()); ForecastUtil.WeatherForecastPerDay ...
116522300_55
class V_000000 implements Migrateable { @Override public void executeMigration(Datastore datastore) { PriceList priceList = datastore.createQuery(PriceList.class).field("lotteryIdentifier").equal(German6aus49Lottery.IDENTIFIER).get(); if (priceList == null) { priceList = new PriceLi...
V_000000 cut = new V_000000(); cut.executeMigration(getDatastore()); PriceList priceList = getDatastore().createQuery(PriceList.class).field("lotteryIdentifier").equal(German6aus49Lottery.IDENTIFIER).get(); assertThat(priceList, notNullValue()); assertThat(priceList.getValidFrom(...
116565956_0
class SubjectMapperDecorator implements SubjectMapper { @Override public List<SubjectDto> questionsToSubjectsDto(List<Question> questions) { Assert.notNull(questions, "Cannot map a null list of questions to a list of subject dtos"); Multimap<Subject, Question> multimap = Multimaps.index(questions, Questio...
Question q1 = new Question().id(1L).label("question1").subject(new Subject().id(1L)); Question q2 = new Question().id(2L).label("question2").subject(new Subject().id(1L)); Question q3 = new Question().id(3L).label("question3").subject(new Subject().id(2L)); List<SubjectDto> subjects = subjectMapper.que...
116678593_1
class CombinedVariablesSource extends VariablesSource { public static CombinedVariablesSource forSources(List<String> sourceNames, InstallHookLogger logger, InstallContext context) { List<VariablesSource> sources = new ArrayList<VariablesSource>(); for (String string : sourceNames) { if...
VariablesSource varSource1 = new VariablesSource("testsource1", new HashMap<String, String>() { { put("var1", "val1"); put("var2", "val2"); } }) { }; VariablesSource varSource...
116714930_15
class ProcessingPartition implements Closeable { protected long getLastCommittedOffset() { OffsetAndMetadata lastCommittedOffset; try { lastCommittedOffset = consumer.committed(topicPartition); } catch (KafkaException e) { throw new IllegalStateException("Unable to r...
when(consumer.committed(topicPartition)).thenReturn(null); partition.earliestBrokerOffset = 123L; doThrow(new KafkaException("unable to commit")).when(consumer).commitSync(anyMap()); partition.getLastCommittedOffset(); verify(consumer).commitSync(Collections.singletonMap(topicPa...
116999027_941
class CreatedQueryLogicCacheBean { public boolean add(String queryId, String userId, QueryLogic<?> logic, Connector cxn) { Triple value = new Triple(userId, logic, cxn); long updateTime = System.currentTimeMillis(); return cache.putIfAbsent(new Pair<>(queryId, updateTime), value) == null; ...
String queryId = "12345"; String userId = "me"; long timestamp = 1l; EasyMock.expect(System.currentTimeMillis()).andReturn(timestamp); PowerMock.replayAll(); boolean ret = qlCache.add(queryId, userId, queryLogic, conn); PowerMoc...
117019016_55
class ProcessHTTPRecordingWithXSLT implements HTTPRecordingResultProcessor { public void process(HttpRecordingDocument result) throws IOException { try { final Transformer transformer = m_transformerFactory .newTransformer(new StreamSource(m_styleSheetInp...
final File badStyleSheetFile = new File(getDirectory(), "bad.xsl"); badStyleSheetFile.createNewFile(); final ProcessHTTPRecordingWithXSLT processor = new ProcessHTTPRecordingWithXSLT( new StyleSheetFile(badStyleSheetFile), m_out, m_logger); final HttpRecordingDocument emp...
117054584_7
class ZookeeperConfiguration implements GovernanceConfiguration { @Override public String getPath(String key) { return getNodePath(key, null); } @Override public void setUrl(URL url); @Override public URL getUrl(); @Override public void init(); @Override public String setConfig(Str...
assertEquals(Constants.PATH_SEPARATOR + Constants.DEFAULT_ROOT + Constants.PATH_SEPARATOR + "test_key", configuration.getPath("test_key")); try { configuration.getPath(null); fail("should throw IllegalArgumentException for null path"); } catch (IllegalArgu...
117060928_69
class JSPackagerClient implements ReconnectingWebSocket.MessageCallback { @Override public void onMessage(String text) { try { JSONObject message = new JSONObject(text); int version = message.optInt("version"); String method = message.optString("method"); Object id = message.opt("id");...
RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage("{\"version\": 2, \"method\": \"methodValue\"}"); verify(handler).onNotification(eq(null)); verify(handler, never()...
117076526_0
class UsersService { public void add(@Valid User newUser) { em.persist(newUser); } public User isValid(String username, String password); public Set<User> getAll(); public boolean update(User updated); public void remove(Long id); public Optional<User> get(Long id); public List...
URL apiUrl = new URL(resource, "resources/users"); JsonObject user = Json.createObjectBuilder() .add("name", "Marcus") .add("email", "marcus_1982@jee8ng.org") .add("credential", credential("marcus", "1234")) .build(); Response init...
117088815_195
class AbstractNotificationServiceImpl implements AbstractNotificationService<T> { @Transactional @Nonnull @Override public T updateNotificationState(@Nonnull final Long notificationId, @Nonnull final NotificationState notificationState) { assertNotificationIdNotNull(notificationId); Ass...
// Test data final Long notificationId = 1L; final NotificationState state = NotificationState.PROCESSING; // Reset resetAll(); // Replay replayAll(); // Run test scenario try { getService().updateNotificationState(null, state); ...
117128136_21
class JavaSystem extends SimpleSystemImpl { @Override public SimpleNode moveTo(String nodeQuery, String... keys) { SimpleNode javaSourceNode=new JavaSourceNode(this,nodeQuery,keys); optionalStartNode(javaSourceNode); return javaSourceNode; } @Override public SimpleSystem connect(String... connecti...
JavaSystem js = new JavaSystem(); JavaSourceNode jsn = (JavaSourceNode) js.moveTo( "../simplegraph-java/src/test/java/com/bitplan/simplegraph/java/TestJavaSystem.java"); debug = true; if (debug) { js.forAll(SimpleNode.printDebug); CompilationUnit cu = jsn.compilationUnit; cu.wa...
117143344_15
class Lang { public static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return true; } public static String RPAD(String str, int len); public static String RPAD(String str, char c, int len); public static String LPAD...
assertEquals(true, Lang.isInteger("1")); assertEquals(false, Lang.isInteger("1.0")); assertEquals(false, Lang.isInteger("1f")); assertEquals(false, Lang.isInteger(null)); assertEquals(true, Lang.isInteger(String.valueOf(Integer.MAX_VALUE))); assertEquals(true, Lang.isInteger(String.valueOf(Integ...
117200555_0
class HoldingsController { @GetMapping public List<Holding> getHoldings(Principal principal) { User user = client.getUser(principal.getName()); String holdingsFromOkta = (String) user.getProfile().get(HOLDINGS_ATTRIBUTE_NAME); List<Holding> holdings = new LinkedList<>(); if (h...
String username = "joe.coder@example.com"; // define mocks Client client = mock(Client.class); User user = mock(User.class); UserProfile userProfile = mock(UserProfile.class); Principal principal = mock(Principal.class); // stub behaviour when(principal...
117255089_189
class WXUtils { public static float getFloat(Object value) { return getFloat(value, Float.NaN); } public static boolean isUiThread(); public static boolean isUndefined(float value); public static Float getFloat(Object value, @Nullable Float df); private static float transferWx(String stringWithWXPostf...
Float test_float = WXUtils.getFloat("100wx"); Float want = 100 * TEST_DENSITY * TEST_VIEW_PORT / TEST_SCREEN_WIDTH; assertEquals(test_float, want , 0.01); test_float = WXUtils.getFloat("100px"); want = 100F; assertEquals(test_float, want); test_float = WXUtils.g...
117256380_1
class MathUtils { public static List<Integer> positive(List<Integer> vals) { return vals.stream().filter(val -> val > 0).collect(Collectors.toList()); } public static Integer sum(List<Integer> vals); public static List<Integer> negative(List<Integer> vals); private static List<Integer> ...
var positiveValues = MathUtils.positive(vals); assertEquals(positiveValues, List.of(2, 1, 3)); } }
117353090_4
class Position { static Position calculateCentre(Disk m, Disk n, double angle) { angle = correctAngle(angle); if (angle == 0 || angle == 360) { return new Position(m.getPosition().x, m.getPosition().y + n.getRadius() + m.getRadius(), n.getPosition().z); } else if (0 < angle && a...
Position position = Position.calculateCentre(disk1, disk2, 90); assert position != null; double x = position.x; double y = position.y; double z = position.z; assertEquals(10.5, x); assertEquals(5, y); assertEquals(0, z); } }
117357780_257
class SoapDocumentService extends AbstractService implements DocumentService { @Override public long upload(String sid, Long docId, Long folderId, boolean release, String filename, String language, DataHandler content) throws Exception { validateSession(sid); if (docId != null) { checkout(sid, docId); ...
File file = new File("pom.xml"); long docId = docService.upload("xxxx", null, 4L, true, "document test.txt", "en", new DataHandler(new FileDataSource(file))); Assert.assertTrue(docId > 0L); long docId2 = docService.upload("xxxx", docId, null, true, "document test.txt", "en", new DataHandler(new FileDa...