auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final Page.Content page = get().get(select(req)); final CurrentUser user = currentUser.get(); final StringWriter w = new StringWriter(); if (user instanceof IdentifiedUser) { w.write(HPD_ID + ".account="); json(((IdentifiedUser) user).getAccount(), w); w.write(";"); w.write(HPD_ID + ".xsrfToken="); json(session.get().getToken(), w); w.write(";"); w.write(HPD_ID + ".accountDiffPref="); json(((IdentifiedUser) user).getAccountDiffPreference(), w); w.write(";"); w.write(HPD_ID + ".theme="); json(signedInTheme, w); w.write(";"); } else { w.write(HPD_ID + ".theme="); json(signedOutTheme, w); w.write(";"); } <START> w.write(HPD_ID + ".plugnisUrls="); <END> json(getPluginUrls(), w); w.write(";"); final byte[] userData = w.toString().getBytes("UTF-8"); final byte[] raw = concat(page.part1, userData, page.part2); final byte[] tosend; if (RPCServletUtils.acceptsGzipEncoding(req)) { rsp.setHeader("Content-Encoding", "gzip"); tosend = HtmlDomUtil.compress(raw); } else { tosend = raw; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); rsp.setContentType("text/html"); rsp.setCharacterEncoding(HtmlDomUtil.ENC); rsp.setContentLength(tosend.length); final OutputStream out = rsp.getOutputStream(); try { out.write(tosend); } finally { out.close(); } }</code><technical_language>s/plugnisUrls/pluginUrls</technical_language>

Target:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { final Page.Content page = get().get(select(req)); final CurrentUser user = currentUser.get(); final StringWriter w = new StringWriter(); if (user instanceof IdentifiedUser) { w.write(HPD_ID + ".account="); json(((IdentifiedUser) user).getAccount(), w); w.write(";"); w.write(HPD_ID + ".xsrfToken="); json(session.get().getToken(), w); w.write(";"); w.write(HPD_ID + ".accountDiffPref="); json(((IdentifiedUser) user).getAccountDiffPreference(), w); w.write(";"); w.write(HPD_ID + ".theme="); json(signedInTheme, w); w.write(";"); } else { w.write(HPD_ID + ".theme="); json(signedOutTheme, w); w.write(";"); } w.write(HPD_ID + ".pluginUrls="); json(getPluginUrls(), w); w.write(";"); final byte[] userData = w.toString().getBytes("UTF-8"); final byte[] raw = concat(page.part1, userData, page.part2); final byte[] tosend; if (RPCServletUtils.acceptsGzipEncoding(req)) { rsp.setHeader("Content-Encoding", "gzip"); tosend = HtmlDomUtil.compress(raw); } else { tosend = raw; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); rsp.setContentType("text/html"); rsp.setCharacterEncoding(HtmlDomUtil.ENC); rsp.setContentLength(tosend.length); final OutputStream out = rsp.getOutputStream(); try { out.write(tosend); } finally { out.close(); } }
Source:
<code>public PinotQueryGeneratorContext visitMarkDistinct(MarkDistinctNode node, PinotQueryGeneratorContext context) { <START> context = node.getSource().accept(this, context); <END> requireNonNull(context, "context is null"); return context; }</code><technical_language>put this line</technical_language>

Target:
public PinotQueryGeneratorContext visitMarkDistinct(MarkDistinctNode node, PinotQueryGeneratorContext context) { requireNonNull(context, "context is null"); return node.getSource().accept(this, context); }
Source:
<code>public void controller(FragmentModel model, @FragmentParam(required = true, value = "conceptId") Concept concept) throws Exception { Collection<Map<String, String>> collection = new ArrayList<Map<String, String>>(); if(concept == null){ model.put("conceptAnswers", collection); } else{ Map<String, String> conceptMap; Locale locale = Context.getLocale(); Collection<ConceptAnswer> conceptAnswers = concept.getAnswers(); String fullname = null; for (ConceptAnswer conceptAnswer : conceptAnswers) { conceptMap = new HashMap<String, String>(); fullname = conceptAnswer.getAnswerConcept().getFullySpecifiedName(locale).getName(); conceptMap.put("label", fullname); <START> conceptMap.put("value", fullname); <END> collection.add(conceptMap); } model.put("conceptAnswers", collection); } }</code><technical_language>uuid id</technical_language>

Target:
public void controller(FragmentModel model, @FragmentParam(required = true, value = "conceptId") Concept concept) throws Exception { Collection<Map<String, String>> collection = new ArrayList<Map<String, String>>(); if(concept == null){ model.put("conceptAnswers", collection); } else{ Map<String, String> conceptMap; Locale locale = Context.getLocale(); Collection<ConceptAnswer> conceptAnswers = concept.getAnswers(); String fullname = null; for (ConceptAnswer conceptAnswer : conceptAnswers) { conceptMap = new HashMap<String, String>(); fullname = conceptAnswer.getAnswerConcept().getName().getName(); conceptMap.put("label", fullname); conceptMap.put("value", fullname); collection.add(conceptMap); } model.put("conceptAnswers", collection); } }
Source:
<code>private static Map<String, String> getHiveVarMap(String[] args) { if (args == null) { return Collections.emptyMap(); } Map<String, String> hiveVarMap = new HashMap<String, String>(); for (int index = 0; index < args.length; index++) { if ("-hivevar".equals(args[index])) { String hiveVarParam = stripSingleDoubleQuote(args[++index]); int gap = hiveVarParam.indexOf("="); if (gap == -1) { logger.warn("Invalid hivevar: " + hiveVarParam); <START> continue; <END> } String name = hiveVarParam.substring(0, gap); String value = hiveVarParam.substring(gap + 1); logger.info("Setting hivevar: " + name + "=" + value); hiveVarMap.put(name, value); } } return hiveVarMap; }</code><technical_language>Curious, if continue, exception throw</technical_language>

Target:
static Map<String, String> getHiveVarMap(String[] args) { if (args == null) { return Collections.emptyMap(); } Map<String, String> hiveVarMap = new HashMap<String, String>(); for (int index = 0; index < args.length; index++) { if ("-hivevar".equals(args[index])) { String hiveVarParam = stripSingleDoubleQuote(args[++index]); int gap = hiveVarParam.indexOf("="); if (gap == -1) { logger.warn("Invalid hivevar: " + hiveVarParam); continue; } String name = hiveVarParam.substring(0, gap); String value = hiveVarParam.substring(gap + 1); logger.info("Setting hivevar: " + name + "=" + value); hiveVarMap.put(name, value); } } return hiveVarMap; }
Source:
<code>private static IType getDeclType(ICPPASTSimpleDeclSpecifier spec) { IASTExpression expr = spec.getDeclTypeExpression(); if (expr == null) { return null; } int specifierType = spec.getType(); <START> if (specifierType == IASTSimpleDeclSpecifier.t_decltype || specifierType == IASTSimpleDeclSpecifier.t_decltype_auto) { <END> return getDeclType(expr); } return expr.getExpressionType(); }</code><technical_language>handle t_decltype_auto here? get in for decltype(auto) getDeclTypeExpression() null</technical_language>

Target:
private static IType getDeclType(ICPPASTSimpleDeclSpecifier spec) { IASTExpression expr = spec.getDeclTypeExpression(); if (expr == null) { return null; } int specifierType = spec.getType(); if (specifierType == IASTSimpleDeclSpecifier.t_decltype) { return getDeclType(expr); } return expr.getExpressionType(); }
Source:
<code>public static FileReftableDatabase convertFrom(FileRepository repo, File refstackName, boolean writeLogs) throws IOException { FileReftableDatabase newDb = null; try { File reftableDir = new File(repo.getDirectory(), Constants.REFTABLE); if (!reftableDir.isDirectory()) { reftableDir.mkdir(); } try (FileReftableStack stack = new FileReftableStack(refstackName, reftableDir, null, () -> repo.getConfig())) { stack.addReftable(rw -> writeConvertTable(repo, rw, writeLogs)); } <START> } catch (Exception e) { <END> refstackName.delete(); throw e; } return newDb; }</code><technical_language>this a try { } finally? other Throwables leak</technical_language>

Target:
public static FileReftableDatabase convertFrom(FileRepository repo, File refstackName, boolean writeLogs) throws IOException { FileReftableDatabase newDb = null; try { File reftableDir = new File(repo.getDirectory(), Constants.REFTABLE); if (!reftableDir.isDirectory()) { reftableDir.mkdir(); } try (FileReftableStack stack = new FileReftableStack(refstackName, reftableDir, null, () -> repo.getConfig())) { stack.addReftable(rw -> writeConvertTable(repo, rw, writeLogs)); } refstackName = null; } finally { if (refstackName != null) { refstackName.delete(); } } return newDb; }
Source:
<code><START> public static String sanitizeForJs(String str){ <END> if(str == null) return null; return Sanitizer.sanitizeForHtml( str.replace("\\", "\\\\") .replace("\"", "\\\"") .replace("'", "\\'") .replace("#", "\\#")); }</code><technical_language>changing this, space {</technical_language>

Target:
public static String sanitizeForJs(String str) { if (str == null) { return null; } return Sanitizer.sanitizeForHtml( str.replace("\\", "\\\\") .replace("\"", "\\\"") .replace("'", "\\'") .replace("#", "\\#")); }
Source:
<code>protected void onCellDoubleClick(final int row, int column) { if (row == 0) { if (column == 1 || column == A) { createCommentEditor(row + 1, A, 0, (short) 0); } else if (column == B || column == 4) { createCommentEditor(row + 1, B, 0, (short) 1); <START> } <END> } else if ((column > 0 && getRowItem(row) instanceof PatchLine)) { final PatchLine line = (PatchLine) getRowItem(row); if (column == 1 || column == A) { createCommentEditor(row + 1, A, line.getLineA(), (short) 0); } else if (column == B || column == 4) { createCommentEditor(row + 1, B, line.getLineB(), (short) 1); } } }</code><technical_language>lines similar copied, this refactored consolidate logic copied lines</technical_language>

Target:
protected void onCellDoubleClick(final int row, int column) { if (column > 0) { if (row == FILE_COMMENT_ROW) { createCommentEditor(row + 1, column == A ? A : B, 0, column == A ? (short) 0 : (short) 1); return; } if (getRowItem(row) instanceof PatchLine) { final PatchLine line = (PatchLine) getRowItem(row); if (column == 1 || column == A) { createCommentEditor(row + 1, A, line.getLineA(), (short) 0); } else if (column == B || column == 4) { createCommentEditor(row + 1, B, line.getLineB(), (short) 1); } } } }
Source:
<code>public void visitFunctionDef(FunctionDef functionDef) { String functionName = functionDef.name().name(); SymbolImpl symbol = (SymbolImpl) symbolsByName.get(functionName); if (symbol != null) { symbol.setKind(OTHER); } else { FunctionSymbolImpl functionSymbol = new FunctionSymbolImpl(functionName, functionName, false, false, false, Collections.emptyList(), null); TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation != null) { <START> functionSymbol.setInferredReturnType(InferredTypes.declaredType(returnTypeAnnotation)); <END> } symbolsByName.put(functionName, functionSymbol); } }</code><technical_language>Is setInferredReturnType right name? setDeclaredReturnType? imagine some day compare return type is declared in a function declaration return type infer body. def f() -> str: return 42</technical_language>

Target:
public void visitFunctionDef(FunctionDef functionDef) { String functionName = functionDef.name().name(); SymbolImpl symbol = (SymbolImpl) symbolsByName.get(functionName); if (symbol != null) { symbol.setKind(OTHER); } else { FunctionSymbolImpl functionSymbol = new FunctionSymbolImpl(functionName, functionName, false, false, false, Collections.emptyList(), null); TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation != null) { functionSymbol.setDeclaredReturnType(InferredTypes.declaredType(returnTypeAnnotation)); } symbolsByName.put(functionName, functionSymbol); } }
Source:
<code>public void testStatsManagerCollectAggregateAndPublish() throws StoreException, IOException, InterruptedException { <START> long[][] aggregatedTestData = new long[][]{{1110, 200, 300}, {350}, {500, 300}, {10, 20, 30, 40, 50}}; <END> StatsSnapshot expectedSnapshot = generateStatsSnapshot(aggregatedTestData); StatsSnapshot actualSnapshot = new StatsSnapshot(0L, null); List<String> unreachableStores = new ArrayList<>(); for (PartitionId partitionId : storeMap.keySet()) { if (!statsManager.collectAndAggregate(actualSnapshot, partitionId)) { unreachableStores.add(partitionId.toString()); } } assertTrue("Aggregated StatsSnapshot does not match with expected snapshot", expectedSnapshot.equals(actualSnapshot)); assertEquals("Skipped store count mismatch with expected value", 1, unreachableStores.size()); StatsHeader statsHeader = new StatsHeader(Description.QUOTA, SystemTime.getInstance().milliseconds(), storeMap.keySet().size(), storeMap.keySet().size() - unreachableStores.size(), unreachableStores); File outputFile = new File(outputFileString); if (outputFile.exists()) { outputFile.createNewFile(); } long fileLengthBefore = outputFile.length(); statsManager.publish(new StatsWrapper(statsHeader, actualSnapshot)); assertTrue("Failed to publish stats to file", outputFile.length() > fileLengthBefore); }</code><technical_language>hardCoding is a good practice. try calculate atleast instance variable tracks this (which is set in setupTest())</technical_language>

Target:
public void testStatsManagerCollectAggregateAndPublish() throws IOException { StatsSnapshot actualSnapshot = new StatsSnapshot(0L, null); List<String> unreachableStores = Collections.EMPTY_LIST; for (PartitionId partitionId : storeMap.keySet()) { statsManager.collectAndAggregate(actualSnapshot, partitionId, unreachableStores); } assertTrue("Actual aggregated StatsSnapshot does not match with expected snapshot", preAggregatedSnapshot.equals(actualSnapshot)); StatsHeader statsHeader = new StatsHeader(Description.QUOTA, SystemTime.getInstance().milliseconds(), storeMap.keySet().size(), storeMap.keySet().size(), unreachableStores); File outputFile = new File(outputFileString); if (outputFile.exists()) { outputFile.createNewFile(); } long fileLengthBefore = outputFile.length(); statsManager.publish(new StatsWrapper(statsHeader, actualSnapshot)); assertTrue("Failed to publish stats to file", outputFile.length() > fileLengthBefore); }
Source:
<code>public int getOpacity() { <START> return PixelFormat.OPAQUE; <END> }</code><technical_language>TRANSLUCENT _every_ pixel drawable's bounds is 100% opaque</technical_language>

Target:
public int getOpacity() { return PixelFormat.TRANSLUCENT; }
Source:
<code>public FtSecure(final Take tks) throws IOException { <START> this(new BkBasic(tks), 443); <END> }</code><technical_language>@bdragan do this(tks, 443), leaving creation of other constructor</technical_language>

Target:
public FtSecure(final Take tks) throws IOException { this(tks, 443); }
Source:
<code>private String decodeBase64EncodedHashWithHex(String base64EncodedHash) { try { return new String(Hex.encode(Base64.getDecoder().decode(Utf8.encode(base64EncodedHash)))); } catch (Exception ex) { <START> logger.warn("Failed to do Base64Decoding " + ex.getMessage()); <END> } return base64EncodedHash; }</code><technical_language>suggestion logger.warn("Failed do decode hash base64! " + ex.getMessage());</technical_language>

Target:
private String decodeBase64EncodedHashWithHex(String base64EncodedHash) { try { return new String(Hex.encode(Base64.getDecoder().decode(Utf8.encode(base64EncodedHash)))); } catch (Exception ex) { logger.warn("decode hash using base64! " + ex.getMessage(), ex); } return base64EncodedHash; }
Source:
<code>public String promptEmail() throws IOException, ConfigurationException { final String message = "Email Address: "; final String error = "Invalid email address."; EmailValidator validator = EmailValidator.getInstance(); <START> String email = null; <END> Console console = System.console(); if (console != null) { email = console.readLine(message); while (email == null || !validator.isValid(email)) { console.printf(error + "\n", email); email = console.readLine(message); } } else { email = IOUtils.toString(System.in); if (email == null || !validator.isValid(email)) { throw new ConfigurationException(error); } } return email; }</code><technical_language>= null needed</technical_language>

Target:
public String promptEmail() throws IOException, ConfigurationException { EmailValidator validator = EmailValidator.getInstance(); final String message = "Email Address: "; final String error = "Invalid email address."; return prompt(message, validator::isValid, error); }
Source:
<code>private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); <START> connection.exec("echo hello > null",baos); <END> final String s; try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }</code><technical_language>this create a file named null, Is this intention</technical_language>

Target:
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("exit 0",baos); final String s; try { s = baos.toString(Charset.defaultCharset().name()); } catch (UnsupportedEncodingException ex) { throw new IOException("Default encoding is unsupported", ex); } if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } }
Source:
<code>protected void augmentMultifactorProviderFlowRegistry(final FlowDefinitionRegistry mfaProviderFlowRegistry) { final String[] flowIds = mfaProviderFlowRegistry.getFlowDefinitionIds(); Arrays.stream(flowIds).forEach(id -> { final Flow flow = Flow.class.cast(mfaProviderFlowRegistry.getFlowDefinition(id)); if (containsFlowState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT)) { final Collection<String> states = getCandidateStatesForMultifactorAuthentication(); states.forEach(s -> { final TransitionableState state = getState(flow, s); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS, CasWebflowConstants.STATE_ID_SUCCESS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS); <START> ensureEndStateTransitionExists(state, flow, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE); <END> ensureEndStateTransitionExists(state, flow, CasWebflowConstants.STATE_ID_MFA_DENIED, CasWebflowConstants.STATE_ID_MFA_DENIED); }); } }); }</code><technical_language>3rd parameter (i.e. CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE) transition ids. If match state id, fine I necessarily recommend this. Separate consts values troubleshooting this</technical_language>

Target:
protected void augmentMultifactorProviderFlowRegistry(final FlowDefinitionRegistry mfaProviderFlowRegistry) { final String[] flowIds = mfaProviderFlowRegistry.getFlowDefinitionIds(); Arrays.stream(flowIds).forEach(id -> { final Flow flow = Flow.class.cast(mfaProviderFlowRegistry.getFlowDefinition(id)); if (containsFlowState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT)) { final Collection<String> states = getCandidateStatesForMultifactorAuthentication(); states.forEach(s -> { final TransitionableState state = getState(flow, s); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS, CasWebflowConstants.STATE_ID_SUCCESS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_UNAVAILABLE, CasWebflowConstants.STATE_ID_MFA_UNAVAILABLE); ensureEndStateTransitionExists(state, flow, CasWebflowConstants.TRANSITION_ID_DENY, CasWebflowConstants.STATE_ID_MFA_DENIED); }); } }); }
Source:
<code>protected void setThreadFocus(final IMIExecutionDMContext newThread, RequestMonitor rm) { if (newThread == null) { <START> GdbPlugin.logErrorMessage("GdbSynchronizer unable to resolve thread context for the selected element"); END> rm.done(); return; } ICommandControlDMContext cmd = DMContexts.getAncestorOfType(newThread, ICommandControlDMContext.class); ICommand<MIInfo> command = fCommandFactory.createMIThreadSelect(cmd, getThreadIdFromContext(newThread)); fCommandControl.queueCommand(command, new ImmediateDataRequestMonitor<MIInfo> (rm) {}); }</code><technical_language>I set error in RM instead</technical_language>

Target:
protected void setThreadFocus(final IMIExecutionDMContext newThread, RequestMonitor rm) { if (newThread == null) { rm.done(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE, "GdbSynchronizer unable to resolve thread context for the selected element", null)); return; } ICommand<MIInfo> command = fCommandFactory.createMIThreadSelect(fGdbcontrol.getContext(), getThreadIdFromContext(newThread)); fGdbcontrol.queueCommand(command, new ImmediateDataRequestMonitor<MIInfo> (rm) {}); }
Source:
<code>static ReplicationFactor fromString(String s) { if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); Preconditions.checkArgument( <START> allPart != null && transientPart != null, <END> "Replication factor format is <replicas> or <replicas>/<transient>"); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); } }</code><technical_language>This is version of driver 4's ReplicationFactor. This logic can/should simplified if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); }</technical_language>

Target:
static ReplicationFactor fromString(String s) { if (s.contains("/")) { int slash = s.indexOf('/'); String allPart = s.substring(0, slash); String transientPart = s.substring(slash + 1); return new ReplicationFactor(Integer.parseInt(allPart), Integer.parseInt(transientPart)); } else { return new ReplicationFactor(Integer.parseInt(s), 0); } }
Source:
<code>public void testStartCommand() throws CarbonToolsIntegrationTestException, NoSuchFieldException, IllegalAccessException { String[] cmdArrayToStart; Process process; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { throw new SkipException("Feature --start is not available for windows"); } else { cmdArrayToStart = new String[] {"sh", "wso2server.sh", "--start", "-DportOffset=" + portOffset}; <START> process = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArrayToStart); <END> } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); Field field = process.getClass().getDeclaredField("pid"); field.setAccessible(true); processId = field.get(process).toString(); log.info("process id for carbon server with offset 1 : " + processId); assertTrue(startupStatus, "Unsuccessful login"); }</code><technical_language>file.separator construct patch, avoid "/bin"</technical_language>

Target:
public void testStartCommand() throws CarbonToolsIntegrationTestException, NoSuchFieldException, IllegalAccessException { String[] cmdArrayToStart; Process process; if (CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase())) { throw new SkipException("Feature --start is not available for windows"); } else { cmdArrayToStart = new String[] {"sh", "wso2server.sh", "--start", "-DportOffset=" + portOffset}; process = CarbonCommandToolsUtil.runScript(carbonHome + "/bin", cmdArrayToStart); } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); Field field = process.getClass().getDeclaredField("pid"); field.setAccessible(true); processId = field.get(process).toString(); log.info("process id for carbon server with offset 1 : " + processId); assertTrue(startupStatus, "Unsuccessful login"); }
Source:
<code>private PhysicalSlot addOneSlot() { final PhysicalSlot slot = createPhysicalSlot(); <START> slots.add(slot); <END> return slot; }</code><technical_language>I is guaranteed changes slot visible bulkChecker mainThreadExecutor run Set implementation is thread safe</technical_language>

Target:
private PhysicalSlot addOneSlot() { final PhysicalSlot slot = createPhysicalSlot(); CompletableFuture.runAsync(() -> slots.add(slot), mainThreadExecutor).join(); return slot; }
Source:
<code>public void setIdpInitSLOReturnToURLs(String[] idpInitSLOReturnToURLs) { <START> this.idpInitSLOReturnToURLs = idpInitSLOReturnToURLs; <END> }</code><technical_language>clone of incoming array</technical_language>

Target:
public void setIdpInitSLOReturnToURLs(String[] idpInitSLOReturnToURLs) { if(idpInitSLOReturnToURLs != null) { this.idpInitSLOReturnToURLs = idpInitSLOReturnToURLs.clone(); } else { this.idpInitSLOReturnToURLs = null; } }
Source:
<code>private void flushAll() { <START> populations.forEach( population -> flush( population, population.takeCurrentBatch() ) ); <END> }</code><technical_language>is need pass param population is passed</technical_language>

Target:
private void flushAll() { populations.forEach( population -> flush( population ) ); }
Source:
<code>public void createLogTable(final String tableName, final String entryTypeName) { createTable( tableName, ImmutableList.of( StringUtils.format( "CREATE TABLE %1$s (\n" + " id %2$s NOT NULL,\n" + " %3$s_id VARCHAR(255) DEFAULT NULL,\n" + " log_payload_id VARCHAR(255) NOT NULL,\n" <START> + " log_payload_order SMALLINT NOT NULL,\n" <END> + " log_payload_part %4$s,\n" + " PRIMARY KEY (id)\n" + ")", tableName, getSerialType(), entryTypeName, getPayloadType() ), StringUtils.format("CREATE INDEX idx_%1$s_%2$s_id ON %1$s(%2$s_id)", tableName, entryTypeName) ) ); }</code><technical_language>this require SQL upgrades metadata storage</technical_language>

Target:
public void createLogTable(final String tableName, final String entryTypeName) { createTable( tableName, ImmutableList.of( StringUtils.format( "CREATE TABLE %1$s (\n" + " id %2$s NOT NULL,\n" + " %3$s_id VARCHAR(255) DEFAULT NULL,\n" + " log_payload_id VARCHAR(255) NOT NULL,\n" + " log_payload_order %4$s NOT NULL,\n" + " log_payload_part %5$s,\n" + " PRIMARY KEY (id)\n" + ")", tableName, getSerialType(), entryTypeName, getIntegerType(), getPayloadType() ), StringUtils.format("CREATE INDEX idx_%1$s_%2$s_id ON %1$s(%2$s_id)", tableName, entryTypeName) ) ); }
Source:
<code>protected <T> T upload(String artifactId, File file, Class<T> clazz, String blobName) { Payload<?> payload = new FilePayload(file); <START> Invocation<T> invocation = put(clazz,uri(ClientConstants.PATH_ARTIFACTS+ClientConstants.URI_SEP+ artifactType.value()+"/%s/%s",artifactId,blobName)); <END> invocation.entity(payload); return invocation.execute(); }</code><technical_language>Maybeuri("%s/%s/%s/%s", PATH_ARTIFACTS,artifactType.value(),artifactId,blobName)</technical_language>

Target:
protected <T> T upload(String artifactId, File file, Class<T> clazz, String blobName) { Payload<?> payload = new FilePayload(file); Invocation<T> invocation = put(clazz,uri(PATH_ARTIFACTS+URI_SEP+ artifactType.value()+"/%s/%s",artifactId,blobName)); invocation.entity(payload); return invocation.execute(); }
Source:
<code>public void testWhenAnyFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<Void>> tasks = new ArrayList<>(); final Task<Void> firstToCompleteSuccess = Task.callInBackground(new Callable<Void>() { @Override public Void call() throws Exception { Thread.sleep(50); return null; } }); tasks.addAll(launchTasksWithRandomCompletions(10)); tasks.add(firstToCompleteSuccess); return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() { @Override public Object then(Task<Task<?>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(task.getResult(), firstToCompleteSuccess); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); <START> assertFalse(task.getResult().isFaulted()); <END> return null; } }); } }); }</code><technical_language>verify result</technical_language>

Target:
public void testWhenAnyFirstSuccess() { runTaskTest(new Callable<Task<?>>() { @Override public Task<?> call() throws Exception { final ArrayList<Task<?>> tasks = new ArrayList<>(); final Task<String> firstToCompleteSuccess = Task.callInBackground(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(50); return "SUCCESS"; } }); tasks.addAll(launchTasksWithRandomCompletions(5)); tasks.add(firstToCompleteSuccess); tasks.addAll(launchTasksWithRandomCompletions(5)); return Task.whenAny(tasks).continueWith(new Continuation<Task<?>, Object>() { @Override public Object then(Task<Task<?>> task) throws Exception { assertTrue(task.isCompleted()); assertFalse(task.isFaulted()); assertFalse(task.isCancelled()); assertEquals(firstToCompleteSuccess, task.getResult()); assertTrue(task.getResult().isCompleted()); assertFalse(task.getResult().isCancelled()); assertFalse(task.getResult().isFaulted()); assertEquals("SUCCESS", task.getResult().getResult()); return null; } }); } }); }
Source:
<code>protected boolean isAppConfiguredInSourceServerXml(String fileName) { <START> boolean bConfigured = false; <END> Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); bConfigured = true; } return bConfigured; }</code><technical_language>a spacing issue here, spaces instead of 4</technical_language>

Target:
protected boolean isAppConfiguredInSourceServerXml(String fileName) { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.contains(fileName)) { log.debug("Application configuration is found in server.xml : " + fileName); return true; } else { return false; } }
Source:
<code>protected Configuration createConfiguration() { final Configuration conf = (null != mStandaloneConf) ? HBaseConfiguration.create(mStandaloneConf) : HBaseConfiguration.create(); <START> conf.addResource("mapred-site.xml"); <END> return conf; }</code><technical_language>is this line necessary? HBaseConfiguration.create() a default Configuration mapred-site.xml a resource</technical_language>

Target:
protected Configuration createConfiguration() { return (null != mStandaloneConf) ? HBaseConfiguration.create(mStandaloneConf) : HBaseConfiguration.create(); }
Source:
<code>public String toString() { <START> return "KafkaIndexTaskTuningConfig{" + <END> "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", maxBytesInMemory=" + getMaxBytesInMemory() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + ", intermediateHandoffPeriod=" + getIntermediateHandoffPeriod() + ", logParseExceptions=" + isLogParseExceptions() + ", maxParseExceptions=" + getMaxParseExceptions() + ", maxSavedParseExceptions=" + getMaxSavedParseExceptions() + '}'; }</code><technical_language>This is missing maxTotalRows</technical_language>

Target:
public String toString() { return "KafkaIndexTaskTuningConfig{" + "maxRowsInMemory=" + getMaxRowsInMemory() + ", maxRowsPerSegment=" + getMaxRowsPerSegment() + ", maxTotalRows=" + getMaxTotalRows() + ", maxBytesInMemory=" + getMaxBytesInMemory() + ", intermediatePersistPeriod=" + getIntermediatePersistPeriod() + ", basePersistDirectory=" + getBasePersistDirectory() + ", maxPendingPersists=" + getMaxPendingPersists() + ", indexSpec=" + getIndexSpec() + ", reportParseExceptions=" + isReportParseExceptions() + ", handoffConditionTimeout=" + getHandoffConditionTimeout() + ", resetOffsetAutomatically=" + isResetOffsetAutomatically() + ", segmentWriteOutMediumFactory=" + getSegmentWriteOutMediumFactory() + ", intermediateHandoffPeriod=" + getIntermediateHandoffPeriod() + ", logParseExceptions=" + isLogParseExceptions() + ", maxParseExceptions=" + getMaxParseExceptions() + ", maxSavedParseExceptions=" + getMaxSavedParseExceptions() + '}'; }
Source:
<code>public static String[] getEnvironmentVariables() { ArrayList vars = new ArrayList(); String[] envVars = null; String var; int i; if(null == SystemTapGUIPlugin.getDefault() || null == SystemTapGUIPlugin.getDefault().getPreferenceStore()) { return null; } IPreferenceStore p = SystemTapGUIPlugin.getDefault().getPreferenceStore(); for(i=0; i<PreferenceConstants.P_ENV.length; i++) { var = p.getString(PreferenceConstants.P_ENV[i][0]).trim(); if(!var.equals("")) { vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); } } if(vars.size() > 0) { envVars = new String[vars.size()]; <START> for(i = 0; i<vars.size(); i++) <END> envVars[i] = (String)vars.get(i); } return envVars; }</code><technical_language>mores set of braces missing here</technical_language>

Target:
public static String[] getEnvironmentVariables() { ArrayList vars = new ArrayList(); String[] envVars = null; String var; int i; if(null == SystemTapGUIPlugin.getDefault() || null == SystemTapGUIPlugin.getDefault().getPreferenceStore()) { return null; } IPreferenceStore p = SystemTapGUIPlugin.getDefault().getPreferenceStore(); for(i=0; i<PreferenceConstants.P_ENV.length; i++) { var = p.getString(PreferenceConstants.P_ENV[i][0]).trim(); if(!var.equals("")) { vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); } } if(vars.size() > 0) { envVars = new String[vars.size()]; for (i = 0; i < vars.size(); i++) { envVars[i] = (String) vars.get(i); } } return envVars; }
Source:
<code>public void obtain_current_OffsetDateTime_using_ZoneOffset() { final int expectedSeconds = 3*Timestamps.SECONDS_PER_HOUR; final ZoneOffset inKiev = ZoneOffsets.ofHours(3); final OffsetDateTime today = OffsetDateTimes.now(inKiev); final Calendar calendar = Calendar.getInstance(); <START> assertEquals(calendar.get(Calendar.YEAR), today.getDate().getYear()); <END> assertEquals(calendar.get(Calendar.MONTH) + 1, today.getDate().getMonthValue()); assertEquals(calendar.get(Calendar.DAY_OF_MONTH), today.getDate().getDay()); final Timestamp time = Timestamps.getCurrentTime(); calendar.setTimeInMillis(time.getSeconds() / 1000); assertEquals(calendar.get(Calendar.HOUR), today.getTime().getHours()); assertEquals(calendar.get(Calendar.MINUTE), today.getTime().getMinutes()); assertEquals(calendar.get(Calendar.SECOND), today.getTime().getSeconds()); assertEquals(expectedSeconds, today.getOffset().getAmountSeconds()); }</code><technical_language>local variables for date time</technical_language>

Target:
public void obtain_current_OffsetDateTime_using_ZoneOffset() { final OffsetDateTime now = OffsetDateTimes.now(ZONE_OFFSET); final Calendar cal = Calendars.nowAt(ZONE_OFFSET); final LocalDate today = now.getDate(); assertEquals(getYear(cal), today.getYear()); assertEquals(getMonth(cal), today.getMonthValue()); assertEquals(getDay(cal), today.getDay()); final LocalTime time = now.getTime(); assertEquals(getHours(cal), time.getHours()); assertEquals(getMinutes(cal), time.getMinutes()); assertEquals(getSeconds(cal), time.getSeconds()); assertEquals(getZoneOffset(cal), now.getOffset() .getAmountSeconds()); }
Source:
<code>public DisruptorAutobatcher<I, O> build() { Preconditions.checkArgument(purpose != null, "purpose must be provided"); EventHandler<BatchElement<I, O>> handler = this.handlerFactory.apply(DEFAULT_BUFFER_SIZE); <START> EventHandler<BatchElement<I, O>> tracingHandler = (event, sequence, endOfBatch) -> { <END> if (endOfBatch) { Tracers.wrapWithNewTrace(purpose, observability, (Callable<Void>) () -> { handler.onEvent(event, sequence, true); return null; }).call(); } else { handler.onEvent(event, sequence, false); } }; EventHandler<BatchElement<I, O>> profiledHandler = new ProfilingEventHandler<>(tracingHandler, purpose, safeTags.build()); return DisruptorAutobatcher.create(profiledHandler, DEFAULT_BUFFER_SIZE, purpose); }</code><technical_language>I interesting test this this handler right (i.e. behaviour new trace)</technical_language>

Target:
public DisruptorAutobatcher<I, O> build() { Preconditions.checkArgument(purpose != null, "purpose must be provided"); EventHandler<BatchElement<I, O>> handler = this.handlerFactory.apply(DEFAULT_BUFFER_SIZE); EventHandler<BatchElement<I, O>> tracingHandler = new TracingEventHandler<>(handler, purpose, observability); EventHandler<BatchElement<I, O>> profiledHandler = new ProfilingEventHandler<>(tracingHandler, purpose, safeTags.build()); return DisruptorAutobatcher.create(profiledHandler, DEFAULT_BUFFER_SIZE, purpose); }
Source:
<code>public void handleCompleteTransactionResponseMessage(CompleteTransactionResponseMessage msg) { TransactionState txn = m_outstandingTxns.get(msg.getTxnId()); DuplicateCounter counter = m_duplicateCounters.get(new DuplicateCounterKey(msg.getTxnId(), msg.getSpHandle())); if (txn != null) { if (!msg.isRestart()) { <START> m_outstandingTxns.remove(msg.getTxnId()); <END> boolean duplicateCounterDone = true; if (counter != null) { duplicateCounterDone = counter.offer(msg) == DuplicateCounter.DONE; } if (m_isLeader && duplicateCounterDone) { assert txn.isDone(); setRepairLogTruncationHandle(txn.m_spHandle); } } } if (!m_isLeader) { m_mailbox.send(msg.getSPIHSId(), msg); } }</code><technical_language>@nshi remove TransactionState DuplicateCounter is DONE</technical_language>

Target:
public void handleCompleteTransactionResponseMessage(CompleteTransactionResponseMessage msg) { TransactionState txn = m_outstandingTxns.get(msg.getTxnId()); final DuplicateCounterKey duplicateCounterKey = new DuplicateCounterKey(msg.getTxnId(), msg.getSpHandle()); DuplicateCounter counter = m_duplicateCounters.get(duplicateCounterKey); boolean txnDone = true; if (msg.isRestart()) { txnDone = false; } if (counter != null) { txnDone = counter.offer(msg) == DuplicateCounter.DONE; } if (txnDone) { m_outstandingTxns.remove(msg.getTxnId()); m_duplicateCounters.remove(duplicateCounterKey); if (txn != null) { assert txn.isDone(); setRepairLogTruncationHandle(txn.m_spHandle); } } if (!m_isLeader) { m_mailbox.send(msg.getSPIHSId(), msg); } }
Source:
<code>public CommandLineParser getCommandLineParser() { if (commandLineParser == null) { commandLineParser = useLegacyParser(getClass()) ? new LegacyCommandLineArgumentParser(this) : new CommandLineArgumentParser(this, <START> Collections.emptyList(), <END> new HashSet<>(Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS))); } return commandLineParser; }</code><technical_language>If end keeping this code new code above, refactored (e.g. a method accepts boolean useLegacyParser) code is written once</technical_language>

Target:
public CommandLineParser getCommandLineParser() { if (commandLineParser == null) { commandLineParser = useLegacyParser() ? new LegacyCommandLineArgumentParser(this) : new CommandLineArgumentParser(this, Collections.EMPTY_LIST, Collections.singleton(CommandLineParserOptions.APPEND_TO_COLLECTIONS)); } return commandLineParser; }
Source:
<code>private Object deleteObjects(Environment context) { if (context.data.isPresent()) { throw new BadRequestException("DELETE must not include data argument"); } if (!context.ids.isPresent()) { throw new BadRequestException("DELETE must include ids argument"); } Set<PersistentResource> toDelete = ((ConnectionContainer) fetchObjects(context)).getPersistentResources(); toDelete.forEach(PersistentResource::deleteResource); <START> return new ConnectionContainer(toDelete, Optional.empty(), "TODO"); <END> }</code><technical_language>remove todo</technical_language>

Target:
private Object deleteObjects(Environment context) { if (context.data.isPresent()) { throw new BadRequestException("DELETE must not include data argument"); } if (!context.ids.isPresent()) { throw new BadRequestException("DELETE must include ids argument"); } ConnectionContainer connection = (ConnectionContainer) fetchObjects(context); Set<PersistentResource> toDelete = connection.getPersistentResources(); toDelete.forEach(PersistentResource::deleteResource); return new ConnectionContainer(toDelete, Optional.empty(), connection.getTypeName()); }
Source:
<code>void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); <START> Random rand = new Random(); <END> for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }</code><technical_language>This</technical_language>

Target:
void addEntriesAndRotateLogs(EntryLogger entryLogger, int numOfRotations) throws IOException { EntryLogManagerBase entryLogManager = (EntryLogManagerBase) entryLogger.getEntryLogManager(); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); for (int i = 0; i < numOfRotations; i++) { addEntries(entryLogger, 10); entryLogManager.setCurrentLogForLedgerAndAddToRotate(EntryLogger.UNASSIGNED_LEDGERID, null); } addEntries(entryLogger, 10); }
Source:
<code>public Map<EventTypePartition, Duration> getTimeLags(final Collection<NakadiCursor> committedPositions, final List<PartitionEndStatistics> endPositions) throws ErrorGettingCursorTimeLagException, InconsistentStateException, LimitReachedException, TimeLagStatsTimeoutException { final TimeLagRequestHandler timeLagHandler = new TimeLagRequestHandler(timelineService, threadPool); final Map<EventTypePartition, Duration> timeLags = new HashMap<>(); final Map<EventTypePartition, CompletableFuture<Duration>> futureTimeLags = new HashMap<>(); try { for (final NakadiCursor cursor : committedPositions) { if (isCursorAtTail(cursor, endPositions)) { timeLags.put(cursor.getEventTypePartition(), Duration.ZERO); } else { final CompletableFuture<Duration> timeLagFuture = timeLagHandler.getCursorTimeLagFuture(cursor); futureTimeLags.put(cursor.getEventTypePartition(), timeLagFuture); } } CompletableFuture .allOf(futureTimeLags.values().toArray(new CompletableFuture[futureTimeLags.size()])) .get(timeLagHandler.getRemainingTimeoutMs(), TimeUnit.MILLISECONDS); for (final EventTypePartition partition : futureTimeLags.keySet()) { timeLags.put(partition, futureTimeLags.get(partition).get()); } } catch (RejectedExecutionException|TimeoutException | ExecutionException e) { LOG.warn("caught exception the timelag stats are not complete"); } catch (Throwable e){ LOG.warn("caught throwable the timelag stats are not complete"); } <START> return timeLags; <END> }</code><technical_language>is NakadiBaseExceptions authorization exception? if authorization is checked earlier in code path, if case, handle this specially. please check that</technical_language>

Target:
public Map<EventTypePartition, Duration> getTimeLags(final Collection<NakadiCursor> committedPositions, final List<PartitionEndStatistics> endPositions) { final TimeLagRequestHandler timeLagHandler = new TimeLagRequestHandler(timelineService, threadPool); final Map<EventTypePartition, Duration> timeLags = new HashMap<>(); final Map<EventTypePartition, CompletableFuture<Duration>> futureTimeLags = new HashMap<>(); try { for (final NakadiCursor cursor : committedPositions) { if (isCursorAtTail(cursor, endPositions)) { timeLags.put(cursor.getEventTypePartition(), Duration.ZERO); } else { final CompletableFuture<Duration> timeLagFuture = timeLagHandler.getCursorTimeLagFuture(cursor); futureTimeLags.put(cursor.getEventTypePartition(), timeLagFuture); } } CompletableFuture .allOf(futureTimeLags.values().toArray(new CompletableFuture[futureTimeLags.size()])) .get(timeLagHandler.getRemainingTimeoutMs(), TimeUnit.MILLISECONDS); for (final EventTypePartition partition : futureTimeLags.keySet()) { timeLags.put(partition, futureTimeLags.get(partition).get()); } } catch (RejectedExecutionException | TimeoutException | ExecutionException e) { LOG.warn("caught exception the timelag stats are not complete - " + e); } catch (Throwable e) { LOG.warn("caught throwable the timelag stats are not complete - " + e); } return timeLags; }
Source:
<code>public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> { assertEquals(HttpResponseException.class, throwable.getClass()); final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) ((HttpResponseException) throwable).getValue(); <START> assertEquals("1022", errorInformation.getErrorCode()); <END> }); }); }</code><technical_language>Consider putting this in a constant</technical_language>

Target:
public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { client = getFormTrainingAsyncClient(httpClient, serviceVersion); beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> { SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoller = client.beginTraining(trainingFilesUrl, useTrainingLabels, new TrainingOptions().setPollInterval(durationTestMode)).getSyncPoller(); syncPoller.waitForCompletion(); CustomFormModel createdModel = syncPoller.getFinalResult(); StepVerifier.create(client.deleteModelWithResponse(createdModel.getModelId())) .assertNext(response -> assertEquals(response.getStatusCode(), HttpResponseStatus.NO_CONTENT.code())) .verifyComplete(); StepVerifier.create(client.getCustomModelWithResponse(createdModel.getModelId())) .verifyErrorSatisfies(throwable -> { assertEquals(HttpResponseException.class, throwable.getClass()); final FormRecognizerErrorInformation errorInformation = (FormRecognizerErrorInformation) ((HttpResponseException) throwable).getValue(); assertEquals(EXPECTED_MODEL_ID_NOT_FOUND_ERROR_CODE, errorInformation.getErrorCode()); }); }); }