auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { <START> Thread.sleep( 1000 ); <END> population.flip(); populations.remove( population ); } catch ( Throwable t ) { fail( population, t ); } } }</code><technical_language>right, fast lets give a cpu some time sleep :)</technical_language>

Target:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { population.flip(); } catch ( Throwable t ) { fail( population, t ); } } }
Source:
<code>private void increaseComplexity(Tree tree, int increase) { complexity += increase; <START> if(!ignored.contains(tree)) { <END> int reportedValue = increase - nestingAdjustment; String message = "+" + reportedValue; if (reportedValue > 1) { message += " (incl " + (reportedValue - 1) + " for nesting)"; } nestingAdjustment = 0; flow.add(new JavaFileScannerContext.Location(message, tree)); } }</code><technical_language>I wrong adding succeeding if tree set achieve purpose simplier</technical_language>

Target:
private void increaseComplexity(Tree tree, int increase) { complexity += increase; if (ignoreNesting) { flow.add(new JavaFileScannerContext.Location("+1", tree)); ignoreNesting = false; } else if (!ignored.contains(tree)) { String message = "+" + increase; if (increase > 1) { message += " (incl " + (increase - 1) + " for nesting)"; } flow.add(new JavaFileScannerContext.Location(message, tree)); } }
Source:
<code><START> public void exact_match_in_one_qualifier() throws IOException { <END> ComponentDto project = db.components().insertComponent(newProjectDto(organization)); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project); SuggestionsWsResponse response = SuggestionsWsResponse.parseFrom(actionTester.newRequest() .setMethod("POST") .setMediaType(PROTOBUF) .setParam(URL_PARAM_QUERY, project.getKey()) .execute() .getInputStream()); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(SuggestionsWsResponse.Qualifier::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(SuggestionsWsResponse.Qualifier::getItemsList) .extracting(WsComponents.Component::getKey, WsComponents.Component::getOrganization) .containsExactly(tuple(project.getKey(), organization.getKey())); }</code><technical_language>throws Exception is good enough in unit tests. need more exact</technical_language>

Target:
public void exact_match_in_one_qualifier() throws Exception { ComponentDto project = db.components().insertComponent(newProjectDto(organization)); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project); SuggestionsWsResponse response = actionTester.newRequest() .setMethod("POST") .setParam(PARAM_QUERY, project.getKey()) .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(Category::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getKey, Suggestion::getOrganization) .containsExactly(tuple(project.getKey(), organization.getKey())); }
Source:
<code><START> public AuditProto.AttemptAuditEventResult convert(AttemptAuditEventResult source) { <END> AuditProto.AttemptAuditEventResult.Builder attemptAuditEventResultBuilder = builderProvider.prepareBuilderForCreateAuditEvent(source); updateResultEventData(attemptAuditEventResultBuilder, source.getResultEventData()); return attemptAuditEventResultBuilder.build(); }</code><technical_language>is reason this? besides, is consistent other converter class</technical_language>

Target:
public AuditProto.AttemptAuditEventResult convert(AttemptAuditEventResult source) { AuditProto.AttemptAuditEventResult.Builder builder = builderProvider.getNewAttemptAuditEventResultBuilder() .setId(source.getId()) .setResultCode(source.getResultCode()); doIfTrue(source.getResultMessage(), StringUtils::isNotEmpty, builder::setResultMessage); updateResultEventData(builder, source.getResultEventData()); return builder.build(); }
Source:
<code>public static void checkTableIsWritable(Table table, boolean writesToNonManagedTablesEnabled) { if (!writesToNonManagedTablesEnabled && !table.getTableType().equals(MANAGED_TABLE.toString()) && !table.isTemporary()) { throw new PrestoException(NOT_SUPPORTED, "Cannot write to non-managed Hive table"); } <START> checkWritable( <END> new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), getProtectMode(table), table.getParameters(), table.getStorage()); }</code><technical_language>nit: exception message cover temp table</technical_language>

Target:
public static void checkTableIsWritable(Table table, boolean writesToNonManagedTablesEnabled) { PrestoTableType tableType = table.getTableType(); if (!writesToNonManagedTablesEnabled && !tableType.equals(MANAGED_TABLE) && !tableType.equals(TEMPORARY_TABLE)) { throw new PrestoException(NOT_SUPPORTED, "Cannot write to non-managed Hive table"); } checkWritable( new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), getProtectMode(table), table.getParameters(), table.getStorage()); }
Source:
<code>private ResponseEntity<String> sendPasswordLostMail(User parsedUser, String oneTimePassword) throws MessagingException, IOException { Optional<String> email = RegistrationHelper.extractSendToEmail(parsedUser); if (!email.isPresent()) { LOGGER.log(Level.WARNING, "No primary email found!"); <START> return new ResponseEntity<>("{\"error\":\"No primary email found!\"}", HttpStatus.BAD_REQUEST); <END> } StringBuilder activateURL = new StringBuilder(passwordlostLinkPrefix); activateURL.append("userId=").append(parsedUser.getId()); activateURL.append("&oneTimePassword=").append(oneTimePassword); Map<String, String> vars = new HashMap<>(); vars.put("$PASSWORDLOSTURL", activateURL.toString()); InputStream mailContentStream = mailSender.getEmailContentAsStream("/WEB-INF/registration/passwordlostmail-content.txt", pathToEmailContent, context); if (mailContentStream == null) { LOGGER.log(Level.SEVERE, "Cant open registermail-content.txt on classpath! Please configure!"); return new ResponseEntity<>( "{\"error\":\"Cant open registermail-content.txt on classpath! Please configure!\"}", HttpStatus.INTERNAL_SERVER_ERROR); } mailSender.sendMail(passwordlostMailFrom, email.get(), passwordlostMailSubject, mailContentStream, vars); return new ResponseEntity<>(HttpStatus.OK); }</code><technical_language>search for primary email anymore</technical_language>

Target:
private ResponseEntity<String> sendPasswordLostMail(User parsedUser, String oneTimePassword) throws MessagingException, IOException { Optional<String> email = RegistrationHelper.extractSendToEmail(parsedUser); if (!email.isPresent()) { LOGGER.log(Level.WARNING, "Could not change password. No email of user " + parsedUser.getUserName() + " found!"); return new ResponseEntity<>("{\"error\":\"Could not change password. No email of user " + parsedUser.getUserName() + " found!\"}", HttpStatus.BAD_REQUEST); } StringBuilder activateURL = new StringBuilder(passwordlostLinkPrefix); activateURL.append("userId=").append(parsedUser.getId()); activateURL.append("&oneTimePassword=").append(oneTimePassword); Map<String, String> vars = new HashMap<>(); vars.put("$PASSWORDLOSTURL", activateURL.toString()); InputStream mailContentStream = mailSender.getEmailContentAsStream("/WEB-INF/registration/passwordlostmail-content.txt", pathToEmailContent, context); if (mailContentStream == null) { LOGGER.log(Level.SEVERE, "Cant open registermail-content.txt on classpath! Please configure!"); return new ResponseEntity<>( "{\"error\":\"Cant open registermail-content.txt on classpath! Please configure!\"}", HttpStatus.INTERNAL_SERVER_ERROR); } mailSender.sendMail(passwordlostMailFrom, email.get(), passwordlostMailSubject, mailContentStream, vars); return new ResponseEntity<>(HttpStatus.OK); }
Source:
<code><START> public synchronized void init(ByteBuffer buffer, int position) <END> { MergingDigest emptyDigest = new MergingDigest(compression); addToMap(buffer, position, emptyDigest); }</code><technical_language>here. synchronize methods</technical_language>

Target:
public void init(ByteBuffer buffer, int position) { MergingDigest emptyDigest = new MergingDigest(compression); addToCache(buffer, position, emptyDigest); }
Source:
<code>public static Object[][] adsVUAPTopDesktop() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), ImmutableMap.of("src", "gpt", "slotName", AdsContent.TOP_LB) <START> <END> } }; }</code><technical_language>This empty is unnecessary, I :)</technical_language>

Target:
public static Object[][] adsVUAPTopDesktop() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), AdsContent.TOP_LB, String.format( "google_ads_iframe_/5441/wka.life/_project43 AdsContent.TOP_LB ) } }; }
Source:
<code>public void expireDynamicConfigWithCustomExpiration() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); <START> Thread.sleep(6000); <END> HeisenbergExtension anotherConfig = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); assertExpired(config, 5000, 1000); assertInitialised(config); }</code><technical_language>a probe instead of thread sleep</technical_language>

Target:
public void expireDynamicConfigWithCustomExpiration() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); try { assertExpired(config, 5000, 1000); } catch (AssertionError e) { HeisenbergExtension anotherConfig = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); } assertExpired(config, 5000, 1000); assertInitialised(config); }
Source:
<code>public static boolean isWikimediaHost(String host) { <START> int MAX_REFERER_LENGTH = 5000; <END> if(host.length() > MAX_REFERER_LENGTH) return false; return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }</code><technical_language>this a class "constant" variable, elsewhere. 5000 is long, length similar UA, 400 chars</technical_language>

Target:
public static boolean isWikimediaHost(String host) { if (host.length() > MAX_ADDRESS_LENGTH) return false; return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }
Source:
<code>private void generateAPIResponse(ServletRequest request, ServletResponse response) throws IOException { response.setContentType(request.getContentType()); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", "Server is under maintenance mode, please try later."); response.getWriter().print(jsonObject); <START> ((HttpServletResponse) response).setStatus(503); <END> }</code><technical_language>+1: 503</technical_language>

Target:
private void generateAPIResponse(ServletRequest request, ServletResponse response) { try { HttpServletRequest httpRequest = (HttpServletRequest) request; String message = "Server is under maintenance mode, please try later."; if (requestIsOfType(JSON, httpRequest)) { response.setContentType("application/json"); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", message); response.getWriter().print(jsonObject); } else if (requestIsOfType(XML, httpRequest)) { response.setContentType("application/xml"); String xml = String.format("<message> %s </message>", message); response.getWriter().print(xml); } else { generateHTMLResponse(response); } } catch (IOException e) { LOGGER.error(String.format("General IOException", e.getMessage())); } ((HttpServletResponse) response).setStatus(503); }
Source:
<code>public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { Transaction tx = getFromOperation(get); if (tx != null) { <START> boolean excludeCurrentWritePtr = isAttributeSet(get, TxConstants.TX_EXCLUDE_CURRENT_WRITE); <END> projectFamilyDeletes(get); get.setMaxVersions(); get.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = Filters.combine(getTransactionFilter(tx, ScanType.USER_SCAN, excludeCurrentWritePtr), get.getFilter()); get.setFilter(newFilter); } }</code><technical_language>@abaranau other visibility constraints - excluding uncommitted write versions - attributes of transaction, individual request. I simply suggesting follow existing model. Code is more maintainable if do similar in similar ways</technical_language>

Target:
public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { Transaction tx = getFromOperation(get); if (tx != null) { projectFamilyDeletes(get); get.setMaxVersions(); get.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = Filters.combine(getTransactionFilter(tx, ScanType.USER_SCAN), get.getFilter()); get.setFilter(newFilter); } }
Source:
<code>public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); startDefaultAgent(testHost()); awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES); final JobId jobId = createJob(testJobName, testJobVersion, BUSYBOX, IDLE_COMMAND, <START> DateTime.now().plusSeconds(10).toDate()); <END> deployJob(jobId, testHost()); TaskStatus taskStatus = awaitJobState( client, testHost(), jobId, RUNNING, WAIT_TIMEOUT_SECONDS, SECONDS); Polling.await(3, MINUTES, new Callable<JobId>() { @Override public JobId call() throws Exception { if (client.jobs().get().containsKey(jobId)) { return null; } else { return jobId; } } }); final ContainerExit exit1 = docker.waitContainer(taskStatus.getContainerId()); assertThat(exit1.statusCode(), is(-1)); }</code><technical_language>+2 spaces</technical_language>

Target:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); startDefaultAgent(testHost()); awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES); final JobId jobId = createJob(testJobName, testJobVersion, BUSYBOX, IDLE_COMMAND, DateTime.now().plusSeconds(10).toDate()); deployJob(jobId, testHost()); TaskStatus taskStatus = awaitJobState( client, testHost(), jobId, RUNNING, WAIT_TIMEOUT_SECONDS, SECONDS); Polling.await(3, MINUTES, new Callable<JobId>() { @Override public JobId call() throws Exception { if (client.jobs().get().containsKey(jobId)) { return null; } else { return jobId; } } }); final ContainerExit exit = docker.waitContainer(taskStatus.getContainerId()); assertThat(exit.statusCode(), is(-1)); }
Source:
<code>public void beforeClass() throws Exception { super.beforeClass(); System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); <START> Assert.assertTrue(_clusterVerifier.verifyByPolling()); <END> _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); }</code><technical_language>Duplicate code</technical_language>

Target:
public void beforeClass() throws Exception { super.beforeClass(); System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis())); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(_clusterVerifier.verifyByPolling()); _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); }
Source:
<code>public FacilityCreated(Facility facility) { this.facility = facility; <START> this.message = formatMessage("Facility created: %s",facility); <END> }</code><technical_language>I afraid this message is one: getPerunBl().getAuditer().log(sess, "Facility created {}.", facility);</technical_language>

Target:
public FacilityCreated(Facility facility) { this.facility = facility; this.message = formatMessage("Facility created %s.",facility); }
Source:
<code>private void generateIndexes() { mongoOperations.getCollection(collection).createIndex(new BasicDBObject( DBObjectToVariantConverter.CHROMOSOME_FIELD, 1) .append(DBObjectToVariantConverter.START_FIELD, 1) .append(DBObjectToVariantConverter.END_FIELD, 1) <START> .append("background", true)); <END> mongoOperations.getCollection(collection).createIndex(new BasicDBObject( DBObjectToVariantConverter.IDS_FIELD, 1).append("background", true)); String filesStudyIdField = String.format("%s.%s", DBObjectToVariantConverter.FILES_FIELD, DBObjectToVariantSourceEntryConverter.STUDYID_FIELD); String filesFileIdField = String.format("%s.%s", DBObjectToVariantConverter.FILES_FIELD, DBObjectToVariantSourceEntryConverter.FILEID_FIELD); mongoOperations.getCollection(collection).createIndex( new BasicDBObject(filesStudyIdField, 1).append(filesFileIdField, 1).append("background", true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject( "annot.xrefs.id", 1).append("background", true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject("annot", 1).append("background", true)); }</code><technical_language>This block is weirdly indented</technical_language>

Target:
private void generateIndexes() { mongoOperations.getCollection(collection).createIndex(new BasicDBObject( VariantToDBObjectConverter.CHROMOSOME_FIELD, 1).append(VariantToDBObjectConverter.START_FIELD, 1) .append(VariantToDBObjectConverter.END_FIELD, 1) .append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection).createIndex(new BasicDBObject( VariantToDBObjectConverter.IDS_FIELD, 1).append(BACKGROUND_INDEX, true)); String filesStudyIdField = String.format("%s.%s", VariantToDBObjectConverter.FILES_FIELD, VariantSourceEntryToDBObjectConverter.STUDYID_FIELD); String filesFileIdField = String.format("%s.%s", VariantToDBObjectConverter.FILES_FIELD, VariantSourceEntryToDBObjectConverter.FILEID_FIELD); mongoOperations.getCollection(collection).createIndex( new BasicDBObject(filesStudyIdField, 1).append(filesFileIdField, 1).append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection) .createIndex(new BasicDBObject(ANNOTATION_XREF_ID_FIELD, 1).append(BACKGROUND_INDEX, true)); mongoOperations.getCollection(collection) .createIndex(new BasicDBObject(ANNOTATION_FIELD, 1).append(BACKGROUND_INDEX, true)); }
Source:
<code>public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { if <START> (active) <END> { return VolumeClassification.Volume; } return VolumeClassification.Snapshot; } return volumeClassification; }</code><technical_language>please change ternary</technical_language>

Target:
public VolumeClassification getVolumeClassification() { if (volumeClassification == null) { return (active ? VolumeClassification.Volume : VolumeClassification.Snapshot); } return volumeClassification; }
Source:
<code>public static final String formatPercentage(double value) { NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); String result = percentFormat.format(value); <START> return result; <END> }</code><technical_language>get rid of String result declaration combine lines return percentFormat.format(value);</technical_language>

Target:
public static final String formatPercentage(double value) { NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); return percentFormat.format(value); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GenericGraph that = (GenericGraph) o; <START> return Objects.equals(jungGraph, that.jungGraph) && <END> Objects.equals(vertexToIdMap, that.vertexToIdMap) && Objects.equals(edgeToIdMap, that.edgeToIdMap) && Objects.equals(focusStrategy, that.focusStrategy) && Objects.equals(graphInfo, that.graphInfo); }</code><technical_language>Please put && beginning of next line. easier read</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GenericGraph that = (GenericGraph) o; return Objects.equals(vertexToIdMap, that.vertexToIdMap) && Objects.equals(edgeToIdMap, that.edgeToIdMap) && Objects.equals(focusStrategy, that.focusStrategy); }
Source:
<code>public ListenableFuture<?> isBlocked() { switch (state) { case CONSUMING_INPUT: return NOT_BLOCKED; case SPILLING_INPUT: return spillInProgress; case LOOKUP_SOURCE_BUILT: <START> return lookupSourceNotNeeded.get(); <END> case LOOKUP_SOURCE_SPILLED: return spilledLookupSourceHandle.getUnspillingOrDisposeRequested(); case LOOKUP_SOURCE_UNSPILLING: return unspillInProgress.get(); case LOOKUP_SOURCE_UNSPILLED_AND_BUILT: return spilledLookupSourceHandle.getDisposeRequested(); case DISPOSED: return lookupSourceFactoryDestroyed; } throw new IllegalStateException("Unhandled state: " + state); }</code><technical_language>add checkState(lookupSourceNotNeeded.isPresent(), "Lookup source built, xxxx set");</technical_language>

Target:
public ListenableFuture<?> isBlocked() { switch (state) { case CONSUMING_INPUT: return NOT_BLOCKED; case SPILLING_INPUT: return spillInProgress; case LOOKUP_SOURCE_BUILT: return lookupSourceNotNeeded.orElseThrow(() -> new IllegalStateException("Lookup source built, but disposal future not set")); case INPUT_SPILLED: return spilledLookupSourceHandle.getUnspillingOrDisposeRequested(); case INPUT_UNSPILLING: return unspillInProgress.orElseThrow(() -> new IllegalStateException("Unspilling in progress, but unspilling future not set")); case INPUT_UNSPILLED_AND_BUILT: return spilledLookupSourceHandle.getDisposeRequested(); case DISPOSED: return lookupSourceFactoryDestroyed; } throw new IllegalStateException("Unhandled state: " + state); }
Source:
<code>public void signupViaFacebook(String code, String state) { if (code == null) { includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } try { String rawToken = facebook.buildToken(code); SignupInfo signupInfo = facebook.getSignupInfo(); User existantFacebookUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.FACEBOOK); if (existantFacebookUser != null) { access.login(existantFacebookUser); redirectToRightUrl(state); return; } User existantGoogleUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.GOOGLE); if (existantGoogleUser != null) { mergeLoginMethod.mergeLoginMethods(rawToken, existantGoogleUser, MethodType.FACEBOOK); logMessages(existantGoogleUser); redirectToRightUrl(state); return; } User existantBrutalUser = users.findByEmailAndMethod(signupInfo.getEmail(), MethodType.BRUTAL); if (existantBrutalUser != null) { mergeLoginMethod.mergeLoginMethods(rawToken, existantBrutalUser, MethodType.FACEBOOK); logMessages(existantBrutalUser); redirectToRightUrl(state); return; <START> } <END> createNewUser(rawToken, signupInfo); redirectToRightUrl(state); } catch (IllegalArgumentException e) { LOG.error("unable to signup user with facebook", e); includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } }</code><technical_language>This ifs pratically - This method grow for loginmethod added, avoid this. inject a List<LoginMergeStrategy> help</technical_language>

Target:
public void signupViaFacebook(String code, String state) { if (code == null) { includeAsList("messages", i18n("error", "error.signup.facebook.unknown")); redirectTo(SignupController.class).signupForm(); return; } Token token = service.getAccessToken(null, new Verifier(code)); SocialAPI facebookAPI = new FacebookAPI(service, token); loginManager.merge(MethodType.FACEBOOK, facebookAPI); redirectToRightUrl(state); }
Source:
<code>public Map<String, Object> toMap() { Base64.Encoder encoder = Base64.getUrlEncoder(); <START> HashMap<String, Object> map = new HashMap(); <END> map.put("credentialId", encoder.encodeToString(id)); map.put("isResidentCredential", isResidentCredential); map.put("rpId", rpId); map.put("privateKey", encoder.encodeToString(privateKey.getEncoded())); if (userHandle != null) map.put("userHandle", encoder.encodeToString(userHandle)); map.put("signCount", signCount); return map; }</code><technical_language>Nit: Map LHS. matter a huge amount, curious ImmutableMap here</technical_language>

Target:
public Map<String, Object> toMap() { Base64.Encoder encoder = Base64.getUrlEncoder(); Map<String, Object> map = new HashMap<String, Object>(); map.put("credentialId", encoder.encodeToString(id)); map.put("isResidentCredential", isResidentCredential); map.put("rpId", rpId); map.put("privateKey", encoder.encodeToString(privateKey.getEncoded())); map.put("signCount", signCount); if (userHandle != null) { map.put("userHandle", encoder.encodeToString(userHandle)); } return Collections.unmodifiableMap(map); }
Source:
<code>public RequestListener(int port, LionConfChange lionConfChange, HttpClientSingle cmdbHttpClient) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); <START> reqistry.register("/search*", new HttpSearchHandler()); <END> reqistry.register("/scaleout*", new HttpScalaoutHandler(lionConfChange, cmdbHttpClient)); reqistry.register("*", new HttpFallbackHandler()); this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }</code><technical_language>remove</technical_language>

Target:
public RequestListener(int port, LionConfChange lionConfChange, HttpClientSingle cmdbHttpClient) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/scaleout*", new HttpScalaoutHandler(lionConfChange, cmdbHttpClient)); reqistry.register("*", new HttpFallbackHandler()); this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
Source:
<code><START> public void test() { <END> TestNG tng = create(ParameterInjectAndOptionSample.class); tng.run(); }</code><technical_language>adding assertion here. add a listener check ensure failed methods</technical_language>

Target:
public void test() { TestNG tng = create(ParameterInjectAndOptionSample.class); TestListenerAdapter tla = new TestListenerAdapter(); tng.addListener((ITestNGListener) tla); tng.run(); Assert.assertEquals(tla.getPassedTests().size(), 1); }
Source:
<code>public void close() { if (isClosed.compareAndSet(false, true)) { <START> ShutdownRunner shutdownRunner = new ShutdownRunner(); <END> shutdownRunner.runShutdownCallbackSafely(super::close); shutdownRunner.runShutdownCallbackSafely(cleaner::close); shutdownRunner.runShutdownCallbackSafely(keyValueService::close); shutdownRunner.runShutdownCallbackSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.runShutdownCallbackSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.runShutdownCallbackSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.runShutdownCallbackSafely(callback); } shutdownRunner.runShutdownCallbackSafely(metricsManager::deregisterMetrics); if (shutdownRunner.isFailed()) { throw new SafeRuntimeException("Close failed."); } } }</code><technical_language>curious if try-with-resources @Override @SuppressWarnings("unused") // try-with-resources closes public void close() { if (isClosed.compareAndSet(false, true)) { SafeRuntimeException exception = new SafeRuntimeException("Close failed."); try { try (AutoCloseable closeParent = super::close; AutoCloseable closeCleaner = cleaner; AutoCloseable closeKvs = keyValueService; AutoCloseable closeDelegate = () -> shutdownExecutor(deleteExecutor); AutoCloseable closeRanges = () -> shutdownExecutor(getRangesExecutor); AutoCloseable closeLockServiceIfPossible = this::closeLockServiceIfPossible; AutoCloseable closeMetrics = metricsManager::deregisterMetrics) { log.info("Shutting transaction manager"); for (Runnable callback : Lists.reverse(closingCallbacks)) { try (AutoCloseable closeCallback = callback::run) { log.info("Closing callback"); } catch (Throwable t) { exception.addSuppressed(t); } } } } catch (Exception e) { exception.initCause(e); throw exception; } } }</technical_language>

Target:
public void close() { if (!isClosed.compareAndSet(false, true)) { return; } try (ShutdownRunner shutdownRunner = new ShutdownRunner()) { shutdownRunner.shutdownSafely(super::close); shutdownRunner.shutdownSafely(cleaner::close); shutdownRunner.shutdownSafely(keyValueService::close); shutdownRunner.shutdownSafely(() -> shutdownExecutor(deleteExecutor)); shutdownRunner.shutdownSafely(() -> shutdownExecutor(getRangesExecutor)); shutdownRunner.shutdownSafely(this::closeLockServiceIfPossible); for (Runnable callback : Lists.reverse(closingCallbacks)) { shutdownRunner.shutdownSafely(callback); } shutdownRunner.shutdownSafely(metricsManager::deregisterMetrics); } }
Source:
<code>public SessionCacheCleaner( SchemaFactory<ReviewDb> reviewDbFactory, @Named(WebSession.CACHE_NAME) final Cache<ActiveSession.Key, ActiveSession> cache) throws OrmException { <START> this.activeSessionAccess = reviewDbFactory.open().activeSessions(); <END> this.cache = cache; }</code><technical_language>Please hold database connection for 12 hours, open close run method time execute. borrowed a small pool, keeping tied for hours friendly other threads in JVM</technical_language>

Target:
public SessionCacheCleaner( SchemaFactory<ReviewDb> reviewDbFactory, @Named(WebSession.CACHE_NAME) final Cache<ActiveSession.Key, ActiveSession> cache) { this.reviewDbFactory = reviewDbFactory; this.cache = cache; }
Source:
<code>public PythonProgramOptions(CommandLine line) throws CliArgsException { super(line); <START> isPython = isPython(line); <END> pythonConfiguration = PythonDependencyUtils.parsePythonDependencyConfiguration(line); if (entryPointClass == null) { entryPointClass = "org.apache.flink.client.python.PythonDriver"; } }</code><technical_language>name isPython is confusing. Considering class PythonProgramOptions is for Python, true? I guess isEntryPointPython? If rename variable isPython util method isPython isEntryPointPython. do think</technical_language>

Target:
public PythonProgramOptions(CommandLine line) throws CliArgsException { super(line); isPythonEntryPoint = isPythonEntryPoint(line); pythonConfiguration = PythonDependencyUtils.parsePythonDependencyConfiguration(line); if (entryPointClass == null) { entryPointClass = "org.apache.flink.client.python.PythonDriver"; } }
Source:
<code>public void run() throws Exception { List<ReportParam> partialReport1 = Lists.newArrayList( new ReportParam("param1.paramA.I", "3"), new ReportParam("param1.paramA.III", "6"), new ReportParam("param1.paramB", "4")); List<ReportParam> partialReport2 = Lists.newArrayList( new ReportParam("param2", "12"), new ReportParam("param1.paramA.II", "2")); AvroTestUtils.createLocalAvroDataStore(partialReport1, inputPartialReportsBasePath + "/report1"); AvroTestUtils.createLocalAvroDataStore(partialReport2, inputPartialReportsBasePath + "/report2"); PortBindings portBindings = new PortBindings( ImmutableMap.of("partial_reports", new Path(inputPartialReportsBasePath)), ImmutableMap.of("report", new Path(outputReportPath))); Configuration conf = new Configuration(false); reportMerger.run(portBindings, conf, Collections.emptyMap()); JsonObject actualReportJson = readJson(outputReportPath); <START> String expectedReportJsonString = "{" <END> + " param1: {" + " paramA: {" + " I: 3," + " II: 2," + " III: 6" + " }," + " paramB: 4" + " }," + " param2: 12" + "}"; JsonObject expectedJsonReport = jsonParser.parse(expectedReportJsonString).getAsJsonObject(); assertEquals(expectedJsonReport, actualReportJson); }</code><technical_language>is hard maintain JSON XML code defined in java. easier defined in external file reading classpath</technical_language>

Target:
public void run() throws Exception { List<ReportParam> partialReport1 = Lists.newArrayList( new ReportParam("param1.paramA.I", "3"), new ReportParam("param1.paramA.III", "6"), new ReportParam("param1.paramB", "4")); List<ReportParam> partialReport2 = Lists.newArrayList( new ReportParam("param2", "12"), new ReportParam("param1.paramA.II", "2")); AvroTestUtils.createLocalAvroDataStore(partialReport1, inputPartialReportsBasePath + "/report1"); AvroTestUtils.createLocalAvroDataStore(partialReport2, inputPartialReportsBasePath + "/report2"); PortBindings portBindings = new PortBindings( ImmutableMap.of("partial_reports", new Path(inputPartialReportsBasePath)), ImmutableMap.of("report", new Path(outputReportPath))); Configuration conf = new Configuration(false); reportMerger.run(portBindings, conf, Collections.emptyMap()); JsonObject actualReportJson = readJson(outputReportPath); JsonObject expectedJsonReport = readJsonFromClasspath("/eu/dnetlib/iis/common/report/report_merged.json"); assertEquals(expectedJsonReport, actualReportJson); }
Source:
<code>public synchronized void startBackgroundScanning() { if (backgroundScanningJob == null) { backgroundScanningJob = scheduler.scheduleWithFixedDelay(() -> { singleScanInternal(false); }, 0, pauseBetweenScans.getSeconds(), TimeUnit.SECONDS); <START> logger.debug("Scheduled usb-serial background discovery every seconds", pauseBetweenScans.getSeconds()); <END> } }</code><technical_language>**USB**-serial</technical_language>

Target:
public synchronized void startBackgroundScanning() { if (backgroundScanningJob == null) { backgroundScanningJob = scheduler.scheduleWithFixedDelay(() -> { singleScanInternal(false); }, 0, pauseBetweenScans.getSeconds(), TimeUnit.SECONDS); logger.debug("Scheduled USB-Serial background discovery every seconds", pauseBetweenScans.getSeconds()); } }
Source:
<code><START> public void addTable(TableSpec tableSpec) { <END> if (tables.containsKey(tableSpec.getId())) { throw new SamzaException("Table " + tableSpec.getId() + " already exists"); } TableCtx ctx = new TableCtx(); TableProviderFactory tableProviderFactory = Util.getObj(tableSpec.getTableProviderFactory()); ctx.tableProvider = tableProviderFactory.getTableProvider(tableSpec); ctx.tableSpec = tableSpec; tables.put(tableSpec.getId(), ctx); }</code><technical_language>is call this method TableManager, change private</technical_language>

Target:
private void addTable(TableSpec tableSpec) { if (tables.containsKey(tableSpec.getId())) { throw new SamzaException("Table " + tableSpec.getId() + " already exists"); } TableCtx ctx = new TableCtx(); TableProviderFactory tableProviderFactory = Util.getObj(tableSpec.getTableProviderFactoryClassName()); ctx.tableProvider = tableProviderFactory.getTableProvider(tableSpec); ctx.tableSpec = tableSpec; tables.put(tableSpec.getId(), ctx); }
Source:
<code>public static Schema appendFields(Schema schema, Schema.Field... fields) { Schema newSchema = schema; if (schema.getType() == Type.RECORD) { newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError()); List<Schema.Field> copyFieldList = new ArrayList<>(); for (Schema.Field se : schema.getFields()) { copyFieldList.add(new Schema.Field(se.name(), se.schema(), se.doc(), se.defaultVal())); } for (Schema.Field field : fields) { copyFieldList.add(field); } newSchema.setFields(copyFieldList); Map<String, Object> props = schema.getObjectProps(); for (String propKey : props.keySet()) { newSchema.addProp(propKey, props.get(propKey)); } } else { <START> throw new RuntimeException("Not support this type " + newSchema.getType() + " now, need to implement"); <END> } return newSchema; }</code><technical_language>In opinion, delete this else block throw exception immediately if schema type is RECORD -- sense add fields other schema type. method below</technical_language>

Target:
public static Schema appendFields(Schema schema, Schema.Field... fields) { Schema newSchema = schema; if (schema.getType() == Type.RECORD) { newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError()); List<Schema.Field> copyFieldList = new ArrayList<>(); for (Schema.Field se : schema.getFields()) { copyFieldList.add(new Schema.Field(se.name(), se.schema(), se.doc(), se.defaultVal())); } for (Schema.Field field : fields) { copyFieldList.add(field); } newSchema.setFields(copyFieldList); Map<String, Object> props = schema.getObjectProps(); for (String propKey : props.keySet()) { newSchema.addProp(propKey, props.get(propKey)); } } else { TalendRuntimeException.build(CommonErrorCodes.UNEXPECTED_EXCEPTION) .setAndThrow("Not support this type " + schema.getType() + ", only support record type"); } return newSchema; }
Source:
<code>public void testConversionAggregated() throws Exception { final String inputFilePath = "/aggregated.vcf.gz"; String inputFile = AggregatedVcfReaderTest.class.getResource(inputFilePath).getFile(); File tempFile = JobTestUtils.createTempFile(); JobTestUtils.uncompress(inputFile, tempFile); String fileId = "5"; String studyId = "7"; String studyName = "study name"; VcfHeaderReader headerReader = new VcfHeaderReader(new File(inputFile), fileId, studyId, studyName, VariantStudy.StudyType.COLLECTION, <START> VariantSource.Aggregation.NONE); <END> VariantSource source = headerReader.read(); char CHARACTER_TO_REPLACE_DOTS = (char) 163; Map<String, Object> meta = source.getMetadata(); BasicDBObject metadataMongo = new BasicDBObject(); for (Map.Entry<String, Object> metaEntry : meta.entrySet()) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(); String key = metaEntry.getKey().replace('.', CHARACTER_TO_REPLACE_DOTS); Object value = metaEntry.getValue(); String jsonString = writer.writeValueAsString(value); metadataMongo.append(key, JSON.parse(jsonString)); } checkFieldsInsideList(metadataMongo, "INFO", Arrays.asList("id", "description", "number", "type")); checkStringInsideList(metadataMongo, "contig"); }</code><technical_language>More repeated initialization code constants..</technical_language>

Target:
public void testConversionAggregated() throws Exception { File input = TestFileUtils.getResource(INPUT_AGGREGATED_FILE_PATH); File tempFile = JobTestUtils.createTempFile(); JobTestUtils.uncompress(input.getAbsolutePath(), tempFile); VcfHeaderReader headerReader = new VcfHeaderReader(input, FILE_ID, STUDY_ID, STUDY_NAME, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); char CHARACTER_TO_REPLACE_DOTS = (char) 163; Map<String, Object> meta = source.getMetadata(); BasicDBObject metadataMongo = new BasicDBObject(); for (Map.Entry<String, Object> metaEntry : meta.entrySet()) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(); String key = metaEntry.getKey().replace('.', CHARACTER_TO_REPLACE_DOTS); Object value = metaEntry.getValue(); String jsonString = writer.writeValueAsString(value); metadataMongo.append(key, JSON.parse(jsonString)); } checkFieldsInsideList(metadataMongo, "INFO", Arrays.asList("id", "description", "number", "type")); checkStringInsideList(metadataMongo, "contig"); }
Source:
<code>private Set<String> getCatalogItemIds(Iterable<CatalogItem<Object, Object>> catalogItems) { return FluentIterable.from(catalogItems) <START> .transform(new Function<CatalogItem<Object, Object>, String>() { <END> @Override public String apply(CatalogItem<Object, Object> input) { return input.getId(); } }) .copyInto(Sets.<String>newHashSet()); }</code><technical_language>EntityPredicates.id(), Function<Identifiable, String> (rather for entities)</technical_language>

Target:
private Set<String> getCatalogItemIds(Iterable<CatalogItem<Object, Object>> catalogItems) { return FluentIterable.from(catalogItems) .transform(EntityFunctions.id()) .copyInto(Sets.<String>newHashSet()); }
Source:
<code>public void process(Session session, DashBoard dash, byte pin, PinType type, String triggerValue) { Eventor eventor = dash.getWidgetByType(Eventor.class); if (eventor == null || eventor.rules == null) { return; } double valueParsed; try { valueParsed = Double.parseDouble(triggerValue); } catch (NumberFormatException nfe) { return; } for (Rule rule : eventor.rules) { if (rule.isReady(pin, type)) { if (rule.isValid(valueParsed)) { if (!rule.isProcessed) { for (BaseAction action : rule.actions) { if (action instanceof SetPinAction) { execute(session, dash.isActive, dash.id, (SetPinAction) action); } else if (action instanceof NotificationAction) { execute(dash, triggerValue, (NotificationAction) action); } } rule.isProcessed = true; } } else { rule.isProcessed = false; } } } <START> globalStats.mark(EVENTOR); <END> }</code><technical_language>Wrong place. need do execute</technical_language>

Target:
public void process(Session session, DashBoard dash, byte pin, PinType type, String triggerValue) { Eventor eventor = dash.getWidgetByType(Eventor.class); if (eventor == null || eventor.rules == null) { return; } double valueParsed; try { valueParsed = Double.parseDouble(triggerValue); } catch (NumberFormatException nfe) { return; } for (Rule rule : eventor.rules) { if (rule.isReady(pin, type)) { if (rule.isValid(valueParsed)) { if (!rule.isProcessed) { for (BaseAction action : rule.actions) { if (action instanceof SetPinAction) { execute(session, dash.isActive, dash.id, (SetPinAction) action); } else if (action instanceof NotificationAction) { execute(dash, triggerValue, (NotificationAction) action); } } rule.isProcessed = true; } } else { rule.isProcessed = false; } } } }
Source:
<code>public Activity(String label, ActivityType activityType, String ref) { this.label = label; this.activityType = activityType; this.ref = ref; this.survey = null; <START> } <END></code><technical_language>This constructor redundant above. Do special need for it, survey? concerned if update this class, update 2 constructors instead of one. least, this constructor call this(label, activityType, ref, null) avoid duplicate instantiation code</technical_language>

Target:
public Activity(String label, ActivityType activityType, String ref) { this(label, activityType, ref, null); }
Source:
<code>protected GoogleApiClient createGoogleApiClient() { <START> return GoogleApiClientFactory.createWithoutSignIn(getApplicationContext()); <END> }</code><technical_language>I if is a good practice create GoogleApiClient ApplicationContext. GoogleApiClient is tied Activity. recreating Activity. needs done. I if this sense</technical_language>

Target:
protected GoogleApiClient createGoogleApiClient() { return GoogleApiClientFactory.createWithoutSignIn(this); }
Source:
<code>public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); <START> log.info("All required capabilities are available"); <END> }</code><technical_language>log.info message is general. multiple bundles this statement confuse troubleshoot OSGi related issues. Instead, message ideally "All required capabilities for web socket service component is available"</technical_language>

Target:
public void onAllRequiredCapabilitiesAvailable() { DataHolder.getInstance().getBundleContext().registerService(WebSocketServerSC.class, this, null); log.info("All required capabilities are available of WebSocket service component is available."); }
Source:
<code>public void testCompactHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin1", 0), new PutOperation<>(1L, "Albin2", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); <START> Chain compactedChain = resolver.compactChain(chain, 3); <END> assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin3", 3)))); }</code><technical_language>this test more "accurate" if changed in entry timestamp (and value)</technical_language>

Target:
public void testCompactHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0), new PutOperation<>(1L, "Albin", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.compactChain(chain, 3); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin", 3)))); }