auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testSelectStarOnForbiddenTable() throws Exception { <START> assertQueryIsForbidden( <END> "SELECT * FROM druid.forbiddenDatasource", CalciteTests.REGULAR_USER_AUTH_RESULT ); testQuery( "SELECT * FROM druid.forbiddenDatasource", CalciteTests.SUPER_USER_AUTH_RESULT, ImmutableList.<Query>of( newScanQueryBuilder() .dataSource(CalciteTests.FORBIDDEN_DATASOURCE) .intervals(QSS(Filtration.eternity())) .columns("__time", "cnt", "dim1", "dim2", "m1", "m2", "unique_dim1") .resultFormat(ScanQuery.RESULT_FORMAT_COMPACTED_LIST) .context(QUERY_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{T("2000-01-01"), 1L, "forbidden", "abcd", 9999.0f, 0.0, HLLCV1.class.getName()} ) ); }</code><technical_language>ExpectedException</technical_language>

Target:
public void testSelectStarOnForbiddenTable() throws Exception { assertQueryIsForbidden( "SELECT * FROM druid.forbiddenDatasource", CalciteTests.REGULAR_USER_AUTH_RESULT ); testQuery( PLANNER_CONFIG_DEFAULT, "SELECT * FROM druid.forbiddenDatasource", CalciteTests.SUPER_USER_AUTH_RESULT, ImmutableList.<Query>of( newScanQueryBuilder() .dataSource(CalciteTests.FORBIDDEN_DATASOURCE) .intervals(QSS(Filtration.eternity())) .columns("__time", "cnt", "dim1", "dim2", "m1", "m2", "unique_dim1") .resultFormat(ScanQuery.RESULT_FORMAT_COMPACTED_LIST) .context(QUERY_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{T("2000-01-01"), 1L, "forbidden", "abcd", 9999.0f, 0.0, HLLCV1.class.getName()} ) ); }
Source:
<code>public OuiaComponentIdAttribute ouiaComponentId() { return new OuiaComponentIdAttribute(OUIA_COMPONENT_TYPE + "-" + <START> dock.getDockPosition().getShortName() + <END> "-" + dock.getIdentifier()); }</code><technical_language>imo need for id hierarchy (I assume variable is parent element, correct if I wrong) - OUIA_COMPONENT_TYPE + "-" + "dock.getIdentifier()" enough, typically navigate in tests by: cy.get(dock-by-ouia-id).get(item-by-ouia-id) item-by-ouia-id selector needs unique in context of dock (thus save some letters in name). Though, based preference rules want set for project</technical_language>

Target:
public OuiaComponentIdAttribute ouiaComponentId() { return new OuiaComponentIdAttribute(OUIA_COMPONENT_TYPE + "-" + dock.getIdentifier()); }
Source:
<code>List<MetricFamilySamples> fromTimer(String name, Timer timer) { return fromSnapshotAndCount(name, timer.getSnapshot(), timer.getCount(), <START> 1.0D / TIME_UNIT.toNanos(1L), getHelpMessage(name, timer)); <END> }</code><technical_language>TimeUnit.Seconds clearer</technical_language>

Target:
List<MetricFamilySamples> fromTimer(String name, Timer timer) { return fromSnapshotAndCount(name, timer.getSnapshot(), timer.getCount(), 1.0D / TimeUnit.SECONDS.toNanos(1L), getHelpMessage(name, timer)); }
Source:
<code>private boolean manageScenarioBodyRightClick(final ScenarioGrid scenarioGrid, final int left, <START> final int top, <END> final int uiRowIndex, final int uiColumnIndex) { ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } String group = scenarioGridColumn.getInformationHeaderMetaData().getColumnGroup(); switch (group) { case GIVEN: case EXPECT: gridContextMenu.show(left, top, uiRowIndex); break; default: unmodifiableColumnGridContextMenu.show(left, top, uiRowIndex); } scenarioGrid.setSelectedCell(uiRowIndex, uiColumnIndex); return true; }</code><technical_language>@gitgabrio please explain removed this? I added scenarioGrid.clearSelections(); clear selection @ line 133, scenarioGrid.deselect(); modifies a status</technical_language>

Target:
private boolean manageScenarioBodyRightClick(final ScenarioGrid scenarioGrid, final int left, final int top, final int uiRowIndex, final int uiColumnIndex) { ScenarioGridColumn scenarioGridColumn = (ScenarioGridColumn) scenarioGrid.getModel().getColumns().get(uiColumnIndex); if (scenarioGridColumn == null) { return false; } String group = scenarioGridColumn.getInformationHeaderMetaData().getColumnGroup(); switch (group) { case "GIVEN": case "EXPECT": gridContextMenu.show(left, top, uiRowIndex); break; default: unmodifiableColumnGridContextMenu.show(left, top, uiRowIndex); } scenarioGrid.setSelectedCell(uiRowIndex, uiColumnIndex); return true; }
Source:
<code>public void init(int position, boolean isDropDownView, String savedLanguageValue) { String languageCode = LangCodeUtils.fixLanguageCode(languageCodesList.get(position)); final String languageName = StringUtils.capitalize(languageNamesList.get(position)); <START> if(savedLanguageValue!=null && savedLanguageValue.equals("")){ <END> savedLanguageValue = Locale.getDefault().getLanguage(); } if (!isDropDownView) { if( !dropDownClicked && savedLanguageValue !=null){ languageCode = LangCodeUtils.fixLanguageCode(savedLanguageValue); } view.setVisibility(View.GONE); if (languageCode.length() > 2) tvLanguage.setText(languageCode.substring(0, 2)); else tvLanguage.setText(languageCode); } else { view.setVisibility(View.VISIBLE); if (languageCodesList.get(position).isEmpty()) { tvLanguage.setText(languageName); tvLanguage.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } else { tvLanguage.setText( String.format("%s [%s]", languageName, languageCode)); if (selectedLanguages.containsKey(languageCodesList.get(position)) && !languageCodesList.get(position).equals(selectedLangCode)) { tvLanguage.setTextColor(Color.GRAY); } } } }</code><technical_language>TextUtils.isEmpty() instead of checks</technical_language>

Target:
public void init(int position, boolean isDropDownView, String savedLanguageValue) { String languageCode = LangCodeUtils.fixLanguageCode(languageCodesList.get(position)); final String languageName = StringUtils.capitalize(languageNamesList.get(position)); if(TextUtils.isEmpty(savedLanguageValue)){ savedLanguageValue = Locale.getDefault().getLanguage(); } if (!isDropDownView) { if( !dropDownClicked && savedLanguageValue !=null){ languageCode = LangCodeUtils.fixLanguageCode(savedLanguageValue); } if (view != null) { view.setVisibility(View.GONE); } if (languageCode.length() > 2) tvLanguage.setText(languageCode.substring(0, 2)); else tvLanguage.setText(languageCode); } else { view.setVisibility(View.VISIBLE); if (languageCodesList.get(position).isEmpty()) { tvLanguage.setText(languageName); tvLanguage.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } else { tvLanguage.setText( String.format("%s [%s]", languageName, languageCode)); if (selectedLanguages.containsKey(languageCodesList.get(position)) && !languageCodesList.get(position).equals(selectedLangCode)) { tvLanguage.setTextColor(Color.GRAY); } } } }
Source:
<code>protected final boolean trySuccessInternal(V result) { boolean done = super.trySuccess(result); <START> return clearTaskAfterCompletion(done, COMPLETED); <END> }</code><technical_language>nit: merge lines</technical_language>

Target:
protected final boolean trySuccessInternal(V result) { return clearTaskAfterCompletion(super.trySuccess(result), COMPLETED); }
Source:
<code>private void check(String databaseName, int expectedFileCount, int expectedStatsCount) { String filesStudyIdField = String.format("%s.%s", FILES_FIELD, STUDYID_FIELD); String statsStudyIdField = String.format("%s.%s", STATS_FIELD, STUDYID_FIELD); DBCollection variantsCollection = mongoRule.getCollection(databaseName, COLLECTION_VARIANTS_NAME); BasicDBObject variantFiles = new BasicDBObject(filesStudyIdField, STUDY_ID_TO_DROP); BasicDBObject variantStats = new BasicDBObject(statsStudyIdField, STUDY_ID_TO_DROP); System.out.println(variantsCollection.count(variantFiles)); <START> System.out.println(variantsCollection.count(variantStats)); <END> assertEquals(expectedFileCount, variantsCollection.count(variantFiles)); assertEquals(expectedStatsCount, variantsCollection.count(variantStats)); }</code><technical_language>remove this prints. logger remove</technical_language>

Target:
private void check(String databaseName, int expectedFileCount, int expectedStatsCount) { String filesStudyIdField = String.format("%s.%s", FILES_FIELD, STUDYID_FIELD); String statsStudyIdField = String.format("%s.%s", STATS_FIELD, STUDYID_FIELD); DBCollection variantsCollection = mongoRule.getCollection(databaseName, COLLECTION_VARIANTS_NAME); BasicDBObject variantFiles = new BasicDBObject(filesStudyIdField, STUDY_ID_TO_DROP); BasicDBObject variantStats = new BasicDBObject(statsStudyIdField, STUDY_ID_TO_DROP); assertEquals(expectedFileCount, variantsCollection.count(variantFiles)); assertEquals(expectedStatsCount, variantsCollection.count(variantStats)); }
Source:
<code><START> public void addReference(NativeObject referent) { <END> new NativeObjectReference(this, referent, referenceQueue); }</code><technical_language>public</technical_language>

Target:
void addReference(NativeObject referent) { new NativeObjectReference(this, referent, referenceQueue); }
Source:
<code>public String send(HttpSession session, @RequestParam(value = "recipient") String recipientUsername, @RequestParam(value = "subject") String subject, @RequestParam(value = "body") String body, @RequestParam(value = "draft_id") Integer draftId) { if (session.getAttribute("member") == null) <START> return "redirect:denied"; <END> MemberDao memberDao = new MemberDao(); MessageDao messageDao = new MessageDao(); Member sender = (Member) session.getAttribute("member"); Member recipient = memberDao.getMemberByUsername(recipientUsername); if (draftId != null) { Message draft = messageDao.getMessageById(draftId); draft.setRecipient(recipient).setSubject(subject).setBody(body).setDraft(false).setSent(true); messageDao.save(draft); } else { Message newMessage = new Message(subject, body, sender, recipient); newMessage.setSent(true); newMessage.setDraft(false); messageDao.save(newMessage); } session.setAttribute("message", "Message sent!"); session.setAttribute("member", memberDao.getMemberById(sender.getId())); return "mail"; }</code><technical_language>/denied</technical_language>

Target:
public String send( HttpSession session, @RequestParam(value = "recipient") String recipientUsername, @RequestParam(value = "subject") String subject, @RequestParam(value = "body") String body, @RequestParam(value = "draft_id") Integer draftId) { if (session.getAttribute("member") == null) return "redirect:/denied"; MemberDao memberDao = new MemberDao(); MessageDao messageDao = new MessageDao(); Member sender = (Member) session.getAttribute("member"); Member recipient = memberDao.getMemberByUsername(recipientUsername); if (draftId != null) { Message draft = messageDao.getById(draftId); draft.setRecipient(recipient).setSubject(subject).setBody(body).setDraft(false).setSent(true); messageDao.merge(draft); } else { Message newMessage = new Message(subject, body, sender, recipient); newMessage.setSent(true); newMessage.setDraft(false); messageDao.merge(newMessage); } session.setAttribute("message", "Message sent!"); session.setAttribute("member", memberDao.getMemberById(sender.getId())); return "mail"; }
Source:
<code>public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.get().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { <START> LOGGER.log(Level.FINEST, "Adding dependent install of " + dep.name + " for plugin " + name); <END> dep.deploy(dynamicLoad, null, batch); } else { LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name}); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad); job.setCorrelationId(correlationId); job.setBatch(batch); return uc.addJob(job); }</code><technical_language>This is a useful message IMO, especially UI a poor job of communicating dependency installations</technical_language>

Target:
public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); UpdateCenter uc = Jenkins.get().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { UpdateCenter.InstallationJob job = uc.getJob(dep); if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) { LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(dynamicLoad, null, batch); } else { LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name}); } } PluginWrapper pw = getInstalled(); if(pw != null) { Future<UpdateCenterJob> enableJob = null; if(!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } if(pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad); job.setCorrelationId(correlationId); job.setBatch(batch); return uc.addJob(job); }
Source:
<code>public SmsDetails sendWakeUpSms(final DlmsDeviceMessageMetadata messageMetadata) throws OsgpException, <START> ProtocolAdapterException { <END> final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); if (!COMMUNICATION_METHOD_GPRS.equals(device.getCommunicationMethod())) { throw new OsgpException(ComponentType.PROTOCOL_DLMS, "Device communication method is not GPRS"); } final SendSMSResponse response = this.smsClient.sendWakeUpSMS(device.getIccId()); return new SmsDetails(device.getDeviceIdentification(), response.getSmsMsgId(), null, null, null); }</code><technical_language>ProtocolAdapterException is thown anytime in this method. removed</technical_language>

Target:
public SmsDetails sendWakeUpSms(final DlmsDeviceMessageMetadata messageMetadata) throws OsgpException { final DlmsDevice device = this.domainHelperService.findDlmsDevice(messageMetadata); if (!COMMUNICATION_METHOD_GPRS.equals(device.getCommunicationMethod())) { throw new OsgpException(ComponentType.PROTOCOL_DLMS, "Device communication method is not GPRS"); } final SendSMSResponse response = this.smsClient.sendWakeUpSMS(device.getIccId()); return new SmsDetails(device.getDeviceIdentification(), response.getSmsMsgId(), null, null, null); }
Source:
<code><START> protected Multimap<String, FaultDomain> computeHostToFaultDomainMap() { <END> Multimap<String, FaultDomain> hostToRackMap = HashMultimap.create(); try { List<NodeReport> nodeReport = yarnClient.getNodeReports(NodeState.RUNNING); nodeReport.forEach(report -> { FaultDomain rack = new FaultDomain(FaultDomainType.RACK, report.getRackName()); hostToRackMap.put(report.getNodeId().getHost(), rack); }); } catch (YarnException | IOException e) { e.printStackTrace(); } return hostToRackMap; }</code><technical_language>nit: package private instead if is for testing</technical_language>

Target:
Multimap<String, FaultDomain> computeHostToFaultDomainMap() { Multimap<String, FaultDomain> hostToRackMap = HashMultimap.create(); try { List<NodeReport> nodeReport = yarnClient.getNodeReports(NodeState.RUNNING); nodeReport.forEach(report -> { FaultDomain rack = new FaultDomain(FaultDomainType.RACK, report.getRackName()); hostToRackMap.put(report.getNodeId().getHost(), rack); }); log.info("Computed the host to rack map successfully from Yarn."); } catch (YarnException | IOException e) { throw new SamzaException("Yarn threw an exception while getting NodeReports.", e); } return hostToRackMap; }
Source:
<code>public void newChangeIsMergedWithFix() throws Exception { Change c = newChange(project, userId); db.changes().insert(singleton(c)); RevCommit commit = repo.branch(c.currentPatchSetId().toRefName()).commit() .parent(tip).create(); PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, userId); db.patchSets().insert(singleton(ps)); repo.branch(c.getDest().get()).update(commit); List<ProblemInfo> problems = checker.check(c, new FixInput()).problems(); assertThat(problems).hasSize(1); ProblemInfo p = problems.get(0); assertThat(p.message).isEqualTo( "Patch set 1 (" + commit.name() + ") is merged into destination ref" + " master (" + commit.name() + "), but change status is NEW"); assertThat(p.status).isEqualTo(ProblemInfo.Status.FIXED); assertThat(p.outcome).isEqualTo("Marked change as merged"); <START> <END> assertProblems(db.changes().get(c.getId())); }</code><technical_language>Add assertion change status changed merged</technical_language>

Target:
public void newChangeIsMergedWithFix() throws Exception { Change c = newChange(project, userId); db.changes().insert(singleton(c)); RevCommit commit = repo.branch(c.currentPatchSetId().toRefName()).commit() .parent(tip).create(); PatchSet ps = newPatchSet(c.currentPatchSetId(), commit, userId); db.patchSets().insert(singleton(ps)); repo.branch(c.getDest().get()).update(commit); List<ProblemInfo> problems = checker.check(c, new FixInput()).problems(); assertThat(problems).hasSize(1); ProblemInfo p = problems.get(0); assertThat(p.message).isEqualTo( "Patch set 1 (" + commit.name() + ") is merged into destination ref" + " master (" + commit.name() + "), but change status is NEW"); assertThat(p.status).isEqualTo(ProblemInfo.Status.FIXED); assertThat(p.outcome).isEqualTo("Marked change as merged"); c = db.changes().get(c.getId()); assertThat(c.getStatus()).isEqualTo(Change.Status.MERGED); assertProblems(c); }
Source:
<code>public boolean isSecure() { <START> return config.getBool("server", "https").orElse(false); <END> }</code><technical_language>Consider return config.get("server", "https-private-key").isPresent() && config.get("server", "https-certificate").isPresent();</technical_language>

Target:
public boolean isSecure() { return config.get("server", "https-private-key").isPresent() && config.get("server", "https-certificate").isPresent(); }
Source:
<code><START> private HashMap<String, VariantAnnotation> generateVariantAnnotations(List<? extends Annotation> annotations) { <END> HashMap<String, VariantAnnotation> variantAnnotations = new HashMap<>(); for (Annotation annotation : annotations) { String id = annotation.buildVariantId(); variantAnnotations.putIfAbsent(id, new VariantAnnotation(annotation)); variantAnnotations.computeIfPresent(id, (key, oldVar) -> oldVar.concatenate(annotation)); } return variantAnnotations; }</code><technical_language>I interface Map is enough return type. Also, sorting methods usage clearer</technical_language>

Target:
private Map<String, VariantAnnotation> generateVariantAnnotations(List<? extends Annotation> annotations) { HashMap<String, VariantAnnotation> variantAnnotations = new HashMap<>(); for (Annotation annotation : annotations) { String id = annotation.buildVariantId(); variantAnnotations.putIfAbsent(id, new VariantAnnotation(annotation)); variantAnnotations.computeIfPresent(id, (key, oldVar) -> oldVar.concatenate(annotation)); } return variantAnnotations; }
Source:
<code>public String getAsLastNamesLatexFree(boolean oxfordComma) { <START> int abbrInt = oxfordComma ? 0 : 1; <END> if (authorsLastOnlyLatexFree[abbrInt] != null) { return authorsLastOnlyLatexFree[abbrInt]; } authorsLastOnlyLatexFree[abbrInt] = LatexToUnicodeAdapter.format(getAsLastNames(oxfordComma)); return authorsLastOnlyLatexFree[abbrInt]; }</code><technical_language>try avoid abbreviations. ironic... :wink: I this abbreviation in other places in this class too, mind. If like, change in places in this class</technical_language>

Target:
public String getAsLastNamesLatexFree(boolean oxfordComma) { int abbreviationIndex = oxfordComma ? 0 : 1; if (authorsLastOnlyLatexFree[abbreviationIndex] != null) { return authorsLastOnlyLatexFree[abbreviationIndex]; } authorsLastOnlyLatexFree[abbreviationIndex] = LatexToUnicodeAdapter.format(getAsLastNames(oxfordComma)); return authorsLastOnlyLatexFree[abbreviationIndex]; }
Source:
<code>public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> accessSectionsLabels = getRefControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); if (refs == null) { r.add(l); } else if (refs.size() == 1 && <START> refs.get(0).equals("sameAsAccess")) <END> { if (accessSectionsLabels.contains(l)) { r.add(l); } } else { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } return new LabelTypes(r); }</code><technical_language>This a boolean label itself, a string comparison in ref patterns. is unclear intended behavior is sameAsAccess is applied other refs. this code appears applies if sameAsAccess matches _or_ of other refs match. longer "same" access controls allow</technical_language>

Target:
public LabelTypes getLabelTypes() { String destBranch = getChange().getDest().get(); List<LabelType> all = getProjectControl().getLabelTypes().getLabelTypes(); List<LabelType> accessSectionsLabels = getRefControl().getLabelTypes().getLabelTypes(); List<LabelType> r = Lists.newArrayListWithCapacity(all.size()); for (LabelType l : all) { List<String> refs = l.getRefPatterns(); boolean branchSameAsAccess = l.branchSameAsAccess(); if (refs == null && !branchSameAsAccess) { r.add(l); } else { if (branchSameAsAccess) { if (accessSectionsLabels.contains(l)) { r.add(l); continue; } } if (refs != null) { for (String refPattern : refs) { if (RefConfigSection.isValid(refPattern) && match(destBranch, refPattern)) { r.add(l); break; } } } } } return new LabelTypes(r); }
Source:
<code>public static Collection<String> descriptions(Collection<ConfigInfo> infos) { if (infos == null) { return Collections.emptyList(); } <START> return Lists.newArrayList(Iterables.transform(infos, new Function<ConfigInfo, String>() { @Override public String apply(ConfigInfo info) { return info.description(); } })); <END> }</code><technical_language>possible, java's built in mapping functions old-style google collections library. suggestion return infos.stream() .map(ConfigInfo::description) .collect(Collectors.toCollection(ArrayList::new));</technical_language>

Target:
public static List<String> descriptions(Collection<ConfigInfo> infos) { if (infos == null) { return Collections.emptyList(); } return infos.stream() .map(ConfigInfo::description) .collect(Collectors.toList()); }
Source:
<code>public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { final Future<Object> future = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { before(); try { try { base.evaluate(); } catch (Throwable throwable) { Throwables.propagateIfPossible(throwable, Exception.class); throw Throwables.propagate(throwable); } } finally { after(); } return null; } }); while (!future.isDone()) { Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS); <START> verifyJobsHealthy(); <END> } try { future.get(); } catch (ExecutionException e) { final Throwable cause = (e.getCause() == null) ? e : e.getCause(); throw Throwables.propagate(cause); } } }; }</code><technical_language>future cancelled if verifyJobsHealthy throws</technical_language>

Target:
public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(); try { perform(base); } finally { after(); } } }; }
Source:
<code>private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); <START> feature.setDescription("Ability to manage gluster bricks"); <END> features.getFeature().add(feature); }</code><technical_language>mention actual action for that</technical_language>

Target:
private void addGlusterBricksFeature(Features features) { Feature feature = new Feature(); feature.setName("Gluster Bricks management"); feature.setDescription("Ability to delete gluster bricks with data migration"); features.getFeature().add(feature); }
Source:
<code>protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { final String username = context.getRequestParameter(this.usernameParameter); UsernamePasswordCredentials credentials; try { credentials = getCredentialsExtractor().extract(context); logger.debug("usernamePasswordCredentials: {}", credentials); if (credentials == null) { <START> if (getAjaxRequestResolver().isAjax(context)) { <END> logger.info("AJAX request detected -> returning 401"); throw RequiresHttpAction.unauthorized("AJAX request -> 401", context, null); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, MISSING_FIELD_ERROR); logger.debug("redirectionUrl: {}", redirectionUrl); final String message = "Username and password cannot be blank -> return to the form with error"; logger.debug(message); throw RequiresHttpAction.redirect(message, context, redirectionUrl); } } getAuthenticator().validate(credentials); } catch (final CredentialsException e) { if (getAjaxRequestResolver().isAjax(context)) { logger.info("AJAX request detected -> returning 403"); throw RequiresHttpAction.forbidden("AJAX request -> 403", context); } else { String redirectionUrl = CommonHelper.addParameter(this.loginUrl, this.usernameParameter, username); String errorMessage = computeErrorMessage(e); redirectionUrl = CommonHelper.addParameter(redirectionUrl, ERROR_PARAMETER, errorMessage); logger.debug("redirectionUrl: {}", redirectionUrl); final String message = "Credentials validation fails -> return to the form with error"; logger.debug(message); throw RequiresHttpAction.redirect(message, context, redirectionUrl); } } return credentials; }</code><technical_language>This is I realized blocks (line 82 - 94 line 99 - 111) of source code close: extract in a method? Thanks</technical_language>

Target:
protected UsernamePasswordCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { final String username = context.getRequestParameter(this.usernameParameter); UsernamePasswordCredentials credentials; try { credentials = getCredentialsExtractor().extract(context); logger.debug("usernamePasswordCredentials: {}", credentials); if (credentials == null) { throw handleInvalidCredentials(context, username, "Username and password cannot be blank -> return to the form with error", MISSING_FIELD_ERROR, 401); } getAuthenticator().validate(credentials); } catch (final CredentialsException e) { throw handleInvalidCredentials(context, username, "Credentials validation fails -> return to the form with error", computeErrorMessage(e), 403); } return credentials; }
Source:
<code>public void setComment(String comment) throws CentralRepoException { String updateClause = "UPDATE personas SET comment = \"" + comment + "\" WHERE id = " + id; CentralRepository.getInstance().executeUpdateSQL(updateClause); <START> } <END></code><technical_language>started adding a null check for CentralRepository.getInstance(). add in other new apis</technical_language>

Target:
public void setComment(String comment) throws CentralRepoException { String updateClause = "UPDATE personas SET comment = \"" + comment + "\" WHERE id = " + id; CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { cr.executeUpdateSQL(updateClause); } }
Source:
<code>notifyAboutOrder(OrderReadyToBeServed orderReady) { <START> throw new RuntimeException(); <END> }</code><technical_language>add a message exception remove suppression? in case, I understand throw exception. discuss</technical_language>

Target:
notifyAboutOrder(OrderReadyToBeServed orderReady) { throw new RuntimeException("Could not send notifications."); }
Source:
<code>private static ListenableFuture<?> getBlockedFuture(Operator operator) { ListenableFuture<?> blocked = operator.isBlocked(); <START> if (blocked.isDone()) { <END> blocked = operator.getOperatorContext().isWaitingForMemory(); } return blocked; }</code><technical_language>want is say, "I'm blocked" of conditions satisfied. If so, simple replace original method with: java return Futures.allAsList(operator.isBlocked(), operator.getOperatorContext().isWaitingForMemory());</technical_language>

Target:
private static Optional<ListenableFuture<?>> getBlockedFuture(Operator operator) { ListenableFuture<?> blocked = operator.isBlocked(); if (!blocked.isDone()) { return Optional.of(blocked); } blocked = operator.getOperatorContext().isWaitingForMemory(); if (!blocked.isDone()) { return Optional.of(blocked); } return Optional.empty(); }
Source:
<code>public void initialize(final String endpointId) { <START> if (initialized.get()) { <END> return; } this.evalPrefix = endpointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", endpointId); if (!addedEval) { if (!initialized.compareAndSet(false, true)) { return; } initRoutingTable(); } else { requestRoutingTable(); } }</code><technical_language>this happen? I supposed happen, this method is called in NetworkContextRegister.RegisterContextHandler. If case, remove this check</technical_language>

Target:
public void initialize(final String endpointId) { this.evalPrefix = endpointId.split("-")[0]; LOG.log(Level.INFO, "Initialize router with localEndPointId: {0}", endpointId); if (!addedEval) { initRoutingTable(); } else { requestRoutingTable(); } }
Source:
<code><START> private void runInBackground() { <END> Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (!stopped) { String commandDescription = null; try { final Command command = queuedCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence); try { command.runnable.run(); } catch (UnavailableAccountException e) { new Thread() { @Override public void run() { try { sleep(30 * 1000); queuedCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") + " Command '" + command.description + "' completed"); for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!queuedCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } } }</code><technical_language>Adding @WorkerThread annotation is adding more noise useful information. Try avoid thread-related annotations methods obvious thread called</technical_language>

Target:
private void runInBackground() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (!stopped) { String commandDescription = null; try { final Command command = queuedCommands.take(); if (command != null) { commandDescription = command.description; if (K9.DEBUG) { Log.i(K9.LOG_TAG, "Running command '" + command.description + "', seq = " + command.sequence + "(" + (command.isForegroundPriority ? "foreground" : "background") + "priority)"); } try { command.runnable.run(); } catch (UnavailableAccountException e) { new Thread() { @Override public void run() { try { sleep(30 * 1000); queuedCommands.put(command); } catch (InterruptedException e) { Log.e(K9.LOG_TAG, "interrupted while putting a pending command for" + " an unavailable account back into the queue." + " THIS SHOULD NEVER HAPPEN."); } } } .start(); } if (K9.DEBUG) { Log.i(K9.LOG_TAG, " Command '" + command.description + "' completed"); } for (MessagingListener l : getListeners(command.listener)) { l.controllerCommandCompleted(!queuedCommands.isEmpty()); } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e); } } }
Source:
<code>public void testRecoveryMonitorWithFailure() throws Exception { XATestResourceXARecovery.setUseFaultyResources(true); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(new XATestResource(XATestResource.OK_JNDI_NAME, false))); assertTrue(tx.enlistResource(new XATestResource(XATestResource.FAULTY_JNDI_NAME, true))); ut.commit(); manager.scan(); <START> assertTrue(!xaRecoveryModule.isPeriodicWorkSuccessful()); <END> }</code><technical_language>assertFalse ... is easier read</technical_language>

Target:
public void testRecoveryMonitorWithFailure() throws Exception { XATestResourceXARecovery.setUseFaultyResources(true); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(new XATestResource(XATestResource.OK_JNDI_NAME, false))); assertTrue(tx.enlistResource(new XATestResource(XATestResource.FAULTY_JNDI_NAME, true))); ut.commit(); manager.scan(); assertFalse(xaRecoveryModule.isPeriodicWorkSuccessful()); }
Source:
<code>public void testEntryInvalidated(boolean isOwner, WriteMethod method) { Cache<Object, String> primary = cache(isOwner ? 0 : 2, DIST); Cache<Object, String> backup = cache(1, DIST); Cache<Object, String> reader = cache(3, DIST); Cache<Object, String> nonOwner = cache(isOwner ? 2 : 0, DIST); Object KEY = getKeyForCache(primary, backup); primary.put(KEY, "value"); <START> assertEquals(null, reader.getAdvancedCache().getDataContainer().get(KEY)); <END> assertEquals("value", reader.get(KEY)); assertEntry(primary.getAdvancedCache().getDataContainer().get(KEY), "value", false); assertEntry(backup.getAdvancedCache().getDataContainer().get(KEY), "value", false); assertEntry(reader.getAdvancedCache().getDataContainer().get(KEY), "value", true); assertEquals(null, nonOwner.getAdvancedCache().getDataContainer().get(KEY)); FunctionalMapImpl<Object, String> functionalMap = FunctionalMapImpl.create(this.<Object, String>cache(0, DIST).getAdvancedCache()); FunctionalMap.WriteOnlyMap<Object, String> wo = WriteOnlyMapImpl.create(functionalMap); FunctionalMap.ReadWriteMap<Object, String> rw = ReadWriteMapImpl.create(functionalMap); Function<ReadEntryView<Object, String>, String> readFunc = MarshallableFunctions.returnReadOnlyFindOrNull(); BiConsumer<WriteEntryView<String>, String> writeFunc = (Serializable & BiConsumer<WriteEntryView<String>, String>) (view, nil) -> view.set("value2"); method.action.eval(KEY, wo, rw, readFunc, writeFunc, FunctionalL1Test.class); assertEntry(primary.getAdvancedCache().getDataContainer().get(KEY), "value2", false); assertEntry(backup.getAdvancedCache().getDataContainer().get(KEY), "value2", false); assertEquals(null, reader.getAdvancedCache().getDataContainer().get(KEY)); assertEquals(null, nonOwner.getAdvancedCache().getDataContainer().get(KEY)); }</code><technical_language>assertNull</technical_language>

Target:
public void testEntryInvalidated(boolean isOwner, WriteMethod method) { Cache<Object, String> primary = cache(isOwner ? 0 : 2, DIST); Cache<Object, String> backup = cache(1, DIST); Cache<Object, String> reader = cache(3, DIST); Cache<Object, String> nonOwner = cache(isOwner ? 2 : 0, DIST); Object KEY = getKeyForCache(primary, backup); primary.put(KEY, "value"); assertNoEntry(reader, KEY); assertEquals("value", reader.get(KEY)); assertEntry(primary, KEY, "value", false); assertEntry(backup, KEY, "value", false); assertEntry(reader, KEY, "value", true); assertNoEntry(nonOwner, KEY); FunctionalMapImpl<Object, String> functionalMap = FunctionalMapImpl.create(this.<Object, String>cache(0, DIST).getAdvancedCache()); FunctionalMap.WriteOnlyMap<Object, String> wo = WriteOnlyMapImpl.create(functionalMap); FunctionalMap.ReadWriteMap<Object, String> rw = ReadWriteMapImpl.create(functionalMap); Function<ReadEntryView<Object, String>, String> readFunc = MarshallableFunctions.returnReadOnlyFindOrNull(); method.eval(KEY, wo, rw, readFunc, (view, nil) -> view.set("value2"), FunctionalL1Test.class); assertEntry(primary, KEY, "value2", false); assertEntry(backup, KEY, "value2", false); assertNoEntry(reader, KEY); assertNoEntry(nonOwner, KEY); }
Source:
<code>public Repo create( final RepoCreate settings ) throws IOException { <START> String user = this.self; <END> final String org = settings.organization(); if (org != null && !org.isEmpty()) { user = "/orgs/".concat(org).concat("/repos"); } final Coordinates coords = new Coordinates.Simple( user, settings.name() ); this.storage.apply( new Directives().xpath(this.xpath()).add("repo") .attr("coords", coords.toString()) .add("name").set(settings.name()).up() .add("description").set("test repository").up() .add("private").set(settings.isPrivate()).up() ); final Repo repo = this.get(coords); repo.patch(settings.json()); Logger.info( this, "repository %s created by %s", coords, user ); return repo; }</code><technical_language>@maviteixeira good; rename this variable owner? in, owner is this.self (the authenticated user) organization</technical_language>

Target:
public Repo create( final RepoCreate settings ) throws IOException { String owner = this.self; final String org = settings.organization(); if (org != null && !org.isEmpty()) { owner = "/orgs/".concat(org).concat("/repos"); } final Coordinates coords = new Coordinates.Simple( owner, settings.name() ); this.storage.apply( new Directives().xpath(this.xpath()).add("repo") .attr("coords", coords.toString()) .add("name").set(settings.name()).up() .add("description").set("test repository").up() .add("private").set(settings.isPrivate()).up() ); final Repo repo = this.get(coords); repo.patch(settings.json()); Logger.info( this, "repository %s created by %s", coords, owner ); return repo; }
Source:
<code>public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); ConfigurationSection section = parameters.getConfigurationSection("attributes"); if (section == null) return; this.attributes = new HashMap<>(); for (String key : section.getKeys(false)) { attributes.put(key, section.getDouble(key, 0)); } for (String key : parameters.getKeys(false)) { if (key.startsWith("attribute_")) { <START> String str = key.replace("attribute_", ""); <END> attributes.put(str, parameters.getDouble(key)); } } }</code><technical_language>I discourage this type of parametrization (such in PotionEffectAction, prefer add_effects effect_slow, etc). this part, options better, confusing</technical_language>

Target:
public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); ConfigurationSection section = parameters.getConfigurationSection("attributes"); if (section == null) return; this.attributes = new HashMap<>(); for (String key : section.getKeys(false)) { attributes.put(key, section.getDouble(key, 0)); } for (String key : parameters.getKeys(false)) { if (key.startsWith("attribute_")) { String str = key.replace("attribute_", ""); if (attributes.containsKey(str)) { continue; } attributes.put(str, parameters.getDouble(key)); } } }
Source:
<code>public String makeBoxes() { <START> String projectStateBackgroundColour = "projectStateInactive"; <END> if( project.isSetState() && project.state == ProjectState.ACTIVE ) { projectStateBackgroundColour = "projectStateActive"; } String clearingStateBackgroundColour = "clearingStateUnknown"; if(project.isSetClearingState()) { switch(project.clearingState) { case CLOSED: clearingStateBackgroundColour = "clearingStateClosed"; break; case IN_PROGRESS: clearingStateBackgroundColour = "clearingStateInProgress"; break; case OPEN: clearingStateBackgroundColour = "clearingStateOpen"; break; } } String box_PS = "<div class=\"stateBox " + projectStateBackgroundColour + " capsuleLeft \" title=\"Project state: " + ThriftEnumUtils.enumToString(project.state) + "\"> PS </div>"; String box_CS = "<div class=\"stateBox capsuleRight " + clearingStateBackgroundColour + "\" title=\"Project clearing state: " + ThriftEnumUtils.enumToString(project.clearingState) + "\"> CS </div>"; return box_PS+box_CS; }</code><technical_language>magic strings constants</technical_language>

Target:
public String makeBoxes() { String projectStateBackgroundColour = PortalConstants.PROJECT_STATE_INACTIVE__CSS; if( project.isSetState() && project.state == ProjectState.ACTIVE ) { projectStateBackgroundColour = PortalConstants.PROJECT_STATE_ACTIVE__CSS; } String clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_UNKNOWN__CSS; if(project.isSetClearingState()) { switch(project.clearingState) { case CLOSED: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_CLOSED__CSS; break; case IN_PROGRESS: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_INPROGRESS__CSS; break; case OPEN: clearingStateBackgroundColour = PortalConstants.CLEARING_STATE_OPEN__CSS; break; } } String box_PS = "<div class=\"stateBox " + projectStateBackgroundColour + " capsuleLeft \" title=\"Project state: " + ThriftEnumUtils.enumToString(project.state) + "\"> PS </div>"; String box_CS = "<div class=\"stateBox capsuleRight " + clearingStateBackgroundColour + "\" title=\"Project clearing state: " + ThriftEnumUtils.enumToString(project.clearingState) + "\"> CS </div>"; return box_PS+box_CS; }
Source:
<code>public void pullRequestReviewComments() throws Exception { String name = "pullRequestReviewComments"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); assertTrue(p.listReviewComments().toList().isEmpty()); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Sample review comment", comment.getBody()); <START> assertNotNull(comment.getHtmlUrl()); <END> comment.update("Updated review comment"); comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); comment = comments.get(0); assertEquals("Updated review comment", comment.getBody()); comment.delete(); comments = p.listReviewComments().toList(); assertTrue(comments.isEmpty()); }</code><technical_language>Needs more non-null</technical_language>

Target:
public void pullRequestReviewComments() throws Exception { String name = "pullRequestReviewComments"; GHPullRequest p = getRepository().createPullRequest(name, "test/stable", "master", "## test"); assertTrue(p.listReviewComments().toList().isEmpty()); p.createReviewComment("Sample review comment", p.getHead().getSha(), "README.md", 1); List<GHPullRequestReviewComment> comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); GHPullRequestReviewComment comment = comments.get(0); assertEquals("Sample review comment", comment.getBody()); assertNotNull(comment.getHtmlUrl()); assertEquals(new URL("<LINK_0>"), comment.getHtmlUrl()); comment.update("Updated review comment"); comments = p.listReviewComments().toList(); assertEquals(1, comments.size()); comment = comments.get(0); assertEquals("Updated review comment", comment.getBody()); comment.delete(); comments = p.listReviewComments().toList(); assertTrue(comments.isEmpty()); }
Source:
<code>public static void addRecipe(ILiquidStack fluidOutput, ILiquidStack fluidInput, int timePerUnit) { <START> fluidOutput.amount(fluidOutput.getAmount() / 100); <END> fluidInput.amount(fluidInput.getAmount() / 100); ModTweaker.LATE_ADDITIONS.add(new Add(new StillRecipe(timePerUnit, toFluid(fluidInput), toFluid(fluidOutput)))); }</code><technical_language>Magic numbers</technical_language>

Target:
public static void addRecipe(ILiquidStack fluidOutput, ILiquidStack fluidInput, int timePerUnit) { ModTweaker.LATE_ADDITIONS.add(new Add(new StillRecipe(timePerUnit, toFluid(fluidInput), toFluid(fluidOutput)))); }
Source:
<code><START> public ContentWriteController( <END> ApplicationConfigurationFetcher appConfigFetcher, ContentWriteExecutor contentWriteExecutor, LookupBackedContentIdGenerator lookupBackedContentIdGenerator, MessageSender<ContentWriteMessage> messageSender, AtlasModelWriter<QueryResult<Identified, ? extends Identified>> outputWriter, LookupEntryStore lookupEntryStore, ContentResolver contentResolver, ContentWriter contentWriter ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.writeExecutor = checkNotNull(contentWriteExecutor); this.lookupBackedContentIdGenerator = checkNotNull(lookupBackedContentIdGenerator); this.messageSender = checkNotNull(messageSender); this.outputWriter = outputWriter; this.lookupEntryStore = checkNotNull(lookupEntryStore); this.contentResolver = checkNotNull(contentResolver); this.contentWriter = checkNotNull(contentWriter); }</code><technical_language>this class, worth changing constructor private making a static factory method bring this in line code style. Leaving campsite a cleaner time that</technical_language>

Target:
private ContentWriteController( ApplicationConfigurationFetcher appConfigFetcher, ContentWriteExecutor contentWriteExecutor, LookupBackedContentIdGenerator lookupBackedContentIdGenerator, MessageSender<ContentWriteMessage> messageSender, AtlasModelWriter<QueryResult<Identified, ? extends Identified>> outputWriter, LookupEntryStore lookupEntryStore, ContentResolver contentResolver, ContentWriter contentWriter ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.writeExecutor = checkNotNull(contentWriteExecutor); this.lookupBackedContentIdGenerator = checkNotNull(lookupBackedContentIdGenerator); this.messageSender = checkNotNull(messageSender); this.outputWriter = outputWriter; this.lookupEntryStore = checkNotNull(lookupEntryStore); this.contentResolver = checkNotNull(contentResolver); this.contentWriter = checkNotNull(contentWriter); }