auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String[][] formatBucketList(final DetailedTapeFailureList result) { final List<DetailedTapeFailure> failures = result.getDetailedTapeFailures(); final String [][] formatArray = new String[failures.size()][]; int i = 0; <START> for(DetailedTapeFailure failure : failures) { <END> final String bucketArray = new String[4]; bucketArray[0] = nullGuard(failure.getType().toString()); bucketArray[1] = nullGuard(failure.getErrorMessage().toString()); bucketArray[2] = nullGuard(failure.getId().toString()); final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); bucketArray[3] = DATE_FORMAT.format(failure.getDate()); formatArray[i++] = bucketArray; } return formatArray; }</code><technical_language>Missing final</technical_language>

Target:
private String[][] formatBucketList(final DetailedTapeFailureList result) { final List<DetailedTapeFailure> failures = result.getDetailedTapeFailures(); final String [][] formatArray = new String[failures.size()][]; int i = 0; for(final DetailedTapeFailure failure : failures) { final String bucketArray = new String[4]; bucketArray[0] = nullGuard(failure.getType().toString()); bucketArray[1] = nullGuard(failure.getErrorMessage().toString()); bucketArray[2] = nullGuard(failure.getId().toString()); final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); bucketArray[3] = DATE_FORMAT.format(failure.getDate()); formatArray[i++] = bucketArray; } return formatArray; }
Source:
<code>Alphametics(String userInput) { <START> String[] array = userInput.split("=="); <END> wordsToSum = Arrays.stream(array[0].split("\\+")) .map(String::new) .map(String::trim) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); wordResult = array[1].trim(); }</code><technical_language>array a descriptive name. naming questionAndAnswer similar more clear is? :)</technical_language>

Target:
Alphametics(String userInput) { String[] questionAndAnswer = userInput.split("=="); wordsToSum = Arrays.stream(questionAndAnswer[0].split("\\+")) .map(String::new) .map(String::trim) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); wordResult = questionAndAnswer[1].trim(); }
Source:
<code>public void addContents(@NonNull Container container) { container.add( new Content("update-center.md") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); Jenkins instance = Jenkins.getInstance(); if (instance == null) { out.println("Jenkins has not started yet. No update center information is available."); } else { hudson.model.UpdateCenter updateCenter = instance.getUpdateCenter(); out.println("=== Sites ==="); for (UpdateSite c : updateCenter.getSiteList()) { out.println(" - Url: " + c.getUrl()); <START> out.println(" - Connection Url: " + c.getConnectionCheckUrl()); <END> } out.println("======"); out.println("Last updated: " + updateCenter.getLastUpdatedString()); } } } ); }</code><technical_language>want updateCenter.getClass().getName()</technical_language>

Target:
public void addContents(@NonNull Container container) { container.add( new Content("update-center.md") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); Jenkins instance = Jenkins.getInstance(); if (instance == null) { out.println("Jenkins has not started yet. No update center information is available."); } else { hudson.model.UpdateCenter updateCenter = instance.getUpdateCenter(); out.println("=== Sites ==="); for (UpdateSite c : updateCenter.getSiteList()) { out.println(" - Url: " + c.getUrl()); out.println(" - Connection Url: " + c.getConnectionCheckUrl()); out.println(" - Implementation Type: " + c.getClass().getName()); } out.println("======"); out.println("Last updated: " + updateCenter.getLastUpdatedString()); } } } ); }
Source:
<code>private long emitResultAndCleanUpState(long currentWatermark) throws Exception { List<RowData> rightRowsSorted = getRightRowSorted(rightRowtimeComparator); long lastUnprocessedTime = Long.MAX_VALUE; Iterator<Map.Entry<Long, RowData>> leftIterator = leftState.entries().iterator(); <START> Map<Long, RowData> orderedOutputs = new TreeMap<>(); <END> while (leftIterator.hasNext()) { Map.Entry<Long, RowData> entry = leftIterator.next(); Long leftSeq = entry.getKey(); RowData leftRow = entry.getValue(); long leftTime = getLeftTime(leftRow); if (leftTime <= currentWatermark) { Optional<RowData> rightRow = latestRightRowToJoin(rightRowsSorted, leftTime); if (rightRow.isPresent() && RowDataUtil.isAccumulateMsg(rightRow.get())) { if (joinCondition.apply(leftRow, rightRow.get())) { orderedOutputs.put(leftSeq, getJoinedRow(leftRow, rightRow.get())); } else { if (isLeftOuterJoin) { orderedOutputs.put(leftSeq, getJoinedRow(leftRow, rightNullRow)); } } } else { if (isLeftOuterJoin) { orderedOutputs.put(leftSeq, getJoinedRow(leftRow, rightNullRow)); } } leftIterator.remove(); } else { lastUnprocessedTime = Math.min(lastUnprocessedTime, leftTime); } } orderedOutputs.forEach((k, v) -> collector.collect(v)); orderedOutputs.clear(); cleanupExpiredVersionInState(currentWatermark, rightRowsSorted); return lastUnprocessedTime; }</code><technical_language>store left row data avoid copy joined result</technical_language>

Target:
private long emitResultAndCleanUpState(long currentWatermark) throws Exception { List<RowData> rightRowsSorted = getRightRowSorted(rightRowtimeComparator); long lastUnprocessedTime = Long.MAX_VALUE; Iterator<Map.Entry<Long, RowData>> leftIterator = leftState.entries().iterator(); final Map<Long, RowData> orderedLeftRecords = new TreeMap<>(); while (leftIterator.hasNext()) { Map.Entry<Long, RowData> entry = leftIterator.next(); Long leftSeq = entry.getKey(); RowData leftRow = entry.getValue(); long leftTime = getLeftTime(leftRow); if (leftTime <= currentWatermark) { orderedLeftRecords.put(leftSeq, leftRow); leftIterator.remove(); } else { lastUnprocessedTime = Math.min(lastUnprocessedTime, leftTime); } } orderedLeftRecords.forEach((leftSeq, leftRow) -> { long leftTime = getLeftTime(leftRow); Optional<RowData> rightRow = latestRightRowToJoin(rightRowsSorted, leftTime); if (rightRow.isPresent() && RowDataUtil.isAccumulateMsg(rightRow.get())) { if (joinCondition.apply(leftRow, rightRow.get())) { collectJoinedRow(leftRow, rightRow.get()); } else { if (isLeftOuterJoin) { collectJoinedRow(leftRow, rightNullRow); } } } else { if (isLeftOuterJoin) { collectJoinedRow(leftRow, rightNullRow); } } }); orderedLeftRecords.clear(); cleanupExpiredVersionInState(currentWatermark, rightRowsSorted); return lastUnprocessedTime; }
Source:
<code>public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; QueryInterruptedException unauthorizedError = new QueryInterruptedException( QueryInterruptedException.UNAUTHORIZED, null, null, DruidNode.getDefaultHost() ); unauthorizedError.setStackTrace(new StackTraceElement[0]); <START> OutputStream out = httpResponse.getOutputStream(); <END> Boolean authInfoChecked = (Boolean) request.getAttribute(AuthConfig.DRUID_AUTH_TOKEN_CHECKED); String authToken = (String) request.getAttribute(AuthConfig.DRUID_AUTH_TOKEN); if (authInfoChecked != null || authToken != null) { sendJsonError(httpResponse, Response.SC_FORBIDDEN, jsonMapper.writeValueAsString(unauthorizedError), out); return; } chain.doFilter(request, response); }</code><technical_language>out closed</technical_language>

Target:
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; OutputStream out = httpResponse.getOutputStream(); Boolean authInfoChecked = (Boolean) request.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED); AuthenticationResult result = (AuthenticationResult) request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT); if (authInfoChecked != null || result != null) { sendJsonError(httpResponse, Response.SC_FORBIDDEN, unauthorizedMessage, out); out.close(); return; } chain.doFilter(request, response); }
Source:
<code>public void showLinkPreview(PageTitle title, int entrySource) { <START> if (getSupportFragmentManager().findFragmentByTag(LinkPreviewDialog.TAG) == null) { <END> LinkPreviewDialog linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), LinkPreviewDialog.TAG); } }</code><technical_language>This needs a fragment tag, a tag for logging</technical_language>

Target:
public void showLinkPreview(PageTitle title, int entrySource) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { LinkPreviewDialog linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } }
Source:
<code>public void enableUI() { connectButton.setEnabled(true); cancelButton.setEnabled(true); <START> Cursor.getPredefinedCursor(DEFAULT_CURSOR); <END> }</code><technical_language>I this be: java setCursor(Cursor.getPredefinedCursor(DEFAULT_CURSOR));</technical_language>

Target:
public void enableUI() { connectButton.setEnabled(true); cancelButton.setEnabled(true); setCursor(Cursor.getPredefinedCursor(DEFAULT_CURSOR)); }
Source:
<code>private static String getName(@NotNull GoFunctionOrMethodDeclaration element) { <START> PsiElement resolved = element.getIdentifier(); <END> if (resolved == null) { return null; } return resolved.getText().toLowerCase(); }</code><technical_language>? element.getName()</technical_language>

Target:
private static String getName(@NotNull GoFunctionOrMethodDeclaration element) { String name = element.getName(); if (name == null) return null; return name.toLowerCase(Locale.getDefault()); }
Source:
<code>public F.Promise<Result> index() { <START> return F.Promise.pure(redirect(productcatalog.controllers.routes.ProductOverviewPageController.pop(1))); <END> }</code><technical_language>Instead of pop (which I avoid, understands PDP POP acronyms), call show for main action of controller</technical_language>

Target:
public F.Promise<Result> index() { return F.Promise.pure(redirect(productcatalog.controllers.routes.ProductOverviewPageController.show(1))); }
Source:
<code>protected final CmdLineParser newCmdLineParserInstance(final Object bean) { Field f = null; ApproveCmdLineParser parser = new ApproveCmdLineParser(bean); try { f = CmdOption.class.getField("value"); for (CmdOption c : optionList) { <START> parser.addOption(new FieldSetter(c, f), c); <END> } } catch (Exception e) { e.printStackTrace(); } return parser; }</code><technical_language>If instead CmdOption implement Setter interface implement public void addValue(Object value) receive directly, reflection. advantage of this is implement range check of addValue method, need do after-the-fact in validateArguments method. Throwing CmdLineException is out of range args4j toss message user, immediately fail out</technical_language>

Target:
protected final CmdLineParser newCmdLineParserInstance(final Object bean) { CmdLineParser parser = new CmdLineParser(bean); for (CmdOption c : optionList) { parser.addOption(c, c); } return parser; }
Source:
<code>protected void hideStereotypeProperty(final Stereotype stereotype, final Property propertyToHide) { if (diagramElement == null) { <START> return; <END> } try { if (stereotype != null && propertyToHide != null) { View nodeToDisplay = StereotypeDisplayHelper.getInstance().getStereotypeProperty((View) diagramElement, stereotype, propertyToHide); View compartment = helper.getStereotypeCompartment((View) diagramElement, stereotype); helper.setPersistency(getDomain(), nodeToDisplay); helper.setVisibility(getDomain(), nodeToDisplay, false); updateCompartmentVisibility(compartment); } } catch (Exception e) { Activator.logException(e); } }</code><technical_language>void return is forbidden</technical_language>

Target:
protected void hideStereotypeProperty(final Stereotype stereotype, final Property propertyToHide) { if (diagramElement != null) { try { if (stereotype != null && propertyToHide != null) { View nodeToDisplay = StereotypeDisplayHelper.getInstance().getStereotypeProperty((View) diagramElement, stereotype, propertyToHide); View compartment = helper.getStereotypeCompartment((View) diagramElement, stereotype); helper.setPersistency(getDomain(), nodeToDisplay); helper.setVisibility(getDomain(), nodeToDisplay, false); updateCompartmentVisibility(compartment); } } catch (Exception e) { Activator.logException(e); } } }
Source:
<code>public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); Map<String, Long> metricMap = new HashMap<>(); <START> metricMap.put(ReplUtils.MetricName.TAGS.name(), 0L); <END> work.getMetricCollector().reportStageStart(getName(), metricMap); LOG.info("Loading atlas metadata from srcDb: to tgtDb: from staging: {}", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); AtlasLoadLogger replLogger = new AtlasLoadLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir().toString()); replLogger.startLog(); int importCount = importAtlasMetadata(atlasReplInfo); replLogger.endLog(importCount); work.getMetricCollector().reportStageProgress(getName(), ReplUtils.MetricName.TAGS.name(), importCount); LOG.info("Atlas entities import count {}", importCount); work.getMetricCollector().reportStageEnd(getName(), Status.SUCCESS); return 0; } catch (Exception e) { LOG.error("Exception while loading atlas metadata", e); setException(e); try { work.getMetricCollector().reportStageEnd(getName(), Status.FAILED); } catch (SemanticException ex) { LOG.error("Failed to collect Metrics ", ex); } return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }</code><technical_language>TAG: entities</technical_language>

Target:
public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); Map<String, Long> metricMap = new HashMap<>(); metricMap.put(ReplUtils.MetricName.ENTITIES.name(), 0L); work.getMetricCollector().reportStageStart(getName(), metricMap); LOG.info("Loading atlas metadata from srcDb: to tgtDb: from staging: {}", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); AtlasLoadLogger replLogger = new AtlasLoadLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir().toString()); replLogger.startLog(); int importCount = importAtlasMetadata(atlasReplInfo); replLogger.endLog(importCount); work.getMetricCollector().reportStageProgress(getName(), ReplUtils.MetricName.ENTITIES.name(), importCount); LOG.info("Atlas entities import count {}", importCount); work.getMetricCollector().reportStageEnd(getName(), Status.SUCCESS); return 0; } catch (Exception e) { LOG.error("Exception while loading atlas metadata", e); setException(e); try { work.getMetricCollector().reportStageEnd(getName(), Status.FAILED); } catch (SemanticException ex) { LOG.error("Failed to collect Metrics ", ex); } return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }
Source:
<code>private void resetOffsetIfNeeded(TopicPartition partition, OffsetResetStrategy requestedResetStrategy, ListOffsetData offsetData) { SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetData.offset, offsetData.leaderEpoch, metadata.leaderAndEpoch(partition)); offsetData.leaderEpoch.ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(partition, epoch)); <START> subscriptions.maybeSeekUnvalidated(partition, position, requestedResetStrategy); <END> }</code><technical_language>Mentioned offline, is a behavioral change here. Previously validate offset reset in case, I if offset returned ListOffset request epoch. I simple do is Optional.empty() defining position</technical_language>

Target:
private void resetOffsetIfNeeded(TopicPartition partition, OffsetResetStrategy requestedResetStrategy, ListOffsetData offsetData) { SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetData.offset, Optional.empty(), metadata.leaderAndEpoch(partition)); offsetData.leaderEpoch.ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(partition, epoch)); subscriptions.maybeSeekUnvalidated(partition, position, requestedResetStrategy); }
Source:
<code>private static void validateSchema(OMElement claimElement) throws UserStoreException { String message = null; if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_CLAIM_URI)) == null) { message = "In valid schema <ClaimUri> element not present"; if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_DESCRIPTION)) == null) { <START> message = "In valid schema <Description> element not present"; <END> if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_ATTR_ID)) == null) { message = "In valid schema <AttributeId> element not present"; if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } }</code><technical_language>This variable assignment appears redundant</technical_language>

Target:
private static void validateSchema(OMElement claimElement) throws UserStoreException { String message; if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_CLAIM_URI)) == null) { message = "In valid schema <ClaimUri> element not present"; if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_DESCRIPTION)) == null) { message = "In valid schema <Description> element not present"; if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } if (claimElement.getFirstChildWithName(new QName(LOCAL_NAME_ATTR_ID)) == null) { message = "In valid schema <AttributeId> element not present"; if (log.isDebugEnabled()) { log.debug(message); } throw new UserStoreException(message); } }
Source:
<code>public void shouldReturn400_whenCorporatePrepaidCreditCardSurchargeOperationIsMissing() { JsonNode jsonNode = new ObjectMapper() .valueToTree(ImmutableMap.of( "path", "corporate_prepaid_credit_card_surcharge_amount", "value", 250)); Response response = resources.client() .target("/v1/api/accounts/12") .request() .method("PATCH", Entity.json(jsonNode)); assertThat(response.getStatus(), is(400)); <START> String errorMessage = response.readEntity(JsonNode.class).get("message").get(0).textValue(); <END> assertThat(errorMessage, is("Field [op] is required")); }</code><technical_language>I related story test assert "message" field is array of size 1 too? more rigorous</technical_language>

Target:
public void shouldReturn400_whenCorporatePrepaidCreditCardSurchargeOperationIsMissing() { JsonNode jsonNode = new ObjectMapper() .valueToTree(ImmutableMap.of( "path", "corporate_prepaid_credit_card_surcharge_amount", "value", 250)); Response response = resources.client() .target("/v1/api/accounts/12") .request() .method("PATCH", Entity.json(jsonNode)); assertThat(response.getStatus(), is(400)); JsonNode body = response.readEntity(JsonNode.class); assertErrorBodyMatches(body, "Field [op] is required", ErrorIdentifier.GENERIC); }
Source:
<code>private SSLEngine createSSLEngine(boolean clientMode) { final SSLContext <START> ctx = <END> this.sslContext; if (ctx == null) { return null; } final SSLEngine engine = ctx.createSSLEngine(); engine.setUseClientMode(clientMode); return engine; }</code><technical_language>a local variable</technical_language>

Target:
private SSLEngine createSSLEngine(boolean clientMode) { final SSLEngine engine = this.sslContext.createSSLEngine(); engine.setUseClientMode(clientMode); return engine; }
Source:
<code>public List<VariableReferenceExpression> getOutputs() { <START> return unmodifiableList(new ArrayList<>(assignments.keySet())); <END> }</code><technical_language>I a bit concerned getOutput random order. ok optimization, lookup variable name. execution, variables changed inputChannel (i.e. index in list returned getOutputs), a change in order mismatching. HashMap's keySet order easily change. Also, code ImmutableList.copyOf(assignments.keySet()); is cheap ImmutableList.copyOf smartly utilized underlying data structure, copy happened. But, do copying time. Here, save member variable construction return this list instead. need extra memory is bad unexpected behavior GC</technical_language>

Target:
public List<VariableReferenceExpression> getOutputs() { return outputs; }
Source:
<code>private BufferedReader getBufferedReader() throws IOException { String extension; Charset charset; if (FileUtil.isUrl(uri)) { extension = FileUtil.getUrlExtension(uri).toLowerCase(PMS.getLocale()); } else { extension = FileUtil.getExtension(uri).toLowerCase(PMS.getLocale()); } if (extension != null && (extension.equals("m3u8") || extension.equals(".cue"))) { charset = StandardCharsets.UTF_8; } else { charset = StandardCharsets.ISO_8859_1; } if (FileUtil.isUrl(uri)) { return new BufferedReader(new InputStreamReader(new BOMInputStream(new URL(uri).openStream()), charset)); } else { File playlistfile = new File(uri); if (playlistfile.length() < 10000000) { try (FileInputStream fis = new FileInputStream(playlistfile)) { <START> return new BufferedReader(new InputStreamReader(new BOMInputStream(fis), charset)); <END> } } } return null; }</code><technical_language>I unsure this one. this, returning a live stream, this returning a closed stream</technical_language>

Target:
private BufferedReader getBufferedReader() throws IOException { String extension; Charset charset; if (FileUtil.isUrl(uri)) { extension = FileUtil.getUrlExtension(uri).toLowerCase(PMS.getLocale()); } else { extension = FileUtil.getExtension(uri).toLowerCase(PMS.getLocale()); } if (extension != null && (extension.equals("m3u8") || extension.equals(".cue"))) { charset = StandardCharsets.UTF_8; } else { charset = StandardCharsets.ISO_8859_1; } if (FileUtil.isUrl(uri)) { return new BufferedReader(new InputStreamReader(new BOMInputStream(new URL(uri).openStream()), charset)); } else { File playlistfile = new File(uri); if (playlistfile.length() < 10000000) { FileInputStream fis = new FileInputStream(playlistfile); return new BufferedReader(new InputStreamReader(new BOMInputStream(fis), charset)); } } return null; }
Source:
<code>public void testAddLocation() { Mockito.when(this.locationDataManager.getUserDefinedFieldIdOfCode(UDTableType.LOCATION_LTYPE, LocationType.BLOCK.getCode())).thenReturn(1001); Mockito.when(this.locationDataManager.getUserDefinedFieldIdOfCode(UDTableType.LOCDES_DTYPE, LocdesType.BLOCK_PARENT.getCode())).thenReturn(1002); this.fieldbookServiceImpl.addLocation("LOCNAME", 1, 101, LocationType.BLOCK.getCode(), LocdesType.BLOCK_PARENT.getCode()); Mockito.verify(this.locationDataManager).getUserDefinedFieldIdOfCode(UDTableType.LOCATION_LTYPE, LocationType.BLOCK.getCode()); Mockito.verify(this.locationDataManager).getUserDefinedFieldIdOfCode(UDTableType.LOCDES_DTYPE, LocdesType.BLOCK_PARENT.getCode()); <START> Mockito.verify(this.locationDataManager).addLocationAndLocdes(ArgumentMatchers.any(Location.class), ArgumentMatchers.any(Locdes.class)); <END> }</code><technical_language>**ArgumentCaptor** perform assertions parameters **addLocationAndLocDes** method code change is default values</technical_language>

Target:
public void testAddLocation() { Mockito.when(this.locationDataManager.getUserDefinedFieldIdOfCode(UDTableType.LOCATION_LTYPE, LocationType.BLOCK.getCode())).thenReturn(1001); Mockito.when(this.locationDataManager.getUserDefinedFieldIdOfCode(UDTableType.LOCDES_DTYPE, LocdesType.BLOCK_PARENT.getCode())).thenReturn(1002); this.fieldbookServiceImpl.addLocation("LOCNAME", 1, 101, LocationType.BLOCK.getCode(), LocdesType.BLOCK_PARENT.getCode()); Mockito.verify(this.locationDataManager).getUserDefinedFieldIdOfCode(UDTableType.LOCATION_LTYPE, LocationType.BLOCK.getCode()); Mockito.verify(this.locationDataManager).getUserDefinedFieldIdOfCode(UDTableType.LOCDES_DTYPE, LocdesType.BLOCK_PARENT.getCode()); final ArgumentCaptor<Location> locationCaptor = ArgumentCaptor.forClass(Location.class); final ArgumentCaptor<Locdes> locdesCaptor = ArgumentCaptor.forClass(Locdes.class); Mockito.verify(this.locationDataManager).addLocationAndLocdes(locationCaptor.capture(), locdesCaptor.capture()); final Location location = locationCaptor.getValue(); final Locdes locdes = locdesCaptor.getValue(); Assert.assertEquals("1001", location.getLtype().toString()); Assert.assertEquals("LOCNAME", location.getLname()); Assert.assertNull(location.getLabbr()); Assert.assertEquals("1002", locdes.getTypeId().toString()); Assert.assertEquals("101", locdes.getUserId().toString()); Assert.assertEquals("1", locdes.getDval()); }
Source:
<code>public void storeCertificate(String pemEncodedCert, boolean force) throws CertificateException { CertificateCodec certificateCodec = new CertificateCodec(securityConfig); try { Path basePath = securityConfig.getCertificateLocation(); String certName; X509Certificate cert = CertificateCodec.getX509Certificate(pemEncodedCert); <START> certName = String.format(CERT_FILE_NAME_FORMAT, <END> cert.getSerialNumber().toString()); certificateCodec.writeCertificate(basePath, certName, pemEncodedCert, force); certificateMap.putIfAbsent(cert.getSerialNumber().toString(), cert); } catch (IOException | java.security.cert.CertificateException e) { throw new CertificateException("Error while storing certificate.", e, CERTIFICATE_ERROR); } }</code><technical_language>NIT: move line 458 461 combine together</technical_language>

Target:
public void storeCertificate(String pemEncodedCert, boolean force) throws CertificateException { CertificateCodec certificateCodec = new CertificateCodec(securityConfig); try { Path basePath = securityConfig.getCertificateLocation(); X509Certificate cert = CertificateCodec.getX509Certificate(pemEncodedCert); String certName = String.format(CERT_FILE_NAME_FORMAT, cert.getSerialNumber().toString()); certificateCodec.writeCertificate(basePath, certName, pemEncodedCert, force); certificateMap.putIfAbsent(cert.getSerialNumber().toString(), cert); } catch (IOException | java.security.cert.CertificateException e) { throw new CertificateException("Error while storing certificate.", e, CERTIFICATE_ERROR); } }
Source:
<code>public String findAllCommentsIdsStartingFrom(Date date) { final String commentsIds = ""; final Objectify objectify = OfyService.ofy(); final List<TechnologyComment> comments = objectify.load().type(TechnologyComment.class) <START> .filter(TechnologyComment.TIMESTAMP + " >" , date).list(); <END> for (TechnologyComment technologyComment : comments) { commentsIds.concat("," + technologyComment.getId()); } return commentsIds; }</code><technical_language>">=" ? @felipeaziz @tsr-thulio @brunoliberal</technical_language>

Target:
public String findAllCommentsIdsStartingFrom(Date date) { String commentsIds = ""; final Objectify objectify = OfyService.ofy(); final List<TechnologyComment> comments = objectify.load().type(TechnologyComment.class) .filter(TechnologyComment.TIMESTAMP + " >" , date).list(); for (TechnologyComment technologyComment : comments) { commentsIds = commentsIds.concat("," + technologyComment.getId()); } return commentsIds; }
Source:
<code>public void request(long n) { if (n < 1) { throw new IllegalArgumentException("Only postive values are valid - passed-in " + n); } requested.addAndGet(n); synchronized (buffer) { InboundSseEvent bufferedEvent = null; while (delivered.get() < requested.get() <START> && (bufferedEvent = ((LinkedList<InboundSseEvent>) buffer).pollFirst()) != null) { <END> InboundSseEvent finalEvent = bufferedEvent; delivered.updateAndGet(l -> { subscriber.onNext(finalEvent); return l + 1; }); } } }</code><technical_language>declare buffer a LinkedList instead of Queue (it is private member anyway) eliminate casting</technical_language>

Target:
public void request(long n) { if (canceled.get()) { return; } if (n < 1) { fireError(new IllegalArgumentException("Only positive values may be requested - passed-in " + n)); return; } requested.addAndGet(n); synchronized (buffer) { InboundSseEvent bufferedEvent = null; synchronized (delivered) { while (delivered.get() < requested.get() && (bufferedEvent = buffer.pollFirst()) != null) { subscriber.onNext(bufferedEvent); delivered.incrementAndGet(); } } } }
Source:
<code>public void setPermissive(String statusDirectory, String importFileName, long badRecordThreshold){ this.permissive=true; this.badRecordThreshold = badRecordThreshold; <START> if(importFileName == null)importFileName="unspecified_" + System.currentTimeMillis(); <END> BadRecordsRecorder badRecordsRecorder = new BadRecordsRecorder(statusDirectory, importFileName, badRecordThreshold); this.badRecordsAccumulator=SpliceSpark.getContext().accumulable(badRecordsRecorder, badRecordsRecorder.getUniqueName(), new BadRecordsAccumulator()); }</code><technical_language>a static contant for reference "unspecified_" of method</technical_language>

Target:
public void setPermissive(String statusDirectory, String importFileName, long badRecordThreshold){ this.permissive=true; this.badRecordThreshold = badRecordThreshold; if(importFileName == null)importFileName=BAD_FILENAME + System.currentTimeMillis(); BadRecordsRecorder badRecordsRecorder = new BadRecordsRecorder(statusDirectory, importFileName, badRecordThreshold); this.badRecordsAccumulator=SpliceSpark.getContext().accumulable(badRecordsRecorder, badRecordsRecorder.getUniqueName(), new BadRecordsAccumulator()); }
Source:
<code>private String enableCapabilities(final ProgressMonitor monitor, OutputStream outputStream) { final StringBuilder line = new StringBuilder(); if (atomic) capableAtomic = wantCapability(line, CAPABILITY_ATOMIC); capableReport = wantCapability(line, CAPABILITY_REPORT_STATUS); capableDeleteRefs = wantCapability(line, CAPABILITY_DELETE_REFS); capableOfsDelta = wantCapability(line, CAPABILITY_OFS_DELTA); <START> capablePushOptions = wantCapability(line, PUSH_OPTIONS); <END> capableSideBand = wantCapability(line, CAPABILITY_SIDE_BAND_64K); if (capableSideBand) { in = new SideBandInputStream(in, monitor, getMessageWriter(), outputStream); pckIn = new PacketLineIn(in); } addUserAgentCapability(line); if (line.length() > 0) line.setCharAt(0, '\0'); return line.toString(); }</code><technical_language>wantCapability(line, ...); 2 things, checks if remote side supports step is adding option line, transmit server selection of options want use. If remote advertises is capable of a push options phase, necessarily want it. (We pushOptions == null command line argument given), I this line conditional pushOptions == null</technical_language>

Target:
private String enableCapabilities(final ProgressMonitor monitor, OutputStream outputStream) { final StringBuilder line = new StringBuilder(); if (atomic) capableAtomic = wantCapability(line, CAPABILITY_ATOMIC); capableReport = wantCapability(line, CAPABILITY_REPORT_STATUS); capableDeleteRefs = wantCapability(line, CAPABILITY_DELETE_REFS); capableOfsDelta = wantCapability(line, CAPABILITY_OFS_DELTA); capablePushOptions = wantCapability(line, CAPABILITY_PUSH_OPTIONS); capableSideBand = wantCapability(line, CAPABILITY_SIDE_BAND_64K); if (capableSideBand) { in = new SideBandInputStream(in, monitor, getMessageWriter(), outputStream); pckIn = new PacketLineIn(in); } addUserAgentCapability(line); if (line.length() > 0) line.setCharAt(0, '\0'); return line.toString(); }
Source:
<code>protected void onResume() { super.onResume(); Log.i("DD", "onResume()"); SharedPreferences sharedPrefs = this.getSharedPreferences( "skip_intro", this.MODE_PRIVATE); <START> Log.i("DD", "" + (sharedPrefs.getInt("clickedSkip", 0))); <END> if(sharedPrefs.getInt("clickedSkip", 0) == 1) { startActivity(new Intent(this, AccountActivity.class)); finish(); } }</code><technical_language>extract shared preferences names constants settings.xml public static final String variables</technical_language>

Target:
protected void onResume() { super.onResume(); if(Preferences.getSkipButton() == true) { startActivity(new Intent(this, AccountActivity.class)); finish(); } }
Source:
<code>protected T validateValueInternal(T rawValue) throws ProcessingException { T validValue; if (rawValue == null) { validValue = null; } else { <START> T t = TypeCastUtility.castValue(rawValue, getHolderType()); <END> IRadioButton b = getButtonFor(t); if (b != null) { validValue = t; } else { throw new ProcessingException("Illegal radio value: " + rawValue); } } return validValue; }</code><technical_language>is need for casting</technical_language>

Target:
protected T validateValueInternal(T rawValue) throws ProcessingException { T validValue; if (rawValue == null) { validValue = null; } else { IRadioButton b = getButtonFor(rawValue); if (b != null) { validValue = rawValue; } else { throw new ProcessingException("Illegal radio value: " + rawValue); } } return validValue; }
Source:
<code>private void tryToConnect(InetSocketAddress socketAddress, int timeout) throws Exception { SocketChannel socketChannel = SocketChannel.open(); Channel channel = connectionManager.createChannel(socketChannel, true); boolean success = false; try { if (ioService.isSocketBind()) { bindSocket(socketChannel); } Level level = silent ? Level.FINEST : Level.INFO; if (logger.isLoggable(level)) { logger.log(level, "Connecting to " + socketAddress + ", timeout: " + timeout + ", bind-any: " + ioService.isSocketBindAny()); } try { channel.connect(socketAddress, timeout); ioService.interceptSocket(socketChannel.socket(), false); TcpIpConnection connection = connectionManager.newConnection(channel, address); connectionManager.sendBindRequest(connection, address, true); success = true; } catch (NullPointerException e) { closeSocket(socketChannel); logger.log(level, "Could not connect to: " + socketAddress + ". Reason: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); logger.log(Level.INFO, "Add this stacktrace to <LINK_0> please!", e); throw e; } catch (Exception e) { closeSocket(socketChannel); logger.log(level, "Could not connect to: " + socketAddress + ". Reason: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); throw e; } } finally { if (!success) { <START> connectionManager.acceptedChannels.remove(channel); <END> } } }</code><technical_language>wrap acceptedChannels.remove() a method? a cleaner way. I think, !success check is needed - remove care of (i.e. want remove in case). If connectionManager.newConnection() implementation is changed in a future remove channel, this a guard</technical_language>

Target:
private void tryToConnect(InetSocketAddress socketAddress, int timeout) throws Exception { SocketChannel socketChannel = SocketChannel.open(); Channel channel = connectionManager.createChannel(socketChannel, true); try { if (ioService.isSocketBind()) { bindSocket(socketChannel); } Level level = silent ? Level.FINEST : Level.INFO; if (logger.isLoggable(level)) { logger.log(level, "Connecting to " + socketAddress + ", timeout: " + timeout + ", bind-any: " + ioService.isSocketBindAny()); } try { channel.connect(socketAddress, timeout); ioService.interceptSocket(socketChannel.socket(), false); TcpIpConnection connection = connectionManager.newConnection(channel, address); connectionManager.sendBindRequest(connection, address, true); } catch (NullPointerException e) { closeSocket(socketChannel); logger.log(level, "Could not connect to: " + socketAddress + ". Reason: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); logger.log(Level.INFO, "Add this stacktrace to <LINK_0> please!", e); throw e; } catch (Exception e) { closeSocket(socketChannel); logger.log(level, "Could not connect to: " + socketAddress + ". Reason: " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); throw e; } } finally { connectionManager.removeAcceptedChannel(channel); } }
Source:
<code>public @Nullable String resolve(ISegment segment) { <START> if (segment instanceof TmfXmlPatternSegment) { <END> StringBuilder value = new StringBuilder(); int nbEntry = 0; for (Map.Entry<String, ITmfStateValue> content : ((TmfXmlPatternSegment) segment).getContent().entrySet()) { if (nbEntry > 0) { value.append(", "); } value.append(content.getKey()).append("=").append(content.getValue()); nbEntry++; } return value.toString(); } return EMPTY_STRING; }</code><technical_language>replace code if this: List<String> values = ((TmfXmlPatternSegment) segment).getContent().entrySet().stream().map(c -> c.getKey() + '=' + c.getValue()).collect(Collectors.toList()); return String.join(", ", values); //$NON-NLS-1$ avoids nbEntry add ',' not</technical_language>

Target:
public @Nullable String resolve(ISegment segment) { if (segment instanceof TmfXmlPatternSegment) { List<String> values = ((TmfXmlPatternSegment) segment).getContent().entrySet().stream().map(c -> c.getKey() + '=' + c.getValue()).collect(Collectors.toList()); return String.join(", ", values); } return EMPTY_STRING; }
Source:
<code><START> public QueriesCommandBase(P parameters, EngineContext engineContext) { <END> this.parameters = parameters; returnValue = new VdcQueryReturnValue(); queryType = initQueryType(); user = initUser(); }</code><technical_language>context</technical_language>

Target:
public QueriesCommandBase(P parameters, EngineContext engineContext) { this.parameters = parameters; returnValue = new VdcQueryReturnValue(); queryType = initQueryType(); user = initUser(); this.engineContext = engineContext; }
Source:
<code>private boolean isInstanceTimedOutDuringMaintenance(HelixDataAccessor accessor, String instance, long timeOutWindow) { PropertyKey.Builder keyBuilder = accessor.keyBuilder(); PropertyKey propertyKey = keyBuilder.participantHistory(instance); ParticipantHistory history = accessor.getProperty(propertyKey); long lastOfflineTime = history.getLastTimeInOfflineHistory(); if (lastOfflineTime < 0) { return false; } long currentTime = System.currentTimeMillis(); if (currentTime - lastOfflineTime > timeOutWindow) { LogUtil.logWarn(logger, getClusterEventId(), String.format( "During maintenance mode, instance %s is timed-out due to its offline time. Current time: " + "%s, Last offline time: %s, Timeout window: %s", instance, currentTime, lastOfflineTime, timeOutWindow)); return true; } return false; <START> } <END></code><technical_language>Due reason, want limit timeout setup more 5 mins (for example). A small number sense, work expected anyway</technical_language>

Target:
private boolean isInstanceTimedOutDuringMaintenance(HelixDataAccessor accessor, String instance, long timeOutWindow) { ParticipantHistory history = accessor.getProperty(accessor.keyBuilder().participantHistory(instance)); List<Long> onlineTimestamps = history.getOnlineTimestampsAsMilliseconds(); List<Long> offlineTimestamps = history.getOfflineTimestampsAsMilliseconds(); onlineTimestamps.add(System.currentTimeMillis()); for (int onlineTimestampIndex = onlineTimestamps.size() - 1, offlineTimestampIndex = offlineTimestamps.size() - 1; onlineTimestampIndex >= 0 && offlineTimestampIndex >= 0; onlineTimestampIndex--) { long onlineWindowRight = onlineTimestamps.get(onlineTimestampIndex); if (onlineWindowRight <= _maintenanceSignal.getTimestamp()) { break; } long onlineWindowLeft = 0L; if (onlineTimestampIndex > 0) { onlineWindowLeft = onlineTimestamps.get(onlineTimestampIndex - 1); } if (offlineTimestamps.get(offlineTimestampIndex) <= onlineWindowLeft) { continue; } while (offlineTimestampIndex >= 0 && offlineTimestamps.get(offlineTimestampIndex) > onlineWindowLeft) { offlineTimestampIndex--; } long offlineTimeStamp = offlineTimestamps.get(offlineTimestampIndex + 1); if (onlineWindowRight - offlineTimeStamp > timeOutWindow) { LogUtil.logWarn(logger, getClusterEventId(), String.format( "During maintenance mode, instance %s is timed-out due to its offline time. Online time: " + "%s, Offline time: %s, Timeout window: %s", instance, onlineWindowRight, offlineTimeStamp, timeOutWindow)); return true; } } return false; }
Source:
<code>public static boolean addResourceToSet(ResourceSet resourceSet, URI resourceURI) { try { final Map<Object, Object> loadOptions = new HashMap<Object, Object>(); loadOptions.put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE); resourceSet.createResource(resourceURI).load(loadOptions); int rsSize = resourceSet.getResources().size(); EcoreUtil.resolveAll(resourceSet); while (rsSize != resourceSet.getResources().size()) { EcoreUtil.resolveAll(resourceSet); rsSize = resourceSet.getResources().size(); } return true; } catch (final IOException e) { <START> <END> } return false; }</code><technical_language>reportservice</technical_language>

Target:
public static boolean addResourceToSet(ResourceSet resourceSet, URI resourceURI) { try { final Map<Object, Object> loadOptions = new HashMap<Object, Object>(); loadOptions.put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE); resourceSet.createResource(resourceURI).load(loadOptions); int rsSize = resourceSet.getResources().size(); EcoreUtil.resolveAll(resourceSet); while (rsSize != resourceSet.getResources().size()) { EcoreUtil.resolveAll(resourceSet); rsSize = resourceSet.getResources().size(); } return true; } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return false; }
Source:
<code>public ElasticAgentRequestProcessor(PluginRequestProcessorRegistry registry, AgentService agentService, AgentConfigService agentConfigService) { <START> this(registry, new ElasticAgentRequestProcessorV1(agentService, agentConfigService), <END> new ElasticAgentRequestProcessorV2(agentService, agentConfigService), new ElasticAgentRequestProcessorV3(agentService, agentConfigService) ); }</code><technical_language>I this is incorrect. While elastic agent extension version changed time, processor contract changed all. create versions for this then</technical_language>

Target:
public ElasticAgentRequestProcessor(PluginRequestProcessorRegistry registry, AgentService agentService, AgentConfigService agentConfigService) { this(registry, new HashMap<String, VersionableElasticAgentProcessor>() {{ put("1.0", new ElasticAgentRequestProcessorV1(agentService, agentConfigService)); put("2.0", new ElasticAgentRequestProcessorV1(agentService, agentConfigService)); put("3.0", new ElasticAgentRequestProcessorV1(agentService, agentConfigService)); }}); }
Source:
<code><START> public static ContentFilter get() { <END> return ExtensionList.lookupSingleton(ContentFilters.class).isEnabled() ? ALL : DISABLED; }</code><technical_language>cleaner get rid of DISABLED filter rewrite code if isEnabled is false access filters create a FilteredOutputStream all. I move filter ContentFilter.java this file is anonymization config settings</technical_language>

Target:
public static ContentFilters get() { return ExtensionList.lookupSingleton(ContentFilters.class); }
Source:
<code>public MultipartUploadMetadata(@Nullable String archiveDescription, Date creationDate, String multipartUploadId, long partSizeInBytes, String vaultARN, @Nullable Iterable<PartMetadata> parts, @Nullable String marker) { super(); this.archiveDescription = archiveDescription; <START> this.creationDate = checkNotNull(creationDate, "creationDate"); <END> this.multipartUploadId = checkNotNull(multipartUploadId, "multipartUploadId"); this.partSizeInBytes = partSizeInBytes; this.vaultARN = checkNotNull(vaultARN, "vaultARN"); this.parts = parts; this.marker = marker; }</code><technical_language>Call creationDate.clone well</technical_language>

Target:
public MultipartUploadMetadata(@Nullable String archiveDescription, Date creationDate, String multipartUploadId, long partSizeInBytes, String vaultARN, @Nullable Iterable<PartMetadata> parts, @Nullable String marker) { super(); this.archiveDescription = archiveDescription; this.creationDate = (Date) checkNotNull(creationDate, "creationDate").clone(); this.multipartUploadId = checkNotNull(multipartUploadId, "multipartUploadId"); this.partSizeInBytes = partSizeInBytes; this.vaultARN = checkNotNull(vaultARN, "vaultARN"); this.parts = parts; this.marker = marker; }
Source:
<code>public boolean matches(NameKey name) { if (matchAll) { return true; } else { String projectName = name.get(); for <START> (final String <END> projectMatch : projectsToMatch) { if (isRE(projectMatch)) { if (projectName.matches(projectMatch)) { return true; } } else if (isWildcard(projectMatch)) { if (projectName.startsWith(projectMatch.substring(0, projectMatch.length() - 1))) { return true; } } else { if (projectName.equals(projectMatch)) { return true; } } } return false; } }</code><technical_language>final in new code. Yes, final in code, copy/paste new code</technical_language>

Target:
public boolean matches(NameKey name) { if (projectPatterns.isEmpty()) { return true; } else { String projectName = name.get(); for (String pattern : projectPatterns) { if (isRE(pattern)) { if (projectName.matches(pattern)) { return true; } } else if (isWildcard(pattern)) { if (projectName.startsWith(pattern.substring(0, pattern.length() - 1))) { return true; } } else { if (projectName.equals(pattern)) { return true; } } } return false; } }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { <START> if (actionsCount > 0 && position >= actionsStartPosition) { <END> HorizontalMediaView tiav = (HorizontalMediaView)convertView; if (tiav == null) { tiav = new HorizontalMediaView(context); } Action currentAction = detail.getCustomActions().get(position - actionsStartPosition); tiav.setDisplay(currentAction.getDisplay()); tiav.setBackgroundResource(R.drawable.list_bottom_tab); int padding = (int)context.getResources().getDimension(R.dimen.entity_padding); tiav.setPadding(padding, padding, padding, padding); return tiav; } Entity<TreeReference> entity = current.get(position); if (usesGridView) { GridEntityView emv = (GridEntityView)convertView; int[] titleColor = AndroidUtil.getThemeColorIDs(context, new int[]{R.attr.entity_select_title_text_color}); if (emv == null) { emv = new GridEntityView(context, detail, entity, currentSearchTerms, mImageLoader, mFuzzySearchEnabled); } else { emv.setSearchTerms(currentSearchTerms); emv.setViews(context, detail, entity); } emv.setTitleTextColor(titleColor[0]); return emv; } else { EntityView emv = (EntityView)convertView; if (emv == null) { emv = EntityView.buildEntryEntityView(context, detail, entity, null, currentSearchTerms, position, mFuzzySearchEnabled); } else { emv.setSearchTerms(currentSearchTerms); emv.refreshViewsForNewEntity(entity, entity.getElement().equals(selected), position); } return emv; } }</code><technical_language>nice factor 2 cases out methods, e.g. getActionView() getNormalView()</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (actionsCount > 0 && position >= actionsStartPosition) { return getActionView(position, (HorizontalMediaView)convertView); } Entity<TreeReference> entity = current.get(position); if (usesGridView) { return getGridView(entity, (GridEntityView)convertView); } else { return getEntityView(entity, (EntityView)convertView, position); } }