id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
198222234_67
class FlatMapIterableStageFactory implements ProcessingStageFactory<Stage.FlatMapIterable> { @Override public <I, O> ProcessingStage<I, O> create(Engine engine, Stage.FlatMapIterable stage) { Function<I, Iterable<O>> mapper = Casts.cast(stage.getMapper()); return new FlatMapIterable<>(mapper); ...
assertThrows(NullPointerException.class, () -> factory.create(null, () -> null)); } }
198238470_474
class ProjectWhiteListSecHubConfigurationValidationService { public void assertAllowedForProject(SecHubConfiguration configuration) { List<URI> allowed = fetchAllowedUris(configuration); Optional<SecHubInfrastructureScanConfiguration> infrascanOpt = configuration.getInfraScan(); if (infrascanOpt.isPresent()) {...
/* test */ expectedException.expect(NotAcceptableException.class); /* prepare */ whiteListFoundForProject.add(new ProjectWhitelistEntry(projectId, new URI(IP_ADRESS_2))); when(support.isWhitelisted(eq(IP_ADRESS_1), any())).thenReturn(false); // not whitelisted - so failure expected /* execute */ service...
198569702_7
class RSACipher implements Cipher { @Override public byte[] decrypt(byte[] encryptData) { try { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(KEY_ALGORITHM); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, privateKey); byte[] result = cipher.doFinal(Base...
byte[] encryptData = rsaCipher.encrypt("我是ukuz😄".getBytes(StandardCharsets.UTF_8)); byte[] decryptData = rsaCipher.decrypt(encryptData); assertEquals("我是ukuz😄", new String(decryptData, StandardCharsets.UTF_8)); } }
199027540_43
class Event implements Comparable<Event> { public long getTime() { return time; } public Event(long timeFromNowNs); public abstract void trigger(); @Override public int compareTo(Event o); } class EventTest { @Test public void testQueueOrder() {
// Events Event e1 = new FlowStartEvent(1000, null, 0, 0); Event e2 = new FlowStartEvent(0, null, 0, 0); Event e3 = new FlowStartEvent(848, null, 0, 0); Event e4 = new FlowStartEvent(1000, null, 0, 0); Event e5 = new FlowStartEvent(999999, null, 0, 0); // Create...
199046636_39
class TagController { @PutMapping("/admin/tag/update") public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { return ResponseUtil.success(tagService.update(id, name)); } @PostMapping("/admin/tag/create") public Response addOne(@RequestParam("name") String n...
Tag tag = tagMapper.getLastestTag(); assertNotNull(tag.getId()); String name = UUID.randomUUID().toString().substring(0, 4); mockMvc.perform(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name).header("Authorization", adminLogin())).andDo(result -> { JSONObject object...
199262429_198
class BST { public boolean isEmpty() { return root == null; } protected int getCount(Node cur); protected Node updateCount(Node cur); public int size(); public boolean contains(Key key); public Val find(Key key); private Node find(Node cur, Key key); public void put(Key key...
Assert.assertEquals(expect.isEmpty(), bst.isEmpty()); } }
199309560_3
class OpenAPIGenerator { public OpenAPI generate() { return generate(OpenApiGeneratorConfigBuilder.defaultConfig().build()); } public OpenAPIGenerator(List<String> modelPackages, List<String> controllerBasePackages, Info info); public OpenAPIGenerator(List<String> modelPackages, List<String>...
OpenAPI openAPI = createTestGenerator().generate( OpenApiGeneratorConfigBuilder.defaultConfig() .withGenerateExamples(true) .withOpenApiExampleResolver(createExampleResolver()) .build() ); assertOpenApiResult...
199431217_0
class PositioningStore implements JournalPersistence, MonitoredPersistence, Closeable { public void recover(Path path, long min, Properties properties) throws IOException { Files.createDirectories(path); this.base = path.toFile(); this.config = toConfig(properties); bufferPool.addP...
JournalPersistence store = new PositioningStore(); store.recover(path, new Properties()); int size = 10; int maxLength = 999; long start = store.max(); List<byte[]> journals = ByteUtils.createRandomSizeByteList(maxLength, size); int length = journa...
199491032_2
class LoadBalance { Result<? extends Record> run() { // Pull the latest state from the DB model.updateData(); // Run the solver and return the virtual machines table with solver-identified values for the // controllable__physical_machines column return model.solve(VIRTUAL_M...
final String allVmsGoToPm3 = "create view constraint_simple as " + "select * from virtual_machine " + "check controllable__physical_machine = 'pm3'"; final LoadBalance lb = new LoadBalance(Collections.singletonList(allVmsGoToPm3))...
199626064_3
class PatternDetectingReader extends FilterReader { @Override public int read() throws IOException { char[] buffer = new char[1]; int read = read(buffer); if (read < 0) { return read; } else { return buffer[0]; } } PatternDetectingRead...
char[] buffer = new char[5]; Reader data = new StringReader("aabbccdd"); PatternDetectingReader in = new PatternDetectingReader(data, "abc"); assertEquals(3, in.read(buffer, 1, 3)); assertEquals(3, in.read(buffer, 1, 3)); assertEquals(2, in.read(buffer, 1, 3)); as...
199703640_0
class FastActorClassFinder implements ActorClassFinder { @SuppressWarnings("unchecked") @Override public <T extends Actor> Collection<Class<? extends T>> findActorInterfaces(final Predicate<Class<T>> predicate) { List<Class<? extends T>> interfaces = null; for (Class<?> concreteInterfac...
Collection<Class<? extends Actor>> actorInterfaces = actorClassFinder.findActorInterfaces(ScheduledTask.class::isAssignableFrom); assertEquals(2, actorInterfaces.size()); } }
199829201_0
class ActivityPartService implements IActivityPartService { @Override public Result<NewCustomerPartResponse> partNewCustomerActivity(NewCustomerPartRequest request) { ContextParam contextParam = new ContextParam(FunctionCodeEnum.ACTIVITY_PARTICIPATE, request, ActivityTypeEnum.NEW_CUSTOM...
NewCustomerPartRequest request = new NewCustomerPartRequest(customerRegisterId, channelId); Result<NewCustomerPartResponse> result = activityPartService.partNewCustomerActivity(request); Assert.assertTrue(result.isSuccess()); Assert.assertNotNull(result.getModel()); } }
199902324_0
class CardRestApi { @POST @ApiOperation(value = "Create a new Card", notes = "Create a card using json") public Response createCard(Card card){ card = cardService.createCard(card); return Response.created(getGetUri(card)).build(); } @PUT @ApiOperation(value = "Update a new Card", n...
WebTarget path = client.target(this.uri).path(PATH); Response response = path .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(testCard, MediaType.APPLICATION_JSON_TYPE), Response.clas...
200044570_0
class UperEncoder { public static byte[] bytesFromHexString(String s) { if ((s.length() % 2) != 0) { throw new IllegalArgumentException( "Converting to bytes requires even number of characters, got " + s.length()); } int len = s.length(); byte[] data ...
String hexString = "AAB"; UperEncoder.bytesFromHexString(hexString); fail("Expected exception."); } }
200053873_12
class RNMarketingCloudSdkModule extends ReactContextBaseJavaModule { @ReactMethod public void enableVerboseLogging() { MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE); MarketingCloudSdk.setLogListener(new MCLogListener.AndroidLogListener()); } public RNMarketingCloudSdkModule(Rea...
// GIVEN ShadowMarketingCloudSdk.isReady(true); // WHEN reactModule.enableVerboseLogging(); // THEN assertEquals(MCLogListener.VERBOSE, ShadowMarketingCloudSdk.getLogLevel()); assertThat(ShadowMarketingCloudSdk.getLogListener(), CoreMatchers.<MCLogListener>insta...
200062847_31
class ParagraphCompletion implements Completion { @Nonnull @Override public CompletionItemKind getKind() { return CompletionItemKind.Method; } @Nonnull @Override public Collection<String> getCompletionSource(MyDocumentModel document); @Nonnull @Override public String getSortOrderPrefix(); private s...
MyDocumentModel document = createModel(); Set<Completion> completionSet = new HashSet<>(); completionSet.add(new ParagraphCompletion()); Completions completions = new Completions(completionSet); List<CompletionItem> completionItems = completions.collectFor(document, createCompletionParams()...
200492090_13
class DssRestHandler extends SimpleChannelInboundHandler<Object> implements DssHandler<DssRestChannelHandlerCommand> { @Override public Behavior<DssRestChannelHandlerCommand> create() { if (initializeBehavior.get()) { throw new DssUserActorDuplicateBehaviorCreateException("Cannot setup twic...
mockChannelHandlerContextChannelId(ctx, "abcedf"); final ChannelFuture channelFuture = Mockito.mock(ChannelFuture.class); Mockito.when(ctx.writeAndFlush(Mockito.anyObject())).thenReturn(channelFuture); final TestProbe<DssRestMasterActorCommand> testProbe = testKit.createTestProbe(); ...
200620451_122
class PlaceServiceImpl implements PlaceService { @Override public List<Place> findAll() { log.info(LogMessage.IN_FIND_ALL); return placeRepo.findAll(); } @Autowired public PlaceServiceImpl(PlaceRepo placeRepo, ModelMapper modelMapper, ...
List<Place> expectedList = Arrays.asList(new Place(), new Place()); when(placeRepo.findAll()).thenReturn(expectedList); assertEquals(expectedList, placeService.findAll()); } }
200642013_0
class ProductService { public Response validateAndAdd(ProductFormData productData) { if ("".equals(productData.getName())) { return new Response(0, -2, "Missing Name"); } if ("".equals(productData.getType()) ) { return new Response(0, -2, "Missing Type"); } ...
// Arrange ProductFormData productData = new ProductFormData("Sample product", "Lipstick", 5D, 10D, false); FakeDatabase db = new FakeDatabase(); ProductService sut = new ProductService(db); // Act Response response = sut.validateAndAdd(productData); ...
200725818_0
class OperationCreditTransformer extends OperationTransformer { @Override public OperationResult transform(Transaction transaction) { String error = validateOperation(transaction); if (error != null) { return new OperationResult(false, transaction, null, error); } BigDecimal creditAmount = transaction.g...
String debitCurrency = "USD"; BigDecimal debitAmount = BigDecimal.valueOf(800d); String creditCurrency = "BTC"; BigDecimal askPrice = BigDecimal.valueOf(8222.21d); BigDecimal bidPrice = BigDecimal.valueOf(8219.04d); BigDecimal initialCreditCurrencyBalance = BigDecimal.valueOf(0.2d); BigDecimal expectedC...
200810412_178
class BeekeeperVacuumToolApplication implements ApplicationRunner { @Override public void run(ApplicationArguments args) { log.warn("Do not run this tool at the same time as replicating to the target table!"); if (isDryRun) { log.warn("Dry-run only!"); } try { metastore = clientSupplier...
initialiseApp(); setPartitionedTable("partition1_"); // create hidden directories Files.createTempDirectory(snapshot1Dir, ".hidden1_"); Files.createTempDirectory(snapshot1Dir, "_hidden2_"); // create directories at levels that shouldn't be seen Files.createTempDirectory(tableDir, "snapshot3...
200980523_46
class ListenerRegistrationService { public void gameStateChanged(GameState newState) { Set<Listener> listenersForNewState = recalculateListenersForNewState(newState); this.registerNew(listenersForNewState); } public ListenerRegistrationService(Plugin plugin, PluginManager pluginManager, L...
List<ListenerRegistration> registrations = new ArrayList<>(); registrations.add(newRegistration(GameState.WAITING)); registrations.add(newRegistration(GameState.WAITING)); runTest(listenerRegistrationService -> { listenerRegistrationService.gameStateChanged(GameState.WAITIN...
201021482_12
class OpenApiScannerSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor.name("OpenAPI Scanner Sensor") .onlyOnFileType(InputFile.Type.MAIN) .onlyOnLanguage(OpenApi.KEY); } public OpenApiScannerSensor(CheckFactory checkFactory, FileLinesContextFa...
activeRules = (new ActiveRulesBuilder()).build(); DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor().describe(descriptor); assertThat(descriptor.name()).isEqualTo("OpenAPI Scanner Sensor"); assertThat(descriptor.languages()).containsOnly("openapi"); assertThat(descript...
201179882_3
class Detail implements Parcelable, ClusterItem { public float getTilt() { return mTilt; } public Detail(String title, String description, LatLng location, float tilt, float bearing); protected Detail(Parcel in); @Override public LatLng getPosition(); public String getDescription();...
assertThat( Math.abs(mDetailUnderTest.getTilt() - mTilt) < MAX_FLOAT_DELTA, is(true)); } }
201194795_9
class JavaScriptEngineFactory implements ScriptEngineFactory { @Override public String getLanguageVersion() { return System.getProperty("java.version"); } @Override public String getEngineName(); @Override public String getEngineVersion(); @Override public List<String> getExtensions();...
JavaScriptEngineFactory factory = new JavaScriptEngineFactory(); assertThat(factory.getLanguageVersion()).isEqualTo(System.getProperty("java.version")); } }
201285390_53
class DefaultMQAdminExt extends ClientConfig implements MQAdminExt { @Override public boolean cleanUnusedTopic(String cluster) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, MQClientException, InterruptedException { return defaultMQAdminExtImpl.cleanUnu...
boolean result = defaultMQAdminExt.cleanUnusedTopic("default-cluster"); assertThat(result).isFalse(); } }
201347287_2
class ParsedStringPack { @Nullable public String getString(int id) { final String result = strings.get(id); if (result == null) { // String not loaded or doesn't exist. return loadString(id); } else { return result; } } public ParsedStringPack(@NonNull InputStream inputStrea...
String nonexistent = parsedStringPack.getString(EXPECTED_STRINGS.length + 1); assertNull(nonexistent); } }
201427469_11
class TwaProviderPicker { public static Action pickProvider(PackageManager pm) { // Setting the Intent Data as seen at // https://cs.android.com/android/platform/superproject/+/fd994cf9ef8207ad03dc3a1d831e9263ddfd4469:packages/apps/PermissionController/src/com/android/packageinstaller/role/model/Br...
installBrowser(BROWSER1); installCustomTabsProvider(CUSTOM_TABS_PROVIDER1); installChrome(CHROME_72_VERSION); installTrustedWebActivityProvider(TWA_PROVIDER2); TwaProviderPicker.Action action = TwaProviderPicker.pickProvider(mPackageManager); assertEquals(TwaProviderPic...
201612522_16
class JShellScriptEngineFactory implements ScriptEngineFactory { @Override public ScriptEngine getScriptEngine() { return new JShellScriptEngine(); } @Override public String getEngineName(); @Override public String getEngineVersion(); @Override public List<String> getExtensions(); ...
JShellScriptEngineFactory factory = new JShellScriptEngineFactory(); assertThat(factory.getScriptEngine() instanceof JShellScriptEngine).isTrue(); } }
201655283_0
class SqlParser { public String Execute(String sql) { this.generateStatements(sql); return parseStatements(); } private void generateStatements(String str); private String parseStatements(); private String getModelName(MySqlCreateTableStatement createTable); public void setStat...
String sql = "CREATE DATABASE IF NOT EXISTS demo_db;\n" + "\n" + "CREATE TABLE IF NOT EXISTS `demo`.`test_tab` (\n" + " `id` bigint(21) unsigned NOT NULL AUTO_INCREMENT,\n" + " user_id int(11) unsigned DEFAULT 0 NOT NULL,\n" + " ...
202089894_59
class EncryptionUtils { public static AsymmetricKeyPair initAsymmetricKeyPair() { return RSACoder.initKey(); } public static byte[] encryptByPrivateKey(byte[] data, byte[] key); public static String encryptByPrivateKeyAsString(byte[] data, String sKey); public static byte[] encryptByPublic...
AsymmetricKeyPair keyPair = EncryptionUtils.initAsymmetricKeyPair(); Assert.assertNotNull(keyPair); log.info("privateKey:{}", keyPair.getPrivateKey()); log.info("publicKey:{}", keyPair.getPublicKey()); } }
202309300_0
class JWTHelper { public static String createSignedJwt(String user, PrivateKey privateKey) throws Exception { Calendar c = Calendar.getInstance(); c.add(Calendar.MINUTE, 1); Date d = c.getTime(); return createSignedJwt(user, d.getTime() / 1000, privateKey); } public static String createSignedJwt(String us...
long future = 1562389592; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(4096, new SecureRandom(new byte[] { 1, 2, 4} )); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); System.out.println("Priva...
202361279_89
class DateTimeHandler { public static void parse(Prefix prefix, QueryParameterValue parameterValue, String v) throws FHIRSearchException { TemporalAccessor value = parse(v); parameterValue.setValueDateLowerBound(generateLowerBound(prefix, value, v)); parameterValue.setValueDateUpperBound(ge...
TemporalAccessor acc = DateTimeHandler.parse("2019-10-11T01:10:00.000002"); assertNotNull(acc); assertTrue(acc.isSupported(ChronoField.YEAR)); assertEquals(acc.getLong(ChronoField.YEAR), 2019); assertTrue(acc.isSupported(ChronoField.MONTH_OF_YEAR)); assertEquals(acc.getLo...
202482196_66
class ServiceProvider { public static <T> T loadClass(String name, Class<?> clazz) { final InputStream is = getResourceAsStream(getContextClassLoader(), name); BufferedReader reader; try { try { reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); ...
AbstractTransactionalMessageCheckListener listener = ServiceProvider.loadClass(ServiceProvider.TRANSACTION_LISTENER_ID, AbstractTransactionalMessageCheckListener.class); assertThat(listener).isNotNull(); } }
202672490_1031
class NetworkBufferPool implements BufferPoolFactory, MemorySegmentProvider { public void destroy() { synchronized (factoryLock) { isDestroyed = true; MemorySegment segment; while ((segment = availableMemorySegments.poll()) != null) { segment.free(); } } } @VisibleForTesting public NetworkBuf...
// the number of requested buffers should be larger than zero NetworkBufferPool globalPool = new NetworkBufferPool(10, 128, 0); globalPool.destroy(); fail("Should throw an IllegalArgumentException"); } }
202839292_117
class SchemaUpdate implements UpdateSchema { @Override public UpdateSchema addColumn(String name, Type type, String doc) { Preconditions.checkArgument(!name.contains("."), "Cannot add column with ambiguous name: %s, use addColumn(parent, name, type)", name); return addColumn(null, name, type, doc);...
// preferences.booleans could be top-level or a field of preferences AssertHelpers.assertThrows("Should reject ambiguous column name", IllegalArgumentException.class, "ambiguous name: preferences.booleans", () -> { UpdateSchema update = new SchemaUpdate(SCHEMA, SCHEMA_LAST_COLUMN_ID); ...
203381991_31
class PacketBufferWrapper implements Comparable<PacketBufferWrapper> { public void setSize(final int size) { if (DEBUG >= LOG_TRACE) { log.trace("Writing packet size field @ 0x{} + {}.", leftPad(virtualAddress), PKT_OFFSET); } mmanager.putIntVolatile(virtualAddress + PKT_OFFSET, size); } @Contract(pure = ...
assume(); val offset = PacketBufferWrapperConstants.HEADER_OFFSET + PacketBufferWrapperConstants.PKT_OFFSET; for (val virtual : virtuals) { assertThat(virtual).isNotZero(); val packet = new PacketBufferWrapper(virtual); val size = random.nextInt(); packet.setSize(size); assertThat(mmanager.getIntVo...
203595784_93
class CliChangeScopeResolver extends JGitChangeScopeResolver implements ChangeScopeResolver { @Override public ChangeScope<Change> getChangeScope(RevisionScope<ObjectId> revisionScope) throws SourceControlException { final ChangeScope<Change> scope = new ChangeScopeImpl(); List<Diff> diffs = Gi...
mockStatic(GitDiffRunner.class); Diff diff = getChangeScopeDeletedFile(); when(GitDiffRunner.diff(any(), any())).thenReturn(singletonList(diff)); RevisionScope<ObjectId> scope = revisionResolver.resolve("fc776fe5e50", "e6f7c3d2954d6"); ChangeScope<Change> changeScope = changeS...
203830892_17
class FloatComparisonStep implements ComparisonStep<T> { @Override public boolean isEqual(T object1, T object2) { float value1 = valueExtractor.applyAsFloat(object1); float value2 = valueExtractor.applyAsFloat(object2); return floatToIntBits(value1) == floatToIntBits(value2); } ...
FloatComparisonStep<TestData> hashStep = new FloatComparisonStep<>(TestData::getValue); boolean result = hashStep.isEqual(new TestData(1234.0f), new TestData(1337.0f)); assertThat(result) .isFalse(); } }
203954530_0
class Result implements Serializable { public <R> Result<R> ifSuccess(Function<T, ? extends Result<R>> function) { if (success()) { return function.apply(data); } return Result.fail(BaseResultCode.SYSTEM_ERROR); } public Result(); protected Result(T data); pro...
Result.ok(Arrays.asList("a", "b", "c")) .ifNotSuccessThrowException() .ifSuccess(data -> { data.forEach(d -> System.out.println(d)); return Result.ok(data); }) .ifSuccess(data -> { data.fo...
203966607_9
class VersionNumber { public String compareTo(VersionNumber latestVersion) { if (versionNumberArray != null) { // Calculate max length of version number int maxLength = Math.max(versionNumberArray.length, latestVersion.versionNumberArray.length); for (int i = 0; i < maxL...
String current = "BETA-SNAPSHOT"; String latest = "20200422"; VersionNumber currentVersion = new VersionNumber(current); VersionNumber latestVersion = new VersionNumber(latest); String receivedValue = currentVersion.compareTo(latestVersion); assertThat(receivedValue).i...
204463745_46
class TransactionAspect { @Around("execution(@org.apache.servicecomb.saga.omega.transaction.annotations.Compensable * *(..)) && @annotation(compensable)") Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Throwable { Method method = ((MethodSignature) joinPoint.getSignature()).getMet...
aspect.advise(joinPoint, compensable); TxEvent startedEvent = messages.get(0); assertThat(startedEvent.globalTxId(), is(globalTxId)); assertThat(startedEvent.localTxId(), is(newLocalTxId)); assertThat(startedEvent.parentTxId(), is(localTxId)); assertThat(startedEvent.type(), is(EventType.TxSta...
204591382_0
class TableExportService implements ITableExportService { @Override public String exportMarkdown(String dbName, List<String> tableList) { StringBuilder markdownBuilder = new StringBuilder(); for (String table : tableList) { TableInfo tableInfo = treeService.oneTable(dbName, table); ...
List<ColumnInfo> columnInfoList1 = new ArrayList<>(); ColumnInfo columnInfo11 = new ColumnInfo(); columnInfo11.setColumnName("id"); columnInfo11.setColumnType("int(11)"); columnInfo11.setAutoIncrement(1); columnInfo11.setNullable("NO"); columnInfo11.setPrimaryKey(...
205042001_2
class ExecutorBizImpl implements ExecutorBiz { @Override public ReturnT<String> beat() { return ReturnT.SUCCESS; } @Override public ReturnT<String> idleBeat(int jobId); @Override public ReturnT<String> kill(int jobId); @Override public ReturnT<LogResult> log(long logDateTim, long logId...
// Act final ReturnT<String> retval = executorBiz.beat(); // Assert result Assert.assertNotNull(retval); Assert.assertNull(((ReturnT<String>) retval).getContent()); Assert.assertEquals(200, retval.getCode()); Assert.assertNull(retval.getMsg()); } }
205116498_415
class AbstractConfig implements Serializable { protected void appendAnnotation(Class<?> annotationClass, Object annotation) { Method[] methods = annotationClass.getMethods(); for (Method method : methods) { if (method.getDeclaringClass() != Object.class && method.get...
parameters = {"k1", "v1", "k2", "v2"}) public void appendAnnotation() throws Exception { Config config = getClass().getMethod("appendAnnotation").getAnnotation(Config.class); AnnotationConfig annotationConfig = new AnnotationConfig(); annotationConfig.appendAnnotation(Config.clas...
205517727_0
class JabelExample { public String run(String[] args) { // Switch Expressions // https://openjdk.java.net/jeps/325 var result = switch (args.length) { case 1 -> { yield """ one... yet pretty long! """; ...
JabelExample jabelExample = new JabelExample(); String result = jabelExample.run(new String[0]); assertTrue("'" + result + "' should start with 'idk '", result.startsWith("idk ")); } }
205635067_6
class AutoComplete { public Set<String> hint(String prefix, long count) { String key = "auto_complete:" + prefix; return client.zrevrange(key, 0, count - 1); } public AutoComplete(); public void feed(String keyword, double weight); } class AutoCompleteTest { @Test public v...
AutoComplete ac = new AutoComplete(); ac.feed("张艺兴", 5000); ac.feed("张艺谋", 3000); ac.feed("张三", 500); assertEquals(ac.hint("张", 10), new LinkedHashSet<String>() {{ add("张艺兴"); add("张艺谋"); add("张三"); ...
205733669_7
class FastMath { public static float asin(float fValue) { if (-1.0f < fValue) { if (fValue < 1.0f) { return (float) Math.asin(fValue); } return HALF_PI; } return -HALF_PI; } private FastMath(); public static boolean isPowe...
final float HALF_PI = 0.5f * (float)Math.PI; assertEquals(-HALF_PI, FastMath.asin(-2.0f), 0.01f); assertEquals(HALF_PI, FastMath.asin(2.0f), 0.01f); assertEquals(HALF_PI, FastMath.asin(Float.POSITIVE_INFINITY), 0.0f); assertEquals(0.0f, FastMath.asin(0.0f), 0.0f); assert...
205759200_0
class SideKEK extends Provider { static String getRandomAlphanumericString(int length) { if (length <= 0) { return ""; } // TODO request fewer bytes byte[] bytes = getRandomBytes(length); // Generate unique name from alphabet [-_a-zA-Z0-9] byte[] encodedBytes = Base64.getUrlEncoder().withoutPaddi...
for (int i = 0; i < 100; i++) { for (int j = 0; j < 10; j++) { String str = SideKEK.getRandomAlphanumericString(i); for (int x = 0; x < str.length(); x++) { assertEquals("Size is not the expected value", i, str.length()); char c = str.charAt(x); if (((c >= 'a') && (c <= 'z')) || ...
205782720_943
class MySQLCDCUtils { public static Object getWritableObject(Integer type, Serializable value) { if (value == null) { return null; } if (type == null) { if (value instanceof byte[]) { return new String((byte[]) value); } else if (value ins...
assertNull(MySQLCDCUtils.getWritableObject(null, null)); assertNull(MySQLCDCUtils.getWritableObject(Types.INTEGER, null)); assertEquals((byte) 1, MySQLCDCUtils.getWritableObject(Types.INTEGER, (byte) 1)); assertEquals("Hello", MySQLCDCUtils.getWritableObject(Types.VARCHAR, "Hello".getByt...
205815601_211
class RouteInfoManager { public byte[] getAllTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); topicList.getTopicList().addAll(this.topicQueueTable.keySet()); } finally { ...
byte[] topicInfo = routeInfoManager.getAllTopicList(); Assert.assertTrue(topicInfo != null); assertThat(topicInfo).isNotNull(); } }
205819560_2
class AndroidInteropSchedulers { public static Scheduler from(Looper looper) { return from(looper, false); } private AndroidInteropSchedulers(); public static Scheduler mainThread(); @SuppressLint("NewApi") // Checking for an @hide API. public static Scheduler from(Looper looper, boolean...
try { AndroidInteropSchedulers.from(null, false); fail(); } catch (NullPointerException e) { assertEquals("looper == null", e.getMessage()); } } }
205889879_2
class Recording implements Parcelable { public static boolean hasIllegalChar(CharSequence fileName) { Pattern pattern = Pattern.compile("[^a-zA-Z0-9.\\- ]"); Matcher matcher = pattern.matcher(fileName); return matcher.find(); } public Recording(); public Recording(Long id, Lo...
String legalChars = "abcde10ABC.-"; assertFalse(Recording.hasIllegalChar(legalChars)); } }
206005266_15
class LogSequenceNumber implements Comparable<LogSequenceNumber> { public static LogSequenceNumber valueOf(long value) { return new LogSequenceNumber(value); } private LogSequenceNumber(long value); public static LogSequenceNumber valueOf(String strValue); public long asLong(); public String asStrin...
LogSequenceNumber result = LogSequenceNumber.valueOf("0/15D68C50"); assertThat(result, notNullValue()); } }
206101640_11
class AddressService extends BaseNodeAddressService { public ResponseEntity<IResponse> getAddresses(GetHistoryAddressesRequest getHistoryAddressesRequest) { try { if (!getHistoryAddressesRequestCrypto.verifySignature(getHistoryAddressesRequest)) { return ResponseEntity.status(Ht...
GetHistoryAddressesRequest getHistoryAddressesRequest = new GetHistoryAddressesRequest(new ArrayList<>()); //create request without signer hash and signature ResponseEntity<IResponse> expectedResponse = ResponseEntity .status(HttpStatus.UNAUTHORIZED) .body(new Ser...
206137428_4
class Ring implements Iterable<Member> { public Iterable<Member> successors(HashKey location, Predicate<Member> predicate) { Iterator<Member> tail = ring.tailMap(location, false).values().iterator(); Iterator<Member> head = ring.headMap(location, false).values().iterator(); Iterator<Member...
Collection<Member> successors = ring.streamSuccessors(members.get(5), m -> m.equals(members.get(3))) .collect(Collectors.toList()); assertFalse(successors.isEmpty()); assertEquals(7, successors.size()); } }
206303197_1
class DefaultBenchConfigurationResolver implements BenchConfigurationResolver { @Override public String resolve(String parameter) { return resolvers.stream() .map(benchConfigurationResolver -> benchConfigurationResolver.resolve(parameter)) .filter(Objects::nonNull) ....
Assert.assertNotNull(resolver.resolve(ENV_TEST_KEY)); } }
206414745_690
class StaticNodesParser { public static Set<EnodeURL> fromPath( final Path path, final EnodeDnsConfiguration enodeDnsConfiguration) throws IOException, IllegalArgumentException { try { return readEnodesFromPath(path, enodeDnsConfiguration); } catch (FileNotFoundException | NoSuchFileExcept...
final URL resource = StaticNodesParserTest.class.getResource("valid_hostname_static_nodes.json"); final File invalidFile = new File(resource.getFile()); assertThatThrownBy( () -> StaticNodesParser.fromPath( invalidFile.toPath(), EnodeDnsConfiguration....
206662517_4
class RecoveryCodeGenerator { public String[] generateCodes(int amount) { // Must generate at least one code if (amount < 1) { throw new InvalidParameterException("Amount must be at least 1."); } // Create an array and fill with generated codes String[] codes = ...
RecoveryCodeGenerator generator = new RecoveryCodeGenerator(); String[] codes = generator.generateCodes(16); // Assert each one is the correct format for (String code : codes) { assertTrue(code.matches("[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}"), code); } ...
206738246_0
class SuperHeroCreator implements Processor { @Transactional(REQUIRED) Hero add(final String legumeItem) { log.info("Legume received: {}", legumeItem); final Hero hero = Hero.builder() .name("SUPER-" + legumeItem) .capeType(CapeType.SUPERMAN) .bu...
final Hero hero = creator.add("broccoli"); assertNotNull(hero); assertNotNull(hero.getId()); assertEquals("SUPER-broccoli", hero.getName()); } }
206873260_1
class Parser { @NonNull public TextMarkdown parse(@NonNull final String string) { List<Element> parents = new ArrayList<>(); Pattern quotePattern = Pattern.compile(QUOTE_REGEX); Pattern pattern = Pattern.compile(BULLET_POINT_CODE_BLOCK_REGEX); Matcher matcher = quotePattern.ma...
String withQuote = "This is not a quote." + LINE_SEPARATOR + "> This is a quote"; List<Element> elements = new Parser().parse(withQuote).getElements(); assertEquals(elements.size(), 2); assertEquals(elements.get(0).getType(), TEXT); assertEquals(elements.get(0).getText(), "This...
207384523_56
class GraphOperationBuilder implements OperationBuilder { private static void setAttrShape(TF_OperationDescription handle, String name, long[] shape, int numDims) { requireHandle(handle); // num_dims and env->GetArrayLength(shape) are assumed to be consistent. // i.e., either num_dims < 0 or num_dims ==...
try (Graph g = new Graph()) { Output<?> n = g.opBuilder("Placeholder", "unknown") .setAttr("dtype", TFloat32.DTYPE) .setAttr("shape", Shape.unknown()) .build() .output(0); assertEquals(-1, n.shape().numDimensions()); assertEquals(TF...
207497806_29
class EntityService { public UpdateResult updateFields(String originalJsonObject, JsonNode jsonToUpdate, String attrId) throws Exception, ResponseException { logger.trace("updateFields() :: started"); String now = SerializationTools.formatter.format(Instant.now()); JsonNode resultJson = objectMapper.createOb...
try { Mockito.doReturn(blankNode).when(objectMapper).createObjectNode(); Mockito.doReturn(payloadNode).when(objectMapper).readTree(any(String.class)); UpdateResult updateResult=entityService.updateFields(entityPayload,updateJsonNode , null); Assert.assertTrue(updateResult.getStatus()); Assert.ass...
207567112_5
class GreetingController { @RequestMapping(value = {"/greeting/{name}", "/greeting"}) Greeting greeting(@PathVariable(required = false) String name) { String object = name != null ? name : "world"; /* Jack Griffin is the name of the "Invisible Man." */ if (object.equalsIgnoreCase("jack...
assertEquals( greetingController.greeting(name).getMessage(), greeting); } }
207726223_11
class NettyProtocolEncoder extends OneToOneEncoder { @Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { RpcDataPack dataPack = (RpcDataPack) msg; List<ByteBuffer> origs = dataPack.getDataLst(); List<By...
NettyProtocolEncoder nettyProtocolEncoder = new NettyProtocolEncoder(); // build RpcDataPack RpcDataPack obj = new RpcDataPack(); // set serial number obj.setSerialNo(123); List<ByteBuffer> dataList = new LinkedList<ByteBuffer>(); dataList.add(ByteBuffer.wrap("abc...
207822084_5
class AuthorizationService extends EscrowAgentService { @Override public final TreeMap<String, String> getParameters() { TreeMap<String, String> parameters = new TreeMap<>(); if (requestType.equals(PDGuardRequestType.ENCRYPTION)) { if (authBundle instanceof EncryptionBundle) { ...
AuthorizationService service = new AuthorizationService(client, escrowAgent, secure, encryptBundle, requestToken, PDGuardRequestType.ENCRYPTION); SignatureBase signatureBase = new SignatureBase(service.getParameters(), "url", "POST"); Assert.assertNotNull(service....
208015762_1
class ExtensionManager { public static <T, M> T getOrLoadExtension(final Class<T> extensible, final M name) { ExtensionPoint<T, M> spi = SNAPSHOT.getOrLoadExtensionPoint(extensible, null, AscendingComparator.INSTANCE, null); return spi == null ? null : spi.get(name); } public static T getE...
Consumer c1 = ExtensionManager.getOrLoadExtension(Consumer.class); Consumer c2 = ExtensionManager.getOrLoadExtension(Consumer.class); Assert.assertNotNull(c1); Assert.assertEquals(c1, c2); } }
208317627_38
class JarLoader implements ClassFileLoader { protected List<JarEntry> extractEntries(final JarFile jarFile) { final List<JarEntry> result = new ArrayList<>(); if (jarFile != null) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) ...
JarFile jarFile = MockEntities.makeMockJarFile(); List<JarEntry> entries = loader.extractEntries(jarFile); Assert.assertEquals(6, entries.size()); } }
208319207_11
class HttpProtocolGeneratorUtils { static void writeHostPrefix(GenerationContext context, OperationShape operation) { TypeScriptWriter writer = context.getWriter(); SymbolProvider symbolProvider = context.getSymbolProvider(); EndpointTrait trait = operation.getTrait(EndpointTrait.class).get...
GenerationContext mockContext = new GenerationContext(); mockContext.setSymbolProvider(new MockProvider()); TypeScriptWriter writer = new TypeScriptWriter("foo"); mockContext.setWriter(writer); Model model = Model.assembler() .addImport(getClass().getResource("en...
208556644_10
class ExceptionCause { public RuntimeException unwrapped() { Throwable cause = exception.getCause(); if (cause instanceof RuntimeException) { return (RuntimeException) cause; } if (cause == null) { return new IllegalStateException(exception.getMessage()); } return new IllegalStateException(cause); ...
exceptionCauseToTest = new ExceptionCause(exceptionWithCause); RuntimeException unwrapped = exceptionCauseToTest.unwrapped(); assertEquals(exceptionWithoutCause, unwrapped); } }
208698479_12
class DeFiClientManageProcessor implements NettyRequestProcessor { @Override public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws Exception { switch (request.getCode()) { case DeFiBusRequestCode.GET_CONSUMER_LIST_BY_GROUP_AND_TOPIC: ...
ConsumerGroupInfo consumerGroupInfo = deFiBrokerController.getConsumerManager().getConsumerGroupInfo(group); assertThat(consumerGroupInfo).isNotNull(); RemotingCommand request = GetConsumerListCommand(); RemotingCommand response = deFiClientManageProcessor.processRequest(handlerContext,...
209076507_85
class SchemaVersionRange { public static SchemaVersionRange parse(String versionStr) { versionStr = StringUtils.stripToNull(versionStr); Validate.notNull(versionStr, "Version string is blank"); if (isVersionStr(versionStr)) { return parseVersionStr(versionStr); } else ...
SchemaVersionRange range = SchemaVersionRange.parse(" [ 1 , ] "); Assert.assertNotNull(range); Assert.assertEquals(1, range.earliest); Assert.assertEquals(Integer.MAX_VALUE, range.latest); } }
209204932_7
class RowsEvent { public void parsePayload(final BinlogContext binlogContext, final ByteBuf in) { int columnsLength = (int) DataTypesCodec.readLengthCodedIntLE(in); columnsPresentBitmap = DataTypesCodec.readBitmap(columnsLength, in); if (EventTypes.UPDATE_ROWS_EVENT_V1 == binlogEventHeader....
binlogEventHeader.setTypeCode(EventTypes.WRITE_ROWS_EVENT_V2); ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(1); byteBuf.writeByte(1); byteBuf.writeByte(1); RowsEvent actual = new RowsEvent(binlogEventHeader); actual.parsePayload(binlogContext, byteBuf); ...
209392510_23
class AbstractWebhookController { public void init() { try { this.createSubscriptions(); } catch (Exception e) { LOG.error("Error on try to create subscription", e); throw e; } } public AbstractWebhookController(MessageEventCallback messageEventHandler); public AbstractWebhookController( Messag...
subscriptions = new Subscription[] { messageStatusSubscription() }; AbstractClient client = new TestClient("TOKEN"); AbstractWebhookController webhook = new TestWebhookController(messageStatusHandler, client, "http://localhost", ChannelType.whatsapp ); webhook.init(); assertTrue(subscriptionListed); assertF...
209484041_160
class BackupManagerService { public void dataChanged(@UserIdInt int userId, String packageName) { UserBackupManagerService userBackupManagerService = getServiceForUserIfCallerHasPermission(userId, "dataChanged()"); if (userBackupManagerService != null) { userBackupManag...
BackupManagerService backupManagerService = createServiceAndRegisterUser(mUserOneId, mUserOneService); setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false); backupManagerService.dataChanged(mUserOneId, TEST_PACKAGE); verify(mUserOneServ...
209677008_4
class App { public String getGreeting() { return "[SMTP Client] Welcome to SMTP Client."; } public Properties getEmailProperties(String propertiesPath); public String buildPrompt(); public String maskPassword(String password); public void sendEmail(Properties props); public static ...
App classUnderTest = new App(); assertNotNull("app should have a greeting", classUnderTest.getGreeting()); } }
209731679_7
class ImmutableGroup implements CommandGroup { @Nonnull @Override public Set<ImmutableGroup> getChildren() { return children; } private ImmutableGroup( ImmutableGroup parent, Set<String> names, Set<? extends CommandCallable> commands); @Nonnull public static CommandGroup merge(@Nonnull Command...
assertThrows(UnsupportedOperationException.class, () -> group.getChildren().clear(), "children set is not immutable"); } }
209813646_10
class Streams { @NotNull public static <T> ReferencedOptional<T> filterToReference(@NotNull Collection<T> in, @NotNull Predicate<T> predicate) { return ReferencedOptional.build(filter(in, predicate)); } private Streams(); @NotNull public static List<String> toLowerCase(@NotNull Collectio...
Map<String, String> map = new HashMap<>(); map.put("ok", "cool"); map.put("derklaro", "cool"); map.put("reformcloud", "good"); ReferencedOptional<String> optional = Streams.filterToReference(map, t -> t.equals("ok")); Assertions.assertTrue(optional.isPresent()); ...
209854470_7
class PersonController { @GetMapping(value = "/list") public String list(Model model) { logger.info("Populating model with list..."); List<Person> persons = personService.findAll(); persons.sort(COMPARATOR_BY_ID); model.addAttribute("persons", persons); return "persons/...
List<Person> list = new ArrayList<>(); Person p = new Person(); p.setId(1L); list.add(p); when(mockService.findAll()).thenReturn(list); ExtendedModelMap model = new ExtendedModelMap(); String viewName = personController.list(model); List<Person> persons ...
210029529_0
class ProjectComparator { static <K> Comparator<K> create0(DependencyGraph<K> dependencyGraph, Map<String, AtomicLong> historicalServiceTimes, Function<K, String> toKey) { final long defaultServiceTime = average(historicalServiceTimes.values()); final Map<K, Long> serviceTi...
MavenProject a = newProject("a"), b = newProject("b"), c = newProject("c"); TestProjectDependencyGraph graph = new TestProjectDependencyGraph(a, b, c); graph.addDependency(b, a); DependencyGraph<MavenProject> dp = DependencyGraph.fromMaven(graph, null); Comparator<MavenProject> ...
210288653_100
class AbstractDir implements DirInterface { public static String normalizePath(final String path) { return path.replace('\\', SEPARATORCHAR); } protected File getCorrespondingRoot(final File file); public static String pathFromURI(String path); @Override public SessionInterface getSession(); @Override...
assertEquals("single relative filename", "test.dat", AbstractDir.normalizePath("test.dat")); assertEquals("relative path (unix)", "foo/test.dat", AbstractDir.normalizePath("foo/test.dat")); assertEquals("absolute path (unix)", "/foo/test.dat", AbstractDir.n...
210292685_59
class NumberOfTicksCriterion extends AbstractAnalysisCriterion { @Override public double calculate(TimeSeries series, TradingRecord tradingRecord) { int nTicks = 0; for (Trade trade : tradingRecord.getTrades()) { nTicks += calculate(series, trade); } return nTicks; ...
MockTimeSeries series = new MockTimeSeries(100, 105, 110, 100, 95, 105); TradingRecord tradingRecord = new TradingRecord( Order.buyAt(0), Order.sellAt(2), Order.buyAt(3), Order.sellAt(5)); AnalysisCriterion numberOfTicks = new NumberOfTicksCriterion(); as...
210568703_68
class GroupByRowComparator implements Comparator<MemoryResultSetRow> { @Override public int compare(final MemoryResultSetRow o1, final MemoryResultSetRow o2) { if (!selectStatement.getOrderByItems().isEmpty()) { return compare(o1, o2, selectStatement.getOrderByItems()); } re...
MemoryResultSetRow o1 = new MemoryResultSetRow(mockResult("1", "2")); MemoryResultSetRow o2 = new MemoryResultSetRow(mockResult("1", "2")); SelectStatement selectStatement = new SelectStatement(); selectStatement.getGroupByItems().addAll(Arrays.asList(new OrderItem(1, OrderType.ASC), new...
210933087_17
class PatchLogger { public String getName() { return slf4jLogger.getName(); } private PatchLogger(String name); PatchLogger(org.slf4j.Logger logger); public static PatchLogger getLogger(String name); public static PatchLogger getLogger(String name, String resourceBundleName); org.slf4j.Logger g...
Set<MethodSignature> patchLoggerMethods = new HashSet<>(); for (Method method : PatchLogger.class.getMethods()) { MethodSignature methodSignature = new MethodSignature(); methodSignature.name = method.getName(); for (Class<?> clazz : method.getParameterTypes()) { String parameterType =...
210939728_0
class Enforcer { public List<T> absent() { if (this.configured.isEmpty()) { return Collections.emptyList(); } Collection<T> existing = this.existing.get(); return Collections.unmodifiableList( this.configured .stream() .filter(c -> existing.stream().noneMatch(e -...
enforcer = new DummyEnforcer(dummies, () -> singletonList(dummies.get(0))); Assert.assertEquals(singletonList(dummies.get(1)), enforcer.absent()); } }
211090195_79
class CaptionJsonSerializer implements JsonSerializer<Caption> { public Caption deserialize(JSONObject response) throws JSONException { Caption caption = new Caption(); if (response.has("uri")) { caption.setUri(response.getString("uri")); } if (response.has("src")) { ...
assertTrue(captionJsonSerializer.deserialize(new JSONArray()).isEmpty()); } }
211099032_1
class DirectDependencies implements ModelRunner { public static Result calculate(Graph graph) { TraceTraversal<Vertex, Vertex> leafs = graph.traversal(TraceTraversalSource.class).leafSpans(); // service to its dependencies Map<String, Set<String>> dependencies = new LinkedHashMap<>(); // service to ...
Span root = Util.newTrace("root", "root"); Span child = Util.newChild("child", "child", root); Span child2 = Util.newChild("child2", "child2", root); Span child2Child = Util.newChild("child2", "child2Child", child2); Span child2ChildChild = Util.newChild("child2ChildChild", "child2ChildChild", child...
211175076_2
class ApkPathUtils { public String name(final TokenMatcher.State state) { // See: https://wiki.alpinelinux.org/wiki/APKBUILD_Reference#pkgver Pattern pattern = Pattern.compile("(.*)-([.0-9]+[a-zA-Z]?)(_?(alpha|beta|pre|rc|cvs|svn|git|hg|p)?([0-9]+)?)?-r([0-9]+)"); String filename = match(state, "fi...
when(state.getTokens()).thenReturn(tokens); when(tokens.get("filename")).thenReturn("lua5.3-libs-5.3.5-r2"); assertThat(underTest.name(state), is(equalTo("lua5.3-libs"))); } }
211330796_63
class ST_Loc extends STBase { public String parent() { int indexOf = loc.lastIndexOf('/'); if (indexOf == -1) { return ""; } return loc.substring(0, indexOf); } public ST_Loc(String path); public static ST_Loc getInstance(String loc); public static ST_...
ST_Loc loc = new ST_Loc("Doc_9/Pages/Page_0/Content.xml"); assertEquals("Doc_9/Pages/Page_0", loc.parent()); loc = new ST_Loc("Content.xml"); assertEquals("", loc.parent()); } }
211971342_16
class ApplicationsService implements ApplicationsApi { @Override public void deleteApplication(final String applicationId) { log.info("Deleting application {}", applicationId); ApplicationRecord applicationRecord = loadApplication(applicationId); Map<String, AttributeValue> expressionAttributeValues = ...
String userId = UUID.randomUUID().toString(); String applicationId = UUID.randomUUID().toString(); Long version = 1L; Map<String, AttributeValue> recordMap = keyMap(userId, applicationId); recordMap.put("version", AttributeValue.builder().n(version.toString()).build()); GetItemResponse response ...
212300461_2
class ClusterH2DaoImpl implements ClusterDao { @Override public ClusterEntity selectByCluster(String cluster) { return transferEntity(clusterJpaRepository.findFirstByAndCluster(cluster)); } @Override public void insert(ClusterEntity clusterEntity); @Override @Transactional public void upda...
ClusterH2Entity envH2Entity = insertOneData(); ClusterEntity envEntity = clusterDao.selectByCluster(envH2Entity.getCluster()); Assert.assertNotNull(envEntity); assertEqualWithIgnore(envH2Entity, envEntity, "id"); clusterJpaRepository.deleteById(envH2Entity.getId()); } }
212338967_8
class UserDao { void create(User user) { entityManager.persist(user); } User read(int id); void update(User user); void delete(int id); User readByName(String name); List<User> readAll(); @Mock private EntityManager entityManager; @InjectMocks private UserDao userDao; } class UserDao...
User user = new User(); userDao.create(user); Mockito.verify(entityManager).persist(user); } }
212382406_249
class RDBStore implements DBStore { @Override public ArrayList<Table> listTables() { ArrayList<Table> returnList = new ArrayList<>(); for (ColumnFamilyHandle handle : handleTable.values()) { returnList.add(new RDBTable(db, handle, writeOptions, rdbMetrics)); } return returnList; } @Visib...
List<Table> tableList = rdbStore.listTables(); Assert.assertNotNull("Table list cannot be null", tableList); Map<String, Table> hashTable = new HashMap<>(); for (Table t : tableList) { hashTable.put(t.getName(), t); } int count = families.size(); // Assert that we have all the tables...
212625733_13
class Path { public boolean matches(String toMatch) { return matches(new Path(toMatch)); } public Path(); public Path(Path path); public Path(String... part); public Path(List<String> parts); public List<String> parts(); public String first(); public String last(); ...
assertTrue(new Path("[{^$}]").matches("")); assertTrue(new Path("*").matches("/something/asdfas/")); assertTrue(new Path("*").matches("something/asdfas/")); assertTrue(new Path("something/{collection:books|customers}").matches("something/books")); assertTrue(new Path("something/...
212816799_1
class SinkUtils { public static int getProperty(Map<String, String> props, String propertyName, int defaultValue) { if (props != null) { String propertyValue = props.get(propertyName); if (StringUtils.isNotBlank(propertyValue)) { return Integer.parseInt(propertyValue); } } retu...
assertEquals(TEST_VALUE, SinkUtils.getProperty( ImmutableMap.of(TEST_KEY, String.valueOf(TEST_VALUE)), TEST_KEY, TEST_DEFAULT_VALUE )); } }
212938936_3
class LibraAccountService { public LibraBalance getBalance(String libraAddress) { LibraBalance libraBalance = new LibraBalance(); Long balance = jLibraUtil.findBalance(libraAddress); libraBalance.setLibra(balance/1000000); libraBalance.setLibraMicro(balance); libraBalance.se...
LibraAccount account = libraAccountService.findAccount(1L); LibraBalance balance = libraAccountService.getBalance(account.getLibraAddressToString()); Assert.assertTrue(balance.getLibra() > 0); } }
213330914_0
class TokenGenerator { @Nonnull String getToken(@Nonnull final TokenConfig tokenConfig, @Nonnull final String issuer) { JwtBuilder builder = Jwts.builder() .setHeaderParam("kid", KEY_ID) // since the specification allows for more than one audience, but JJWT only accepts ...
String token = generator.getToken( aTokenConfig() .withAudience(AUDIENCE) .withAuthorizedParty(AUTHORIZED_PARTY) .withSubject(SUBJECT) .withScope(SCOPE) .withRealmRoles(REALM_ROLES) .withResourceRoles...
213344827_96
class ConsumedThingProperty extends ThingProperty<T> { public Observable<Optional<T>> observer() throws ConsumedThingException { try { Pair<ProtocolClient, Form> clientAndForm = thing.getClientFor(getForms(), Operation.OBSERVE_PROPERTY); ProtocolClient client = clientAndForm.first()...
when(thing.getClientFor(any(List.class), any())).thenReturn(new Pair(client, form)); when(client.writeResource(any(), any())).thenReturn(completedFuture(null)); when(client.observeResource(any())).thenReturn(observable); ConsumedThingProperty<Object> consumedThingProperty = new Consumed...
213594368_20
class VariableAqlPath { public boolean isPartialAqlDataValuePath(){ return getSuffix().matches(jsonPathQualifierMatcher); } public VariableAqlPath(String path); public String getSuffix(); public String getInfix(); } class VariableAqlPathTest { @Test public void testIsPartialAq...
String aPath = "data[at0001]/events[at0002]/data[at0003]/items[at0007]/value"; assertTrue(new VariableAqlPath(aPath).isPartialAqlDataValuePath()); aPath = "data[at0001]/events[at0002]/data[at0003]/items[at0007]/value/magnitude"; assertFalse(new VariableAqlPath(aPath).isPartialAqlDataV...
213687575_123
class Polygon extends BasePointCollection { public int getFillColor() { return fillColor; } Polygon(); public int getStrokeColor(); public List<List<LatLng>> getHoles(); public void setFillColor(int color); public void setStrokeColor(int color); public void setHoles(@NonNull List<? extends List...
Polygon polygon = new PolygonOptions().fillColor(1).getPolygon(); assertEquals(1, polygon.getFillColor()); } }