auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGetCompatibleModelFields() { List<String> compatibleModelFields = formEditorHelper.getCompatibleModelFields(nameField); assertEquals(2, compatibleModelFields.size()); assertTrue(compatibleModelFields.contains(nameField.getId())); <START> assertTrue(compatibleModelFields.contains(lastNameField.getId())); <END> compatibleModelFields = formEditorHelper.getCompatibleModelFields(ageField); assertEquals(1, compatibleModelFields.size()); assertTrue(compatibleModelFields.contains(ageField.getId())); assertFalse(compatibleModelFields.contains(weightField.getId())); compatibleModelFields = formEditorHelper.getCompatibleModelFields(weightField); assertEquals(1, compatibleModelFields.size()); assertTrue(compatibleModelFields.contains(weightField.getId())); assertFalse(compatibleModelFields.contains(ageField.getId())); IntegerSliderDefinition slider = new IntegerSliderDefinition(); slider.setId("slider"); slider.setName("slider"); slider.setLabel("slider"); compatibleModelFields = formEditorHelper.getCompatibleModelFields(slider); assertEquals(2, compatibleModelFields.size()); assertTrue(compatibleModelFields.contains(weightField.getId())); assertTrue(compatibleModelFields.contains(ageField.getId())); }</code><technical_language>FYI Assertions class of AssertJ some helpful methods here. Specifically, this code this: Assertions.assertThat(compatibleModelFields).containsExactly(nameField.getId(), lastNameField.getId())); is a bit more readable, in case of a failure, assertion message more readable. (Instead of "true != false".)</technical_language>

Target:
public void testGetCompatibleModelFields() { List<String> compatibleModelFields = formEditorHelper.getCompatibleModelFields(nameField); assertEquals(2, compatibleModelFields.size()); Assertions.assertThat(compatibleModelFields).containsExactly(lastNameField.getId(), nameField.getId()); compatibleModelFields = formEditorHelper.getCompatibleModelFields(ageField); assertEquals(1, compatibleModelFields.size()); Assertions.assertThat(compatibleModelFields).containsOnly(ageField.getId()); compatibleModelFields = formEditorHelper.getCompatibleModelFields(weightField); assertEquals(1, compatibleModelFields.size()); Assertions.assertThat(compatibleModelFields).containsOnly(weightField.getId()); IntegerSliderDefinition slider = new IntegerSliderDefinition(); slider.setId("slider"); slider.setName("slider"); slider.setLabel("slider"); compatibleModelFields = formEditorHelper.getCompatibleModelFields(slider); assertEquals(2, compatibleModelFields.size()); Assertions.assertThat(compatibleModelFields).containsExactly(ageField.getId(), weightField.getId()); }
Source:
<code>protected void removeMessageReference(ConsumerHolder<? extends Consumer> holder, MessageReference ref) { <START> if (!isNonDestructive()) { <END> holder.iter.remove(); refRemoved(ref); } }</code><technical_language>change here? internal class, hot path, field access</technical_language>

Target:
protected void removeMessageReference(ConsumerHolder<? extends Consumer> holder, MessageReference ref) { if (!nonDestructive) { holder.iter.remove(); refRemoved(ref); } }
Source:
<code><START> public List<String> listContentUris(ContentListingCriteria criteria) { <END> List<Publisher> publishers = remainingPublishers(criteria); if(publishers.isEmpty()) { return Collections.emptyList(); } Iterator<Content> contentIterator = iteratorsFor(publishers, criteria, true); Iterator<String> uriIterator = Iterators.transform(contentIterator, Identified::getCanonicalUri ); List<String> allContent = new ArrayList<>(); uriIterator.forEachRemaining(allContent::add); return allContent; }</code><technical_language>this return Iterator<String> a List is a bit specific forces extra memory if required</technical_language>

Target:
public Iterator<String> listContentUris(ContentListingCriteria criteria) { List<Publisher> publishers = remainingPublishers(criteria); if(publishers.isEmpty()) { return Iterators.emptyIterator(); } Iterator<Content> contentIterator = iteratorsFor(publishers, criteria, true); Iterator<String> uriIterator = Iterators.transform(contentIterator, Identified::getCanonicalUri ); return uriIterator; }
Source:
<code>public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) { FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate(); SchemaCompatibilityValidator.validate(filterPredicate, schema); List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>(); for (BlockMetaData block : blocks) { boolean drop = false; if(levels.contains(FilterLevel.STATISTICS)) { drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns()); } if(!drop && levels.contains(FilterLevel.DICTIONARY)) { drop = DictionaryFilter.canDrop(filterPredicate, block.getColumns(), reader.getDictionaryReader(block)); } if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) { drop = BloomFilterImpl.canDrop(filterPredicate, block.getColumns(), reader.getBloomFilterDataReader(block)); <START> if (drop) logger.info("Block drop by Bloom filter"); <END> } if(!drop) { filteredBlocks.add(block); } } return filteredBlocks; }</code><technical_language>I think, this logging is useful. Other filters logs dropped row groups. If a more useful log, a good idea log index of row group filter type triggered drop. Also, please curly braces for blocks format accordingly</technical_language>

Target:
public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) { FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate(); SchemaCompatibilityValidator.validate(filterPredicate, schema); List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>(); for (BlockMetaData block : blocks) { boolean drop = false; if(levels.contains(FilterLevel.STATISTICS)) { drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns()); } if(!drop && levels.contains(FilterLevel.DICTIONARY)) { drop = DictionaryFilter.canDrop(filterPredicate, block.getColumns(), reader.getDictionaryReader(block)); } if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) { drop = BloomFilterImpl.canDrop(filterPredicate, block.getColumns(), reader.getBloomFilterDataReader(block)); } if(!drop) { filteredBlocks.add(block); } } return filteredBlocks; }
Source:
<code>public void run() { final ExecutorService executor = executorServiceInjectedValue.getOptionalValue(); <START> if (executor != null) { <END> executor.submit(this::persistTimer); } }</code><technical_language>This null, this is optional dependency. Functionally difference confusing reading code</technical_language>

Target:
public void run() { executorServiceInjectedValue.getValue().submit(this::persistTimer); }
Source:
<code>public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 1, "Exactly 1 argument is required for transform function: %s", getName()); TransformFunction transformFunction = arguments.get(0); Preconditions.checkArgument(transformFunction.getResultMetadata().isSingleValue(), <START> "Argument must be single-valued for transform function: %s", getName()); <END> _transformFunction = transformFunction; }</code><technical_language>check data type, BYTES. for other classes</technical_language>

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 1, "Exactly 1 argument is required for transform function: %s", getName()); TransformFunction transformFunction = arguments.get(0); Preconditions.checkArgument(transformFunction.getResultMetadata().isSingleValue(), "Argument must be single-valued for transform function: %s", getName()); Preconditions.checkArgument(transformFunction.getResultMetadata().getDataType() == FieldSpec.DataType.BYTES, "The argument must be of bytes type"); _transformFunction = transformFunction; }
Source:
<code>public void readManyAsync_whenHitsStale_shouldNotBeBlocked() throws Exception { ICompletableFuture<ReadResultSet<String>> f = clientRingbuffer.readManyAsync(0, 1, 10, null); serverRingbuffer.addAllAsync(asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), OVERWRITE); <START> f.get(); <END> }</code><technical_language>f.get() throw ExecutionException wrapping other kind of exception. match root ExpectedException rule? expected.expect(new RootCauseMatcher(StaleSequenceException.class)); f.get();</technical_language>

Target:
public void readManyAsync_whenHitsStale_shouldNotBeBlocked() throws Exception { ICompletableFuture<ReadResultSet<String>> f = clientRingbuffer.readManyAsync(0, 1, 10, null); serverRingbuffer.addAllAsync(asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), OVERWRITE); expectedException.expect(new RootCauseMatcher(StaleSequenceException.class)); f.get(); }
Source:
<code>public void buildCidMap__onMultipartWithNoParts__shouldReturnEmptyMap() throws Exception { AttachmentInfoExtractor attachmentInfoExtractor = mock(AttachmentInfoExtractor.class); Part multipartPart = mock(Part.class); Multipart multipartBody = mock(Multipart.class); <START> when(multipartPart.getBody()).thenReturn(multipartBody); <END> when(multipartBody.getBodyParts()).thenReturn(Collections.EMPTY_LIST); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart); assertTrue(result.isEmpty()); }</code><technical_language>Part friends simple enough real for testing mocking them. tests more robust changes of implementation details of class test</technical_language>

Target:
public void buildCidMap__onMultipartWithNoParts__shouldReturnEmptyMap() throws Exception { Multipart multipartBody = new MimeMultipart(); Part multipartPart = new MimeBodyPart(multipartBody); Map<String,Uri> result = AttachmentResolver.buildCidToAttachmentUriMap(attachmentInfoExtractor, multipartPart); assertTrue(result.isEmpty()); }
Source:
<code>public static boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) OpenMRS.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); <START> return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); <END> }</code><technical_language>I asked for. checking toggle in addition networkinfo. If toggle is set offline return false. If toggle is set online check network info if connection set toggle offline return false, return true</technical_language>

Target:
public static boolean isNetworkAvailable() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OpenMRS.getInstance()); boolean toggle=prefs.getBoolean("sync", false); if(toggle==true) { ConnectivityManager connectivityManager = (ConnectivityManager) OpenMRS.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); if(isConnected) return true; else { SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("sync", false); editor.commit(); return false; } } else return false; }
Source:
<code>void execute(long taskId, String taskName, Object arg, Set<UUID> nodeIds, byte flags, long timeout) { assert taskName != null; this.taskId = taskId; <START> GridTaskProcessor task = ctx.kernalContext().task(); <END> IgnitePredicate<ClusterNode> nodePredicate = F.isEmpty(nodeIds) ? F.alwaysTrue() : F.nodeForNodeIds(nodeIds); UUID subjId = ctx.securityContext() == null ? null : ctx.securityContext().subject().id(); task.setThreadContextIfNotNull(TC_SUBGRID_PREDICATE, nodePredicate); task.setThreadContextIfNotNull(TC_SUBJ_ID, subjId); task.setThreadContext(TC_TIMEOUT, timeout); task.setThreadContext(TC_NO_FAILOVER, (flags & NO_FAILOVER_FLAG_MASK) != 0); task.setThreadContext(TC_NO_RESULT_CACHE, (flags & NO_RESULT_CACHE_FLAG_MASK) != 0); taskFut = task.execute(taskName, arg); if (taskFut.isDone() && taskFut.error() != null) throw new IgniteClientException(ClientStatus.FAILED, taskFut.error().getMessage()); }</code><technical_language>please explain reason internal API instead of public IgniteCompute</technical_language>

Target:
void execute(long taskId, String taskName, Object arg, Set<UUID> nodeIds, byte flags, long timeout) { assert taskName != null; this.taskId = taskId; GridTaskProcessor task = ctx.kernalContext().task(); IgnitePredicate<ClusterNode> nodePredicate = F.isEmpty(nodeIds) ? F.alwaysTrue() : F.nodeForNodeIds(nodeIds); UUID subjId = ctx.securityContext() == null ? null : ctx.securityContext().subject().id(); task.setThreadContext(TC_SUBGRID_PREDICATE, nodePredicate); task.setThreadContextIfNotNull(TC_SUBJ_ID, subjId); task.setThreadContext(TC_TIMEOUT, timeout); task.setThreadContext(TC_NO_FAILOVER, (flags & NO_FAILOVER_FLAG_MASK) != 0); task.setThreadContext(TC_NO_RESULT_CACHE, (flags & NO_RESULT_CACHE_FLAG_MASK) != 0); taskFut = task.execute(taskName, arg); if (taskFut.isDone() && taskFut.error() != null) throw new IgniteClientException(ClientStatus.FAILED, taskFut.error().getMessage()); }
Source:
<code><START> private String dataObjectToProcessVariableFormat(DataObject dataObject) { <END> StringBuilder builder = new StringBuilder(); builder.append(dataObject.getName().getValue()); builder.append(":"); builder.append(dataObject.getType().getValue().getType()); return builder.toString(); }</code><technical_language>static</technical_language>

Target:
private static String dataObjectToProcessVariableFormat(DataObject dataObject) { return dataObject.getName().getValue() + ":" + dataObject.getType().getValue().getType(); }
Source:
<code>public String create(Project project, User user) { String name = project.getName(); FetchProjectHandler fetchProjectHandler = new FetchProjectHandler(); try { final List<Project> projects = this.dbOperator .query(FetchProjectHandler.SELECT_PROJECT_WITH_NAME_AND_SPACE_ID, fetchProjectHandler, name, project.getSpaceId()); if (!projects.isEmpty()) { throw new ProjectManagerException( "Project with name " + name + " already exists."); } } catch (final SQLException ex) { log.error("Check if project '" + name + "' exists failed with: " + ex); throw new ProjectManagerException("Check if project '" + name + "' exists failed"); } final SQLTransaction<Long> insertAndGetProjectId = transOperator -> { <START> String currentTime = DateTime.now().toLocalDateTime().toString(); <END> transOperator.update(INSERT_PROJECT, project.getName(), project.getDescription(), project.getSpaceId(), user.getUserId(), currentTime, user.getUserId(), currentTime, 1, true, 2, null); transOperator.getConnection().commit(); return transOperator.getLastInsertId(); }; String projectId = ""; try { projectId = dbOperator.transaction(insertAndGetProjectId).toString(); if (projectId.isEmpty()) { throw new ProjectManagerException("Insert project for '" + name + "' failed."); } projectAdminDaoImpl.addAdmins(projectId, project.getAdmins()); } catch (SQLException ex) { log.error(INSERT_PROJECT + " failed with exception:", ex); throw new ProjectManagerException("Insert project for '" + name + "' failed.", ex); } return projectId; }</code><technical_language>POC store dates times in local time</technical_language>

Target:
public String create(Project project, User user) { String name = project.getName(); FetchProjectHandler fetchProjectHandler = new FetchProjectHandler(); try { final List<Project> projects = this.dbOperator .query(FetchProjectHandler.SELECT_PROJECT_WITH_NAME_AND_SPACE_ID, fetchProjectHandler, name, project.getSpaceId()); if (!projects.isEmpty()) { throw new ProjectManagerException( "Project with name " + name + " already exists."); } } catch (final SQLException ex) { log.error("Check if project '" + name + "' exists failed with: " + ex); throw new ProjectManagerException("Check if project '" + name + "' exists failed"); } final SQLTransaction<Long> insertAndGetProjectId = transOperator -> { long timestamp = System.currentTimeMillis(); transOperator.update(INSERT_PROJECT, project.getName(), 1, timestamp, timestamp, 1, user.getUserId(), project.getDescription(), 2, null, project.getSpaceId(), user.getUserId()); transOperator.getConnection().commit(); return transOperator.getLastInsertId(); }; String projectId = ""; try { projectId = dbOperator.transaction(insertAndGetProjectId).toString(); if (projectId.isEmpty()) { throw new ProjectManagerException("Insert project for '" + name + "' failed."); } projectAdminDaoImpl.addAdmins(projectId, project.getAdmins()); } catch (SQLException ex) { log.error(INSERT_PROJECT + " failed with exception:", ex); throw new ProjectManagerException("Insert project for '" + name + "' failed.", ex); } return projectId; }
Source:
<code>public abstract boolean exists() throws IOException; public abstract @Nonnull VirtualFile[] list() throws IOException; @Restricted(NoExternalUse.class) <START> public boolean supportQuickRecursiveListing() { <END> return false; }</code><technical_language>NIT: support**s**QuickRecursiveListing</technical_language>

Target:
public abstract boolean exists() throws IOException; public abstract @Nonnull VirtualFile[] list() throws IOException; @Restricted(NoExternalUse.class) public boolean supportsQuickRecursiveListing() { return false; }
Source:
<code>public void testContent() throws Exception { ______TS("Typical case: large session with no sections"); resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Session with no sections", true, "question"); AssertHelper.assertContains(Const.StatusMessages.FEEDBACK_RESULTS_QUESTIONVIEWWARNING, <START> resultsPage.getStatus()); <END> ______TS("Typical case: standard session results"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtml("/instructorFeedbackResultsPageOpen.html"); ______TS("Typical case: standard session results: helper view"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper1", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperOne.html"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper2", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperTwo.html"); ______TS("Typical case: empty session"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Empty Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageEmpty.html"); }</code><technical_language>Is status message subjected variation? If status message is exact, resultsPage.verifyStatus(...) instead. If is, align [r]esultsPage.getStatus() [C]onst.StatusMessage</technical_language>

Target:
public void testContent() throws Exception { ______TS("Typical case: large session with no sections"); resultsPage = loginToInstructorFeedbackResultsPageWithViewType("CFResultsUiT.instr", "Session with no sections", true, "question"); resultsPage.verifyStatus(Const.StatusMessages.FEEDBACK_RESULTS_QUESTIONVIEWWARNING); ______TS("Typical case: standard session results"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtml("/instructorFeedbackResultsPageOpen.html"); ______TS("Typical case: standard session results: helper view"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper1", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperOne.html"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.helper2", "Open Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageOpenViewForHelperTwo.html"); ______TS("Typical case: empty session"); resultsPage = loginToInstructorFeedbackResultsPage("CFResultsUiT.instr", "Empty Session"); resultsPage.waitForPanelsToExpand(); resultsPage.verifyHtmlMainContent("/instructorFeedbackResultsPageEmpty.html"); }
Source:
<code>private boolean handleDefinedMappings() { boolean errorOccurred = false; Set<String> handledTargets = new HashSet<>(); if ( method.getMappingOptions().hasNestedTargetReferences() ) { errorOccurred = handleDefinedNestedTargetMapping( handledTargets ); } for ( Map.Entry<String, List<Mapping>> entry : methodMappings.entrySet() ) { <START> String target = null; <END> for ( Mapping mapping : entry.getValue() ) { TargetReference targetReference = mapping.getTargetReference(); if ( targetReference.isValid() ) { target = first( targetReference.getPropertyEntries() ).getFullName(); if ( !handledTargets.contains( target ) ) { if ( handleDefinedMapping( mapping, handledTargets ) ) { errorOccurred = true; } } if ( mapping.getSourceReference() != null && mapping.getSourceReference().isValid() ) { List<PropertyEntry> sourceEntries = mapping.getSourceReference().getPropertyEntries(); if ( !sourceEntries.isEmpty() ) { String source = first( sourceEntries ).getFullName(); unprocessedSourceProperties.remove( source ); } } } else { errorOccurred = true; } } } for ( String handledTarget : handledTargets ) { unprocessedTargetProperties.remove( handledTarget ); unprocessedDefinedTargets.remove( handledTarget ); } return errorOccurred; }</code><technical_language>reasons define target in this scope is used? (line 400ff)</technical_language>

Target:
private boolean handleDefinedMappings() { boolean errorOccurred = false; Set<String> handledTargets = new HashSet<>(); if ( method.getMappingOptions().hasNestedTargetReferences() ) { errorOccurred = handleDefinedNestedTargetMapping( handledTargets ); } for ( Map.Entry<String, List<Mapping>> entry : methodMappings.entrySet() ) { for ( Mapping mapping : entry.getValue() ) { TargetReference targetReference = mapping.getTargetReference(); if ( targetReference.isValid() ) { String target = first( targetReference.getPropertyEntries() ).getFullName(); if ( !handledTargets.contains( target ) ) { if ( handleDefinedMapping( mapping, handledTargets ) ) { errorOccurred = true; } } if ( mapping.getSourceReference() != null && mapping.getSourceReference().isValid() ) { List<PropertyEntry> sourceEntries = mapping.getSourceReference().getPropertyEntries(); if ( !sourceEntries.isEmpty() ) { String source = first( sourceEntries ).getFullName(); unprocessedSourceProperties.remove( source ); } } } else { errorOccurred = true; } } } for ( String handledTarget : handledTargets ) { unprocessedTargetProperties.remove( handledTarget ); unprocessedDefinedTargets.remove( handledTarget ); } return errorOccurred; }
Source:
<code>public void addPages() { <START> <END> addPage(selectRepoPage); addPage(importWithDirectoriesPage); addPage(myProjectsImportPage); addPage(myCreateGeneralProjectPage); addPage(mySharePage); }</code><technical_language>style: unnecessary blank line</technical_language>

Target:
public void addPages() { addPage(selectRepoPage); addPage(importWithDirectoriesPage); addPage(projectsImportPage); addPage(createGeneralProjectPage); addPage(shareProjectsPage); }
Source:
<code>public void testCreateMtlsKeyStoreNoCert() throws Exception { final InputStream certMissing = getClass() .getClassLoader() .getResourceAsStream("com/google/api/client/util/privateKey.pem"); <START> IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { SecurityUtils.createMtlsKeyStore(certMissing); } }); <END> assertThat(exception) .hasMessageThat() .isEqualTo("certificate is missing from certAndKey string"); }</code><technical_language>a try/catch block for asserting exceptions thrown: java boolean thrown = false; try { SecurityUtils.createMtlsKeyStore(certMissing); fail("should thrown"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("some message")); thrown = true; } assertTrue(thrown, "should caught IllegalArgumentException");</technical_language>

Target:
public void testCreateMtlsKeyStoreNoCert() throws Exception { final InputStream certMissing = getClass() .getClassLoader() .getResourceAsStream("com/google/api/client/util/privateKey.pem"); boolean thrown = false; try { SecurityUtils.createMtlsKeyStore(certMissing); fail("should have thrown"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("certificate is missing from certAndKey string")); thrown = true; } assertTrue("should have caught an IllegalArgumentException", thrown); }
Source:
<code>private void checkConnectivity() throws IOException { final ObjectWalk ow = new ObjectWalk(db); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() != Result.NOT_ATTEMPTED) continue; if (cmd.getType() == ReceiveCommand.Type.DELETE) continue; ow.markStart(ow.parseAny(cmd.getNewId())); } for (final Ref ref : refs.values()) ow.markUninteresting(ow.parseAny(ref.getObjectId())); ObjectIdSubclassMap<ObjectId> provided = new ObjectIdSubclassMap<ObjectId>(); <START> if (ensureObjectsProvidedVisible) { <END> for (ObjectId id : getNewObjectIds()) { provided.add(id); } } RevCommit c; while ((c = ow.next()) != null) { if (ensureObjectsProvidedVisible) { if (!provided.contains(c)) { reject(commands); break; } } } RevObject o; while ((o = ow.nextObject()) != null) { if (o instanceof RevBlob && !db.hasObject(o)) throw new MissingObjectException(o, Constants.TYPE_BLOB); if (ensureObjectsProvidedVisible) { if (!provided.contains(o)) { reject(commands); break; } } } }</code><technical_language>If ensureObjectsProvidedVisible is true I need do verify user "see" base objects in pack file. I failed give a implement part of this method. In theory, send-pack/receive-pack protocol works in Git, base objects *must* marked UNINTERESTING markUninteresting calls. I do this here: for (ObjectId id : getBaseObjectIds()) { RevObject b = ow.lookupAny(id); if (!b.has(RevFlag.UNINTERESTING)) throw new MissingObjectException(b, b.getType()); }</technical_language>

Target:
private void checkConnectivity() throws IOException { final ObjectWalk ow = new ObjectWalk(db); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() != Result.NOT_ATTEMPTED) continue; if (cmd.getType() == ReceiveCommand.Type.DELETE) continue; ow.markStart(ow.parseAny(cmd.getNewId())); } for (final Ref ref : refs.values()) ow.markUninteresting(ow.parseAny(ref.getObjectId())); ObjectIdSubclassMap<ObjectId> provided = new ObjectIdSubclassMap<ObjectId>(); if (ensureObjectsProvidedVisible) { for (ObjectId id : getBaseObjectIds()) { RevObject b = ow.lookupAny(id); if (!b.has(RevFlag.UNINTERESTING)) throw new MissingObjectException(b, b.getType()); } for (ObjectId id : getNewObjectIds()) { provided.add(id); } } RevCommit c; while ((c = ow.next()) != null) { if (ensureObjectsProvidedVisible && !provided.contains(c)) throw new MissingObjectException(c, Constants.TYPE_COMMIT); } RevObject o; while ((o = ow.nextObject()) != null) { if (o instanceof RevBlob && !db.hasObject(o)) throw new MissingObjectException(o, Constants.TYPE_BLOB); if (ensureObjectsProvidedVisible && !provided.contains(o)) throw new MissingObjectException(o, Constants.TYPE_BLOB); } }
Source:
<code>private void logInitializationError(String message) { <START> log.error("The Mac pool is not initialized"); <END> AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("Message",message); AuditLogDirector.log(logable, AuditLogType.MAC_POOL_NOT_INITIALIZED); }</code><technical_language>s/Mac pool/MAC addresses pool</technical_language>

Target:
private void logInitializationError(String message) { log.error("The MAC addresses pool is not initialized"); AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("Message",message); AuditLogDirector.log(logable, AuditLogType.MAC_ADDRESSES_POOL_NOT_INITIALIZED); }
Source:
<code>public List<PTOperator> getLeafOperators() { List<PTOperator> operators = new ArrayList<>(); for (OperatorMeta opMeta : dag.getLeafOperators()) { <START> Collection<PTOperator> allOpers = getAllOperators(opMeta); <END> if (allOpers != null) { operators.addAll(getAllOperators(opMeta)); } } return operators; }</code><technical_language>this</technical_language>

Target:
public List<PTOperator> getLeafOperators() { List<PTOperator> operators = new ArrayList<>(); for (OperatorMeta opMeta : dag.getLeafOperators()) { Collection<PTOperator> allOpers = getAllOperators(opMeta); if (allOpers != null) { operators.addAll(allOpers); } } return operators; }
Source:
<code>public void deleteSchema(Long id, Long maxRowsPerSecond) throws SQLException { String[] tables = { "columns", "tables", "databases" }; try ( Connection connection = connectionPool.getConnection() ) { <START> connection.createStatement().execute("delete from `maxwell`.`schemas` where id = " + id); <END> for ( String tName : tables ) { for (;;) { long nDeleted = connection.createStatement().executeUpdate( "DELETE FROM maxwell." + tName + " WHERE schema_id = " + id + " LIMIT " + maxRowsPerSecond ); if (isStopRequested()) return; if (nDeleted == 0) break; LOGGER.debug("deleted " + nDeleted + " rows from maxwell." + tName + " schema: " + id); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } }</code><technical_language>i a bit worried deleting id get rows. this done after</technical_language>

Target:
public void deleteSchema(Long id, Long maxRowsPerSecond) throws SQLException { String[] tables = { "columns", "tables", "databases" }; try ( Connection connection = connectionPool.getConnection() ) { for ( String tName : tables ) { for (;;) { long nDeleted = connection.createStatement().executeUpdate( "DELETE FROM maxwell." + tName + " WHERE schema_id = " + id + " LIMIT " + maxRowsPerSecond ); if (isStopRequested()) return; if (nDeleted == 0) break; LOGGER.debug("deleted " + nDeleted + " rows from maxwell." + tName + " schema: " + id); try { Thread.sleep(1000); } catch (InterruptedException e) { } if (isStopRequested()) return; } } connection.createStatement().execute("delete from `maxwell`.`schemas` where id = " + id); } }
Source:
<code>public void prepare() throws InfrastructureException { Client k8sClient = clientFactory.create(workspaceId); if (k8sClient.serviceAccounts().inNamespace(namespace).withName(serviceAccountName).get() == null) { createWorkspaceServiceAccount(k8sClient); } else { <START> return; <END> } createRole(k8sClient, EXEC_ROLE_NAME); createRole(k8sClient, VIEW_ROLE_NAME); roleBindings .apply(k8sClient) .inNamespace(namespace) .createOrReplace(createRoleBinding(EXEC_ROLE_NAME, serviceAccountName + "-exec", false)); roleBindings .apply(k8sClient) .inNamespace(namespace) .createOrReplace(createRoleBinding(VIEW_ROLE_NAME, serviceAccountName + "-view", false)); int idx = 0; for (String clusterRoleName : this.clusterRoleNames) { if (k8sClient.rbac().clusterRoles().withName(clusterRoleName).get() != null) { roleBindings .apply(k8sClient) .inNamespace(namespace) .createOrReplace( createRoleBinding(clusterRoleName, serviceAccountName + "-cluster" + idx++, true)); } else { LOG.warn( "Unable to find the cluster role {}. Skip creating custom role binding.", clusterRoleName); } } }</code><technical_language>solve in another issue <LINK_0></technical_language>

Target:
public void prepare() throws InfrastructureException { Client k8sClient = clientFactory.create(workspaceId); if (k8sClient.serviceAccounts().inNamespace(namespace).withName(serviceAccountName).get() == null) { createWorkspaceServiceAccount(k8sClient); createImplicitRolesWithBindings(k8sClient); createExplicitClusterRoleBindings(k8sClient); } }
Source:
<code>private void tryInitialize() { keyValueService.createTable(AtlasDbConstants.PUNCH_TABLE, new TableMetadata( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription.Builder() <START> .componentName("time_rounded_to_day") <END> .type(ValueType.FIXED_LONG_LITTLE_ENDIAN) .build())), new ColumnMetadataDescription(new DynamicColumnDescription( NameMetadataDescription.create(ImmutableList.of(new NameComponentDescription.Builder() .componentName("millis_in_day") .type(ValueType.VAR_LONG) .build())), ColumnValueDescription.forType(ValueType.VAR_LONG))), ConflictHandler.IGNORE_ALL, TableMetadataPersistence.LogSafety.SAFE).persistToBytes()); }</code><technical_language>This artifact of resolution previously set 1 day</technical_language>

Target:
private void tryInitialize() { keyValueService.createTable(AtlasDbConstants.PUNCH_TABLE, new TableMetadata( NameMetadataDescription.create(ImmutableList.of( new NameComponentDescription.Builder() .componentName("time_rounded_millis") .type(ValueType.FIXED_LONG_LITTLE_ENDIAN) .build())), new ColumnMetadataDescription(new DynamicColumnDescription( NameMetadataDescription.create(ImmutableList.of(new NameComponentDescription.Builder() .componentName("remainder_millis") .type(ValueType.VAR_LONG) .build())), ColumnValueDescription.forType(ValueType.VAR_LONG))), ConflictHandler.IGNORE_ALL, TableMetadataPersistence.LogSafety.SAFE).persistToBytes()); }
Source:
<code>public void onReady() { try (LockResource lr = new LockResource(mLock)) { if (shouldRestartDataReader() && !mFinished.get()) { try { mDataReaderExecutor.submit(createDataReader(mContext, mResponseObserver)); mContext.setDataReaderActive(true); <START> } catch (RejectedExecutionException e) { <END> handleStreamEndingException(e, Status.RESOURCE_EXHAUSTED); } } } }</code><technical_language>exceptions</technical_language>

Target:
public void onReady() { try (LockResource lr = new LockResource(mLock)) { if (shouldRestartDataReader()) { try { mDataReaderExecutor.submit(createDataReader(mContext, mResponseObserver)); mContext.setDataReaderActive(true); } catch (RejectedExecutionException e) { handleStreamEndingException(Status.RESOURCE_EXHAUSTED.withCause(e) .withDescription("Failed to create a new data reader")); } } } }
Source:
<code>public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "SchemaTablePrefix is null"); List<SchemaTableName> tables; if (prefix.getSchemaName() == null) { tables = listTables(session, null); } else if (prefix.getTableName() == null) { tables = listTables(session, prefix.getSchemaName()); <START> } <END> else { tables = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); for (SchemaTableName tableName : tables) { KuduTableHandle tableHandle = getTableHandle(session, tableName); ConnectorTableMetadata tableMetadata = getTableMetadata(tableHandle); columns.put(tableName, tableMetadata.getColumns()); } return columns.build(); }</code><technical_language>if this table exists</technical_language>

Target:
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { requireNonNull(prefix, "SchemaTablePrefix is null"); List<SchemaTableName> tables; if (prefix.getTableName() == null) { tables = listTables(session, prefix.getSchemaName()); } else { tables = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); for (SchemaTableName tableName : tables) { KuduTableHandle tableHandle = getTableHandle(session, tableName); if (tableHandle != null) { ConnectorTableMetadata tableMetadata = getTableMetadata(tableHandle); columns.put(tableName, tableMetadata.getColumns()); } } return columns.build(); }
Source:
<code>public void removeFromDevicesTag( @Auth final AccessToken accessToken, @PathParam("tag_name") final String tagName, @PathParam("device_id") final String deviceId){ <START> final List<String> ids = new ArrayList<>(); <END> ids.add(deviceId); tagStore.remove(tagName, TagStoreDAODynamoDB.Type.DEVICES, ids); }</code><technical_language>this Lists.newArrayList(deviceId);</technical_language>

Target:
public void removeFromDevicesTag( @Auth final AccessToken accessToken, @PathParam("tag_name") final String tagName, @PathParam("device_id") final String deviceId){ final List<String> ids = Lists.newArrayList(); ids.add(deviceId); tagStore.remove(tagName, TagStoreDAODynamoDB.Type.DEVICES, ids); }
Source:
<code><START> public static BiFunction<Object, Object[], Object> superMethod( <END> Function<String, BiFunction> enhancer, Method method) { return enhancer.apply(signature(method)); }</code><technical_language>ditto keeping this package private</technical_language>

Target:
static BiFunction<Object, Object[], Object> superMethod( Function<String, BiFunction> enhancer, Method method) { return enhancer.apply(signature(method)); }
Source:
<code>protected void executeCommand(IDeviceManagementInteractor executor) throws DeploymentException { <START> try { executor.startFB(resource, new FBDeploymentData("", resFB)); } catch (DeploymentException e) { throw e; } <END> }</code><technical_language>is point of catching exception here</technical_language>

Target:
protected void executeCommand(IDeviceManagementInteractor executor) throws DeploymentException { executor.startFB(resource, new FBDeploymentData("", resFB)); }
Source:
<code>String createOrUpdate(Request request, Response response) throws IOException { SiteUrls siteUrls = buildEntityFromRequestBody(request); try { serverConfigService.createOrUpdateServerSiteUrls(siteUrls); } catch (GoConfigInvalidException e) { response.status(HttpStatus.UNPROCESSABLE_ENTITY.value()); String errorMessage = entityConfigValidationFailed(siteUrls.getClass().getAnnotation(ConfigTag.class).value(), e.getAllErrorMessages()); return MessageJson.create(errorMessage, jsonWriter(siteUrls)); } <START> return index(request, response); <END> }</code><technical_language>specific reason for index() writerForTopLevelObject</technical_language>

Target:
String createOrUpdate(Request request, Response response) throws IOException { SiteUrls siteUrls = buildEntityFromRequestBody(request); try { serverConfigService.createOrUpdateServerSiteUrls(siteUrls); return writerForTopLevelObject(request, response, writer -> ServerSiteUrlsConfigRepresenter.toJSON(writer, siteUrls)); } catch (GoConfigInvalidException e) { return writerForTopLevelObject(request, response, writer -> { writer.add("message", e.getMessage()); ServerSiteUrlsConfigRepresenter.toJSON(writer, siteUrls); }); } }
Source:
<code>public void createValidation() { getMorphia().map(DocumentValidation.class); getDs().enableDocumentValidation(); try { getDs().save(new DocumentValidation("John", 1, new Date())); } catch (WriteConcernException e) { <START> assertTrue(e.getMessage().contains("Document failed validation")); <END> } }</code><technical_language>is this assertion here? Morphia-specific code tested. for assertions _should_ here</technical_language>

Target:
public void createValidation() { getMorphia().map(DocumentValidation.class); getDs().enableDocumentValidation(); assertEquals(Document.parse(DocumentValidation.class.getAnnotation(Validation.class).value()), getValidator()); try { getDs().save(new DocumentValidation("John", 1, new Date())); fail("Document should have failed validation"); } catch (WriteConcernException e) { assertTrue(e.getMessage().contains("Document failed validation")); } getDs().save(new DocumentValidation("Harold", 100, new Date())); }
Source:
<code>public Map<String, String> getAttributes() { Map<String, String> attributes = new HashMap<String, String>( BPUserLibraryElement.this.fAttributes.size()); for (Map.Entry<String, String> entry : BPUserLibraryElement.this.fAttributes .entrySet()) { attributes.put(entry.getKey(), entry.getValue()); } <START> return attributes; <END> }</code><technical_language>this here: return fAttributes != null ? Collections.unmodifiableMap(fAttributes) : Collections.emptyMap(); modifying other 2 constructors</technical_language>

Target:
public Map<String, String> getAttributes() { return fAttributes != null ? Collections.<String, String>unmodifiableMap(fAttributes) : Collections.<String, String> emptyMap(); }
Source:
<code>public Object handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest httpServletRequest) { <START> LOG.info("", e); <END> return handleTypedException(isHtmlRequest(httpServletRequest), NotFoundController.URI, e.getLocalizedMessage(), NOT_FOUND); }</code><technical_language>Do want log empty string in cases</technical_language>

Target:
public Object handleNoHandlerFoundException(NoHandlerFoundException e, HttpServletRequest httpServletRequest) { LOG.info("", e); return handleTypedException(isHtmlRequest(httpServletRequest), BadRequestController.URI, e.getLocalizedMessage(), NOT_FOUND); }
Source:
<code>private Long getHostsByCapability(List<Long> hostList, String hostCapability) { int totalHostswithCapability = 0; for (Long host : hostList) { Map<String, String> details = hostDetailsDao.findDetails(host); if (details.containsKey(Host.HOST_UEFI_ENABLE)) { if (details.get(Host.HOST_UEFI_ENABLE).equalsIgnoreCase("Yes")) { <START> totalHostswithCapability++; <END> } } } return totalHostswithCapability > 0 ? new Long(1) : new Long(0); }</code><technical_language>return a host UEFI capability satisfies return cond</technical_language>

Target:
private Long getHostsByCapability(List<Long> hostList, String hostCapability) { for (Long host : hostList) { Map<String, String> details = hostDetailsDao.findDetails(host); if (details.containsKey(Host.HOST_UEFI_ENABLE)) { if (details.get(Host.HOST_UEFI_ENABLE).equalsIgnoreCase("Yes")) { return new Long(1); } } } return new Long(0); }
Source:
<code>public void purgeObs(Obs obs, boolean cascade) throws APIException { <START> if (purgeComplexData(obs) == false) { <END> throw new APIException("Unable to purge complex data for obs: " + obs); } purgeObsDao(obs, cascade); }</code><technical_language>changing purgeComplexData() return true if complex obs is found. return false if else wrong (Failure delete existing complex obs, e.g due permissions, etc)</technical_language>

Target:
public void purgeObs(Obs obs, boolean cascade) throws APIException { if (purgeComplexData(obs) == false) { throw new APIException("Unable to purge complex data for obs: " + obs); } if (cascade) { throw new APIException("Cascading purge of obs not yet implemented"); } dao.deleteObs(obs); }
Source:
<code>protected void nocache(final HttpServletResponse rsp) { rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); <START> rsp.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate"); <END> }</code><technical_language>Some proxies grok comma-separated headers; reason do Cache-Control: no-cache here</technical_language>

Target:
protected void nocache(final HttpServletResponse rsp) { rsp.setHeader(HDR_EXPIRES, "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader(HDR_PRAGMA, "no-cache"); rsp.setHeader(HDR_CACHE_CONTROL, "no-cache, max-age=0, must-revalidate"); }
Source:
<code>public void test_example() { ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("sonarqube")); ComponentDto longLivingBranch = db.components().insertProjectBranch(project, b -> b.setKey("feature/bar").setBranchType(BranchType.LONG)); ComponentDto shortLivingBranch = db.components().insertProjectBranch(project, b -> b.setKey("feature/foo").setBranchType(BranchType.SHORT).setMergeBranchUuid(longLivingBranch.uuid())); userSession.logIn().addProjectPermission(UserRole.USER, project); db.getDbClient().snapshotDao().insert(db.getSession(), <START> SnapshotTesting.newAnalysis(longLivingBranch).setLast(true).setCreatedAt(DateUtils.parseDateTime("2017-04-01T01:15:42+0100").getTime())); <END> db.getDbClient().snapshotDao().insert(db.getSession(), SnapshotTesting.newAnalysis(shortLivingBranch).setLast(true).setCreatedAt(DateUtils.parseDateTime("2017-04-03T13:37:00+0100").getTime())); db.commit(); String json = ws.newRequest() .setParam("project", project.getDbKey()) .execute() .getInput(); assertJson(json).isSimilarTo(ws.getDef().responseExampleAsString()); }</code><technical_language>update json example add assertion validate in 2 ways line 130: assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(json);</technical_language>

Target:
public void test_example() { ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("sonarqube")); ComponentDto longLivingBranch = db.components() .insertProjectBranch(project, b -> b.setKey("feature/bar").setBranchType(LONG)); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(longLivingBranch).setLast(true).setCreatedAt(parseDateTime("2017-04-01T01:15:42+0100").getTime())); db.measures().insertLiveMeasure(longLivingBranch, qualityGateStatus, m -> m.setData("OK")); ComponentDto shortLivingBranch = db.components() .insertProjectBranch(project, b -> b.setKey("feature/foo").setBranchType(SHORT).setMergeBranchUuid(longLivingBranch.uuid())); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(shortLivingBranch).setLast(true).setCreatedAt(parseDateTime("2017-04-03T13:37:00+0100").getTime())); db.measures().insertLiveMeasure(shortLivingBranch, qualityGateStatus, m -> m.setData("OK")); RuleDefinitionDto rule = db.rules().insert(); db.issues().insert(rule, shortLivingBranch, shortLivingBranch, i -> i.setType(BUG).setResolution(null)); issueIndexer.indexOnStartup(emptySet()); userSession.logIn().addProjectPermission(USER, project); String json = ws.newRequest() .setParam("project", project.getDbKey()) .execute() .getInput(); assertJson(json).isSimilarTo(ws.getDef().responseExampleAsString()); assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(json); }
Source:
<code>public static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return BOND0; } int modeStartIndex = bondOptions.indexOf(MODE); int bondModeIndex = modeStartIndex + MODE.length(); if (modeStartIndex >= 0 && bondOptions.length() >= bondModeIndex +1){ <START> int bondMode = Integer.parseInt(bondOptions.substring(bondModeIndex, bondModeIndex + 1)); <END> if (bondMode >= 0 && bondMode < BondMode.values().length) return BondMode.values()[bondMode]; } return BOND0; }</code><technical_language>if custom bond mode more digit? read number next space "mode="</technical_language>

Target:
public static BondMode getBondMode(String bondOptions){ if(bondOptions == null){ return BOND0; } String bondModeValue = findMode(bondOptions); if (bondModeValue == null){ return BOND0; } for (BondMode bondMode : BondMode.values()){ if (bondMode.getValue().equals(bondModeValue)){ return bondMode; } } return BOND0; }
Source:
<code><START> private Collection<String> getBranchNames(Collection<Branch> branches) { <END> return branches.stream().map(p -> p.getName()).collect(Collectors.toList()); }</code><technical_language>is a duplicate implementation in PushTest. a good candidate for a test util function imported statically</technical_language>

Target:
private Collection<String> getBranchNames(Collection<Branch> branches) { return branches.stream().map(Branch::getName).collect(toList()); }