auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); Preconditions.checkArgument(tableSinkConfig.containsMacro(Properties.Table.PROPERTY_SCHEMA_ROW_FIELD) || !Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Row field must be given as a property."); Schema outputSchema = SchemaValidator.validateOutputSchemaAndInputSchemaIfPresent(tableSinkConfig.getSchemaStr(), tableSinkConfig.getRowField(), pipelineConfigurer); if (outputSchema != null) { if (outputSchema.getFields().size() == 1) { String fieldName = outputSchema.getFields().get(0).getName(); if (fieldName.equals(tableSinkConfig.getRowField())) { <START> throw new IllegalArgumentException( <END> String.format("Output schema should have columns other than rowkey.")); } } else if (outputSchema.getField(tableSinkConfig.getRowField()) == null) { throw new IllegalArgumentException( String.format("Output schema should contain the rowkey column.")); } } pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }</code><technical_language>hmmm this code suspicious. I error scenarios: a) schema field field is row field b) schema field field is row field c) schema more fields row field if case b) is covered</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); Preconditions.checkArgument(tableSinkConfig.containsMacro(Properties.Table.PROPERTY_SCHEMA_ROW_FIELD) || !Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Row field must be given as a property."); Schema outputSchema = SchemaValidator.validateOutputSchemaAndInputSchemaIfPresent(tableSinkConfig.getSchemaStr(), tableSinkConfig.getRowField(), pipelineConfigurer); if (outputSchema != null) { if (outputSchema.getField(tableSinkConfig.getRowField()) == null) { throw new IllegalArgumentException("Output schema should contain the rowkey column."); } if (outputSchema.getFields().size() == 1) { throw new IllegalArgumentException("Output schema should have columns other than rowkey."); } } pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }
Source:
<code>public void initialize() { themeChoiceBox.getItems().addAll(UiTheme.applicableValues()); if (!themeChoiceBox.getItems().contains(settings.theme().get())) { settings.theme().set(UiTheme.LIGHT); } themeChoiceBox.valueProperty().bindBidirectional(settings.theme()); themeChoiceBox.setConverter(new UiThemeConverter(resourceBundle)); startHiddenCheckbox.selectedProperty().bindBidirectional(settings.startHidden()); debugModeCheckbox.selectedProperty().bindBidirectional(settings.debugMode()); autoStartStrategy.ifPresent(autoStart -> { <START> CompletableFuture.completedFuture(autoStart.isEnabled()).thenAccept(enabled -> { <END> Platform.runLater(() -> autoStartCheckbox.setSelected(enabled)); }); }); nodeOrientationLtr.setSelected(settings.userInterfaceOrientation().get() == NodeOrientation.LEFT_TO_RIGHT); nodeOrientationRtl.setSelected(settings.userInterfaceOrientation().get() == NodeOrientation.RIGHT_TO_LEFT); nodeOrientation.selectedToggleProperty().addListener(this::toggleNodeOrientation); keychainBackendChoiceBox.getItems().addAll(getAvailableBackends()); keychainBackendChoiceBox.setConverter(new KeychainBackendConverter(resourceBundle)); keychainBackendChoiceBox.valueProperty().bindBidirectional(settings.keychainBackend()); }</code><technical_language>this a normal if statement</technical_language>

Target:
public void initialize() { themeChoiceBox.getItems().addAll(UiTheme.applicableValues()); if (!themeChoiceBox.getItems().contains(settings.theme().get())) { settings.theme().set(UiTheme.LIGHT); } themeChoiceBox.valueProperty().bindBidirectional(settings.theme()); themeChoiceBox.setConverter(new UiThemeConverter(resourceBundle)); startHiddenCheckbox.selectedProperty().bindBidirectional(settings.startHidden()); debugModeCheckbox.selectedProperty().bindBidirectional(settings.debugMode()); autoStartProvider.ifPresent(realProvider -> autoStartCheckbox.setSelected(realProvider.isEnabled())); nodeOrientationLtr.setSelected(settings.userInterfaceOrientation().get() == NodeOrientation.LEFT_TO_RIGHT); nodeOrientationRtl.setSelected(settings.userInterfaceOrientation().get() == NodeOrientation.RIGHT_TO_LEFT); nodeOrientation.selectedToggleProperty().addListener(this::toggleNodeOrientation); keychainBackendChoiceBox.getItems().addAll(getAvailableBackends()); keychainBackendChoiceBox.setConverter(new KeychainBackendConverter(resourceBundle)); keychainBackendChoiceBox.valueProperty().bindBidirectional(settings.keychainBackend()); }
Source:
<code>public LocalWorkspaceFolderPathProvider(@Named("che.workspace.storage") String workspacesMountPoint, Provider<WorkspaceManager> workspaceManager) throws IOException { this.workspacesMountPoint = workspacesMountPoint; this.workspaceManager = workspaceManager; this.isWindows = SystemInfo.isWindows(); String allowFoldersCreationEnvVar = System.getenv(ALLOW_FOLDERS_CREATION_ENV_VARIABLE); <START> if (allowFoldersCreationEnvVar != null) { <END> if ("false".equalsIgnoreCase(allowFoldersCreationEnvVar)) { createFolders = false; } } }</code><technical_language>remove this check. merge next && I prefer variant</technical_language>

Target:
public LocalWorkspaceFolderPathProvider(@Named("che.workspace.storage") String workspacesMountPoint, Provider<WorkspaceManager> workspaceManager) throws IOException { this.workspacesMountPoint = workspacesMountPoint; this.workspaceManager = workspaceManager; this.isWindows = SystemInfo.isWindows(); }
Source:
<code>public List<AntiCsrfToken> getTokensFromResponse(HttpMessage msg, Source source) { List<AntiCsrfToken> list = new ArrayList<>(); List<Element> formElements = source.getAllElements(HTMLElementName.FORM); if (formElements != null && formElements.size() > 0) { log.debug("Found " + formElements.size() + " forms"); int formIndex = 0; for (Element formElement : formElements) { List<Element> inputElements = formElement.getAllElements(HTMLElementName.INPUT); if (inputElements != null && inputElements.size() > 0) { log.debug("Found " + inputElements.size() + " inputs"); for (Element inputElement : inputElements) { String value = inputElement.getAttributeValue("VALUE"); if (value == null) { continue; } String attId = inputElement.getAttributeValue("ID"); boolean found = false; <START> if (attId != null && isKnownAntiCsrfToken(attId)) { <END> list.add(new AntiCsrfToken(msg, attId, value, formIndex)); found = true; } if (!found) { String name = inputElement.getAttributeValue("NAME"); if (name != null && isKnownAntiCsrfToken(name)) { list.add(new AntiCsrfToken(msg, name, value, formIndex)); } } } } formIndex++; } } return list; }</code><technical_language>null check moved isKnownAntiCsrfToken well</technical_language>

Target:
public List<AntiCsrfToken> getTokensFromResponse(HttpMessage msg, Source source) { List<AntiCsrfToken> list = new ArrayList<>(); List<Element> formElements = source.getAllElements(HTMLElementName.FORM); if (formElements != null && formElements.size() > 0) { log.debug("Found " + formElements.size() + " forms"); int formIndex = 0; for (Element formElement : formElements) { List<Element> inputElements = formElement.getAllElements(HTMLElementName.INPUT); if (inputElements != null && inputElements.size() > 0) { log.debug("Found " + inputElements.size() + " inputs"); for (Element inputElement : inputElements) { String value = inputElement.getAttributeValue("VALUE"); if (value == null) { continue; } String attId = inputElement.getAttributeValue("ID"); boolean found = false; if (isKnownAntiCsrfToken(attId)) { list.add(new AntiCsrfToken(msg, attId, value, formIndex)); found = true; } if (!found) { String name = inputElement.getAttributeValue("NAME"); if (isKnownAntiCsrfToken(name)) { list.add(new AntiCsrfToken(msg, name, value, formIndex)); } } } } formIndex++; } } return list; }
Source:
<code>public static Book random() { <START> return new Book("title" + uuid(), "isbn" + uuid()); <END> }</code><technical_language>I included fix in test code cleanup, #51</technical_language>

Target:
public static Book random() { return new Book(uuid(), uuid()); }
Source:
<code>public Persister createPersister(ServiceParameters params, RrdRepository repository, boolean dontPersistCounters, boolean forceStoreByGroup, boolean dontReorderAttributes) { <START> delegate = SERVICE_LOOKUP.lookup(PersisterFactory.class, "(strategy=kafka)"); <END> if (delegate != null) { Persister persister = delegate.createPersister(params, repository); return persister; } return null; }</code><technical_language>find a avoid hard-coding "kafka" name else this persister is generic</technical_language>

Target:
public Persister createPersister(ServiceParameters params, RrdRepository repository, boolean dontPersistCounters, boolean forceStoreByGroup, boolean dontReorderAttributes) { final PersisterFactory delegate = getDelegate(); if (delegate == null) { LOG.info("Unable to find any persister factory from osgi registry, use NullPersister"); return new NullPersister(); } return delegate.createPersister(params, repository, dontPersistCounters, forceStoreByGroup, dontReorderAttributes); }
Source:
<code>static <I> AggregateEventRecord newEventRecord(I aggregateId, Snapshot snapshot) { checkNotNull(aggregateId); checkNotNull(snapshot); Timestamp value = checkValid(snapshot.getTimestamp()); String stringId = Stringifiers.toString(aggregateId); String snapshotTimestamp = Timestamps.toString(snapshot.getTimestamp()); String snapshotColumnName = AggregateEventRecordColumn.snapshot.name() .value(); String snapshotId = format("%s_%s_%s", snapshotColumnName, stringId, snapshotTimestamp); AggregateEventRecordId recordId = eventRecordId(snapshotId); return AggregateEventRecord .newBuilder() .setId(recordId) .setAggregateId(Identifier.pack(aggregateId)) .setTimestamp(value) .setSnapshot(snapshot) <START> .build(); <END> }</code><technical_language>Consider .vBuild()</technical_language>

Target:
static <I> AggregateEventRecord newEventRecord(I aggregateId, Snapshot snapshot) { checkNotNull(aggregateId); checkNotNull(snapshot); Timestamp value = checkValid(snapshot.getTimestamp()); String stringId = Stringifiers.toString(aggregateId); String snapshotTimestamp = Timestamps.toString(snapshot.getTimestamp()); String snapshotColumnName = AggregateEventRecordColumn.snapshot.name() .value(); String snapshotId = format("%s_%s_%s", snapshotColumnName, stringId, snapshotTimestamp); AggregateEventRecordId recordId = eventRecordId(snapshotId); AggregateEventRecord result = AggregateEventRecord .newBuilder() .setId(recordId) .setAggregateId(Identifier.pack(aggregateId)) .setTimestamp(value) .setSnapshot(snapshot) .vBuild(); return result; }
Source:
<code>public static void register(TestGroups groups) { groups.media.add(JavaBuiltIn.mediaTransformer, new GenericSerializer<MediaContent>("json/fastjson_array/databind", MediaContent.class), new SerFeatures( <START> SerFormat.BINARY, <END> SerGraph.FLAT_TREE, SerClass.ZERO_KNOWLEDGE, "" ) ); }</code><technical_language>this is binary</technical_language>

Target:
public static void register(TestGroups groups) { groups.media.add(JavaBuiltIn.mediaTransformer, new GenericSerializer<MediaContent>("json-array/fastjson/databind", MediaContent.class), new SerFeatures( SerFormat.JSON, SerGraph.FLAT_TREE, SerClass.ZERO_KNOWLEDGE, "" ) ); }
Source:
<code>public void shareStoreWithMapTest() { CompilerHelper helper = new CompilerHelper(); Map<String, Object> kieMap = new HashMap<>(); String compilationID = UUID.randomUUID().toString(); kieMap.put("compilation.ID", compilationID); ProjectClassLoader pcl = ProjectClassLoader.createProjectClassLoader(); String hexContent = "e04fd020ea3a6910a2d808002b30309d"; String className = "org/my/Clazz"; pcl.storeClass(className, hexStringToByteArray(hexContent)); helper.shareStoreWithMap(pcl, compilationID, kieMap, log); StringBuilder sbTypes = new StringBuilder(compilationID).append(".").append("ProjectClassloaderStore"); kieMap.get(sbTypes.toString()); Map store = (Map) kieMap.get(sbTypes.toString()); assertThat(store).isNotNull(); <START> assertThat(store.size()).isEqualTo(1); <END> byte[] bytez = (byte[]) store.get(className + ".class"); assertThat(bytez).isNotNull(); String hex = toHexString(bytez); assertThat(hex).isEqualTo(hexContent); }</code><technical_language>assertThat(store).hasSize(1);</technical_language>

Target:
public void shareStoreWithMapTest() { CompilerHelper helper = new CompilerHelper(); Map<String, Object> kieMap = new HashMap<>(); String compilationID = UUID.randomUUID().toString(); kieMap.put("compilation.ID", compilationID); ProjectClassLoader pcl = ProjectClassLoader.createProjectClassLoader(); String hexContent = "e04fd020ea3a6910a2d808002b30309d"; String className = "org/my/Clazz"; pcl.storeClass(className, hexStringToByteArray(hexContent)); helper.shareStoreWithMap(pcl, compilationID, kieMap, log); StringBuilder sbTypes = new StringBuilder(compilationID).append(".").append("ProjectClassloaderStore"); kieMap.get(sbTypes.toString()); Map store = (Map) kieMap.get(sbTypes.toString()); assertThat(store).isNotNull(); assertThat(store).hasSize(1); byte[] bytez = (byte[]) store.get(className + ".class"); assertThat(bytez).isNotNull(); String hex = toHexString(bytez); assertThat(hex).isEqualTo(hexContent); }
Source:
<code>public void should_pick_skip_pattern_from_sleuth_properties() throws Exception { contextRunner.withPropertyValues("spring.sleuth.web.skip-pattern=foo.*|bar.*") .run(context -> { SkipPatternProvider skipPatternProvider = context .getBean(SkipPatternProvider.class); <START> Pattern pattern = skipPatternProvider.skipPattern(); <END> then(pattern.pattern()).isEqualTo("foo.*|bar.*"); }); }</code><technical_language>test do this, nice extract this code a private method improve readability reduce duplication. java private String extractPattern(ApplicationContext context) { return context.getBean(SkipPatternProvider.class).skipPattern().pattern(); }</technical_language>

Target:
public void should_pick_skip_pattern_from_sleuth_properties() throws Exception { contextRunner.withPropertyValues("spring.sleuth.web.skip-pattern=foo.*|bar.*") .run(context -> { final String pattern = extractPattern(context); then(pattern).isEqualTo("foo.*|bar.*"); }); }
Source:
<code>public IndexRDFCollection(Args args) throws Exception { this.args = args; <START> String defaultAnalyzerName = "org.apache.lucene.analysis.standard.StandardAnalyzer"; <END> ANALYZER = (Analyzer) Class.forName(defaultAnalyzerName).newInstance(); LOG.info("Collection path: " + args.input); LOG.info("Index path: " + args.index); if (args.predicatesToIndex != null && args.predicatesToIndex.size() > 0) { LOG.info("Predicates to index: " + String.join(",", args.predicatesToIndex)); } else { LOG.info("Predicates to index: None"); } this.indexPath = Paths.get(args.index); if (!Files.exists(this.indexPath)) { Files.createDirectories(this.indexPath); } collectionPath = Paths.get(args.input); if (!Files.exists(collectionPath) || !Files.isReadable(collectionPath)) { throw new IllegalArgumentException("Document file/directory " + collectionPath.toString() + " does not exist or is not readable, please check the path"); } this.transformerClass = Class.forName("io.anserini.index.generator." + args.generatorClass); this.collectionClass = Class.forName("io.anserini.collection." + args.collectionClass); collection = (Collection) this.collectionClass.newInstance(); collection.setCollectionPath(collectionPath); this.counters = new Counters(); }</code><technical_language>Class.forName? create a static final instance</technical_language>

Target:
public IndexRDFCollection(Args args) throws Exception { this.args = args; LOG.info("Collection path: " + args.input); LOG.info("Index path: " + args.index); if (args.predicatesToIndex != null && args.predicatesToIndex.size() > 0) { LOG.info("Predicates to index: " + String.join(",", args.predicatesToIndex)); } else { LOG.info("Predicates to index: None"); } this.indexPath = Paths.get(args.index); if (!Files.exists(this.indexPath)) { Files.createDirectories(this.indexPath); } collectionPath = Paths.get(args.input); if (!Files.exists(collectionPath) || !Files.isReadable(collectionPath)) { throw new IllegalArgumentException("Document file/directory " + collectionPath.toString() + " does not exist or is not readable, please check the path"); } this.collectionClass = Class.forName("io.anserini.collection." + args.collectionClass); collection = (Collection) this.collectionClass.newInstance(); collection.setCollectionPath(collectionPath); this.counters = new Counters(); }
Source:
<code>private String changeUserPasswd(HttpServletRequest request, Credentials userCredentials) throws AuthenticationException { log.debug("Calling Authn to change password for user '{}@{}'.", userCredentials.getUsername(), userCredentials.getProfile()); AuthenticationUtils.changePassword(request, userCredentials); <START> SSOUtils.getSsoSession(request).setLoginMessage("Change password succeeded, enter new credentials to login."); <END> SSOUtils.getSsoSession(request).setTempCredentials(null); if (SSOUtils.isUserAuthenticated(request)) { log.debug("User is authenticated updating password in SSOSession for password-access scope"); SSOUtils.persistUserPassword(request, SSOUtils.getSsoSession(request), userCredentials.getNewPassword1()); } return request.getContextPath() + SSOConstants.INTERACTIVE_LOGIN_URI; }</code><technical_language>this^ done if authenticated, right</technical_language>

Target:
private String changeUserPasswd(HttpServletRequest request, Credentials userCredentials) throws AuthenticationException { log.debug("Calling Authn to change password for user '{}@{}'.", userCredentials.getUsername(), userCredentials.getProfile()); AuthenticationUtils.changePassword(ssoContext, request, userCredentials); SSOUtils.getSsoSession(request).setChangePasswdCredentials(null); if (SSOUtils.isUserAuthenticated(request)) { log.debug("User is authenticated updating password in SSOSession for password-access scope."); SSOUtils.persistUserPassword(request, SSOUtils.getSsoSession(request), userCredentials.getCredentialsNew1()); } else { log.debug("User password change succeeded, redirecting to login page."); SSOUtils.getSsoSession(request).setLoginMessage("Change password succeeded, enter new credentials to login."); } return request.getContextPath() + SSOConstants.INTERACTIVE_LOGIN_URI; }
Source:
<code>public IRenderRunnable[] getRenderRunnables() { <START> return renderRunnables == null ? new IRenderRunnable[ 0 ] : renderRunnables; <END> }</code><technical_language>Instead of creating a new IRenderRunnable[0] in request, empty array in a constant</technical_language>

Target:
public Runnable[] getRenderRunnables() { return renderRunnables == null ? EMPTY : renderRunnables; }
Source:
<code>public void shouldInvalidReturnNotNull() { <START> assertThat(invalid(new Error("error"))).isNotNull(); <END> }</code><technical_language>same, "error" redundant</technical_language>

Target:
public void shouldInvalidReturnNotNull() { assertThat(Invalid(new Error())).isNotNull(); }
Source:
<code><START> public String getProperty(String name) { <END> switch (name) { case ConfigurationProperties.COMPATIBLE_MODE: return Boolean.toString(compatibleModeEnabled); case ConfigurationProperties.RETURNING_CLAUSE_CASE_SENSITIVE: return Boolean.toString(returningClauseCaseSensitive); case ConfigurationProperties.SIZE_TO_COUNT_TRANSFORMATION: return Boolean.toString(sizeToCountTransformationEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_SELECT: return Boolean.toString(implicitGroupByFromSelectEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_HAVING: return Boolean.toString(implicitGroupByFromHavingEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_ORDER_BY: return Boolean.toString(implicitGroupByFromOrderByEnabled); case ConfigurationProperties.EXPRESSION_OPTIMIZATION: return Boolean.toString(expressionOptimizationEnabled); case ConfigurationProperties.EXPRESSION_CACHE_CLASS: return expressionCacheClass; case ConfigurationProperties.VALUES_CLAUSE_FILTER_NULLS: return Boolean.toString(valuesClauseFilterNullsEnabled); case ConfigurationProperties.PARAMETER_AS_LITERAL_RENDERING: return Boolean.toString(parameterAsLiteralRenderingEnabled); default: return null; } }</code><technical_language>missing implementations for getProperty getProperties methods for property</technical_language>

Target:
public String getProperty(String name) { switch (name) { case ConfigurationProperties.COMPATIBLE_MODE: return Boolean.toString(compatibleModeEnabled); case ConfigurationProperties.RETURNING_CLAUSE_CASE_SENSITIVE: return Boolean.toString(returningClauseCaseSensitive); case ConfigurationProperties.SIZE_TO_COUNT_TRANSFORMATION: return Boolean.toString(sizeToCountTransformationEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_SELECT: return Boolean.toString(implicitGroupByFromSelectEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_HAVING: return Boolean.toString(implicitGroupByFromHavingEnabled); case ConfigurationProperties.IMPLICIT_GROUP_BY_FROM_ORDER_BY: return Boolean.toString(implicitGroupByFromOrderByEnabled); case ConfigurationProperties.EXPRESSION_OPTIMIZATION: return Boolean.toString(expressionOptimizationEnabled); case ConfigurationProperties.EXPRESSION_CACHE_CLASS: return expressionCacheClass; case ConfigurationProperties.VALUES_CLAUSE_FILTER_NULLS: return Boolean.toString(valuesClauseFilterNullsEnabled); case ConfigurationProperties.PARAMETER_AS_LITERAL_RENDERING: return Boolean.toString(parameterAsLiteralRenderingEnabled); case ConfigurationProperties.OPTIMIZED_KEYSET_PREDICATE_RENDERING: return Boolean.toString(optimizedKeysetPredicateRenderingEnabled); default: return null; } }
Source:
<code>public void replaceBrick(GlusterBrickEntity oldBrick, GlusterBrickEntity newBrick) { getCallsHandler().executeModification("UpdateGlusterVolumeBrick", getCustomMapSqlParameterSource().addValue("id", oldBrick.getId()) .addValue("new_id", newBrick.getId()) .addValue("new_server_id", newBrick.getServerId()) .addValue("new_brick_dir", newBrick.getBrickDirectory()) <START> .addValue("new_brick_order", oldBrick.getBrickOrder()) <END> .addValue("new_status", EnumUtils.nameOrNull(newBrick.getStatus()))); }</code><technical_language>replace brick order of new brick brick, parameter "new_brick_order" need passed SP</technical_language>

Target:
public void replaceBrick(GlusterBrickEntity oldBrick, GlusterBrickEntity newBrick) { getCallsHandler().executeModification("UpdateGlusterVolumeBrick", getCustomMapSqlParameterSource().addValue("id", oldBrick.getId()) .addValue("new_id", newBrick.getId()) .addValue("new_server_id", newBrick.getServerId()) .addValue("new_status", EnumUtils.nameOrNull(newBrick.getStatus()))); }
Source:
<code>private OskariLayer getWFSLayer(String version) { OskariLayer layer = new OskariLayer(); <START> layer.setType("WFS"); <END> layer.setId(1); layer.setUrl(LAYER_URL); layer.setName(LAYER_NAME); layer.setUsername(USERNAME); layer.setPassword(PASSWORD); layer.setVersion(version); return layer; }</code><technical_language>suggestion layer.setType(OskariLayer.TYPE_WFS);</technical_language>

Target:
private OskariLayer getWFSLayer(String version) { OskariLayer layer = new OskariLayer(); layer.setType(OskariLayer.TYPE_WFS); layer.setId(1); layer.setUrl(LAYER_URL); layer.setName(LAYER_NAME); layer.setUsername(USERNAME); layer.setPassword(PASSWORD); layer.setVersion(version); return layer; }
Source:
<code>public VdsFenceOptions(String agent, String fencingOptions) { <START> if (!StringUtils.isEmpty(agent)) { <END> this.fenceAgent = agent; this.fencingOptions = fencingOptions; } InitCache(); Init(); }</code><technical_language>s/!StringUtils.isEmpty/StringUtils.isNotEmpty</technical_language>

Target:
public VdsFenceOptions(String agent, String fencingOptions) { if (StringUtils.isNotEmpty(agent)) { this.fenceAgent = agent; this.fencingOptions = fencingOptions; } InitCache(); Init(); }
Source:
<code>public Properties getPageProperties(final APISession apiSession, final byte[] zipContent, final boolean checkIfItAlreadyExists, final Long processDefinitionId) throws InvalidPageZipMissingPropertiesException, InvalidPageZipMissingIndexException, InvalidPageZipInconsistentException, InvalidPageZipMissingAPropertyException, InvalidPageTokenException, AlreadyExistsException, BonitaException { final PageAPI pageAPI = getPageAPI(apiSession); Properties properties; if (processDefinitionId == null) { properties = pageAPI.getPageProperties(zipContent, checkIfItAlreadyExists); } else { properties = pageAPI.getPageProperties(zipContent, false); if (checkIfItAlreadyExists) { final String pageName = properties.getProperty(NAME_PROPERTY); try { pageAPI.getPageByNameAndProcessDefinitionId(pageName, processDefinitionId); throw new AlreadyExistsException("A page with name " + pageName + " already exists for the process " + processDefinitionId); } catch (final PageNotFoundException e) { try { pageAPI.getPageByName(pageName); <START> throw new AlreadyExistsException("A page with name " + pageName + " already exists for the process " + processDefinitionId); <END> } catch (final PageNotFoundException e1) { } } } } return properties; }</code><technical_language>I message of exception sshould changed ("for tenant" instead of "for process")</technical_language>

Target:
public Properties getPageProperties(final APISession apiSession, final byte[] zipContent, final boolean checkIfItAlreadyExists, final Long processDefinitionId) throws InvalidPageZipMissingPropertiesException, InvalidPageZipMissingIndexException, InvalidPageZipInconsistentException, InvalidPageZipMissingAPropertyException, InvalidPageTokenException, AlreadyExistsException, BonitaException { final PageAPI pageAPI = getPageAPI(apiSession); Properties properties; if (processDefinitionId == null) { properties = pageAPI.getPageProperties(zipContent, checkIfItAlreadyExists); } else { properties = pageAPI.getPageProperties(zipContent, false); if (checkIfItAlreadyExists) { final String pageName = properties.getProperty(NAME_PROPERTY); try { pageAPI.getPageByNameAndProcessDefinitionId(pageName, processDefinitionId); throw new AlreadyExistsException("A page with name " + pageName + " already exists for the process " + processDefinitionId); } catch (final PageNotFoundException e) { try { pageAPI.getPageByName(pageName); throw new AlreadyExistsException("A page with name " + pageName + " already exists for the tenant"); } catch (final PageNotFoundException e1) { } } } } return properties; }
Source:
<code>protected IResource getResource() { <START> Object element <END> = getElement(); IResource resource = null; if (element instanceof IResource) { resource = (IResource) element; } else if (element != null) { resource = ((IAdaptable)element).getAdapter(IResource.class); } return resource; }</code><technical_language>change IAdaptable</technical_language>

Target:
protected IResource getResource() { IAdaptable element = getElement(); IResource resource = null; if (element instanceof IResource) { resource = (IResource) element; } else if (element != null) { resource = element.getAdapter(IResource.class); } return resource; }
Source:
<code>public void clickDeleteAllDesktopDisplaysConfirmationDialog() { DeleteDialog confirmationDialog = getDeleteAllButton(UserWithPosts.getUserId()).click(); <START> Assertion.assertTrue(confirmationDialog.isVisible()); <END> }</code><technical_language>Static import assertTrue</technical_language>

Target:
public void clickDeleteAllDesktopDisplaysConfirmationDialog() { DeleteDialog confirmationDialog = getDeleteAllButton(userWithPosts.getUserId()).click(); assertTrue(confirmationDialog.isVisible()); }
Source:
<code>public void test445675_autobuild() throws Exception { setAutobuilding(false); project = importProject("projects/updateProject/simple/pom.xml"); copyContent(project, "pom.xml", "pomWithOneDependency.xml"); <START> assertEventsFromProjects(events, project); <END> project.close(monitor); waitForJobsToComplete(); assertNull(manager.getProject(project)); project.open(monitor); waitForJobsToComplete(); assertNotNull(manager.getProject(project)); events.clear(); copyContent(project, "pomWithSecondDependency.xml", "pom.xml"); waitForJobsToComplete(); assertEquals(0, events.size()); copyContent(project, "pomWithOneDependency.xml", "pom.xml"); setAutobuilding(true); waitForJobsToComplete(); assertEventsFromProjects(events, project); events.clear(); copyContent(project, "pomWithSecondDependency.xml", "pom.xml"); waitForJobsToComplete(); assertEventsFromProjects(events, project); }</code><technical_language>yeah, "assertEventsFromProjects" name is informative. I assert checking code</technical_language>

Target:
public void test445675_autobuild() throws Exception { project = importProject("projects/updateProject/simple/pom.xml"); assertContainsOnly(getProjectsFromEvents(events), project); copyContent(project, "pom.xml", "pomWithOneDependency.xml"); project.close(monitor); waitForJobsToComplete(); assertNull(manager.getProject(project)); project.open(monitor); waitForJobsToComplete(); assertNotNull(manager.getProject(project)); events.clear(); copyContent(project, "pomWithSecondDependency.xml", "pom.xml", false); waitForJobsToComplete(); assertEquals(0, events.size()); setAutoBuilding(true); waitForJobsToComplete(); assertContainsOnly(getProjectsFromEvents(events), project); events.clear(); copyContent(project, "pomWithOneDependency.xml", "pom.xml", false); waitForJobsToComplete(); assertContainsOnly(getProjectsFromEvents(events), project); }
Source:
<code>private Map<String, PrivateKeyEntry> getPrivateKeyEntries() throws CertificateManagerException { Map<String, PrivateKeyEntry> pkEntries = new HashMap<>(); final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { Enumeration enumeration = keyStore.aliases(); while(enumeration.hasMoreElements()) { String alias = (String)enumeration.nextElement(); PrivateKeyEntry pkEntry = (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray())); pkEntries.put(alias, pkEntry); } } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { <START> LOG.error("Error initializing Private Keys: {}", ex.getLocalizedMessage(), ex); <END> throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } return pkEntries; }</code><technical_language>Optional: need log throw exception here. caller catch log it</technical_language>

Target:
private Map<String, PrivateKeyEntry> getPrivateKeyEntries() throws CertificateManagerException { Map<String, PrivateKeyEntry> pkEntries = new HashMap<>(); final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { Enumeration enumeration = keyStore.aliases(); while(enumeration.hasMoreElements()) { String alias = (String)enumeration.nextElement(); PrivateKeyEntry pkEntry = (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray())); pkEntries.put(alias, pkEntry); } } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } return pkEntries; }
Source:
<code>private void prepareFilterBar() { final boolean cacheTypeFilterActive = Settings.getCacheType() != CacheType.ALL; if (cacheTypeFilterActive || adapter.isFiltered()) { final List<String> filters = new ArrayList<>(); <START> if (cacheTypeFilterActive) { <END> filters.add(Settings.getCacheType().getL10n()); } if (adapter.isFiltered()) { filters.add(adapter.getFilterName()); } final TextView filterTextView = ButterKnife.findById(this, R.id.filter_text); filterTextView.setText(TextUtils.join(", ", filters)); findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } else { findViewById(R.id.filter_bar).setVisibility(View.GONE); } }</code><technical_language>I duplication of conditions. extract if block function takes filter name parameter? call new function Settings.getCacheType().getL10n() adapter.getFilterName(), respectively</technical_language>

Target:
private void prepareFilterBar() { final List<String> filterNames = getFilterNames(); if (filterNames.isEmpty()) { findViewById(R.id.filter_bar).setVisibility(View.GONE); } else { final TextView filterTextView = ButterKnife.findById(this, R.id.filter_text); filterTextView.setText(TextUtils.join(", ", filterNames)); findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } }
Source:
<code>private Object evaluateCondition(Method method, ExtensionContext context) { Preconditions.condition(method.getReturnType() == boolean.class, () -> format("method [%s] should return a boolean", method.getName())); Preconditions.condition(areParametersSupported(method), () -> format("method [%s] should take either an ExtensionContext or no parameters", method.getName())); <START> Object testInstance = context.getRequiredTestInstance(); <END> if (method.getParameterCount() == 0) { return ReflectionUtils.invokeMethod(method, testInstance); } return ReflectionUtils.invokeMethod(method, testInstance, context); }</code><technical_language>I missing integration test for applying condition class level in case test instance present</technical_language>

Target:
private Object evaluateCondition(Method method, ExtensionContext context) { Preconditions.condition(method.getReturnType() == boolean.class, () -> format("method [%s] should return a boolean", method.getName())); Preconditions.condition(areParametersSupported(method), () -> format("method [%s] should take either an ExtensionContext or no parameters", method.getName())); Object testInstance = context.getTestInstance().orElse(null); if (method.getParameterCount() == 0) { return ReflectionUtils.invokeMethod(method, testInstance); } return ReflectionUtils.invokeMethod(method, testInstance, context); }
Source:
<code>private void loadModel() { ISecurePreferences secureAccountRoot = getSecureAccountsPreferences(); Preferences accountsRoot = getAccountsPreferences(); try { String[] ids = accountsRoot.childrenNames(); for(String id: ids) { Cluster cluster = new Cluster(this, id); Preferences clusterNode = accountsRoot.node(id); ISecurePreferences secureClusterNode = secureAccountRoot.node(id); <START> try { <END> cluster.load(clusterNode, secureClusterNode); clusters.add(cluster); } catch (StorageException e) { OpenShiftIOCoreActivator.logError(e.getLocalizedMessage(), e); } } } catch (BackingStoreException e) { OpenShiftIOCoreActivator.logError(e.getLocalizedMessage(), e); } if (clusters.isEmpty()) { addCluster(createCluster("OpenShift.io")); } }</code><technical_language>extract this try/catch block #addCluster(cluster, clusterNode, secureClusterNode)</technical_language>

Target:
private void loadModel() { ISecurePreferences secureAccountRoot = getSecureAccountsPreferences(); Preferences accountsRoot = getAccountsPreferences(); try { String[] ids = accountsRoot.childrenNames(); for(String id: ids) { Cluster cluster = new Cluster(this, id); Preferences clusterNode = accountsRoot.node(id); ISecurePreferences secureClusterNode = secureAccountRoot.node(id); addCluster(cluster, clusterNode, secureClusterNode); } } catch (BackingStoreException e) { OpenShiftIOCoreActivator.logError(e.getLocalizedMessage(), e); } if (clusters.isEmpty()) { addCluster(createCluster("OpenShift.io")); } }
Source:
<code>protected float getAssignmentScore(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { if (!replica.isReplicaTopState()) { return 0; } <END> int curTopPartitionCountForResource = node.getAssignedTopStatePartitionsCount(); int estimatedMaxTopStateCount = clusterContext.getEstimatedMaxTopStateCount(); return computeUtilizationScore(estimatedMaxTopStateCount, curTopPartitionCountForResource); <START> }</code><technical_language>smoothing</technical_language>

Target:
protected double getAssignmentScore(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { if (!replica.isReplicaTopState()) { return 0; } int curTopPartitionCountForResource = node.getAssignedTopStatePartitionsCount(); int estimatedMaxTopStateCount = clusterContext.getEstimatedMaxTopStateCount(); return computeUtilizationScore(estimatedMaxTopStateCount, curTopPartitionCountForResource); }
Source:
<code><START> public HashGenerationOptimizer(FunctionManager functionManager) <END> { this.functionManager = functionManager; }</code><technical_language>empty line is needed static non-static variables</technical_language>

Target:
public HashGenerationOptimizer(FunctionManager functionManager) { this.functionManager = requireNonNull(functionManager, "functionManager is null"); }
Source:
<code>public void run() { threadPool = Executors.newCachedThreadPool(); int read = -1; int bufferSize = 0; while (!isInterrupted() || reConnectCounter == -1) { try { if(inputStream == null) { reconnect(); } else { read = inputStream.read(); lastReceiveTime = System.nanoTime(); bufferSize = inputStream.available(); if(read == -1) { <START> logger.info("eBUS read timeout occured, no data on bus ..."); <END> } else { byte receivedByte = (byte)(read & 0xFF); inputBuffer.put(receivedByte); if(receivedByte == EBusTelegram.SYN) { onEBusSyncReceived(bufferSize==0); } } } } catch (IOException e) { logger.error("An IO exception has occured! Try to reconnect eBus connector ...", e); try { reconnect(); } catch (IOException e1) { logger.error(e.toString(), e); } catch (InterruptedException e1) { logger.error(e.toString(), e); } } catch (BufferOverflowException e) { logger.error("eBUS telegram buffer overflow - not enough sync bytes received! Try to adjust eBus adapter."); inputBuffer.clear(); } catch (Exception e) { logger.error(e.toString(), e); inputBuffer.clear(); } } try { disconnect(); } catch (IOException e) { logger.error(e.toString(), e); } if(threadPool != null && !threadPool.isShutdown()) threadPool.shutdown(); }</code><technical_language>please decrease severity debug</technical_language>

Target:
public void run() { threadPool = Executors.newCachedThreadPool(); int read = -1; int bufferSize = 0; while (!isInterrupted() || reConnectCounter == -1) { try { if(inputStream == null) { reconnect(); } else { read = inputStream.read(); lastReceiveTime = System.nanoTime(); bufferSize = inputStream.available(); if(read == -1) { logger.debug("eBUS read timeout occured, no data on bus ..."); } else { byte receivedByte = (byte)(read & 0xFF); inputBuffer.put(receivedByte); if(receivedByte == EBusTelegram.SYN) { onEBusSyncReceived(bufferSize==0); } } } } catch (IOException e) { logger.error("An IO exception has occured! Try to reconnect eBus connector ...", e); try { reconnect(); } catch (IOException e1) { logger.error(e.toString(), e); } catch (InterruptedException e1) { logger.error(e.toString(), e); } } catch (BufferOverflowException e) { logger.error("eBUS telegram buffer overflow - not enough sync bytes received! Try to adjust eBus adapter."); inputBuffer.clear(); } catch (Exception e) { logger.error(e.toString(), e); inputBuffer.clear(); } } try { disconnect(); } catch (IOException e) { logger.error(e.toString(), e); } if(threadPool != null && !threadPool.isShutdown()) threadPool.shutdown(); }
Source:
<code>public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor = m != null ? m : new NullProgressMonitor(); IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); pm.subTask(MessageFormat.format( CoreText.RevertCommitOperation_reverting, Integer.valueOf(commits.size()))); RevertCommand command = new Git(repo).revert(); <START> for (RevCommit commit : commits) { <END> command.include(commit); } try { newHead = command.call(); reverted = command.getRevertedRefs(); result = command.getFailingResult(); } catch (GitAPIException e) { throw new TeamException(e.getLocalizedMessage(), e.getCause()); } pm.worked(1); ProjectUtil.refreshValidProjects( ProjectUtil.getValidOpenProjects(repo), new SubProgressMonitor(pm, 1)); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor = m != null ? m : new NullProgressMonitor(); IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor pm) throws CoreException { pm.beginTask("", 2); pm.subTask(MessageFormat.format( CoreText.RevertCommitOperation_reverting, Integer.valueOf(commits.size()))); RevertCommand command = new Git(repo).revert(); for (RevCommit commit : commits) command.include(commit); try { newHead = command.call(); reverted = command.getRevertedRefs(); result = command.getFailingResult(); } catch (GitAPIException e) { throw new TeamException(e.getLocalizedMessage(), e.getCause()); } pm.worked(1); ProjectUtil.refreshValidProjects( ProjectUtil.getValidOpenProjects(repo), new SubProgressMonitor(pm, 1)); pm.done(); } }; ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); }
Source:
<code>public boolean validateTarget(ClassMetaData clazz) { VariableElement field = clazz.getDeclaredField(sourceField); if (field == null) { Utils.error(String.format( "Field \"%s\", the target of the @LinkedObjects annotation on field \"%s.%s\", does not exist in class \"%s\".", sourceField, targetClass, targetField, sourceClass)); return false; } String fieldType = field.asType().toString(); if (!(targetClass.equals(fieldType) || targetClass.equals(Utils.getRealmListType(field)))) { Utils.error(String.format( "Field \"%s.%s\", the target of the @LinkedObjects annotation on field \"%s.%s\", has type \"%s\" instead of \"%s\".", <START> sourceClass, <END> sourceField, targetClass, targetField, fieldType, targetClass)); return false; } return true; }</code><technical_language>%1$s avoid duplicating sourceField, targetClass etc. example: <LINK_0></technical_language>

Target:
public boolean validateTarget(ClassMetaData clazz) { VariableElement field = clazz.getDeclaredField(sourceField); if (field == null) { Utils.error(String.format( "Field \"%s\", the target of the @LinkedObjects annotation on field \"%s.%s\", does not exist in class \"%s\".", sourceField, targetClass, targetField, sourceClass)); return false; } String fieldType = field.asType().toString(); if (!(targetClass.equals(fieldType) || targetClass.equals(Utils.getRealmListType(field)))) { Utils.error(String.format( "Field \"%s.%s\", the target of the @LinkedObjects annotation on field \"%s.%s\", has type \"%s\" instead of \"%3$s\".", sourceClass, sourceField, targetClass, targetField, fieldType)); return false; } return true; }
Source:
<code>public ContainerVirtualGuestConfiguration(Set<ContainerVirtualGuestConfigurationOption> blockDevices, Set<ContainerVirtualGuestConfigurationOption> datacenters, Set<ContainerVirtualGuestConfigurationOption> memory, Set<ContainerVirtualGuestConfigurationOption> networkComponents, Set<ContainerVirtualGuestConfigurationOption> operatingSystems, Set<ContainerVirtualGuestConfigurationOption> processors) { this.blockDevices = blockDevices; this.datacenters = datacenters; this.memory = memory; this.networkComponents = networkComponents; this.operatingSystems = operatingSystems; <START> this.processors = processors; <END> }</code><technical_language>Add null checks mandatory fields</technical_language>

Target:
public ContainerVirtualGuestConfiguration(Set<ContainerVirtualGuestConfigurationOption> blockDevices, Set<ContainerVirtualGuestConfigurationOption> datacenters, Set<ContainerVirtualGuestConfigurationOption> memory, Set<ContainerVirtualGuestConfigurationOption> networkComponents, Set<ContainerVirtualGuestConfigurationOption> operatingSystems, Set<ContainerVirtualGuestConfigurationOption> processors) { this.blockDevices = checkNotNull(blockDevices, "blockDevices"); this.datacenters = checkNotNull(datacenters, "datacenters"); this.memory = checkNotNull(memory, "memory"); this.networkComponents = checkNotNull(networkComponents, "networkComponents"); this.operatingSystems = checkNotNull(operatingSystems, "operatingSystems"); this.processors = checkNotNull(processors, "processors"); }
Source:
<code><START> private GHRepository resolveRepository() throws ProjectConfigurationException { <END> String repositoryURL; GithubProjectProperty githubProperty = build.getParent().getProperty(GithubProjectProperty.class); if (isNull(githubProperty) || isBlank(githubProperty.getProjectUrlStr())) { throw new ProjectConfigurationException("pullRequest: GitHub repository not configured for build project"); } repositoryURL = githubProperty.getProjectUrlStr(); GitHubRepositoryName repoName = GitHubRepositoryName.create(repositoryURL); if (isNull(repoName)) { throw new ProjectConfigurationException("Invalid URL \"" + repositoryURL + "\" provided as GitHub project"); } GHRepository resolvedRepo = repoName.resolveOne(); if (isNull(resolvedRepo)) { throw new ProjectConfigurationException("No configuration found for GitHub server at \"" + repositoryURL + "\". Check global configuration."); } return resolvedRepo; }</code><technical_language>AFAIR get trigger</technical_language>

Target:
private GHRepository resolveRepository() throws ProjectConfigurationException { try { GitHubPRTrigger trigger = JobInfoHelpers.triggerFrom(run.getParent(), GitHubPRTrigger.class); return trigger.getRemoteRepo(); } catch (Exception e) { throw new ProjectConfigurationException("pullRequest: GitHub repository not configured for project", e); } }
Source:
<code>protected void addParametersToContext(ActionContext ac, Map<String, ?> newParams) { HttpParameters previousParams = ac.getParameters(); HttpParameters.Builder combinedParams = HttpParameters.create(); if (overwrite) { if (previousParams != null) { combinedParams = combinedParams.withParent(previousParams); } if (newParams != null) { combinedParams = combinedParams.withExtraParams(newParams); } } else { if (newParams != null) { HttpParameters newHttpParameters = HttpParameters.create(newParams).build(); combinedParams = combinedParams.withParent(newHttpParameters); } if (previousParams != null) { <START> combinedParams = combinedParams.withParent(previousParams); <END> } } ac.setParameters(combinedParams.build()); }</code><technical_language>@lukaszlenart I for this means for previous params, combinedParams.withParent(previousParams) needs replace combinedParams.withExtraParams(previousParams) extra parameters in newParams in previousParams lost. Please if missing here</technical_language>

Target:
protected void addParametersToContext(ActionContext ac, Map<String, ?> newParams) { HttpParameters previousParams = ac.getParameters(); HttpParameters.Builder combinedParams; if (overwrite) { combinedParams = HttpParameters.create().withParent( previousParams); combinedParams = combinedParams.withExtraParams(newParams); } else { combinedParams = HttpParameters.create(newParams); combinedParams = combinedParams.withExtraParams(previousParams); } ac.setParameters(combinedParams.build()); }