auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String decodeBase64EncodedPassword(String prefixEncodedPasswordString) { try { String algorithmUsed = extractId(prefixEncodedPasswordString); String base64DecodedPasswordAfterAlgorithm; String extractBase64EncodedHash = prefixEncodedPasswordString; if (StringUtils.isNotEmpty(algorithmUsed)) { extractBase64EncodedHash = extractEncodedPassword(prefixEncodedPasswordString); <START> base64DecodedPasswordAfterAlgorithm = PREFIX + algorithmUsed + SUFFIX + decodeBase64EncodedHashWithHex(extractBase64EncodedHash); <END> } else { base64DecodedPasswordAfterAlgorithm = new String( java.util.Base64.getDecoder().decode(Utf8.encode(extractBase64EncodedHash))); } return base64DecodedPasswordAfterAlgorithm; } catch (Exception e) { logger.warn("Failed to match password after decoding base64encoded hash after algorithm"); return prefixEncodedPasswordString; } }</code><technical_language>suggestion base64DecodedPasswordAfterAlgorithm = PREFIX + algorithmUsed + SUFFIX + decodeBase64EncodedHashWithHex(extractBase64EncodedHash);</technical_language>

Target:
private String decodeBase64EncodedPassword(String prefixEncodedPasswordString) { try { String algorithmUsed = extractId(prefixEncodedPasswordString); String extractBase64EncodedHash = prefixEncodedPasswordString; if (!StringUtils.isEmpty(algorithmUsed)) { extractBase64EncodedHash = extractEncodedPassword(prefixEncodedPasswordString); return PREFIX + algorithmUsed + SUFFIX + decodeBase64EncodedHashWithHex(extractBase64EncodedHash); } else { return new String(Base64.getDecoder().decode(Utf8.encode(extractBase64EncodedHash))); } } catch (Exception e) { logger.warn("Failed to match password after decoding base64encoded hash after algorithm", e); return prefixEncodedPasswordString; } }
Source:
<code>public void onLogout() { AsyncQuery query = new AsyncQuery(); query.setHandleFailure(true); <START> query.setModel(this); <END> query.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { Window.Location.reload(); } }; frontend.logoffAsync(frontend.getLoggedInUser(), query); }</code><technical_language>"this" is a model, a UI infra object (BaseApplicationInit). Original code (in UserPortal ApplicationInit) copy-pasted CommonModel#signOut method, "this" refers CommonModel. I suggest remove this line, I effect here</technical_language>

Target:
public void onLogout() { AsyncQuery query = new AsyncQuery(); query.setHandleFailure(true); query.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { Window.Location.reload(); } }; frontend.logoffAsync(frontend.getLoggedInUser(), query); }
Source:
<code>public void canSupportGuaranteedSize() throws CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; <START> if (CameraUtil.hasCameraWithLensFacing(lensFacing)) { <END> continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageCapture useCase = new ImageCapture.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync( () -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); }); AtomicReference<ImageProperties> imageProperties = new AtomicReference<>(null); OnImageCapturedCallback callback = createMockOnImageCapturedCallback(imageProperties); useCase.takePicture(mListenerExecutor, callback); verify(callback, timeout(3000)).onCaptureSuccess(any(ImageProxy.class)); assertEquals(GUARANTEED_RESOLUTION, imageProperties.get().size); } }</code><technical_language>miss "!" . sense "continue" if camera exists</technical_language>

Target:
public void canSupportGuaranteedSize() throws CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; if (!CameraUtil.hasCameraWithLensFacing(lensFacing)) { continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageCapture useCase = new ImageCapture.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync( () -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); }); AtomicReference<ImageProperties> imageProperties = new AtomicReference<>(null); OnImageCapturedCallback callback = createMockOnImageCapturedCallback(imageProperties); useCase.takePicture(mListenerExecutor, callback); verify(callback, timeout(3000)).onCaptureSuccess(any(ImageProxy.class)); assertEquals(GUARANTEED_RESOLUTION, imageProperties.get().size); mInstrumentation.runOnMainSync(() -> { CameraX.unbindAll(); mLifecycleOwner.pauseAndStop(); }); } }
Source:
<code>public void addFileField(String name, File file) throws IOException { <START> String fileName = file.getName(); <END> writer.append("--" + boundary).append(LINE_BREAK); writer.append( "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"").append( LINE_BREAK); String probableContentType = URLConnection .guessContentTypeFromName(fileName); writer.append("Content-Type: " + probableContentType) .append(LINE_BREAK); writer.append("Content-Transfer-Encoding: binary").append(LINE_BREAK); writer.append(LINE_BREAK); FileInputStream inputStream = new FileInputStream(file); try { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } finally { inputStream.close(); } writer.append(LINE_BREAK); }</code><technical_language>if this is correct place, please assert (somewhere) file exists, is a file (vs directory), read permissions</technical_language>

Target:
public void addFileField(String name, File file) throws IOException { String fileName = file.getName(); writer.append("--" + boundary).append(LINE_BREAK); writer.append( "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + fileName + "\"").append( LINE_BREAK); String probableContentType = URLConnection .guessContentTypeFromName(fileName); writer.append("Content-Type: " + probableContentType) .append(LINE_BREAK); writer.append("Content-Transfer-Encoding: binary").append(LINE_BREAK); writer.append(LINE_BREAK); writer.flush(); FileInputStream inputStream = new FileInputStream(file); try { byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } finally { inputStream.close(); } writer.append(LINE_BREAK); writer.flush(); }
Source:
<code>private JobDescriptorImpl createJob(JobPriority jobPriority, Optional<Date> deadline) { final JobDescriptorImpl job = mock(JobDescriptorImpl.class); final JobId jobId = mock(JobId.class); if (deadline.isPresent()) { when(jobId.value()).thenReturn("id " + jobPriority + deadline.get()); } else { when(jobId.value()).thenReturn("id " + jobPriority + " no date"); <START> } <END> when(job.getJobId()).thenReturn(jobId); final InternalJob internalJob = mock(InternalJob.class); when(job.getInternal()).thenReturn(internalJob); when(internalJob.getJobDeadline()).thenReturn(deadline); when(internalJob.getPriority()).thenReturn(jobPriority); final EligibleTaskDescriptor taskDescriptor0 = mock(EligibleTaskDescriptor.class); when(taskDescriptor0.getJobId()).thenReturn(jobId); final EligibleTaskDescriptor taskDescriptor1 = mock(EligibleTaskDescriptor.class); when(taskDescriptor1.getJobId()).thenReturn(jobId); when(job.getEligibleTasks()).thenReturn(Arrays.asList(taskDescriptor0, taskDescriptor1)); return job; }</code><technical_language>Replace if else condition java when(jobId.value()).thenReturn("id " + jobPriority + deadline.map(Date::toString).orElse(" date"))</technical_language>

Target:
private JobDescriptorImpl createJob(JobPriority jobPriority, Optional<Date> deadline) { final JobDescriptorImpl job = mock(JobDescriptorImpl.class); final JobId jobId = mock(JobId.class); when(jobId.value()).thenReturn("id " + jobPriority + deadline.map(Date::toString).orElse(" no deadline")); when(job.getJobId()).thenReturn(jobId); final InternalJob internalJob = mock(InternalJob.class); when(job.getInternal()).thenReturn(internalJob); when(internalJob.getJobDeadline()).thenReturn(deadline); when(internalJob.getPriority()).thenReturn(jobPriority); final EligibleTaskDescriptor taskDescriptor0 = mock(EligibleTaskDescriptor.class); when(taskDescriptor0.getJobId()).thenReturn(jobId); final EligibleTaskDescriptor taskDescriptor1 = mock(EligibleTaskDescriptor.class); when(taskDescriptor1.getJobId()).thenReturn(jobId); when(job.getEligibleTasks()).thenReturn(Arrays.asList(taskDescriptor0, taskDescriptor1)); return job; }
Source:
<code>protected void addPermissionSubjectForAdminLevelProperties(List<PermissionSubject> permissionList) { VmStatic vmFromParams = getParameters().getVmStaticData(); VmTemplate vmTemplate = getVmTemplate(); if (vmFromParams != null && vmTemplate != null <START> && !vmTemplate.isBlank()) { <END> if (!Objects.equals(vmFromParams.getCustomProperties(), vmTemplate.getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } Set<Guid> dedicatedVmForVdsFromUser = new HashSet<>(vmFromParams.getDedicatedVmForVdsList()); Set<Guid> dedicatedVmForVdsFromTemplate = new HashSet<>(vmTemplate.getDedicatedVmForVdsList()); if (!dedicatedVmForVdsFromUser.equals(dedicatedVmForVdsFromTemplate) || !StringUtils.isEmpty(vmFromParams.getCpuPinning())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.EDIT_ADMIN_VM_PROPERTIES)); } } }</code><technical_language>This overrides custom properties I want change part. extra template check wrap section line 1424</technical_language>

Target:
protected void addPermissionSubjectForAdminLevelProperties(List<PermissionSubject> permissionList) { VmStatic vmFromParams = getParameters().getVmStaticData(); VmTemplate vmTemplate = getVmTemplate(); if (vmFromParams != null && vmTemplate != null) { if (!Objects.equals(vmFromParams.getCustomProperties(), vmTemplate.getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } if(vmTemplate.isBlank()){ return; } Set<Guid> dedicatedVmForVdsFromUser = new HashSet<>(vmFromParams.getDedicatedVmForVdsList()); Set<Guid> dedicatedVmForVdsFromTemplate = new HashSet<>(vmTemplate.getDedicatedVmForVdsList()); if (!dedicatedVmForVdsFromUser.equals(dedicatedVmForVdsFromTemplate) || !StringUtils.isEmpty(vmFromParams.getCpuPinning())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.EDIT_ADMIN_VM_PROPERTIES)); } } }
Source:
<code>public static ClientCompactQueryTuningConfig from( @Nullable UserCompactTuningConfig userCompactionTaskQueryTuningConfig, @Nullable Integer maxRowsPerSegment ) { return new ClientCompactQueryTuningConfig( maxRowsPerSegment, userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getMaxRowsInMemory(), userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getMaxBytesInMemory(), userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getMaxTotalRows(), <START> userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getSplitHintSpec(), <END> userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getIndexSpec(), userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getMaxPendingPersists(), userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getPushTimeout(), userCompactionTaskQueryTuningConfig == null ? null : userCompactionTaskQueryTuningConfig.getMaxNumConcurrentSubTasks() ); }</code><technical_language>more readable if check for null userCompactionTaskQueryTuningConfig is moved up: java if (userCompactionTaskQueryTuningConfig == null) { return new ClientCompactQueryTuningConfig( maxRowsPerSegment, null, null, ... ) } else { return new ClientCompactQueryTuningConfig( maxRowsPerSegment, userCompactionTaskQueryTuningConfig.getMaxRowsInMemory(), userCompactionTaskQueryTuningConfig.getMaxBytesInMemory(), ... ) }</technical_language>

Target:
public static ClientCompactQueryTuningConfig from( @Nullable UserCompactTuningConfig userCompactionTaskQueryTuningConfig, @Nullable Integer maxRowsPerSegment ) { if (userCompactionTaskQueryTuningConfig == null) { return new ClientCompactQueryTuningConfig( maxRowsPerSegment, null, null, null, null, null, null, null, null ); } else { return new ClientCompactQueryTuningConfig( maxRowsPerSegment, userCompactionTaskQueryTuningConfig.getMaxRowsInMemory(), userCompactionTaskQueryTuningConfig.getMaxBytesInMemory(), userCompactionTaskQueryTuningConfig.getMaxTotalRows(), userCompactionTaskQueryTuningConfig.getSplitHintSpec(), userCompactionTaskQueryTuningConfig.getIndexSpec(), userCompactionTaskQueryTuningConfig.getMaxPendingPersists(), userCompactionTaskQueryTuningConfig.getPushTimeout(), userCompactionTaskQueryTuningConfig.getMaxNumConcurrentSubTasks() ); } }
Source:
<code>private <K, V> RemoteCache<K, V> getRemoteCache(HotRodServer hotRodServer) { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder .marshaller(GenericJBossMarshaller.class) .addServer() .host("localhost") <START> .port(hotRodServer.getPort()); <END> RemoteCacheManager remoteCacheManager = new RemoteCacheManager(clientBuilder.build()); return remoteCacheManager.getCache(CACHE_NAME); }</code><technical_language>Nitpicking, prefer creating builder org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer); setting marshalling. in RemoteStoreMixedAccessTest</technical_language>

Target:
private <K, V> RemoteCache<K, V> getRemoteCache(HotRodServer hotRodServer) { RemoteCacheManager remoteCacheManager = new RemoteCacheManager( HotRodClientTestingUtil.newRemoteConfigurationBuilder(hotRodServer) .marshaller(GenericJBossMarshaller.class) .build() ); return remoteCacheManager.getCache(CACHE_NAME); }
Source:
<code>@Override public <K, V> IgniteModel<I, List<O>> update(IgniteModel<I, List<O>> mdl, DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, L> lbExtractor) { ModelsParallelComposition<I, O> typedMdl = (ModelsParallelComposition<I, O>)mdl; assert typedMdl.submodels().size() == trainers.size(); List<IgniteModel<I, O>> mdls = new ArrayList<>(); for (int i = 0; i < trainers.size(); i++) <START> mdls.add(trainers.get(i).update(typedMdl.submodels().get(i), datasetBuilder, featureExtractor, lbExtractor)); <END> return new ModelsParallelComposition<>(mdls); }</code><technical_language>update models in parallel manner</technical_language>

Target:
@Override public <K, V> IgniteModel<I, List<O>> update(IgniteModel<I, List<O>> mdl, DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, L> lbExtractor) { ModelsParallelComposition<I, O> typedMdl = (ModelsParallelComposition<I, O>)mdl; assert typedMdl.submodels().size() == trainers.size(); List<IgniteSupplier<IgniteModel<I, O>>> tasks = new ArrayList<>(); for (int i = 0; i < trainers.size(); i++) { int j = i; tasks.add(() -> trainers.get(j).update(typedMdl.submodels().get(j), datasetBuilder, featureExtractor, lbExtractor)); } List<IgniteModel<I, O>> mdls = environment.parallelismStrategy().submit(tasks).stream() .map(Promise::unsafeGet) .collect(Collectors.toList()); return new ModelsParallelComposition<>(mdls); }
Source:
<code>public void acceptDraftDataFilteredByVariable( final Integer datasetId, final ObservationUnitsSearchDTO searchDTO, final int studyId) { final String variableId = searchDTO.getFilter().getVariableId().toString(); final List<Phenotype> phenotypes = new ArrayList<>(); this.fillSearchDTO(studyId, datasetId, searchDTO); final List<ObservationUnitRow> observationUnitsByVariable = this.daoFactory.getObservationUnitsSearchDAO().getObservationUnitsByVariable(searchDTO); if (!observationUnitsByVariable.isEmpty()) { for (final ObservationUnitRow observationUnitRow : observationUnitsByVariable) { final ObservationUnitData observationUnitData = observationUnitRow.getVariables().get( variableId); Phenotype phenotype = null; if (observationUnitData != null) { phenotype = this.daoFactory.getPhenotypeDAO().getById(observationUnitData.getObservationId()); } if (phenotype != null) { phenotypes.add(phenotype); if (StringUtils.isEmpty(phenotype.getDraftValue())) { this.deletePhenotype(phenotype.getPhenotypeId()); } else { this.updatePhenotype(phenotype, phenotype.getDraftCValueId(), phenotype.getDraftValue(), null, null, false); } } } } final List<Phenotype> allPhenotypes = this.daoFactory.getPhenotypeDAO().getPhenotypes(datasetId); <START> this.reorganizePhenotypesStatus(studyId, datasetId, phenotypes, allPhenotypes); <END> }</code><technical_language>datasetId is unused in reorganizePhenotypesStatus method</technical_language>

Target:
public void acceptDraftDataFilteredByVariable( final Integer datasetId, final ObservationUnitsSearchDTO searchDTO, final int studyId) { final String variableId = searchDTO.getFilter().getVariableId().toString(); final List<Phenotype> phenotypes = new ArrayList<>(); this.fillSearchDTO(studyId, datasetId, searchDTO); final List<ObservationUnitRow> observationUnitsByVariable = this.daoFactory.getObservationUnitsSearchDAO().getObservationUnitsByVariable(searchDTO); if (!observationUnitsByVariable.isEmpty()) { for (final ObservationUnitRow observationUnitRow : observationUnitsByVariable) { final ObservationUnitData observationUnitData = observationUnitRow.getVariables().get( variableId); Phenotype phenotype = null; if (observationUnitData != null) { phenotype = this.daoFactory.getPhenotypeDAO().getById(observationUnitData.getObservationId()); } if (phenotype != null) { phenotypes.add(phenotype); if (StringUtils.isEmpty(phenotype.getDraftValue())) { this.deletePhenotype(phenotype.getPhenotypeId()); } else { this.updatePhenotype(phenotype, phenotype.getDraftCValueId(), phenotype.getDraftValue(), null, null, false); } } } } this.reorganizePhenotypesStatus(studyId, phenotypes); }
Source:
<code>public static List<NameValuePair> buildParameters(ArticleSearchQuery asq) { UrlParamBuilder params = UrlParamBuilder.params(); params.add("wt", "json"); if (asq.isPartialSearch()) { params.add("qf", "doc_partial_body"); params.add("fl", "*"); params.add("fq", "doc_type:partial"); } else { params.add("fq", "doc_type:full"); } params.add("fq", "!article_type_facet:\"Issue Image\""); if (asq.getStart() > 0) { params.add("start", Integer.toString(asq.getStart())); } params.add("rows", Integer.toString(asq.getRows())); params.add("hl", "false"); String queryString = asq.getQuery(); params.add("q", queryString); if (asq.isSimple()) { params.add("defType", "dismax"); } if (asq.getFacetFields().size() > 0) { params.add("facet", "true"); for (String field: asq.getFacetFields()) { params.add("facet.field", field); } params.add("facet.mincount", Integer.toString(asq.getFacetMinCount())); params.add("facet.limit", Integer.toString(asq.getFacetLimit())); <START> params.add("facet.threads", Integer.toString(-1)); <END> params.add("json.nl", "map"); } else { params.add("facet", "false"); } List<String> fields = asq.getFields().orElse(ArticleSearchQuery.ARTICLE_FIELDS); params.add("fl", Joiner.on(",").join(fields)); asq.getCursor().ifPresent(cursor -> params.add("cursorMark", cursor)); setQueryFilters(asq, params); if (asq.getStatsField().isPresent()) { params.add("stats", "true"); params.add("stats.field", asq.getStatsField().get()); } return params.build(); }</code><technical_language>Thanks for explaining magic number! :thread: :thread: :thread:</technical_language>

Target:
public static List<NameValuePair> buildParameters(ArticleSearchQuery asq) { UrlParamBuilder params = UrlParamBuilder.params(); params.add("wt", "json"); if (asq.isPartialSearch()) { params.add("qf", "doc_partial_body"); params.add("fl", "*"); params.add("fq", "doc_type:partial"); } else { params.add("fq", "doc_type:full"); } params.add("fq", "!article_type_facet:\"Issue Image\""); if (asq.getStart() > 0) { params.add("start", Integer.toString(asq.getStart())); } params.add("rows", Integer.toString(asq.getRows())); params.add("hl", "false"); String queryString = asq.getQuery(); params.add("q", queryString); if (asq.isSimple()) { params.add("defType", "dismax"); } if (asq.getFacetFields().size() > 0) { params.add("facet", "true"); for (String field: asq.getFacetFields()) { params.add("facet.field", field); } params.add("facet.mincount", Integer.toString(asq.getFacetMinCount())); params.add("facet.limit", Integer.toString(asq.getFacetLimit())); params.add("facet.threads", Integer.toString(THREAD_PER_FACET)); params.add("json.nl", "map"); } else { params.add("facet", "false"); } List<String> fields = asq.getFields().orElse(ArticleSearchQuery.ARTICLE_FIELDS); params.add("fl", Joiner.on(",").join(fields)); asq.getCursor().ifPresent(cursor -> params.add("cursorMark", cursor)); setQueryFilters(asq, params); if (asq.getStatsField().isPresent()) { params.add("stats", "true"); params.add("stats.field", asq.getStatsField().get()); } return params.build(); }
Source:
<code>public void should_create_error_message_for_ignoring_case_with_multiple_findings() { ErrorMessageFactory factory = ShouldNotContainCharSequence.shouldNotContainIgnoringCase("Yoda", Arrays.array("OD", "da", "Luke"), <START> Sets.newSet("OD", "da")); <END> String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); then(message).isEqualTo(format("[Test] %n" + "Expecting:%n" + " <\"Yoda\">%n" + "not to contain (ignoring case):%n" + " <[\"OD\", \"da\", \"Luke\"]>%n" + "but found:%n" + " <[\"OD\", \"da\"]>%n")); }</code><technical_language>static import shouldNotContainIgnoringCase, array newSet if fit line</technical_language>

Target:
public void should_create_error_message_for_ignoring_case_with_multiple_findings() { ErrorMessageFactory factory = shouldNotContainIgnoringCase("Yoda", array("OD", "da", "Luke"), newSet("OD", "da")); String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); then(message).isEqualTo(format("[Test] %n" + "Expecting:%n" + " <\"Yoda\">%n" + "not to contain (ignoring case):%n" + " <[\"OD\", \"da\", \"Luke\"]>%n" + "but found:%n" + " <[\"OD\", \"da\"]>%n")); }
Source:
<code>IndexedTableJoinMatcher( final IndexedTable table, final ColumnSelectorFactory leftSelectorFactory, final JoinConditionAnalysis condition, final boolean remainderNeeded ) { this.table = table; <START> this.currentRow = -1; <END> if (condition.isAlwaysTrue()) { this.conditionMatchers = Collections.singletonList(() -> IntIterators.fromTo(0, table.numRows())); } else if (condition.isAlwaysFalse()) { this.conditionMatchers = Collections.singletonList(() -> IntIterators.EMPTY_ITERATOR); } else if (condition.getNonEquiConditions().isEmpty()) { this.conditionMatchers = condition.getEquiConditions() .stream() .map(eq -> makeConditionMatcher(table, leftSelectorFactory, eq)) .collect(Collectors.toCollection(ArrayList::new)); } else { throw new IAE( "Cannot build hash-join matcher on non-equi-join condition: %s", condition.getOriginalExpression() ); } this.currentMatchedRows = new IntIterator[conditionMatchers.size()]; this.selectorFactory = new IndexedTableColumnSelectorFactory(table, () -> currentRow); if (remainderNeeded) { this.matchedRows = new IntRBTreeSet(); } else { this.matchedRows = null; } }</code><technical_language>create a named constant for this reset() method in this class</technical_language>

Target:
IndexedTableJoinMatcher( final IndexedTable table, final ColumnSelectorFactory leftSelectorFactory, final JoinConditionAnalysis condition, final boolean remainderNeeded ) { this.table = table; this.currentRow = UNINITIALIZED_CURRENT_ROW; if (condition.isAlwaysTrue()) { this.conditionMatchers = Collections.singletonList(() -> IntIterators.fromTo(0, table.numRows())); } else if (condition.isAlwaysFalse()) { this.conditionMatchers = Collections.singletonList(() -> IntIterators.EMPTY_ITERATOR); } else if (condition.getNonEquiConditions().isEmpty()) { this.conditionMatchers = condition.getEquiConditions() .stream() .map(eq -> makeConditionMatcher(table, leftSelectorFactory, eq)) .collect(Collectors.toCollection(ArrayList::new)); } else { throw new IAE( "Cannot build hash-join matcher on non-equi-join condition: %s", condition.getOriginalExpression() ); } this.currentMatchedRows = new IntIterator[conditionMatchers.size()]; this.selectorFactory = new IndexedTableColumnSelectorFactory(table, () -> currentRow); if (remainderNeeded) { this.matchedRows = new IntRBTreeSet(); } else { this.matchedRows = null; } }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Integer.valueOf(maxBatchSize).hashCode(); <START> return result; <END> }</code><technical_language>this int result = super.hashCode(); result = 31*result + maxBatchSize;</technical_language>

Target:
public int hashCode() { return 31 * super.hashCode() + maxBatchSize; }
Source:
<code>private void generateRequires(StringBuilder buffer) { for (Map.Entry<String, String> entry : model.getDependencies() .entrySet()) { buffer.append("BuildRequires: mvn(" + entry.getKey() + ":" + entry.getValue() + ")\n"); } buffer.append("BuildRequires: maven-local\n"); <START> for (Map.Entry<String, String> entry : model.getDependencies() <END> .entrySet()) { buffer.append("Requires: mvn(" + entry.getKey() + ":" + entry.getValue() + ")\n"); } }</code><technical_language>is need generate mvn(groupId:artifactId) requires. RPM depgenerator handles itself</technical_language>

Target:
private void generateRequires(StringBuilder buffer) { buffer.append("BuildRequires: maven-local\n"); }
Source:
<code>public List<DataPoint> getValues() { return _values; <START> } <END></code><technical_language>ImmutableList</technical_language>

Target:
public ImmutableList<DataPoint> getValues() { return _values; }
Source:
<code>public void readFields(DataInput dataInput) throws IOException { long numObjects = dataInput.readLong(); <START> totalBytes = dataInput.readLong(); <END> fileMetaDataList = new ArrayList<>(); for (long i = 0; i < numObjects; i++) { AbstractFileMetadata metadata = readFileMetaData(dataInput); fileMetaDataList.add(metadata); totalBytes += metadata.getFileSize(); } }</code><technical_language>move this reading number of files write() is changed</technical_language>

Target:
public void readFields(DataInput dataInput) throws IOException { totalBytes = dataInput.readLong(); long numObjects = dataInput.readLong(); fileMetaDataList = new ArrayList<>(); for (long i = 0; i < numObjects; i++) { AbstractFileMetadata metadata = readFileMetaData(dataInput); fileMetaDataList.add(metadata); } }
Source:
<code>protected Set<String> getGroupsForUser(IPerson person) { final IGroupMember member = GroupService.getGroupMember(person.getEntityIdentifier()); final Set<String> groupKeys = new LinkedHashSet<String>(); for (final Iterator<IEntityGroup> groupItr = member.getAncestorGroups().iterator(); groupItr.hasNext();) { final IGroupMember group = groupItr.next(); <START> final String groupKey = group.getKey(); <END> if (IncludeExcludeUtils.included(groupKey, this.groupIncludes, this.groupExcludes)) { groupKeys.add(groupKey); } } return groupKeys; }</code><technical_language>Another 'for (each)' opportunity thanks refactor of getAncestorGroups()</technical_language>

Target:
protected Set<String> getGroupsForUser(IPerson person) { final IGroupMember member = GroupService.getGroupMember(person.getEntityIdentifier()); final Set<String> groupKeys = new LinkedHashSet<>(); for (IGroupMember group : member.getAncestorGroups()) { final String groupKey = group.getKey(); if (IncludeExcludeUtils.included(groupKey, this.groupIncludes, this.groupExcludes)) { groupKeys.add(groupKey); } } return groupKeys; }
Source:
<code>private void configureSaxonExtensions(net.sf.saxon.TransformerFactoryImpl tfi) { <START> net.sf.saxon.Configuration conf = tfi.getConfiguration(); <END> for (ExtensionFunctionDefinition def : ServiceLoader.load(ExtensionFunctionDefinition.class)) { try { conf.registerExtensionFunction(def.getClass().newInstance()); } catch (InstantiationException e) { throw new RuntimeException("Failed to register " + def.getFunctionQName().getDisplayName() + ". Cannot create instance of " + def.getClass().getName() + ": " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }</code><technical_language>final variable declarations</technical_language>

Target:
private void configureSaxonExtensions(net.sf.saxon.TransformerFactoryImpl tfi) { final net.sf.saxon.Configuration conf = tfi.getConfiguration(); for (ExtensionFunctionDefinition def : ServiceLoader.load(ExtensionFunctionDefinition.class)) { try { conf.registerExtensionFunction(def.getClass().newInstance()); } catch (InstantiationException e) { throw new RuntimeException("Failed to register " + def.getFunctionQName().getDisplayName() + ". Cannot create instance of " + def.getClass().getName() + ": " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
Source:
<code>public void toTop() { <START> recordA.recordIndex = -1; <END> }</code><technical_language>minor: toTop() record.reset() implement logic, topTop() call recordA.reset(). record.reset() renamed record.toTop()</technical_language>

Target:
public void toTop() { recordA.reset(); }
Source:
<code>private boolean next0() { do { if (readNextFileFromDisk) { foundMetadataFile = false; final long pname = ff.findName(findFileStruct); if (hasNextFile) { nativeLPSZ.of(pname); if ( ff.findType(findFileStruct) == Files.DT_DIR && !Chars.equals(nativeLPSZ, '.') && !Chars.equals(nativeLPSZ, "..") ) { path.trimTo(plimit); path.concat(pname); if (ff.exists(path.concat(TableUtils.META_FILE_NAME).$())) { foundMetadataFile = true; metaMem.of(ff, path, ff.getPageSize(), ff.length(path)); columnCount = metaMem.getInt(TableUtils.META_OFFSET_COUNT); tableId = metaMem.getInt(TableUtils.META_OFFSET_TABLE_ID); } } hasNextFile = ff.findNext(findFileStruct) > 0; } } if (foundMetadataFile) { long offset = TableUtils.getColumnNameOffset(columnCount); for (int i = 0; i < columnCount; i++) { CharSequence name = metaMem.getStr(offset); if (columnIndex == i) { diskReadingRecord.name = name; diskReadingRecord.columnNumber = (short) (i + 1); diskReadingRecord.tableId = tableId; columnIndex++; if (columnIndex == columnCount) { readNextFileFromDisk = true; columnIndex = 0; } else { readNextFileFromDisk = false; } return true; } offset += ReadOnlyMemory.getStorageLength(name); } } } while (hasNextFile); <START> ff.findClose(findFileStruct); <END> findFileStruct = 0; hasNextFile = true; foundMetadataFile = false; return false; }</code><technical_language>cursor is fully scrolled file descriptor leak</technical_language>

Target:
private boolean next0() { do { if (readNextFileFromDisk) { foundMetadataFile = false; final long pname = ff.findName(findFileStruct); if (hasNextFile) { nativeLPSZ.of(pname); if ( ff.findType(findFileStruct) == Files.DT_DIR && Chars.notDots(nativeLPSZ) ) { path.trimTo(plimit); path.concat(pname); if (ff.exists(path.concat(TableUtils.META_FILE_NAME).$())) { foundMetadataFile = true; metaMem.of(ff, path, ff.getPageSize(), ff.length(path)); columnCount = metaMem.getInt(TableUtils.META_OFFSET_COUNT); tableId = metaMem.getInt(TableUtils.META_OFFSET_TABLE_ID); } } hasNextFile = ff.findNext(findFileStruct) > 0; } } if (foundMetadataFile) { long offset = TableUtils.getColumnNameOffset(columnCount); for (int i = 0; i < columnCount; i++) { CharSequence name = metaMem.getStr(offset); if (columnIndex == i) { diskReadingRecord.name = name; diskReadingRecord.columnNumber = (short) (i + 1); diskReadingRecord.tableId = tableId; columnIndex++; if (columnIndex == columnCount) { readNextFileFromDisk = true; columnIndex = 0; } else { readNextFileFromDisk = false; } return true; } offset += ReadOnlyMemory.getStorageLength(name); } } } while (hasNextFile); ff.findClose(findFileStruct); findFileStruct = 0; hasNextFile = true; foundMetadataFile = false; return false; }
Source:
<code>public void getPrograms_shouldTestGetPrograms() { <START> List<Program> programs = pws.getPrograms("MAL"); <END> List<Program> programs1 = pws.getPrograms("PR"); assertEquals(programs.size(), 1); assertEquals(programs1.size(), 3); }</code><technical_language>suggestion List<Program> malPrograms = pws.getPrograms("MAL");</technical_language>

Target:
public void getPrograms_shouldTestGetPrograms() { List<Program> malPrograms = pws.getPrograms("MAL"); List<Program> prPrograms = pws.getPrograms("PR"); assertEquals(malPrograms.size(), 1); assertEquals(prPrograms.size(), 3); }
Source:
<code>public void factoryWithDirectUrlWithRootFolder() throws Exception { String expectedMessInTheEventsPanel = "Project " + EXPECTED_PROJECT + " imported"; List<String> expectedItemsAfterClonning = Arrays.asList( "CHANGELOG.md", "Dockerfile", "LICENSE", "README.md", "favicon.ico", "index.html", "karma-test-shim.js", "karma.conf.js", "package.json", "protractor.config.js", "styles.css", "systemjs.config.js", "tsconfig.json", "tslint.json", "typings.json", "wallaby.js"); try { testFactoryWithRootFolder.authenticateAndOpen(); } catch (TimeoutException ex) { <START> fail("Known issue <LINK_0>"); <END> } projectExplorer.waitProjectExplorer(); projectExplorer.waitItem(EXPECTED_PROJECT); notificationsPopupPanel.waitProgressPopupPanelClose(); events.clickEventLogBtn(); try { events.waitExpectedMessage(expectedMessInTheEventsPanel); } catch (TimeoutException ex) { fail("Known issue <LINK_1>"); } projectExplorer.openItemByPath(EXPECTED_PROJECT); String currentWsId = workspaceServiceClient .getByName(seleniumWebDriver.getWorkspaceNameFromBrowserUrl(), testUser.getName()) .getId(); List<String> visibleItems = projectExplorer.getNamesOfAllOpenItems(); assertTrue(visibleItems.containsAll(expectedItemsAfterClonning)); String currentTypeOfProject = projectServiceClient.getFirstProject(currentWsId).getType(); assertTrue(currentTypeOfProject.equals("blank")); }</code><technical_language>pass **ex** variable fail() method additional info catching exception</technical_language>

Target:
public void factoryWithDirectUrlWithRootFolder() throws Exception { String expectedMessInTheEventsPanel = "Project " + EXPECTED_PROJECT + " imported"; List<String> expectedItemsAfterClonning = Arrays.asList( "CHANGELOG.md", "Dockerfile", "LICENSE", "README.md", "favicon.ico", "index.html", "karma-test-shim.js", "karma.conf.js", "package.json", "protractor.config.js", "styles.css", "systemjs.config.js", "tsconfig.json", "tslint.json", "typings.json", "wallaby.js"); try { testFactoryWithRootFolder.authenticateAndOpen(); } catch (TimeoutException ex) { fail("Known issue <LINK_0>", ex); } projectExplorer.waitProjectExplorer(); projectExplorer.waitItem(EXPECTED_PROJECT); notificationsPopupPanel.waitProgressPopupPanelClose(); events.clickEventLogBtn(); try { events.waitExpectedMessage(expectedMessInTheEventsPanel); } catch (TimeoutException ex) { fail("Known issue <LINK_1>"); } projectExplorer.openItemByPath(EXPECTED_PROJECT); String currentWsId = workspaceServiceClient .getByName(seleniumWebDriver.getWorkspaceNameFromBrowserUrl(), testUser.getName()) .getId(); List<String> visibleItems = projectExplorer.getNamesOfAllOpenItems(); assertTrue(visibleItems.containsAll(expectedItemsAfterClonning)); String currentTypeOfProject = projectServiceClient.getFirstProject(currentWsId).getType(); assertTrue(currentTypeOfProject.equals("blank")); }
Source:
<code>void flush() { Producer<K, V> producer; try { _producerLock.lock(); producer = _kafkaProducer; } finally { _producerLock.unlock(); } if (producer != null) { try { producer.flush(_producerFlushTimeoutMs, TimeUnit.MILLISECONDS); <START> } catch (InterruptException | TimeoutException | IllegalStateException e) { <END> try { _producerLock.lock(); if (producer == _kafkaProducer) { _log.warn("Kafka producer flush may be interrupted/timed out, closing producer {}.", producer); shutdownProducer(); } else { _log.warn("Kafka producer flush may be interrupted/timed out, producer already closed.", producer); } throw e; } finally { _producerLock.unlock(); } } } }</code><technical_language>is stale Sonam is catching is IllegalStateException is list</technical_language>

Target:
void flush() { Producer<K, V> producer; try { _producerLock.lock(); producer = _kafkaProducer; } finally { _producerLock.unlock(); } if (producer != null) { try { producer.flush(_producerFlushTimeoutMs, TimeUnit.MILLISECONDS); } catch (Exception e) { try { _producerLock.lock(); if (producer == _kafkaProducer) { _log.warn("Kafka producer flush may be interrupted/timed out, closing producer {}.", producer); shutdownProducer(); } else { _log.warn("Kafka producer flush may be interrupted/timed out, producer already closed.", producer); } throw e; } finally { _producerLock.unlock(); } } } }
Source:
<code>public List<JdbcColumnHandle> getColumns(JdbcTableHandle tableHandle) { try (Connection connection = driver.connect(connectionUrl, connectionProperties)) { try (ResultSet resultSet = getColumns(tableHandle, connection.getMetaData())) { List<JdbcColumnHandle> columns = new ArrayList<>(); boolean found = false; while (resultSet.next()) { found = true; Type columnType = toPrestoType( resultSet.getInt("DATA_TYPE"), resultSet.getInt("COLUMN_SIZE"), resultSet.getInt("DECIMAL_DIGITS")); if (columnType != null) { String columnName = resultSet.getString("COLUMN_NAME"); columns.add(new JdbcColumnHandle(connectorId, columnName, columnType)); } } if (!found) { throw new TableNotFoundException(tableHandle.getSchemaTableName()); } <START> return ImmutableList.copyOf(columns); <END> } } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }</code><technical_language>move this check JdbcMetadata.getTableMetadata(), return invalid metadata object. I trigger check in StatementAnalyzer provide correct error message</technical_language>

Target:
public List<JdbcColumnHandle> getColumns(JdbcTableHandle tableHandle) { try (Connection connection = driver.connect(connectionUrl, connectionProperties)) { try (ResultSet resultSet = getColumns(tableHandle, connection.getMetaData())) { List<JdbcColumnHandle> columns = new ArrayList<>(); while (resultSet.next()) { Type columnType = toPrestoType( resultSet.getInt("DATA_TYPE"), resultSet.getInt("COLUMN_SIZE"), resultSet.getInt("DECIMAL_DIGITS")); if (columnType != null) { String columnName = resultSet.getString("COLUMN_NAME"); columns.add(new JdbcColumnHandle(connectorId, columnName, columnType)); } } if (columns.isEmpty()) { throw new TableNotFoundException(tableHandle.getSchemaTableName()); } return ImmutableList.copyOf(columns); } } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }
Source:
<code><START> public HttpMessage buildMessage(String body) throws HttpMalformedHeaderException { <END> HttpMessage msg = new HttpMessage(); msg.setRequestHeader("GET <LINK_0> HTTP/1.1"); msg.setResponseBody(body); return msg; }</code><technical_language>private static</technical_language>

Target:
private static HttpMessage buildMessage(String body) throws HttpMalformedHeaderException { HttpMessage msg = new HttpMessage(); msg.setRequestHeader("GET <LINK_0> HTTP/1.1"); msg.setResponseBody(body); return msg; }
Source:
<code>public void logsMessage() throws IOException { <START> new TkSlf4j(new TkEmpty()).act(new RqFake()); <END> }</code><technical_language>@rui-castro this change</technical_language>

Target:
public void logsMessage() throws IOException { new TkSlf4j(new TkText("test")).act(new RqFake()); }
Source:
<code>static ExportMode getExportFeatureMode(FeaturesType features) throws SetupException { if (features == null) { return ExportMode.BASIC; } for (FeatureType feature : features.getFeature()) { if (feature.getName().equalsIgnoreCase(EXPORT_FEATURE)) { String mode = feature.getOption(); for (ExportMode modeEnum : ExportMode.values()) { <START> if (mode.equalsIgnoreCase(modeEnum.toString())) { <END> if (!VoltDB.instance().getConfig().m_isEnterprise && modeEnum == ExportMode.ADVANCED) { throw new SetupException("Cannot use ADVANCED export mode in community edition"); } return modeEnum; } } throw new SetupException("Unknown export feature mode: " + mode); } } return ExportMode.BASIC; }</code><technical_language>is name() instead of toString() get name of enum</technical_language>

Target:
static ExportMode getExportFeatureMode(FeaturesType features) throws SetupException { if (features == null) { return ExportMode.BASIC; } for (FeatureType feature : features.getFeature()) { if (feature.getName().equalsIgnoreCase(EXPORT_FEATURE)) { String mode = feature.getOption(); for (ExportMode modeEnum : ExportMode.values()) { if (mode.equalsIgnoreCase(modeEnum.name())) { if (!VoltDB.instance().getConfig().m_isEnterprise && modeEnum == ExportMode.ADVANCED) { throw new SetupException("Cannot use ADVANCED export mode in community edition"); } return modeEnum; } } throw new SetupException("Unknown export feature mode: " + mode); } } return ExportMode.BASIC; }
Source:
<code>public long scanAndAggregate( TopNQuery query, Selector selector, Cursor cursor, Aggregator[][] rowSelector ) { <START> initAggregateStore(); <END> long processedRows = 0; while (!cursor.isDone()) { if (hasNulls && selector.isNull()) { if (nullValueAggregates == null) { nullValueAggregates = BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()); } for (Aggregator aggregator : nullValueAggregates) { aggregator.aggregate(); } } else { Aggregator[] valueAggregates = getValueAggregators(query, selector, cursor); for (Aggregator aggregator : valueAggregates) { aggregator.aggregate(); } } cursor.advance(); processedRows++; } return processedRows; }</code><technical_language>I initAggregateStore call moved HeapBasedTopNAlgorithm.scanAndAggregate impls call step</technical_language>

Target:
public long scanAndAggregate( TopNQuery query, Selector selector, Cursor cursor, Aggregator[][] rowSelector ) { long processedRows = 0; while (!cursor.isDone()) { if (hasNulls && selector.isNull()) { if (nullValueAggregates == null) { nullValueAggregates = BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()); } for (Aggregator aggregator : nullValueAggregates) { aggregator.aggregate(); } } else { Aggregator[] valueAggregates = getValueAggregators(query, selector, cursor); for (Aggregator aggregator : valueAggregates) { aggregator.aggregate(); } } cursor.advance(); processedRows++; } return processedRows; }
Source:
<code>public String[] getCallStackPath() { <START> return new String[] { CallStackStateProvider.CALL_STACK }; <END> }</code><technical_language>arrays defined statically in this class, create a new array time this method is called</technical_language>

Target:
public String[] getCallStackPath() { return CALL_STACK_PATH; }
Source:
<code>private int randInt() { Random rand = new Random(); int min = 1; int max = 200; int res = rand.nextInt((max - min) + 1) + min; <START> System.out.println(res); <END> return res; }</code><technical_language>Please out prints for debugging. If need display this information, Logger a String clear this number means</technical_language>

Target:
private int randInt() { Random rand = new Random(); int min = 1; int max = 200; int res = rand.nextInt((max - min) + 1) + min; return res; }
Source:
<code>public void changeMessageCommitFormatSimple() throws Exception { Change c = newChange(); ChangeUpdate update = newUpdate(c, changeOwner); update.setChangeMessage("Just a little code change.\nHow about a new line"); update.commit(); assertEquals("refs/changes/01/1/meta", update.getRefName()); RevWalk walk = new RevWalk(repo); try { RevCommit commit = walk.parseCommit(update.getRevision()); walk.parseBody(commit); assertEquals("Update patch set 1\n" + "\n" <START> + "Just a little code change.\nHow about a new line\n" <END> + "\n" + "Patch-set: 1\n", commit.getFullMessage()); } finally { walk.release(); } }</code><technical_language>Nit: put line of mutli-line string line end \n, more closely resembles output if print it</technical_language>

Target:
public void changeMessageCommitFormatSimple() throws Exception { Change c = newChange(); ChangeUpdate update = newUpdate(c, changeOwner); update.setChangeMessage("Just a little code change.\n" + "How about a new line"); update.commit(); assertEquals("refs/changes/01/1/meta", update.getRefName()); RevWalk walk = new RevWalk(repo); try { RevCommit commit = walk.parseCommit(update.getRevision()); walk.parseBody(commit); assertEquals("Update patch set 1\n" + "\n" + "Just a little code change.\n" + "How about a new line\n" + "\n" + "Patch-set: 1\n", commit.getFullMessage()); } finally { walk.release(); } }
Source:
<code>public void testSshWithoutKnownHostsWithProviderAsk() throws Exception { File copiedHosts = new File(knownHosts.getParentFile(), "copiedKnownHosts"); assertTrue("Failed to rename known_hosts", knownHosts.renameTo(copiedHosts)); TestCredentialsProvider provider = new TestCredentialsProvider(); cloneWith("ssh://localhost/doesntmatter", defaultCloneDir, provider, "Host localhost", "HostName localhost", "Port " + testPort, "User " + TEST_USER, "IdentityFile " + privateKey1.getAbsolutePath()); Map<URIish, List<CredentialItem>> messages = provider.getLog(); assertFalse("Expected user <START> iteraction", <END> messages.isEmpty()); if (getSessionFactory() instanceof JschConfigSessionFactory) { assertEquals("Expected to be asked about the key", 1, messages.size()); return; } assertEquals( "Expected to be asked about the key, and the file creation", 2, messages.size()); assertTrue("~/.ssh/known_hosts should exist now", knownHosts.exists()); File clonedAgain = new File(getTemporaryDirectory(), "cloned2"); cloneWith("ssh://localhost/doesntmatter", clonedAgain, provider, "Host localhost", "HostName localhost", "Port " + testPort, "User " + TEST_USER, "IdentityFile " + privateKey1.getAbsolutePath()); }</code><technical_language>interaction</technical_language>

Target:
public void testSshWithoutKnownHostsWithProviderAsk() throws Exception { File copiedHosts = new File(knownHosts.getParentFile(), "copiedKnownHosts"); assertTrue("Failed to rename known_hosts", knownHosts.renameTo(copiedHosts)); TestCredentialsProvider provider = new TestCredentialsProvider(); cloneWith("ssh://localhost/doesntmatter", defaultCloneDir, provider, "Host localhost", "HostName localhost", "Port " + testPort, "User " + TEST_USER, "IdentityFile " + privateKey1.getAbsolutePath()); Map<URIish, List<CredentialItem>> messages = provider.getLog(); assertFalse("Expected user interaction", messages.isEmpty()); if (getSessionFactory() instanceof JschConfigSessionFactory) { assertEquals("Expected to be asked about the key", 1, messages.size()); return; } assertEquals( "Expected to be asked about the key, and the file creation", 2, messages.size()); assertTrue("~/.ssh/known_hosts should exist now", knownHosts.exists()); File clonedAgain = new File(getTemporaryDirectory(), "cloned2"); cloneWith("ssh://localhost/doesntmatter", clonedAgain, provider, "Host localhost", "HostName localhost", "Port " + testPort, "User " + TEST_USER, "IdentityFile " + privateKey1.getAbsolutePath()); }