auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testMissingPrimaryKeyLookupQuery() throws Exception { indexType2TweeterDocuments(); final Table table = dataContext.getDefaultSchema().getTableByName(DEFAULT_TABLE_NAME); <START> final Column[] pks = table.getPrimaryKeys().toArray(new Column[0]); <END> try (DataSet ds = dataContext.query().from(table).selectAll().where(pks[0]).eq("missing").execute()) { assertFalse(ds.next()); } }</code><technical_language>Please a name (primaryKeys, primaryKeyColumns)</technical_language>

Target:
public void testMissingPrimaryKeyLookupQuery() throws Exception { indexType2TweeterDocuments(); final Table table = dataContext.getDefaultSchema().getTableByName(DEFAULT_TABLE_NAME); final Column[] primaryKeys = table.getPrimaryKeys().toArray(new Column[0]); try (final DataSet dataSet = dataContext .query() .from(table) .selectAll() .where(primaryKeys[0]) .eq("missing") .execute()) { assertFalse(dataSet.next()); } }
Source:
<code>public void loadJavaRDD() throws Exception { doReturn(javaPairRDD).when(sparkContext).newAPIHadoopFile(any(), any(), any(), any(), any()); <START> doReturn(javaRDD).when(javaPairRDD).map(any()); <END> JavaRDD<Country> retJavaRDD = SparkAvroLoader.loadJavaRDD(sparkContext, "/avro/datastore", Country.class); assertTrue(javaRDD == retJavaRDD); verify(sparkContext).newAPIHadoopFile( eq("/avro/datastore"), eq(AvroKeyInputFormat.class), eq(Country.class), eq(NullWritable.class), configurationCaptor.capture()); assertEquals(Country.SCHEMA$.toString(), configurationCaptor.getValue().get("avro.schema.input.key")); verify(javaPairRDD).map(mapFunctionCaptor.capture()); assertMapFunction(mapFunctionCaptor.getValue()); verifyNoMoreInteractions(sparkContext, javaPairRDD); verifyZeroInteractions(javaRDD); }</code><technical_language>Wouln't expected type instead of any()</technical_language>

Target:
public void loadJavaRDD() throws Exception { doReturn(javaPairRDD).when(sparkContext).newAPIHadoopFile(eq("/avro/datastore"), eq(AvroKeyInputFormat.class), eq(Country.class), eq(NullWritable.class), any(Configuration.class)); doReturn(javaRDD).when(javaPairRDD).map(any(Function.class)); JavaRDD<Country> retJavaRDD = SparkAvroLoader.loadJavaRDD(sparkContext, "/avro/datastore", Country.class); assertTrue(javaRDD == retJavaRDD); verify(sparkContext).newAPIHadoopFile( eq("/avro/datastore"), eq(AvroKeyInputFormat.class), eq(Country.class), eq(NullWritable.class), configurationCaptor.capture()); assertEquals(Country.SCHEMA$.toString(), configurationCaptor.getValue().get("avro.schema.input.key")); verify(javaPairRDD).map(mapFunctionCaptor.capture()); assertMapFunction(mapFunctionCaptor.getValue()); verifyNoMoreInteractions(sparkContext, javaPairRDD); verifyZeroInteractions(javaRDD); }
Source:
<code>protected AuditMessageType getParticipantObjectIdentificationForRequest(PRPAIN201306UV02 request, AssertionType assertion, AuditMessageType auditMsg) { auditMsg = getPatientParticipantObjectIdentificationForResponse(request, auditMsg); try { auditMsg = getQueryParamsParticipantObjectIdentificationForResponse(request, auditMsg); } catch (JAXBException ex) { <START> if (LOG.isDebugEnabled()) { <END> LOG.error("Error while creating ParticipantObjectIdentificationQueryByParameters segment : " + ex.getLocalizedMessage(), ex); } } return auditMsg; }</code><technical_language>Remove this "if" statement. said, a for future reference: 1. "is[Level]Enabled" check specific level (e.g., if log trace, check "isTraceEnabled()", "isDebugEnabled"). 2. is "isErrorEnabled" -- disable logging altogether, enabled. I suppose "isEnabledFor(Level.ERROR)", checking if logging is all. 3. a rule of thumb, logging operation is extremely heavy (e.g., transforming a large object for trace logs), want check if "Info" level enabled, higher (debug, trace)</technical_language>

Target:
protected AuditMessageType getParticipantObjectIdentificationForRequest(PRPAIN201306UV02 request, AssertionType assertion, AuditMessageType auditMsg) { auditMsg = getPatientParticipantObjectIdentificationForResponse(request, auditMsg); try { auditMsg = getQueryParamsParticipantObjectIdentificationForResponse(request, auditMsg); } catch (JAXBException ex) { LOG.error("Error while creating ParticipantObjectIdentificationQueryByParameters segment : " + ex.getLocalizedMessage(), ex); } return auditMsg; }
Source:
<code>private synchronized void addNode(DiscoveryDruidNode druidNode) { <START> DiscoveryDruidNode prev = nodes.put(druidNode.getDruidNode().getHostAndPortToUse(), druidNode); <END> if (prev == null) { for (DruidNodeDiscovery.Listener l : nodeListeners) { listenerExecutor.submit(() -> { try { l.nodeAdded(druidNode); } catch (Exception ex) { log.error(ex, "Exception occured in DiscoveryDruidNode.nodeAdded(node=[%s]) in listener [%s].", druidNode, l); } }); } } else { log.warn("Node[%s] discovered but existed already [%s].", druidNode, prev); } }</code><technical_language>is getDruidNode() getHostAndPortToUse() null</technical_language>

Target:
private void addNode(DiscoveryDruidNode druidNode) { synchronized (lock) { DiscoveryDruidNode prev = nodes.putIfAbsent(druidNode.getDruidNode().getHostAndPortToUse(), druidNode); if (prev == null) { for (DruidNodeDiscovery.Listener l : nodeListeners) { listenerExecutor.submit(() -> { try { l.nodeAdded(druidNode); } catch (Exception ex) { log.error( ex, "Exception occured in DiscoveryDruidNode.nodeAdded(node=[%s]) in listener [%s].", druidNode, l ); } }); } } else { log.warn("Node[%s] discovered but existed already [%s].", druidNode, prev); } } }
Source:
<code>public Step variantsLoadStep() throws Exception { <START> return stepBuilderFactory.get(LOAD_VARIANTS).<Variant, Variant>chunk(10) <END> .reader(reader) .writer(variantMongoWriter) .faultTolerant().skipLimit(50).skip(FlatFileParseException.class) .listener(new SkippedItemListener()) .build(); }</code><technical_language>talked setting a chunk size. 1000 set in JobOptions? happy location other includeSrc, compressGenotypes, etc, too</technical_language>

Target:
public Step variantsLoadStep() throws Exception { return stepBuilderFactory.get(LOAD_VARIANTS) .<Variant, Variant>chunk(jobOptions.getPipelineOptions().getInt(JobParametersNames.CONFIG_CHUNK_SIZE)) .reader(reader) .writer(variantMongoWriter) .faultTolerant().skipLimit(50).skip(FlatFileParseException.class) .listener(new SkippedItemListener()) .build(); }
Source:
<code><START> public int hashCode() <END> { int result = name != null ? name.hashCode() : 0; result = 31 * result + zScore.hashCode(); return result; }</code><technical_language>Please implement equals() method either. This remove potential problem working collections</technical_language>

Target:
public int hashCode() { int result = name.hashCode(); result = 31 * result + zScore.hashCode(); return result; }
Source:
<code>public Object execute(final ExecutionEvent event) throws ExecutionException { final TaskData data = getTaskData(event); if (data == null) return null; Job job = new Job(MessageFormat.format( Messages.RebasePullRequestHandler_RebaseJob, data.getTaskId())) { @Override protected IStatus run(IProgressMonitor monitor) { PullRequestComposite prComp = PullRequestConnector .getPullRequest(data); if (prComp == null) return Status.CANCEL_STATUS; PullRequest request = prComp.getRequest(); Repository repo = PullRequestUtils.getRepository(request); if (repo == null) return Status.CANCEL_STATUS; String branchName = PullRequestUtils.getBranchName(request); try { String target = request.getBase().getRef(); Ref targetRef = repo.findRef(request.getBase().getRef()); if (targetRef != null) { <START> SubMonitor progress = SubMonitor.convert(monitor, 2); <END> if (!PullRequestUtils.isCurrentBranch(branchName, repo)) { monitor.setTaskName(MessageFormat .format(Messages.RebasePullRequestHandler_TaskCheckout, branchName)); BranchOperationUI.checkout(repo, branchName).run( progress.split(1)); } else { progress.setWorkRemaining(1); } monitor.setTaskName(MessageFormat.format( Messages.RebasePullRequestHandler_TaskRebase, branchName, target)); new RebaseOperation(repo, targetRef) .execute(progress.split(1)); executeCallback(event); } } catch (IOException e) { GitHubUi.logError(e); } catch (CoreException e) { GitHubUi.logError(e); } return Status.OK_STATUS; } }; schedule(job, event); return null; }</code><technical_language>more progress monitor change</technical_language>

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final TaskData data = getTaskData(event); if (data == null) return null; Job job = new Job(MessageFormat.format( Messages.RebasePullRequestHandler_RebaseJob, data.getTaskId())) { protected IStatus run(IProgressMonitor monitor) { PullRequestComposite prComp = PullRequestConnector .getPullRequest(data); if (prComp == null) return Status.CANCEL_STATUS; PullRequest request = prComp.getRequest(); Repository repo = PullRequestUtils.getRepository(request); if (repo == null) return Status.CANCEL_STATUS; String branchName = PullRequestUtils.getBranchName(request); try { String target = request.getBase().getRef(); Ref targetRef = repo.findRef(request.getBase().getRef()); if (targetRef != null) { if (!PullRequestUtils.isCurrentBranch(branchName, repo)) { monitor.setTaskName(MessageFormat .format(Messages.RebasePullRequestHandler_TaskCheckout, branchName)); BranchOperationUI.checkout(repo, branchName).run( new SubProgressMonitor(monitor, 1)); } monitor.setTaskName(MessageFormat.format( Messages.RebasePullRequestHandler_TaskRebase, branchName, target)); new RebaseOperation(repo, targetRef) .execute(new SubProgressMonitor(monitor, 1)); executeCallback(event); } } catch (IOException e) { GitHubUi.logError(e); } catch (CoreException e) { GitHubUi.logError(e); } return Status.OK_STATUS; } }; schedule(job, event); return null; }
Source:
<code>public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { for (Element autoMountElement : roundEnv.getElementsAnnotatedWith(SecureAutoMount.class)) { final AutoMountContext context = getAutoMountContext(autoMountElement, SecureAutoMount.class); if (context == null) { continue; } for (Element elem : roundEnv.getElementsAnnotatedWith(AuthorizeInstantiation.class)) { final AuthorizeInstantiation mp = elem.getAnnotation(AuthorizeInstantiation.class); processMountPoint(context, elem, mp); } for (Element elem : roundEnv.getElementsAnnotatedWith(MountPath.class)) { final MountPath mp = elem.getAnnotation(MountPath.class); processMountPoint(context, elem, mp); } generateSource(context); } return true; } catch (IOException ex) { <START> Logger.getLogger(SecureMountAnnotationProcessor.class.getName()).log(Level.SEVERE, null, ex); <END> } return true; }</code><technical_language>return false</technical_language>

Target:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { for (Element autoMountElement : roundEnv.getElementsAnnotatedWith(SecureAutoMount.class)) { final AutoMountContext context = getAutoMountContext(autoMountElement, SecureAutoMount.class); if (context == null) { continue; } for (Element elem : roundEnv.getElementsAnnotatedWith(AuthorizeInstantiation.class)) { final AuthorizeInstantiation mp = elem.getAnnotation(AuthorizeInstantiation.class); processMountPoint(context, elem, mp); } for (Element elem : roundEnv.getElementsAnnotatedWith(MountPath.class)) { final MountPath mp = elem.getAnnotation(MountPath.class); processMountPoint(context, elem, mp); } generateSource(context); } } catch (IOException ex) { Logger.getLogger(SecureMountAnnotationProcessor.class.getName()).log(Level.SEVERE, null, ex); } return true; }
Source:
<code><START> public void testFrameworkProducerDelete() throws Exception { <END> setupFrameworkProducer(false); Exchange mockExchangeCreate = mock(Exchange.class); Exchange mockExchangeDelete = mock(Exchange.class); Message message = mock(Message.class); Metacard metacard = mock(MetacardImpl.class); when(metacard.getId()).thenReturn("metacard1"); when(mockExchangeCreate.getIn()).thenReturn(message); when(mockExchangeCreate.getOut()).thenReturn(message); when(mockExchangeCreate.getIn().getHeader(OPERATION_HEADER_KEY)).thenReturn(CREATE_OPERATION); when(mockExchangeCreate.getIn().getHeader(TIMEOUT_HEADER_KEY)).thenReturn(1000L); when(mockExchangeCreate.getIn().getBody()).thenReturn(metacard); when(mockExchangeCreate.getIn().getBody(any())).thenReturn(metacard); frameworkProducer.process(mockExchangeCreate); when(mockExchangeDelete.getIn()).thenReturn(message); when(mockExchangeDelete.getOut()).thenReturn(message); when(mockExchangeDelete.getIn().getHeader(OPERATION_HEADER_KEY)).thenReturn(DELETE_OPERATION); when(mockExchangeDelete.getIn().getHeader(TIMEOUT_HEADER_KEY)).thenReturn(1000L); }</code><technical_language>This test needs a verification</technical_language>

Target:
public void testFrameworkProducerDelete() throws Exception { setupFrameworkProducer(false); Exchange mockExchangeDelete = mock(Exchange.class); Message message = mock(Message.class); List ids = Collections.singletonList("metacardId"); when(message.getBody()).thenReturn(ids); when(message.getBody(any())).thenReturn(ids); when(mockExchangeDelete.getIn()).thenReturn(message); when(mockExchangeDelete.getOut()).thenReturn(message); when(mockExchangeDelete.getIn().getHeader(OPERATION_HEADER_KEY)).thenReturn(DELETE_OPERATION); when(mockExchangeDelete.getIn().getHeader(TIMEOUT_HEADER_KEY)).thenReturn(1000L); DeleteResponse response = mock(DeleteResponse.class); when(response.getDeletedMetacards()).thenReturn(Collections.singletonList(new MetacardImpl())); when(catalogFramework.delete(any())).thenReturn(response); frameworkProducer.process(mockExchangeDelete); verify(catalogFramework).delete(any(DeleteRequest.class)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); super.onCreate(savedInstanceState); PreferencesState.getInstance().onCreateActivityPreferences(getResources(), getTheme()); if (EyeSeeTeaApplication.permissions == null) { EyeSeeTeaApplication.permissions = Permissions.getInstance(this); } if (!EyeSeeTeaApplication.permissions.areAllPermissionsGranted()) { EyeSeeTeaApplication.permissions.requestNextPermission(); } initView(savedInstanceState); PreferencesState.getInstance().setPushInProgress(false); List<SurveyDB> surveyDBs = SurveyDB.getAllSendingSurveys(); Log.d(TAG, "Surveys sending: " + surveyDBs.size()); for (SurveyDB surveyDB : surveyDBs) { surveyDB.setStatus(Constants.SURVEY_QUARANTINE); surveyDB.save(); } <START> AlarmPushReceiver.setPushAlarm(this); <END> AlarmPushReceiver.setPushAlarm(this); AlarmPushReceiver.setPushAlarm(this); AlarmPushReceiver.setPushAlarm(this); try { Thread.sleep(100); AlarmPushReceiver.setPushAlarm(this); AlarmPushReceiver.setPushAlarm(this); Thread.sleep(100); AlarmPushReceiver.setPushAlarm(this); AlarmPushReceiver.setPushAlarm(this); Thread.sleep(100); AlarmPushReceiver.setPushAlarm(this); AlarmPushReceiver.setPushAlarm(this); } catch (InterruptedException e) { e.printStackTrace(); } mBaseActivityStrategy.onCreate(); }</code><technical_language>this code is strange, explain is necessary</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); super.onCreate(savedInstanceState); PreferencesState.getInstance().onCreateActivityPreferences(getResources(), getTheme()); if (EyeSeeTeaApplication.permissions == null) { EyeSeeTeaApplication.permissions = Permissions.getInstance(this); } if (!EyeSeeTeaApplication.permissions.areAllPermissionsGranted()) { EyeSeeTeaApplication.permissions.requestNextPermission(); } initView(savedInstanceState); PreferencesState.getInstance().setPushInProgress(false); List<SurveyDB> surveyDBs = SurveyDB.getAllSendingSurveys(); Log.d(TAG, "Surveys sending: " + surveyDBs.size()); for (SurveyDB surveyDB : surveyDBs) { surveyDB.setStatus(Constants.SURVEY_QUARANTINE); surveyDB.save(); } AlarmPushReceiver.setPushAlarm(this); mBaseActivityStrategy.onCreate(); }
Source:
<code>public void testProcessNonJavaFilesWithoutException() throws Exception { final TreeWalker treeWalker = new TreeWalker(); treeWalker.setTabWidth(1); treeWalker.configure(new DefaultConfiguration("default config")); final File file = new File("src/main/resources/checkstyle_packages.xml"); final FileText fileText = new FileText(file, StandardCharsets.ISO_8859_1.name()); try { treeWalker.processFiltered(file, fileText); } catch (CheckstyleException ex) { <START> fail("Exception not expected"); <END> } }</code><technical_language>I mentioned others, try-catch-fail is a good option. JUnit automatically populates exception user fails test. If exception occurs, user get a bland message stack trace of problem. is assert here</technical_language>

Target:
public void testProcessNonJavaFilesWithoutException() throws Exception { final TreeWalker treeWalker = new TreeWalker(); treeWalker.setTabWidth(1); treeWalker.configure(new DefaultConfiguration("default config")); final File file = new File("src/main/resources/checkstyle_packages.xml"); final FileText fileText = new FileText(file, StandardCharsets.ISO_8859_1.name()); treeWalker.processFiltered(file, fileText); final Collection<Checks> checks = (Collection<Checks>) Whitebox.getInternalState(treeWalker, "ordinaryChecks"); assertTrue("No checks -> No parsing", checks.isEmpty()); }
Source:
<code>private void closeConfirmationWindow() { if(getConfirmWindow() == null) { return; } else { setConfirmWindow(null); <START> } <END> }</code><technical_language>do setConfirmWindow(null); method</technical_language>

Target:
private void closeConfirmationWindow() { setConfirmWindow(null); }
Source:
<code>public void queryFile1Contributors() { final IFileHistory history = historyProvider.getFileHistoryFor(iFile1, IFileHistoryProvider.NONE, new NullProgressMonitor()); assertNotNull(history); final IFileRevision[] revisions = history.getFileRevisions(); IFileRevision branchFileRevision1 = null; IFileRevision masterFileRevision3 = null; IFileRevision masterFileRevision1 = null; for (IFileRevision revision : revisions) { final String revisionId = revision.getContentIdentifier(); <START> if (branchCommit1.getName().equals(revisionId)) { <END> branchFileRevision1 = revision; } else if (masterCommit3.getName().equals(revisionId)) { masterFileRevision3 = revision; } else if (masterCommit1.getName().equals(revisionId)) { masterFileRevision1 = revision; } } assertNotNull(branchFileRevision1); assertNotNull(masterFileRevision3); assertNotNull(masterFileRevision1); final IFileRevision[] branchCommit1Parents = history.getContributors(branchFileRevision1); assertEquals(1, branchCommit1Parents.length); assertRevisionMatchCommit(branchCommit1Parents[0], masterCommit1); final IFileRevision[] masterCommit3Parents = history .getContributors(masterFileRevision3); assertEquals(1, masterCommit3Parents.length); assertRevisionMatchCommit(masterCommit3Parents[0], masterCommit1); final IFileRevision[] masterCommit1Parents = history .getContributors(masterFileRevision1); assertEquals(0, masterCommit1Parents.length); }</code><technical_language>braces single line blocks, more occurrences in this patch</technical_language>

Target:
public void queryFile1Contributors() { final IFileHistory history = historyProvider.getFileHistoryFor(iFile1, IFileHistoryProvider.NONE, new NullProgressMonitor()); assertNotNull(history); final IFileRevision[] revisions = history.getFileRevisions(); IFileRevision branchFileRevision1 = null; IFileRevision masterFileRevision3 = null; IFileRevision masterFileRevision1 = null; for (IFileRevision revision : revisions) { final String revisionId = revision.getContentIdentifier(); if (branchCommit1.getName().equals(revisionId)) branchFileRevision1 = revision; else if (masterCommit3.getName().equals(revisionId)) masterFileRevision3 = revision; else if (masterCommit1.getName().equals(revisionId)) masterFileRevision1 = revision; } assertNotNull(branchFileRevision1); assertNotNull(masterFileRevision3); assertNotNull(masterFileRevision1); final IFileRevision[] branchCommit1Parents = history .getContributors(branchFileRevision1); assertEquals(1, branchCommit1Parents.length); assertRevisionMatchCommit(branchCommit1Parents[0], masterCommit1); final IFileRevision[] masterCommit3Parents = history .getContributors(masterFileRevision3); assertEquals(1, masterCommit3Parents.length); assertRevisionMatchCommit(masterCommit3Parents[0], masterCommit1); final IFileRevision[] masterCommit1Parents = history .getContributors(masterFileRevision1); assertEquals(0, masterCommit1Parents.length); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> finishIfNotRoot(); <END> if (savedInstanceState != null) { wasExternal = savedInstanceState.getBoolean("was_external"); } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); uiController.setupUI(); }</code><technical_language>this bail this call if root, returning v. returning onCreate() in case affect anything</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (finishIfNotRoot()) { return; } if (savedInstanceState != null) { wasExternal = savedInstanceState.getBoolean("was_external"); } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); }
Source:
<code>public void testCheckoutExistingBranch() throws Exception { Git git = new Git(db); writeTrashFile("a", "Hello world a"); git.add().addFilepattern(".").call(); git.commit().setMessage("commit file a").call(); git.branchCreate().setName("branch_1").call(); git.rm().addFilepattern("a").call(); FileUtils.mkdirs(new File(db.getWorkTree(), "a")); writeTrashFile("a/b", "Hello world b"); <START> git.add().addFilepattern("a").call(); <END> git.commit().setMessage("commit folder a").call(); git.rm().addFilepattern("a").call(); writeTrashFile("a", "New Hello world a"); git.add().addFilepattern(".").call(); assertEquals( "error: Your local changes to the following files would be overwritten by checkout:", execute("git checkout branch_1")); }</code><technical_language>want add a/b</technical_language>

Target:
public void testCheckoutExistingBranch() throws Exception { Git git = new Git(db); writeTrashFile("a", "Hello world a"); git.add().addFilepattern(".").call(); git.commit().setMessage("commit file a").call(); git.branchCreate().setName("branch_1").call(); git.rm().addFilepattern("a").call(); FileUtils.mkdirs(new File(db.getWorkTree(), "a")); writeTrashFile("a/b", "Hello world b"); git.add().addFilepattern("a/b").call(); git.commit().setMessage("commit folder a").call(); git.rm().addFilepattern("a").call(); writeTrashFile("a", "New Hello world a"); git.add().addFilepattern(".").call(); assertEquals( "error: Your local changes to the following files would be overwritten by checkout:", execute("git checkout branch_1")); }
Source:
<code>private String formRevertMessage(RevertResult revertResult) { StringBuilder message = new StringBuilder(); if (revertResult.getNewHead() != null) { message.append(constant.revertedNewHead(revertResult.getNewHead())); } List<String> commits = revertResult.getRevertedCommits(); if (commits != null && commits.size() > 0) { StringBuilder revertedCommits = new StringBuilder(); for (String commit : commits) { <START> revertedCommits.append(" "); <END> revertedCommits.append(commit); } message.append( revertedCommits.length() > 0 ? " " + constant.revertedCommits(revertedCommits.toString()) : "\n"); } return message.toString(); }</code><technical_language>a bit clearer append chain here</technical_language>

Target:
private String formRevertMessage(RevertResult revertResult) { StringBuilder message = new StringBuilder(); if (revertResult.getNewHead() != null) { message.append(constant.revertedNewHead(revertResult.getNewHead())); } List<String> commits = revertResult.getRevertedCommits(); if (commits != null && commits.size() > 0) { StringBuilder revertedCommits = new StringBuilder(); for (String commit : commits) { revertedCommits.append(" ").append(commit); } message.append( revertedCommits.length() > 0 ? " " + constant.revertedCommits(revertedCommits.toString()) : "\n"); } return message.toString(); }
Source:
<code>private List<StoragePool> searchStoragePool() { Optional<Version> optionalVersion = Config.<HashSet<Version>> getValue(ConfigValues.SupportedClusterLevels).stream() .max(Comparator.naturalOrder()); List<StoragePool> dataCenters = genericSearch(storagePoolDao, true); <START> optionalVersion.ifPresent( version -> dataCenters.forEach( dataCenter -> { dataCenter.setStoragePoolCompatibilityLevelUpgradeNeeded( version.compareTo(dataCenter.getCompatibilityVersion()) > 0); dataCenter.setMacPoolId(dcSingleMacPoolFinder.find(dataCenter.getId())); } )); <END> return dataCenters; }</code><technical_language>I easier do check !ifPresent skip rest, instead of creating lambda. if 2 lambdas approach instead of if lambda, fine, extract method lambda, lambda in lambda ... watching Inception again, forced watch that..</technical_language>

Target:
private List<StoragePool> searchStoragePool() { List<StoragePool> dataCenters = genericSearch(storagePoolDao, true); dataCenters.forEach(this::setDcSingleMacPoolId); setDcCompatibilityLevelUpgradeNeeded(dataCenters); return dataCenters; }
Source:
<code>public boolean save(final Tuple<String, LogicalPlan> tuple){ final LogicalPlan plan = tuple.getValue(); final String queryId = tuple.getKey(); <START> final File storedPlanFile= new File(planFolderPath + queryId + ".plan"); <END> if (!storedPlanFile.exists()) { final DataFileWriter<LogicalPlan> dataFileWriter = new DataFileWriter<LogicalPlan>(datumWriter); try { dataFileWriter.create(plan.getSchema(), storedPlanFile); dataFileWriter.append(plan); dataFileWriter.close(); return true; } catch (final Exception e) { e.printStackTrace(); } } return false; }</code><technical_language>File(planStorePath, queryId + ".plan")</technical_language>

Target:
public boolean save(final Tuple<String, LogicalPlan> tuple) throws IOException { final LogicalPlan plan = tuple.getValue(); final String queryId = tuple.getKey(); final File storedPlanFile= new File(planStorePath, queryId + ".plan"); if (!storedPlanFile.exists()) { final DataFileWriter<LogicalPlan> dataFileWriter = new DataFileWriter<LogicalPlan>(datumWriter); dataFileWriter.create(plan.getSchema(), storedPlanFile); dataFileWriter.append(plan); dataFileWriter.close(); return true; } return false; }
Source:
<code>public void onMessage(NodeRegistrationContainerReport nodeRegistrationContainerReport, EventPublisher publisher) { if (chillModeManager.getInChillMode()) { if (validate()) { <START> chillModeManager.validateChillModeExitRules(publisher); <END> return; } } else { return; } process(nodeRegistrationContainerReport); if(chillModeManager.getInChillMode()) { SCMChillModeManager.getLogger().info( "SCM in chill mode. DataNodes registered, required.", registeredDns, requiredDns); } if (validate()) { chillModeManager.validateChillModeExitRules(publisher); return; } }</code><technical_language>process data this report validating again</technical_language>

Target:
public void onMessage(NodeRegistrationContainerReport nodeRegistrationContainerReport, EventPublisher publisher) { if (chillModeManager.getInChillMode()) { if (validate()) { return; } process(nodeRegistrationContainerReport); if (chillModeManager.getInChillMode()) { SCMChillModeManager.getLogger().info( "SCM in chill mode. DataNodes registered, required.", registeredDns, requiredDns); } if (validate()) { chillModeManager.validateChillModeExitRules(publisher); } } }
Source:
<code>protected int doWork() { initializeAggregationState(); IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFilesAreReadable(INTERVALS); final int returnValue; if ( INTERVAL_ITERATOR ) { returnValue = processDataIntervalIteration(); } else { returnValue = processDataNormalIteration(); } if (returnValue != 0) { return returnValue; } log.info("Iteration complete, generating metric files"); aggregatorList.forEach(this::writeMetricsFileForAggregator); log.info(String.format("Examined %d loci, Processed %d loci, Skipped %d loci.\n" + "Computation took %d seconds.", nTotalLoci, nProcessedLoci, nSkippedLoci, progressLogger.getElapsedSeconds())); <START> return returnValue; <END> }</code><technical_language>this point returnValue==0, change</technical_language>

Target:
protected int doWork() { initializeAggregationState(); IOUtil.assertFileIsReadable(INPUT); IOUtil.assertFileIsReadable(VCF); IOUtil.assertFileIsReadable(REFERENCE_SEQUENCE); IOUtil.assertFilesAreReadable(INTERVALS); final int returnValue = processData(); if (returnValue == 0) { log.info("Iteration complete, generating metric files"); aggregatorList.forEach(this::writeMetricsFileForAggregator); log.info(String.format("Examined %d loci, Processed %d loci, Skipped %d loci.\n" + "Computation took %d seconds.", nTotalLoci, nProcessedLoci, nSkippedLoci, progressLogger.getElapsedSeconds())); } return returnValue; }
Source:
<code>private void setExecutionEnvironment(TargetPlatformConfiguration result, Xpp3Dom configuration) { String value = getStringValue(configuration.getChild("executionEnvironment")); if (value == null) { return; } <START> if (value.startsWith("?")) { <END> throw new RuntimeException( "The target-platform-configuration parameter <executionEnvironment> must not start with a '?'. Use <defaultExecutionEnvironment> without a leading '?' instead."); } try { ExecutionEnvironmentUtils.getExecutionEnvironment(value); } catch (UnknownEnvironmentException e) { throw new RuntimeException("Invalid execution environment profile name " + value); } result.setExecutionEnvironment(value); }</code><technical_language>need this check. if "?" is somewhere, I doubt, UnknownEnvironmentException self-exlanatory enough for investigate fix it</technical_language>

Target:
private void setExecutionEnvironment(TargetPlatformConfiguration result, Xpp3Dom configuration) { String value = getStringValue(configuration.getChild("executionEnvironment")); if (value == null) { return; } try { ExecutionEnvironmentUtils.getExecutionEnvironment(value); } catch (UnknownEnvironmentException e) { throw new RuntimeException("Invalid execution environment profile name " + value); } result.setExecutionEnvironment(value); }
Source:
<code>protected boolean corsRequest() { if (!deployment.isCors()) return false; KeycloakSecurityContext securityContext = facade.getSecurityContext(); String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN); String exposeHeaders = deployment.getCorsExposedHeaders(); String requestOrigin = UriUtils.getOrigin(facade.getRequest().getURI()); log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI()); if (securityContext != null && origin != null && !origin.equals(requestOrigin)) { AccessToken token = securityContext.getToken(); Set<String> allowedOrigins = token.getAllowedOrigins(); if (log.isDebugEnabled()) { for (String a : allowedOrigins) log.debug(" " + a); } if (allowedOrigins == null || (!allowedOrigins.contains("*") && !allowedOrigins.contains(origin))) { if (allowedOrigins == null) { log.debugv("allowedOrigins was null in token"); } else { log.debugv("allowedOrigins did not contain origin"); } facade.getResponse().sendError(403); facade.getResponse().end(); return true; } log.debugv("returning origin: {0}", origin); facade.getResponse().setStatus(200); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); <START> facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, exposeHeaders); <END> } else { log.debugv("cors validation not needed as we're not a secure session or origin header was null: {0}", facade.getRequest().getURI()); } return false; }</code><technical_language>set header if "deployment.getCorsExposedHeaders() != null"</technical_language>

Target:
protected boolean corsRequest() { if (!deployment.isCors()) return false; KeycloakSecurityContext securityContext = facade.getSecurityContext(); String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN); String exposeHeaders = deployment.getCorsExposedHeaders(); String requestOrigin = UriUtils.getOrigin(facade.getRequest().getURI()); log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI()); if (securityContext != null && origin != null && !origin.equals(requestOrigin)) { AccessToken token = securityContext.getToken(); Set<String> allowedOrigins = token.getAllowedOrigins(); if (log.isDebugEnabled()) { for (String a : allowedOrigins) log.debug(" " + a); } if (allowedOrigins == null || (!allowedOrigins.contains("*") && !allowedOrigins.contains(origin))) { if (allowedOrigins == null) { log.debugv("allowedOrigins was null in token"); } else { log.debugv("allowedOrigins did not contain origin"); } facade.getResponse().sendError(403); facade.getResponse().end(); return true; } log.debugv("returning origin: {0}", origin); facade.getResponse().setStatus(200); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); if (exposeHeaders != null) { facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, exposeHeaders); } } else { log.debugv("cors validation not needed as we're not a secure session or origin header was null: {0}", facade.getRequest().getURI()); } return false; }
Source:
<code>public void beforeSend( ServerSession session, Transaction tx, Message message, boolean direct, boolean noAutoCreateQueue) { try { if (brokerMessageInterceptor == null) { BundleContext bundleContext = getBundleContext(); brokerMessageInterceptor = bundleContext.getService( ((List<ServiceReference<BrokerMessageInterceptor>>) bundleContext.getServiceReferences( BrokerMessageInterceptor.class, "(name=subjectInjectorPlugin)")) .get(0)); } brokerMessageInterceptor.handleMessage(session, tx, message, direct, noAutoCreateQueue); } catch (InvalidSyntaxException e) { <START> LOGGER.error( <END> "Could retrieve the Subject Injector Plugin, subject will not be correctly applied to the message.", e); } }</code><technical_language>Is error right log level here? warn info more appropriate</technical_language>

Target:
public void beforeSend( ServerSession session, Transaction tx, Message message, boolean direct, boolean noAutoCreateQueue) { try { if (brokerMessageInterceptor == null) { BundleContext bundleContext = getBundleContext(); brokerMessageInterceptor = bundleContext.getService( ((List<ServiceReference<BrokerMessageInterceptor>>) bundleContext.getServiceReferences( BrokerMessageInterceptor.class, "(name=subjectInjectorPlugin)")) .get(0)); } brokerMessageInterceptor.handleMessage(session, tx, message, direct, noAutoCreateQueue); } catch (InvalidSyntaxException e) { LOGGER.warn( "Could retrieve the Subject Injector Plugin, subject will not be correctly applied to the message.", e); } }
Source:
<code>public void delete() throws IOException, InterruptedException { checkPermission(DELETE); FolderComputation<I> computation = getComputation(); Executor executor = Executor.of(computation); if (executor != null) { LOGGER.log(Level.INFO, "Interrupting {0} in order to delete it", this); executor.interrupt(Result.ABORTED, new CauseOfInterruption.UserInterruption(User.current())); long expiration = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); while (executor.isAlive() <START> && executor.getCurrentExecutable() == computation <END> && expiration - System.nanoTime() > 0L) { Thread.sleep(50L); } if (executor.isAlive() && executor.getCurrentExecutable() == computation) { LOGGER.log(Level.WARNING, "Interrupted {0} in order to delete it, but it has not stopped yet", this); } } super.delete(); }</code><technical_language>Superfluous check I think-it a long time Executors reused</technical_language>

Target:
public void delete() throws IOException, InterruptedException { checkPermission(DELETE); FolderComputation<I> computation = getComputation(); Executor executor = Executor.of(computation); if (executor != null) { LOGGER.log(Level.INFO, "Interrupting {0} in order to delete it", this); executor.interrupt(Result.ABORTED, new CauseOfInterruption.UserInterruption(User.current())); long expiration = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); while (executor.isAlive() && executor.getCurrentExecutable() == computation && expiration - System.nanoTime() > 0L) { Thread.sleep(50L); } if (executor.isAlive() && executor.getCurrentExecutable() == computation) { throw new AbortException("Failed to stop computation of " + getFullDisplayName()); } } super.delete(); }
Source:
<code>public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, <START> InvalidArgumentException { <END> if (offset < 0) { throw new InvalidArgumentException("offset should be zero or greater"); } if (length != null && length <= 0) { throw new InvalidArgumentException("length should be greater than zero"); } if ((bucketName == null) || (bucketName.isEmpty())) { throw new InvalidArgumentException("bucket name cannot be empty"); } if ((objectName == null) || (objectName.isEmpty())) { throw new InvalidArgumentException("object name cannot be empty"); } Map<String,String> headerMap = new HashMap<>(); if (offset > 0) { if (length != null) { headerMap.put("Range", "bytes=" + offset + "-" + (offset + length - 1)); } else { headerMap.put("Range", "bytes=" + offset + "-"); } } HttpResponse response = executeGet(bucketName, objectName, headerMap, null); return response.body().byteStream(); }</code><technical_language>Do this validation first. order of method arguments</technical_language>

Target:
public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException { if ((bucketName == null) || (bucketName.isEmpty())) { throw new InvalidArgumentException("bucket name cannot be empty"); } if ((objectName == null) || (objectName.isEmpty())) { throw new InvalidArgumentException("object name cannot be empty"); } if (offset < 0) { throw new InvalidArgumentException("offset should be zero or greater"); } if (length != null && length <= 0) { throw new InvalidArgumentException("length should be greater than zero"); } Map<String,String> headerMap = new HashMap<>(); if (offset > 0) { if (length != null) { headerMap.put("Range", "bytes=" + offset + "-" + (offset + length - 1)); } else { headerMap.put("Range", "bytes=" + offset + "-"); } } HttpResponse response = executeGet(bucketName, objectName, headerMap, null); return response.body().byteStream(); }
Source:
<code>public static FileUtils.FileCopyResult unzip( final ByteSource byteSource, final File outDir, boolean cacheLocally ) throws IOException { <START> return unzip(byteSource, outDir, Predicates.<Throwable>alwaysTrue(), cacheLocally); <END> }</code><technical_language>I default retry Exceptions other kinds of Throwables</technical_language>

Target:
public static FileUtils.FileCopyResult unzip( final ByteSource byteSource, final File outDir, boolean cacheLocally ) throws IOException { return unzip(byteSource, outDir, FileUtils.IS_EXCEPTION, cacheLocally); }
Source:
<code>public PrologEnvironment newPrologEnvironment() throws CompileException { <START> <END> PrologEnvironment env; if(urlLoader != null) { env = envFactory.create(urlLoader); return env; } else { env = envFactory.create(getClass().getClassLoader()); } String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }</code><technical_language>Style-nit: Unnecessary blank line</technical_language>

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException { PrologEnvironment env; if (cLoader != null) { return envFactory.create(cLoader); } env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }
Source:
<code>public void scheduleTask(TaskDefinition task) throws SchedulerException { <START> if (!Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { <END> Context.getSchedulerService().scheduleTask(task); } }</code><technical_language>a look, i do need this call all. check of ensure a service is started schedule, etc, belong service layer API. role is simply call Context.getSchedulerService().scheduleTask(task) is all</technical_language>

Target:
public void scheduleTask(TaskDefinition task) throws SchedulerException { Context.getSchedulerService().scheduleTask(task); }
Source:
<code>public String validate(String parameterValue, ModelValidatorContext context) throws ValidationException { try { if (!isValidJSON(parameterValue)) { <START> throw new ValidationException("Expected value should match JSON format, received " + parameterValue); <END> } } catch (ValidationException er) { throw new ValidationException("Validator error from JsonParser: Expected value should match JSON format, received " + parameterValue); } return parameterValue; }</code><technical_language>I this part improved. isValidJSON returns a boolean throws a ValidationException. decide a single strategy, return true false return void throw exception. I prefer latter, exception contains more meaningful error messages true/false. In case method renamed checkValidJson</technical_language>

Target:
public String validate(String parameterValue, ModelValidatorContext context) throws ValidationException { try { final JsonParser parser = new ObjectMapper().getJsonFactory().createJsonParser(parameterValue); while (parser.nextToken() != null) { } } catch (Exception jpe) { throw new ValidationException("Invalid JSON: " + jpe.getMessage(), jpe); } return parameterValue; }
Source:
<code>public void getVersion() throws Exception { <START> String version = gApi.config().server().getVersion(); <END> Truth.assertThat(version).is(Version.getVersion()); }</code><technical_language>inlined in assertThat statement below</technical_language>

Target:
public void getVersion() throws Exception { assertThat(gApi.config().server().getVersion()) .isEqualTo(Version.getVersion()); }
Source:
<code>public HttpRequest filter(HttpRequest request) throws HttpException { Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null"); Signer signer = Signer.getSigner(); String signature; Multimap<String, String> decodedParams = queryParser().apply(request.getEndpoint().getRawQuery()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); String timestamp = df.format(new Date()); String signatureNonce = UUID.randomUUID().toString(); decodedParams.put("AccessKeyId", currentCreds.identity); decodedParams.put("Timestamp", timestamp); decodedParams.put("SignatureNonce", signatureNonce); String prefix; try { prefix = request.getMethod() + SEPARATOR + AcsURLEncoder.percentEncode("/") + SEPARATOR; } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); } String stringToSign = prefix; ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder(); for (Map.Entry<String, String> entry : decodedParams.entries()) builder.add(Strings2.urlEncode(entry.getKey()) + "=" + Strings2.urlEncode(entry.getValue())); <START> stringToSign += Strings2.urlEncode(Joiner.on("&").join(builder.build())); <END> signature = signer.signString(stringToSign, currentCreds.credential + "&"); decodedParams.put("Signature", signature); request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build(); return request; }</code><technical_language>If jclouds Uris UriBuilder classes I worry manually encoding parameters</technical_language>

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null"); Multimap<String, String> decodedParams = queryParser().apply(request.getEndpoint().getQuery()); SimpleDateFormat df = new SimpleDateFormat(ECS_DATE_FORMAT); df.setTimeZone(new SimpleTimeZone(0, "GMT")); String timestamp = df.format(new Date()); String signatureNonce = UUID.randomUUID().toString(); decodedParams.put("AccessKeyId", currentCreds.identity); decodedParams.put("Timestamp", timestamp); decodedParams.put("SignatureNonce", signatureNonce); String stringToSign = createStringToSign(request.getMethod(), decodedParams); String signature = sign(stringToSign, creds.get().credential); decodedParams.put("Signature", signature); request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build(); return request; }
Source:
<code>public void beforeDocumentChange(DocumentEvent event) { Document document = event.getDocument(); SPath path = editorManager.getEditorPool().getFile(document); if (path == null) { VirtualFile virtualFile = FileDocumentManager.getInstance() .getFile(document); if (virtualFile == null) { <START> LOG.debug("Ignoring event for document " + document <END> + " - document is not known to the editor pool and a " + "VirtualFile for the document could not be found"); return; } path = virtualFileConverter.convertToPath(virtualFile); if (path == null) { LOG.debug("Ignoring event for document " + document + " - document is not known to the editor pool and an " + "SPath for the document could not be found"); return; } else if (!editorManager.getSession() .isShared(path.getResource())) { LOG.debug("Ignoring Event for document " + document + " - document is not shared"); return; } } String newText = event.getNewFragment().toString(); String replacedText = event.getOldFragment().toString(); editorManager .generateTextEdit(event.getOffset(), newText, replacedText, path); }</code><technical_language>tracking files in IDE ? If this flood log file a bit depending sharing setup, e.g do a partial sharing a files</technical_language>

Target:
public void beforeDocumentChange(DocumentEvent event) { Document document = event.getDocument(); SPath path = editorManager.getEditorPool().getFile(document); if (path == null) { VirtualFile virtualFile = FileDocumentManager.getInstance() .getFile(document); if (virtualFile == null) { LOG.trace("Ignoring event for document " + document + " - document is not known to the editor pool and a " + "VirtualFile for the document could not be found"); return; } path = virtualFileConverter.convertToPath(virtualFile); if (path == null) { LOG.trace("Ignoring Event for document " + document + " - document is not shared"); return; } } String newText = event.getNewFragment().toString(); String replacedText = event.getOldFragment().toString(); editorManager .generateTextEdit(event.getOffset(), newText, replacedText, path); }
Source:
<code>private void initialize() { <START> Assert.isNotNull(scope, "Task scope should not be null."); END> events.addAll(manager.getEvents(scope)); try { ReviewTaskProvider reviewTaskProvider = new ReviewTaskProvider(); reviewTaskProvider.open(manager); reviewTaskProvider.query(scope, null); } catch (CoreException e) { System.out.println(e); } events.addAll(manager.getEvents(scope)); }</code><technical_language>constructor asserts</technical_language>

Target:
private void initialize() { events.addAll(manager.getEvents(scope)); }