id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
172743796_31
class LoggingSupplier implements RbacMappingSupplier { @Override public Map<String, Set<String>> get() { return supplier.get(); } public LoggingSupplier(final Supplier<Map<String, Set<String>>> supplier); private void logMapping(); } class LoggingSupplierTest { @Test public void testDefaultBehaviourNull...
final RbacMappingSupplier supplier = () -> null; final Map<String, Set<String>> result = new LoggingSupplier(supplier).get(); assertThat(result, is(nullValue())); } }
172750723_127
class LongValueRecorderSdk extends AbstractSynchronousInstrument<BoundInstrument> implements LongValueRecorder { @Override public void record(long value, Labels labels) { BoundInstrument boundInstrument = bind(labels); boundInstrument.record(value); boundInstrument.unbind(); } private LongValueRe...
long startTime = testClock.now(); LongValueRecorderSdk longMeasure = testSdk.longValueRecorderBuilder("testRecorder").build(); BoundLongValueRecorder boundMeasure = longMeasure.bind(Labels.of("K", "V")); try { // Do some records using bounds and direct calls and bindings. longMeasure.record(...
172981843_7
class SqsStreamProvisioner implements ProvisioningProvider<ExtendedConsumerProperties<SqsConsumerProperties>, ExtendedProducerProperties<SqsProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String name, ...
ExtendedProducerProperties<SqsProducerProperties> producerProperties = new ExtendedProducerProperties<>(new SqsProducerProperties()); sqsStreamProvisioner.provisionProducerDestination("topic-name", producerProperties); List<String> topicArns = listTopicsArns(); assertThat(topicArns).ha...
173167316_16
class TransactionProcessor { public void setAvailableKeys(@NotNull List<String> availableKeys) { this.availableKeys = availableKeys; } public TransactionProcessor( @NotNull ISerializationProvider serializationProvider, @NotNull IRPCProvider rpcProvider, @NotNul...
this.mockDefaultSuccessData(); TransactionProcessor processor = createAndPrepareTransaction(this.defaultActions()); assertNotNull(processor); List<String> availableKey = new ArrayList<>(); availableKey.add("Key3"); availableKey.add("Key4"); processor.setAvailable...
173228436_63
class IntPropertySet extends PropertySet { public void putInt(long index, int value) { PropertyPage page = getOrCreatePage(getPageID(index)); int n = page.getSize(); page.addInt(getPageOffset(index), value); numProperties += page.getSize() - n; } public IntPropertySet(String name); @Override public int ...
for (int i = 0; i < 10000; i++) { ps.putInt(i, i); } LongIterator it = ps.getPropertyIterator(); int i = 0; while (it.hasNext()) { long l = it.next(); assertEquals(i, l); i++; } assertEquals(i, 10000); } }
173230987_13
class DownstreamPathCalculator { public String calculateDownstreamPath(final String receivedRequestUri) { // This function is required to join httpDownStreamPathPrefix with receivedRequestURI // remove any duplicate "/" // Not have an ending "/" if the path // assumes httpdownstreamPathPrefix does no...
final DownstreamPathCalculator calc = new DownstreamPathCalculator("/"); final String result = calc.calculateDownstreamPath("/"); assertThat(result).isEqualTo("/"); } }
173306807_22
class ParameterizableStringListFactory extends AbstractFeatureFactory<T> { @Override public Pair<T, T> crossover(T parentA, T parentB) { Set<String> union = new HashSet<>(); for (ParameterizableString p : parentA.getParameterizableStrings()) { union.add(p.getFactoryId()); }...
String paramString = "recip(rord(creationDate),[1,2,3],[10,100,1000],[$2])"; TestParam t1 = new TestParam("bf", "0", "recip(rord(creationDate),2,100,100)"); TestParam t2 = new TestParam("bf", "0", "recip(rord(creationDate),1,1000,1000)"); ParameterizableS...
173335706_175
class DataSourceController extends BaseController { @ApiOperation(value = "delete", notes = "DELETE_DATA_SOURCE_NOTES") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "DATA_SOURCE_ID", required = true, dataType = "Int", example = "100") }) @GetMapping(value = "/delete") @Re...
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("id","16"); MvcResult mvcResult = mockMvc.perform(get("/datasources/delete") .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) ...
173409096_54
class ResolverUtil { public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; } public Set<Class<? extends T>> getClasses(); public ClassLoader getClassLoader(); public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames); public Res...
ResolverUtil resolverUtil = new ResolverUtil(); AccessController.doPrivileged((PrivilegedAction<Void>) () -> { resolverUtil.setClassLoader(new ClassLoader() { }); return null; }); assertNotEquals(resolverUtil.getClassLoader(), currentContextClassLoader...
173534034_11
class CodeRequest { public static CodeRequest newCodeRequest(HarRequest harRequest) throws Exception { return new CodeRequest(harRequest); } private CodeRequest(HarRequest harRequest); private void validateMimeType(); public Map<String, List<String>> queryStringsToMap(); public Optional<HarHeader> f...
HarRequest harRequest = new HarRequest() .withUrl(HTTP_URL) .withPostData(new HarPostData().withMimeType(MediaType.APPLICATION_JSON)) ; Exception thrown = assertThrows( Exception.class, () -> newCodeRequest(harRequest), "Expected exception thrown")...
173572330_47
class CustomViewTarget implements Target<Z> { @Override public final void getSize(@NonNull SizeReadyCallback cb) { sizeDeterminer.getSize(cb); } public CustomViewTarget(@NonNull T view); protected abstract void onResourceCleared(@Nullable Drawable placeholder); protected void onResou...
activity.visible(); view.setLayoutParams(new FrameLayout.LayoutParams(100, 100)); view.setPadding(25, 25, 25, 25); view.requestLayout(); target.getSize(cb); verify(cb).onSizeReady(50, 50); } }
173721564_1
class ProtobufMsgFactory { @SuppressWarnings("unchecked") public static <T extends Message> T newMessageByProtoClassName(final String className, final byte[] bs) { final MethodHandle handle = PARSE_METHODS_4PROTO.get(className); if (handle == null) { throw new MessageClassNotFoundEx...
SnapshotMeta meta = SnapshotMeta.newBuilder().setLastIncludedIndex(99).setLastIncludedTerm(1).build(); SnapshotMeta pMeta = ProtobufMsgFactory.newMessageByProtoClassName("jraft.SnapshotMeta", meta.toByteArray()); assertNotNull(pMeta); assertNotSame(pMeta, meta); assertEquals(pMet...
173756598_3
class BillingService { public synchronized Transaction makeTransaction(String fromAddress, String toAddress, long value) throws ServerException { Wallet from = walletRepository.findByAddress(fromAddress); Wallet to = walletRepository.findByAddress(toAddress); if (from == null || to == null) throw new Ser...
String firstAddress= "firstAddress"; String secondAddresss= "secondAddress"; Wallet secondWallet = new Wallet(); secondWallet.setBalance(0); Long value = 30000L; String address = "some address"; when(walletRepository.findByAddress(firstAddress)).thenReturn(null); when(walletRepos...
173833378_0
class HelloController { @Get("/{name}") public String index(final String name) { return "Hello, " + name + ". From " + embeddedServer.getHost() + ":" + embeddedServer.getPort() + "\n"; } @Get("/enemies") public String enemies(); @Get("/config/{key}") public String config(String key); ...
try(RxHttpClient client = embeddedServer.getApplicationContext().createBean(RxHttpClient.class, embeddedServer.getURL())) { assertTrue(client.toBlocking().exchange("/hello/Alvaro", String.class).body().startsWith("Hello, Alvaro")); } } }
173952800_1
class ExpressionEvaluator { public ComputedValues evaluateForAll(VariableEnvironment environment, Expression expression) throws Exception { return evaluate(environment, VariableEnvironment.NO_VALUE_SET_SELECTED, expression, false); } public ExpressionEvaluator(IExpressionEvaluatorErrorCallback ev...
// This test ensures the correct propagation of increment/decrement operator side effets through // conditional and short-circuiting operators in a value-recoding VariableEnvironment // Environment: Create two integer variables x, y with values 5, 10 VariableEnvironment environment = ne...
174011880_1
class FileParsingElementLoader implements ConfigLoader, ConfigConstants { public List<ParsingElement> load(boolean reload) { if (isLoaded() && !reload) { return getParsingElements(); } Map<String, Object> map = configLoader.readConfiguration(); fillParameters(map); ...
FileParsingElementLoader parsingElementLoader = TestUtils.prepareParsingElementFile(pathPlace, "parsingElementTest.yaml"); List<ParsingElement> load = parsingElementLoader.load(true); TestUtils.initXmlParsingAbsolutePath(load); ParsingElement root = load.get(0); assertEquals(3, ...
174065041_172
class MetadataEntityManager implements SecuredEntityManager { @Transactional(propagation = Propagation.REQUIRED) public void deleteMetadataEntitiesInProject(Long projectId, String entityClassName) { Objects.requireNonNull(projectId); if (StringUtils.hasText(entityClassName)) { Metad...
entityManager.deleteMetadataEntitiesInProject(folder.getId(), null); assertTrue(loadEntities(SAMPLE_CLASS, folder.getId()).isEmpty()); assertTrue(loadEntities(PAIR_CLASS, folder.getId()).isEmpty()); } }
174097909_25
class Vm { public double getTotalUtilizationOfCpu(double time) { return getCloudletScheduler().getTotalUtilizationOfCpu(time); } public Vm( int id, int userId, double mips, int numberOfPes, int ram, long bw, long size, String vmm, CloudletScheduler cloudletScheduler); public double ...
assertEquals(0, vm.getTotalUtilizationOfCpu(0), 0); } }
174098511_6
class RabbitMQPasswordConverter { public boolean passwordMatchesHash(final String password, final String hash) { final byte[] decodedHash = base64Decoder.decode(hash); final int salt = ByteBuffer.wrap(decodedHash).getInt(); return convertPasswordToHash(password, salt).equals(hash); } ...
assertTrue(converter.passwordMatchesHash(PASSWORD, HASH_FROM_RABBIT)); } }
174185245_79
class ComplexNumber { public ComplexNumber[] root(int n) { if (n <= 0) { throw new IllegalArgumentException("Cannot calculate negative roots."); } double magnitude = Math.pow(getMagnitude(), 1.0 / n); double angle = getAngle() / n; double angleStep = 2 * Math.PI / n; ComplexNumber[] roots = new Compl...
assertThrows(IllegalArgumentException.class, () -> ComplexNumber.MINUS_ONE.root(-1)); } }
174314296_1
class CountriesResource { public JsonNode jsonName(JsonNode nameNode) { Country country = countriesService.getByName(nameNode.get("name").asText()).iterator().next(); ObjectMapper mapper = new ObjectMapper(); JsonNode retNode = mapper.convertValue(country, JsonNode.class); return r...
String jsonString = "{\"name\": \"greece\"}"; ObjectMapper mapper = new ObjectMapper(); JsonNode inputNode = mapper.readTree(jsonString); JsonNode retNode = resource.jsonName(inputNode); assertNotNull(retNode); assertEquals("Greece", retNode.get("name").textValue()); ...
174354196_1
class ProdutoController { @PutMapping(value = "/{id}", produces = "application/json") public Produto update(@PathVariable("id") long id, @RequestBody Produto produto) { return storage.update(id, produto); } @PostMapping @ResponseStatus(code=HttpStatus.CREATED) public String save(@RequestBody P...
Long produtoId = 1L; Produto produto = new Produto(); produto.setId(produtoId); produto.setNome("Produto"); Mockito.when(storage.update(Mockito.anyLong(), Mockito.any(Produto.class))).thenReturn(produto); ObjectMapper objectMapper = new ObjectMapper(); String produtoJson = objectMapper.writeValue...
174398263_151
class HttpClientImpl implements OktaHttpClient { @Override public void cleanUp() { mUrlConnection = null; } private void enableTlsV1_2(HttpURLConnection urlConnection); @VisibleForTesting protected HttpURLConnection openConnection(URL url, ConnectionParameters params); @Override public...
mHttpClient.cleanUp(); assertNull(mHttpClient.getUrlConnection()); } }
174912621_0
class InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } // TODO: 2019/3/26 请解决数据量大的问题,加一个时间...
// prepare basic test data testSave(); System.out.println( "[" + System.currentTimeMillis() + "] Basic test data ready in testListResourcesOfApp"); List<CompletableFuture> futures = Lists.newArrayList(); // concurrent query resources of app final CyclicBarrier cyclicBar...
174912738_6
class DefaultChangerCollector implements ChangerCollector { @Override public List<Item> collect(Object source) { if (source == null){ return Collections.emptyList(); } List<Item> result = Lists.newArrayList(); ReflectionUtils.doWithFields(source.getClass(), field -> ...
List<ChangerCollector.Item> items = this.changerCollector.collect(this.data); Assert.assertEquals(5, items.size()); } }
175050767_27
class UriUtils { public static String extractEtherAddressFromUri(String uri) throws InvalidEthereumAddressException { String uriWithoutSchema = uri.replaceFirst("ethereum:", ""); uriWithoutSchema = Numeric.cleanHexPrefix(uriWithoutSchema); if (uriWithoutSchema.length() != 40) { ...
final String result = UriUtils.extractEtherAddressFromUri("0x6E670C473A2AD5894AE354B832AD4BADF1D919BF"); assertEquals("0x6E670C473A2AD5894AE354B832AD4BADF1D919BF", result); } }
175055878_2
class BoardGameGeekRatingService implements GameRatingService { @Override public Optional<BigDecimal> getAverageRating(final UUID gameId) { return this.resolveBoardGameGeekId(gameId) .map(bggId -> this.bggClient.getItemsWithRating(bggId)) .map(Items::getItems) .map(List::stream) .flatMap(Stream::findFi...
//Given BoardGameGeekRatingService boardGameGeekRatingService = new BoardGameGeekRatingService(bggClient, queryRepository); when(queryRepository.findBoardGameById(GAME_ID)).thenReturn(Optional.of(createBoardGame(null))); //When Optional<BigDecimal> rating = boardGameGeekRatingService.getAverageRating(GAME_ID...
175193018_1
class JavaUtils { public static boolean isAsciiAlpha(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); } public static String getClassName(String scriptContent); public static boolean isDigital(char ch); } class JavaUtilsTest { @Test public void testIsAsciiAlph...
Assert.assertTrue(JavaUtils.isAsciiAlpha('B')); Assert.assertTrue(JavaUtils.isAsciiAlpha('b')); Assert.assertFalse(JavaUtils.isAsciiAlpha('%')); } }
175482179_3
class DayView extends ViewGroup { protected void setRect(@NonNull DirectionalRect rect, int start, int top, int end, int bottom) { rect.set(isRtl, parentWidth, start, top, end, bottom); } public DayView(@NonNull Context context); public DayView(@NonNull Context context, @Nullable AttributeSe...
DirectionalRect rect = new DirectionalRect(); rect.set(false, 20, 1, 2, 3, 4); assertThat(rect.getLeft(), is(1)); assertThat(rect.getTop(), is(2)); assertThat(rect.getRight(), is(3)); assertThat(rect.getBottom(), is(4)); rect.set(true, 20, 1, 2, 3, 4); ...
175804011_5
class StreamUtils { public static <T,U,R> Stream<R> merge(Stream<T> seq1, Stream<U> seq2, BiPredicate<T,U> pred, BiFunction<T,U,R> transf, U defaultVal) { // TODO return null; } private final List<String> seq1; private final List<Integer> seq2Asc; private final List<Integer> seq2As...
final List<String> merged = merge(seq2DescDupl); assertEquals(expected, merged); } }
175889566_2
class SetParameterValuesCommand extends AbstractCommand { public Map<String, Object> getValues() { return values; } public SetParameterValuesCommand(); public void setValues(Map<String, Object> values); @Override public int hashCode(); @Override public boolean equals(Object obj); @Override public String to...
SetParameterValuesCommand command1 = ser.fromJson(new InputStreamReader(this.getClass().getResourceAsStream("command-setparametervalues-1.json")), SetParameterValuesCommand.class); assertEquals(CommandType.SetParameterValues, command1.getCommand()); assertNotNull(command1.getValues()); assertEquals(2, comman...
175961394_11
class ExampleParametersResolver { public Optional<Object[]> resolve(final Method testMethod, final Example.Builder example) { // TODO fchovich MOVE LOGIC FROM THE RESOLVER. CREATE CONVERTIBLES BEFORE. return this.parameterConverterResolver .resolveConverters(testMethod, example) .flatMap(c ->...
final Optional<Object[]> conversions; final Example.Builder example; final Method testMethod; given: // TODO fchovich feature class and scenario name are unnecessary here example = new Example.Builder(ExampleParametersResolverTest.class.getName(), "", Collections.emptyList()); testMethod = ...
176135637_75
class SlayerPlugin extends Plugin { @Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() != ChatMessageType.SERVER && event.getType() != ChatMessageType.FILTERED) { return; } String chatMsg = Text.removeTags(event.getMessage()); //remove color and linebreaks if (chatMsg.start...
ChatMessage chatMessageEvent = new ChatMessage(SERVER, "Perterter", TASK_LARGE_STREAK, null); slayerPlugin.onChatMessage(chatMessageEvent); assertEquals(2465, slayerPlugin.getStreak()); assertEquals("", slayerPlugin.getTaskName()); assertEquals(0, slayerPlugin.getAmount()); assertEquals(17_566_000, slayerP...
176206805_10
class CarbonSecurityManager extends SecurityManager { public void checkAccess(ThreadGroup g) { if (g == null) { throw new NullPointerException("thread group can't be null"); } checkPermission(SecurityConstants.MODIFY_THREADGROUP_PERMISSION); } public CarbonSecurityMa...
System.setProperty("denied.system.properties", "mockDeniedProperty"); carbonSecurityManager = new CarbonSecurityManager(); Thread thread = null; assertNull(thread); carbonSecurityManager.checkAccess(thread); } }
176291010_75
class BaseViewManager extends ViewManager<T, C> { @ReactProp(name = PROP_ACCESSIBILITY_ROLE) public void setAccessibilityRole(@Nonnull T view, @Nullable String accessibilityRole) { if (accessibilityRole == null) { return; } view.setTag(R.id.accessibility_role, AccessibilityRole.fromValue(accessi...
mViewManager.setAccessibilityRole(mView, "none"); assertThat(mView.getTag(R.id.accessibility_role)).isEqualTo(AccessibilityRole.NONE); } }
176770877_0
class OpenApiParser { public void parse() throws Exception { // TODO: Verify compatible OpenAPI version. logger.info("Parsing definitions."); this.generateAlgodIndexerObjects(root); // Generate classes from the return types which have more than one return element logger.in...
// Given - mock subscriber listening to all events while parsing "petstore.json" Subscriber subscriber = mock(Subscriber.class); InputStream istream = getInputStreamForResource("petstore.json"); Publisher publisher = new Publisher(); publisher.subscribeAll(subscriber); /...
177104472_11
class DefaultRegistryClient implements RegistryClient { @Override public Publisher register(PublisherRegistration registration, String... data) { if (!init.get()) { throw new IllegalStateException("Client needs to be initialized before using."); } if (null == registration) ...
PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); Publisher publisher = registryClient.register(publisherRegistration); PublisherRegister register = ((DefaultPublisher) publisher).assembly(); assertEquals(appName, register.getAppName()); } }
177177812_0
class DateOperation { public static String getStringDate(Date date) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); int month = getMonth(date); StringBuilder stringBuilder = new StringBuilder(); calendar.setTime(date); stringBuilder.append(calendar.get(Cal...
String s = DateOperation.getCurrentDateAsString(); // String s = DateOperation.getStringDate(new Date()); assertEquals("10-8-2019", s); } }
177503596_3
class JpaUserDao extends JpaAbstractSearchTextDao<UserEntity, User> implements UserDao { @Override public List<User> findTenantAdmins(UUID tenantId, TextPageLink pageLink) { return DaoUtil.convertDataList( userRepository .findUsersByAuthority( ...
UUID tenantId = UUIDs.timeBased(); UUID customerId = UUIDs.timeBased(); create30Adminsand60Users(tenantId, customerId); List<User> tenantAdmins1 = userDao.findTenantAdmins(tenantId, new TextPageLink(20)); assertEquals(20, tenantAdmins1.size()); List<User> tenantAdmins2 = ...
177547877_1
class StatusResponseHelper extends ResponseHelper { public boolean isStatusResponse(String json) throws CouldNotReadJsonException { if (StringUtils.isBlank(json)) { return false; } String id = getRawId(json); return StringUtils.startsWithIgnoreCase(id, TmRpcMethod.STATUS...
String dumpConsensus = DUMP_CONSENSUS_STATE; Assert.assertFalse(classUnderTest.isStatusResponse(dumpConsensus)); String statusResponse = STATUS; Assert.assertThat("StatusResponseHelper didn't recognize our status response.", classUnderTest.isStatusResponse(statusResponse), is(true)); ...
177672258_0
class Util { public static <T, E> T getKeyByValue(Map<T, E> map, E value) { for (Map.Entry<T, E> entry : map.entrySet()) { if (Objects.equals(value, entry.getValue())) { return entry.getKey(); } } return null; } } class UtilTest { @Test ...
// Given Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); // When String key = Util.getKeyByValue(map, "value1"); // Then assertEquals("key1", key); } }
177745239_136
class Quant1PropertiesGroupingAsgStrategy implements AsgStrategy { @Override public void apply(AsgQuery query, AsgStrategyContext context) { // phase 1 - group all Eprops to EPropGroups AsgQueryUtil.elements(query, Quant1.class).forEach(quant -> { List<AsgEBase<EProp>> ePropsAsg...
AsgQuery query = start("q1", "ont").next(typed(1, "1")).next(quant1(2, all)) .next(quant1(3, all)).in( eProp(4, "p1", of(eq, "abc" )), eProp(5, "p2", of(eq, 1 )), eProp(6, "p3", of(gt, 6))) .build(); ...
177751597_24
class TransactionRetStore extends TronStoreWithRevoking<TransactionRetCapsule> { @Override public void put(byte[] key, TransactionRetCapsule item) { if (BooleanUtils.toBoolean(Args.getInstance().getStorage().getTransactionHistoreSwitch())) { super.put(key, item); } } @Autowired public Transacti...
TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); transactionInfoCapsule.setId(transactionId); transactionInfoCapsule.setFee(1000L); transactionInfoCapsule.setBlockNumber(100L); transactionInfoCapsule.setBlockTimeStamp(200L); TransactionRetCapsule transactionRetCapsu...
178002723_4
class ProtoDescriptorSerializer { public List<FileContent> descriptorToString(FileDescriptorSet descriptorSet) { List<FileContent> result = new LinkedList<>(); for (FileDescriptorProto protoFileDesc : descriptorSet.getFileList()) { StringBuilder buffer = new StringBuilder(); buffer.append("syntax = \"...
String file = IOUtils.toString(getClass().getResourceAsStream("/HelloService.proto")); FileDescriptorSet descriptorSet = toDescriptor(file); var sut = new ProtoDescriptorSerializer(); var generatedFiles = sut.descriptorToString(descriptorSet); var generatedContent = generatedFiles.get(0).getContents(); ...
178064729_22
class RegexPredicate implements Predicate<String> { @Override public boolean test(String httpText) { return this.patterns.stream() .anyMatch(p -> p.matcher(httpText).matches()); } public RegexPredicate(List<Pattern> patterns); public static Predicate<String> createDefaultUrlAllowlist(); public static Pr...
RegexPredicate test = new RegexPredicate(Arrays.asList(Pattern.compile("^$"))); assertThat(test.test("foo")).isFalse(); } }
178169608_2
class ObjectMapperHelper { public static Optional<SnykTestStatus> unmarshall(Path path) throws IOException { if (path == null) { return Optional.empty(); } try (JsonParser parser = JSON_FACTORY.createParser(path.toFile())) { JsonToken token = parser.nextToken(); if (token == JsonToken....
Path snykReportJsonForMultiProject = Paths.get(TEST_FIXTURES_DIRECTORY.getAbsolutePath(), "multi-module-project", "snyk_report_with_vulns.json"); Optional<SnykTestStatus> snykTestStatus = ObjectMapperHelper.unmarshall(snykReportJsonForMultiProject); assertTrue(snykTestStatus.isPresent()); assertAll("m...
178173999_39
class NeuralNetwork implements Serializable { public synchronized void addListener(NeuralNetworkEventListener listener) { if (listener == null) throw new IllegalArgumentException("listener is null!"); listeners.add(listener); } public NeuralNetwork(); public void addLaye...
NeuralNetworkEventListener l = Mockito.mock(NeuralNetworkEventListener.class); instance.addListener(l); NeuralNetworkEvent event = Mockito.mock(NeuralNetworkEvent.class); instance.fireNetworkEvent(event); Mockito.verify(l).handleNeuralNetworkEvent(event); NeuralNetworkEv...
178313880_0
class TableEnv { public DataTable sqlQuery(String sql) { try { executeBeforeSqlQuery(sql); if (sql2ExecutionPlanCache != null) { TableExecutionPlan executionPlan = sql2ExecutionPlanCache .getIfPresent( cacheKeyPrefix + sql); if (executionPlan != null) { ...
DataTable table1 = tableEnv.sqlQuery("select * from test.t1"); Assert.assertNotNull(table1); DataTable table2 = tableEnv.sqlQuery("select * from t2"); Assert.assertNotNull(table2); Assert.assertEquals("hello,marble", tableEnv.sqlQuery("select hello('marble') as c1") .toMapList() ...
178461625_308
class DefaultCompletableAsyncCompletion implements CompletableAsyncCompletion { @Override public void join() throws CompletionException, InterruptedException { try { join(10, TimeUnit.SECONDS); } catch (TimeoutException ex) { throw new RuntimeException("Default timeout triggered for blocking ca...
AtomicReference<Boolean> executed = new AtomicReference<>(); AsyncCompletion completion = AsyncCompletion.executeBlocking(() -> executed.set(true)); completion.join(); assertTrue(executed.get()); } }
178518612_3
class FreeMarkerUtils { public static String generate(String ftl, Object dataModel){ try { Template template = getTemplate(ftl); return buildResult(template, dataModel); } catch (IOException e) { logger.error("Error: {}\n{}", e.getMessage(), e.getStackTrace()); ...
String ftl = "${str?substring(str?last_index_of('.') + 1)}"; Map<String, String> model = new HashMap<>(); model.put("str", "java.utils.List"); String result = FreeMarkerUtils.generate(ftl, model); Assert.assertEquals("List", result); } }
178760528_3
class NamingChangelogAndRepartitionTopics { public Topology buildTopology(Properties envProps) { final StreamsBuilder builder = new StreamsBuilder(); final String inputTopic = envProps.getProperty("input.topic.name"); final String outputTopic = envProps.getProperty("output.topic.name"); final String ...
envProps.put("add.names", "true"); Topology topology = namingChangelogAndRepartitionTopics.buildTopology(envProps); final String firstTopologyNoFilter = topology.describe().toString(); final String initialStateStoreName = "the-counting-store"; final String initialAggregationRep...
178830383_11
class AuditRequestBodyAdvice extends RequestBodyAdviceAdapter { @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, ...
advice.afterBodyRead(new Consents(), null, null, null, null); assertThat(MDC.get("consentModel")).contains("unknown"); } }
178922614_6
class CsvParser { public static List<TestData> parse(Path testFile) throws IOException { Reader reader = Files.newBufferedReader(testFile); try { return parse(testFile.getFileName().toString(), reader); } catch (RuntimeException e) { throw new RuntimeException("Fail...
String content = "# Basic Scalar Types\n" + "1| type ScalarHolder | bigDecimalObject: BigDecimal | Expecting a BigDecimal Scalar Type in type ScalarHolder\n"; final List<TestData> testDate = CsvParser.parse("shouldHandleComments", new StringReader(content)); Assert.assertEquals...
179002056_18
class Database implements Runnable { @Override public void run() { try { switch (method) { case "get": runGet(); break; case "delete": runDelete(); break; case "put": runPut(); break; case "scan": runSca...
// Arrange // Action CommandLine.run(database, "delete", "-p {\"partition\":\"p\"}"); // Assert Key partition = new Key(new TextValue("partition", "p")); Delete expected = new Delete(partition); verify(backend).delete(expected); } }
179494421_7
class ArrayCreator { public static Optional<Array> createArray(Type type) { return createArray(null, type, false); } private ArrayCreator(); public static Optional<Array> createArray(Type type, boolean batched); public static Optional<Array> createArray(Type fieldType, Type methodType); ...
final ParameterizedType stringList = ParameterizedType.create(DotName.createSimple(List.class.getName()), new Type[] { STRING_TYPE }, null); final ParameterizedType type = ParameterizedType.create(Classes.COMPLETION_STAGE, new Type[] { stringList }, null); assert...
179502880_327
class DefectService { boolean areEqualDownToSeconds(Date date1, Date date2) { final boolean bothNull = (date1 == null && date2 == null); final boolean bothNotNull = (date1 != null && date2 != null); return bothNull || (bothNotNull && (date1.getTime() / 1000) == (date2.getTime() / 1000)); ...
// GIVEN final Date date1 = new Date(2001); final Date date2 = new Date(1000); // WHEN boolean areEqual = cut.areEqualDownToSeconds(date1, date2); // THEN assertThat(areEqual).isFalse(); } }
179541399_2
class JSONPointer { public TDPath parse(String str) { TDPath path = new TDPath(); if (StringUtil.isEmpty(str)) return path; if (str.endsWith("#")) // Ignore the last # which indicate "key" of the map str = str.substring(0, str.length() - 1); if (str.indexOf('#') < 0) { if (parsePa...
verify("//ab.c/p1#/p1", new TDPath().setDocPath("//ab.c/p1").addParts(Part.ofRoot(), Part.ofChild("p1"))); verify("//ab.c/p1#p1/p2", new TDPath().setDocPath("//ab.c/p1").addParts(Part.ofId("p1"), Part.ofChild("p2"))); verify("1/p1", new TDPath().addParts(Part.ofRelative(1), Part.ofChild("p1"))); verify(...
179849363_8
class CpdTokensFiller implements Filler { @Override public void fill(InputFile file, SensorContext context, AntlrContext antlrContext) { try { if (!(file instanceof DefaultInputFile)) { return; } NewCpdTokens newCpdTokens = context.newCpdTokens().onFile(file); List<? extends Token> tokens = antlrCo...
SensorContextTester ctxTester = SensorContextTester.create(folder.getRoot()); ctxTester.fileSystem().setWorkDir(folder.getRoot().toPath()); File baseFile = folder.newFile("test.sql"); FileUtils.copyURLToFile(getClass().getResource("/tsql/sample1.sql"), baseFile); String contents = FileUtils.readFileToString...
179925476_3
class SingleLevelCacheRepository extends BaseRepository<M, P> implements Repository<M, P> { @NotNull @Override public Single<M> getLatest(P params) { return networkDataSource.getAndUpdate(params, cacheDataSource) .map(TimeStampedData::getModel) .toSingle(); } ...
TestObserver<String> testObserver = TestObserver.create(); when(networkDataSource.getAndUpdate(parameter, cacheDataSource)).thenReturn(Maybe.just(NETWORK_DATA)); sut.getLatest(parameter) .subscribe(testObserver); testObserver.assertResult(NETWORK_STRING); // includes .a...
179952747_0
class Utils { static String capitalize(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } } class UtilsTest { @Test public void capitalize() {
assertEquals(Utils.capitalize("id"), "Id"); assertEquals(Utils.capitalize("location"), "Location"); assertEquals(Utils.capitalize("ABTesting"), "ABTesting"); assertEquals(Utils.capitalize("user"), "User"); } }
180526285_34
class QueryIndexEndpointStrategy implements EndpointDetectionStrategy { @Override public Mono<Endpoints> detectEndpoints(Instance instance) { Registration registration = instance.getRegistration(); String managementUrl = registration.getManagementUrl(); if (managementUrl == null || Obje...
//given Instance instance = Instance.create(InstanceId.of("id")) .register(Registration.create("test", wireMock.url("/mgmt/health")) .managementUrl(wireMock.url("/mgmt")) ...
180537027_5
class ReadOnlyAttributesEraser { public T eraseAllFormCustomExtensions(final T resource) { List<Extension> extensions = resource.getExtensions().values().stream().map(extension -> { if (extension instanceof EnterpriseExtension) { // https://github.com/SAP/scimono/issues/77 // EnterpriseExte...
MockitoAnnotations.initMocks(this); Attribute attribute = new Attribute.Builder().name(ATTRIBUTE1).type(COMPLEX.toString()).mutability("readWrite") .addSubAttribute(new Attribute.Builder().name(ATTRIBUTE1).type(STRING.toString()).mutability("readWrite").build()) .addSubAttribute(new Attribute.B...
180588003_85
class RedirectConsentServiceImpl implements RedirectConsentService { @Override public ConsentWorkflow identifyConsent(String encryptedConsentId, String authorizationId, boolean strict, String consentCookieString, BearerTokenTO bearerToken) { // Parse and verify the consent cookie. ConsentRefere...
// Given when(referencePolicy.fromRequest(any(), any(), any(), anyBoolean())).thenReturn(getConsentReference()); when(cmsPsuAisClient.getConsentIdByRedirectId(any(), any())).thenReturn(ResponseEntity.ok(getCmsAisConsentResponse(AisConsentRequestType.DEDICATED_ACCOUNTS, IBAN_DE))); when(c...
180757477_5
class BackgroundFunctionExecutor extends HttpServlet { static Optional<Type> backgroundFunctionTypeArgument( Class<? extends BackgroundFunction<?>> functionClass) { // If this is BackgroundFunction<Foo> then the user must have implemented a method // accept(Foo, Context), so we look for that method and...
assertThat(backgroundFunctionTypeArgument(PubSubFunction.class)).hasValue(PubSubMessage.class); } }
180773046_12
class InstantDeserializer extends StdScalarDeserializer<Instant> { @Override public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { try { String text = p.readValueAs(String.class); return text == null ? null : converter.convert(text); } catch (Exception e) { ...
// given given(parser.readValueAs(String.class)).willReturn(null); // when var actual = deserializer.deserialize(parser, ctx); // then assertThat(actual).isNull(); verify(parser).readValueAs(String.class); verify(converter, never()).convert(any()); } }
180834808_1
class InjectorHandler { public InjectorService getInjectorService() { Map<String, InjectorService> beansOfType = context.getBeansOfType(InjectorService.class); if (beansOfType.entrySet().isEmpty()) { throw new NoSuchBeanDefinitionException("No InjectorType found"); } ret...
Connection properties = new Connection("localhost", 12345); doReturn(remoteInjector).when(connectionService).createRemoteInjector(any()); connectionService.createConnection(properties); InjectorService currentConnection = injectorHandler.getInjectorService(); Assert.assertNotNull...
180961537_0
class LoansourceApplication { @Bean public Supplier<Loan> supplyLoan(){ Supplier<Loan> loanSupplier = () -> { Loan loan = new Loan(UUID.randomUUID().toString(), names.get(new Random().nextInt(names.size())), amounts.get(new Random().nextInt(amounts.size()))); log.info("...
LoansourceApplication app = new LoansourceApplication(); Supplier<Loan> loan = app.supplyLoan(); assertNotNull(loan); assertNotNull(loan.get()); assertNotNull(loan.get().getAmount()); assertNotNull(loan.get().getName()); } }
181194375_2
class PluggableLoggerFactory extends AbstractSimpleLoggerFactory { public PluggableLoggerFactory addLogger(LoggerChannel logger, Level level) { mSortedLoggers.add(new SortedLogger(logger, level.toInt())); Collections.sort(mSortedLoggers, mSortedLoggersComparator); return this; } @O...
// Fixture LoggerChannel loggerTrace = mock(LoggerChannel.class); LoggerChannel loggerInfo = mock(LoggerChannel.class); LoggerChannel loggerError = mock(LoggerChannel.class); PluggableLoggerFactory factory = new PluggableLoggerFactory(); factory.addLogger(loggerInfo, Leve...
181286172_8
class RomanConverter { static int convertRomanToArabicNumber(String roman) { roman = roman.toUpperCase(); int sum = 0; int current = 0; int previous = 0; for (int index = roman.length() - 1; index >= 0; index--) { if (doesSymbolsContainsRomanCharacter(roman, i...
assertEquals(36, convertRomanToArabicNumber("XXXVI"), "Roman XXXVI should equal to 36"); } }
181400274_0
class RocketMQAutoConfiguration { @Bean @ConditionalOnMissingBean(DefaultMQProducer.class) @ConditionalOnProperty(prefix = "spring.rocketmq", value = {"name-server", "producer.group"}) public DefaultMQProducer defaultMQProducer(RocketMQProperties rocketMQProperties) { RocketMQProperties.Produce...
runner.withPropertyValues("spring.rocketmq.name-server=127.0.0.1:9876", "spring.rocketmq.producer.group=spring_rocketmq"). run((context) -> { assertThat(context).hasSingleBean(DefaultMQProducer.class); }); } }
181445409_46
class SslCustomizer implements HttpServerOptionsCustomizer { @Override public HttpServerOptions apply(HttpServerOptions options) { Ssl ssl = factory.getSsl(); if (ssl == null) { return options; } options.setSsl(ssl.isEnabled()); options.setKeyCertOptions(ke...
given(mockSsl.isEnabled()).willReturn(true); customizer.apply(mockHttpServerOptions); verify(mockHttpServerOptions).setSsl(true); } }
181519091_56
class BlottingPaperRestController extends BaseValidatingRestController<BlottingPaper, BlottingPaperService> { @NonNull @PostMapping @ResponseStatus(HttpStatus.CREATED) public BlottingPaper createItem(@NonNull @Valid @RequestBody BlottingPaper input) { return this.service.createItem(input); ...
final BlottingPaper blottingPaper = BlottingPaper.builder() .label("label 3") .manufacturer("A manufacturer") .model("The new model") .build(); final String json = new ObjectMapper().writeValueAsString(blottingPaper); getMockMvc()....
181683494_110
class ProcessorEventPublisher { public void splitSegment(String context, List<String> clientIds, String processorName) { Map<ClientSegmentPair, SegmentStatus> clientToTracker = buildClientToTrackerMap(clientIds, processorName, REGULAR_ORDER); Integer biggestSegment = clientToTracke...
testSubject.splitSegment(CONTEXT, CLIENTS, PROCESSOR_NAME_TO_SPLIT); ArgumentCaptor<SplitSegmentRequest> argumentCaptor = ArgumentCaptor.forClass(SplitSegmentRequest.class); verify(applicationEventPublisher).publishEvent(argumentCaptor.capture()); SplitSegmentRequest result = argumentCa...
181777958_2
class VectorText { public static int[] count(Map<String, Integer> dictionary, String s) { int[] result = new int[dictionary.size()]; VectorText.tokenize(s).forEach(w -> { if (dictionary.containsKey(w)) { result[dictionary.get(w)]++; } }); retu...
// build a dictionary of all words we see in a subset of the text Map<String, Integer> dict = VectorText.tokenize(sample.split("\\.")[0]).collect( TreeMap::new, (Map<String, Integer> d, String s) -> d.put(s, d.size()), Map::putAll ); dict.r...
181845258_121
class TransactionalMessageBridge { public PullResult getOpMessage(int queueId, long offset, int nums) { String group = TransactionalMessageUtil.buildConsumerGroup(); String topic = TransactionalMessageUtil.buildOpTopic(); SubscriptionData sub = new SubscriptionData(topic, "*"); retu...
when(messageStore.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class))).thenReturn(createGetMessageResult(GetMessageStatus.NO_MESSAGE_IN_QUEUE)); PullResult result = transactionBridge.getOpMessage(0, 0, 1); assertThat(result.getPull...
181888758_2
class CanvasCommandLineRunner { public void run(String... args) throws Exception { CommandLine cmd = parseCommandLine(args); String inputFile = cmd.getOptionValue("input"); String outputFile = cmd.getOptionValue("output"); String yml = FileUtils.readFileToString(new File(inputFile), (String)null)...
CanvasCommandLineRunner runner = new CanvasCommandLineRunner(); File tmpFile = File.createTempFile("example", ".adoc"); String resource = getClass().getResource("/example.yml").toExternalForm(); assertTrue(resource.startsWith("file:")); String[] args = new String[]{"--input", resource.substring("fil...
181997557_0
class ReserveBuffer { public byte[] update(byte[] input, int offset, int inputLength) { int reserveToApply = Math.min(reserve.length, inputLength); int reserveToRelease = Math.max(reserveToApply - capacity(), 0); byte[] output = new byte[reserveToRelease + (inputLength - reserveToApply)...
ReserveBuffer buffer = new ReserveBuffer(16); byte[] input = new byte[1]; for (int i=0;i<16;i++) { input[0] = (byte)i; byte[] result = buffer.update(input, 0, 1); assertEquals(0, result.length); } byte[] largeInput = new byte[16]; Arrays.fill(largeInput, (byte)16); byte[...
182006329_182
class FabricTopicAdmin implements IEventTopic { @Override public boolean open(String topic, String channelName) throws BrokerException { log.info("open topic: {} channelName: {}", topic, channelName); ParamCheckUtils.validateTopicName(topic); validateChannelName(channelName); t...
try { String topicStr = "topiclengthlonger64asdfghjklpoiuytrewqazxswcdevfrbg-" + System.currentTimeMillis(); this.iProducer.open(topicStr, this.channelName); Assert.fail(); } catch (BrokerException e) { Assert.assertEquals(ErrorCode.TOPIC_EXCEED_MAX_LENGTH...
182082980_6
class SshUriPropertyProcessor { public Map<String, SshUri> getSshKeysByHostname() { return extractNestedProperties(sshUriProperties); } public SshUriPropertyProcessor(SshUriProperties sshUriProperties); private Map<String, SshUri> extractNestedProperties(SshUriProperties uriProperties); protected static Stri...
SshUriPropertyProcessor sshUriPropertyProcessor = new SshUriPropertyProcessor(SshUri.builder().uri("https://user@github.com/proj/repo.git").build()); Map<String, SshUri> sshKeysByHostname = sshUriPropertyProcessor.getSshKeysByHostname(); assertThat(sshKeysByHostname.values(), hasSize(0)); } }
182200911_1
class UniqueToken { public static String create() { return Base64Utils.encodeToUrlSafeString(UUID.randomUUID().toString().getBytes()); } private UniqueToken(); } class UniqueTokenTest { @Test void create() {
Set<Object> set = new HashSet<>(); for (int i = 0; i < 10E6; i++) { String token = UniqueToken.create(); assertNotNull(token); assertFalse(set.contains(token)); set.add(token); } } }
182454442_4
class ResourcePreparer { public GenericScimResource trimRetrievedResource(final T returnedResource) { return trimReturned(returnedResource, null, null); } public ResourcePreparer(final ResourceTypeDefinition resourceType, final String attributesString, ...
ResourcePreparer<ScimResource> preparer = new ResourcePreparer<>(resourceTypeDefinition, "default", null, testBaseUri); ObjectNode node = (ObjectNode) JsonUtils.getObjectReader() .readTree("{\n" + " \"default\": {\n" + " \"never\": \"here\"\n" + " }\...
182813463_18
class TfVarFilesOptionFormatter implements TfOptionFormatter { public String convert(String format, Object value) { String str = ""; if (value instanceof String) { str = csvConverter("-var-file=%s ", (String) value); } return str; } TfOptionFormatter formatter; } class TfVarFilesOptionF...
String format = "-var-file"; String value = "test1.txt "; Assert.assertEquals(formatter.convert(format, value), "-var-file=test1.txt "); } }
182842409_47
class SpannerConnectionConfiguration { public String getFullyQualifiedDatabaseName() { return this.fullyQualifiedDbName; } private SpannerConnectionConfiguration(String url, GoogleCredentials credentials); private SpannerConnectionConfiguration( String projectId, String instanceName, S...
SpannerConnectionConfiguration config = this.configurationBuilder .setProjectId("project1") .setInstanceName("an-instance") .setDatabaseName("db") .build(); assertThat(config.getFullyQualifiedDatabaseName()) .isEqualTo("projects/project1/instances/an-instance/databases/db...
183382045_2
class HelloProxyServiceImpl implements HelloProxyService { @Override public ServiceCall<NotUsed, String> proxyViaHttp(String id) { return req -> helloService.hello(id).invoke(); } @Inject public HelloProxyServiceImpl( HelloService helloService, GreeterServiceClient greeterClie...
String msg = proxyServiceClient.proxyViaHttp("Alice").invoke() .toCompletableFuture().get(5, SECONDS); assertEquals("Hello Alice", msg); } }
183462598_0
class CustomCodeGenerator implements CodeGenerator, InitializingBean { @Override public String generateCode(String phone) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLength; i++) { int index = random.nextInt(arr.size()); sb.append(arr.get(index)); ...
CustomCodeGenerator generator = new CustomCodeGenerator(CustomCodeGenerator.Mode.NUMBER); String code = generator.generateCode("xxx"); Assert.assertEquals(6, code.length()); String code2 = generator.generateCode("xxx"); Assert.assertNotEquals(code, code2); } }
183523285_12
class QueryRegistry { public boolean deregisterQuery(String targetApp, String subId, String query) { appToSubscriptionMap.computeIfPresent(targetApp, (k, v) -> { v.deregisterQuery(subId, query); return v; }); return true; } private QueryRegistry(String cli...
try { QueryRegistry queryRegistry = new QueryRegistry.Builder().build(); fail(); } catch (IllegalArgumentException ignored) { } QueryRegistry queryRegistry = new QueryRegistry.Builder().withClientIdPrefix("myPrefix").build(); String targetApp = "myapp"; ...
183536958_1
class Presentation implements ConvertJwt { @Override public Jwt buildJwt(Date issued, Date expiration) { String kid = issuerDid.getDid() + "#" + issuerDid.getKeyId(); return new Jwt.Builder() .alg(issuerDid.getAlgorithm()) .kid(kid) .iss(issuerDid...
String keyId = TestKeys.HOLDER_KEY_ID; AlgorithmProvider.Type type = AlgorithmProvider.Type.ES256; Algorithm algorithm = AlgorithmProvider.create(type); PrivateKey priKey = algorithm.byteToPrivateKey(EncodeType.HEX.decode(TestKeys.PRIVATE_KEY_ES256)); String rawCredential = "ey...
183646665_3
class Step implements DeepComparable, Serializable { @Override public boolean deepEquals(Object o) { if (this == o) { return true; } if (!(o instanceof Step)) { return false; } Step step = (Step) o; if (this.id != null ? !this.id.equals(step.id) : step.id != null) { retu...
String id = UUID.randomUUID().toString(); Step one = getStep(id, "B"); Step two = getStep(id, "C"); Assert.assertEquals("same values same step", false, one.deepEquals(two)); Assert.assertEquals("same id <=> equals step", true, one.equals(two)); } }
183916330_0
class BPlusTree { @SuppressWarnings("unused") public void insertPair(ArrayList<Object> key, long value) throws IOException, MiniDBException, IllegalStateException { if(root == null) {throw new IllegalStateException("Can't insert to null tree");} conf.padKey...
BPlusTree bt = createCommonTree(false); bt.insertPair(new ArrayList<>(Arrays.asList(100, 200.0, "12")), 12L); bt.insertPair(new ArrayList<>(Arrays.asList(100, 200.0, "120")), 0L); bt.insertPair(new ArrayList<>(Arrays.asList(100, 200.0, "9")), 254L); bt.insertPair(new ArrayList<>(...
183933015_15
class JdbcDBClient extends DB { @Override public Status read(String tableName, String key, Set<String> fields, Map<String, ByteIterator> result) { try { StatementType type = new StatementType(StatementType.Type.READ, tableName, 1, "", getShardIndexByKey(key)); PreparedStatement readStatement = cach...
String insertKey = "user0"; HashMap<String, ByteIterator> insertMap = insertRow(insertKey); Set<String> readFields = new HashSet<String>(); HashMap<String, ByteIterator> readResultMap = new HashMap<String, ByteIterator>(); // Test reading a single field readFields.add("F...
183937162_747
class BinaryReader { public String readUnicodeString(long index) throws IOException { StringBuffer buffer = new StringBuffer(); while (index < length()) { int ch = readUnsignedShort(index); if (ch == 0) { break; } buffer.append((char) ch); index += 2; } return buffer.toString().trim(); } ...
BinaryReader br = br(false, 1, 1, 1, 0, 'A', 0, 'B', 0, 'C', 0x80, 0, 0); assertEquals("ABC\u8000", br.readUnicodeString(3, 4)); } }
184035533_3
class CompassConfigParserRM extends CompassConfigParser { @NotNull @Override public CompassConfig parse(@NotNull final VirtualFile file, @NotNull final String importPathsRoot, @Nullable final PsiManager psiManager) { return ReadAction.compute(() -> { ...
assertEmpty(parse().getImportPaths()); } }
184219031_10
class HintCommand implements Command { @Override public String name() { return "hint"; } public HintCommand(Shell shell); @Override public Usage usage(); @Override public void run(Line line); } class HintCommandTest { @Test public void testName() {
HintCommand command = new HintCommand(new Shell()); assertThat(command.name(), is("hint")); } }
184265896_209
class BasicMonthViewUI extends MonthViewUI { protected Rectangle getMonthBoundsAtLocation(int x, int y) { if (!calendarGrid.contains(x, y)) return null; int calendarRow = (y - calendarGrid.y) / fullCalendarHeight; int calendarColumn = (x - calendarGrid.x) / fullCalendarWidth; ...
if (GraphicsEnvironment.isHeadless()) { LOG.fine("cannot run test - headless environment"); return; } BasicMonthViewUI ui = getRealizedMonthViewUI(ComponentOrientation.LEFT_TO_RIGHT); Rectangle monthBounds = ui.getMonthBoundsAtLocation(20, 20); assertEqual...
184285250_188
class Format { public static String l(long v, int width) { return pad(Long.toString(v), width, true); } public static void tab(StringBuilder sbuff, int tabStop, boolean alwaysOne); public static String s(String s, int width); public static String pad(String s, int width, boolean rightJustify); public ...
long num = 12345L; assertThat(Format.l(num, 2)).isEqualTo("12345"); assertThat(Format.l(num, 3)).isEqualTo("12345"); assertThat(Format.l(num, 4)).isEqualTo("12345"); assertThat(Format.l(num, 5)).isEqualTo("12345"); assertThat(Format.l(num, 6)).isEqualTo(" 12345"); assertThat(Format.l(num, 7)...
184301969_5
class DijkstraAlgorithm { public static PathData findShortestPath(Graph graph, String sourceNodeIdentifier, String targetNodeIdentifier) throws ArrayStoreException { return findShortestPath(graph, graph.getNode(sourceNodeIdentifier), graph.getNode(targetNodeIdentifier)); } public static PathDataOb...
String[] sourceIDs = {"1", "1", "0", "4", "3", "3", "3", "2", "2"}; String[] targetIDs = {"0", "3", "4", "0", "0", "4", "5", "3", "5"}; double[] weights = {4, 1, 2, 3, 5, 2, 1, 3, 4}; graph = GraphBuilder.Build().WithNodes(6).SomeConnected(sourceIDs, targetIDs, weights).getGraph(); ...
184386453_0
class GoogleTranslateApi { public String translate(String text, String lang) { Translation translationResult = translateApi.translate(text, TranslateOption.targetLanguage(lang)); return translationResult.getTranslatedText(); } public GoogleTranslateApi(); } class GoogleTranslateApiTest ...
GoogleTranslateApi service = new GoogleTranslateApi(); String result = service.translate("Hi there", "ja"); assertThat(result, is("こんにちは")); } }
184471389_18
class SpecificPageFilterFactory implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; // Skip filter if there isn't...
request.setResource(context.resourceResolver().resolve("/content/product-page")); MockRequestPathInfo pathInfo = (MockRequestPathInfo) request.getRequestPathInfo(); pathInfo.setSelectorString("productId1"); filter.doFilter(request, null, chain); // Check that the request dispatc...
184496771_3
class DeleteHandler extends BaseHandler<CallbackContext> { @Override public ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final Lo...
final DeleteHandler handler = new DeleteHandler(); doThrow(ConfigurationSetDoesNotExistException.class) .when(proxy) .injectCredentialsAndInvokeV2( ArgumentMatchers.any(), ArgumentMatchers.any() ); final ResourceModel model = ...
184569540_75
class ImageName { public String getFullName() { return getFullName(null); } public ImageName(String fullName); public ImageName(String fullName, String givenTag); public String getRepository(); public String getRegistry(); public String getTag(); public String getDigest(); ...
assertEquals("docker.jolokia.org/org/jolokia/jolokia_demo:0.18", new ImageName("org/jolokia/jolokia_demo:0.18").getFullName("docker.jolokia.org")); assertEquals("docker.jolokia.org/org/jolokia/jolokia_demo:latest", new ImageName("org/jolokia/jolokia_demo").getFullName("do...