auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<String> getTableNames() throws IOException { try { String nextToken = null; List<String> tableNames = new ArrayList<>(); do { GetTablesRequest tablesRequest = new GetTablesRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withNextToken(nextToken); GetTablesResult tablesResult = mGlueClient.getTables(tablesRequest); tablesResult.getTableList().forEach(table -> tableNames.add(table.getName())); nextToken = tablesResult.getNextToken(); } while (nextToken != null); return tableNames; } catch (EntityNotFoundException e) { <START> throw new IOException("Failed to get glue tables: " + e.getMessage(), e); <END> } }</code><technical_language>add catalog id database name message</technical_language>

Target:
public List<String> getTableNames() throws IOException { try { String nextToken = null; List<String> tableNames = new ArrayList<>(); do { GetTablesRequest tablesRequest = new GetTablesRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withNextToken(nextToken); GetTablesResult tablesResult = mGlueClient.getTables(tablesRequest); tablesResult.getTableList().forEach(table -> tableNames.add(table.getName())); nextToken = tablesResult.getNextToken(); } while (nextToken != null); return tableNames; } catch (EntityNotFoundException e) { throw new IOException("Failed to get glue tables: " + e.getMessage() + " in Database: " + mGlueDbName + "; with Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ".", e); } }
Source:
<code>private HostVO getNuageVspHost(Long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { <START> throw new CloudRuntimeException("Nuage VSD is not configured on physical network " + physicalNetworkId); <END> } return nuageVspHost; }</code><technical_language>Please add identifying Nuage VSP device failed</technical_language>

Target:
private HostVO getNuageVspHost(Long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { throw new CloudRuntimeException("There is no Nuage VSP device configured on physical network " + physicalNetworkId); } return nuageVspHost; }
Source:
<code>public void afterExam() throws Exception { <START> getServiceManager().stopManagedService(registryPid); <END> cswServer.stop(); getServiceManager().stopFeature(true, CATALOG_REGISTRY); getServiceManager().stopFeature(true, CATALOG_REGISTRY_CORE); }</code><technical_language>question in terms of support for null if initialization failed</technical_language>

Target:
public void afterExam() throws Exception { if (registryPid != null) { getServiceManager().stopManagedService(registryPid); } if (cswServer != null) { cswServer.stop(); } getServiceManager().stopFeature(true, CATALOG_REGISTRY); getServiceManager().stopFeature(true, CATALOG_REGISTRY_CORE); }
Source:
<code>protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration lc = super.findLaunchConfiguration(bin, mode); <START> IResource resource = (IResource) ((IAdaptable) bin) <END> .getAdapter(IResource.class); if (resource instanceof IFile) { try { ILaunchConfigurationWorkingCopy wc = lc.getWorkingCopy(); wc.setAttribute( ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, resource.getLocation().toOSString()); wc.doSave(); } catch (CoreException e) { CDebugUIPlugin.log(e); } } return lc; }</code><technical_language>need cast IAdaptable IBinary is IAdaptable</technical_language>

Target:
protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration lc = super.findLaunchConfiguration(bin, mode); IResource resource = (IResource) bin.getAdapter(IResource.class); if (resource instanceof IFile) { try { ILaunchConfigurationWorkingCopy wc = lc.getWorkingCopy(); wc.setAttribute( ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, resource.getLocation().toOSString()); wc.doSave(); } catch (CoreException e) { CDebugUIPlugin.log(e); } } return lc; }
Source:
<code>protected RecordSupplier<Integer, Long> setupRecordSupplier() { final Map<String, Object> consumerConfigs = new HashMap<>(); consumerConfigs.put("metadata.max.age.ms", "1"); consumerConfigs.put("group.id", StringUtils.format("kafka-supervisor-%s", RandomIdUtils.getRandomId())); consumerConfigs.put("auto.offset.reset", "none"); consumerConfigs.put("enable.auto.commit", "false"); consumerConfigs.put("isolation.level", "read_committed"); final Properties props = new Properties(); consumerProperties.get("key.deserializer"); <START> System.out.println("consumerProperties"); consumerProperties.forEach((key, value) -> System.out.println(key + ":" + value)); <END> KafkaRecordSupplier.addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.putAll(consumerConfigs); Deserializer keyDeserializerObject = getKafkaDeserializer(props, "key.deserializer"); Deserializer valueDeserializerObject = getKafkaDeserializer(props, "value.deserializer"); return new KafkaRecordSupplier( consumerProperties, sortingMapper, new KafkaConsumer<>(props, keyDeserializerObject, valueDeserializerObject) ); }</code><technical_language>Is this for debugging</technical_language>

Target:
protected RecordSupplier<Integer, Long> setupRecordSupplier() { final Map<String, Object> consumerConfigs = KafkaConsumerConfigs.getConsumerProperties(); consumerConfigs.put("metadata.max.age.ms", "1"); final Properties props = new Properties(); KafkaRecordSupplier.addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.putAll(consumerConfigs); Deserializer keyDeserializerObject = new ByteArrayDeserializer(); Deserializer valueDeserializerObject = new ByteArrayDeserializer(); return new KafkaRecordSupplier( consumerProperties, sortingMapper, new KafkaConsumer<>(props, keyDeserializerObject, valueDeserializerObject) ); }
Source:
<code>public static void afterClass() throws Exception { try { operations.removeIfExists(SINGLETON_POLICY_ADDRESS); operations.removeIfExists(SINGLETON_POLICY_EDIT_ADDRESS); SingletonSubsystemOperations.withOperations(operations).removeCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); <START> socketBindingResources.close(); <END> administration.reloadIfRequired(); } finally { client.close(); } }</code><technical_language>in some finally block, removeCacheContainer throw exception</technical_language>

Target:
public static void afterClass() throws Exception { try { operations.removeIfExists(SINGLETON_POLICY_ADDRESS); operations.removeIfExists(SINGLETON_POLICY_EDIT_ADDRESS); singletonOperations.removeCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); socketBindingResources.clean(); administration.reloadIfRequired(); } finally { client.close(); } }
Source:
<code>public void organizeImports(EditorPartPresenter editor) { this.editor = editor; this.document = ((TextEditor) editor).getDocument(); this.file = editor.getEditorInput().getFile(); if (file instanceof Resource) { final Optional<Resource> srcFolder = ((Resource) file).getParentWithMarker(SourceFolderMarker.ID); if (!srcFolder.isPresent()) { return; } clientServerEventService .sendFileTrackingSuspendEvent() .then( arg -> { <START> doOrganizeImports(file.getLocation().toString()); <END> }); } }</code><technical_language>Assuming workspace files, this work</technical_language>

Target:
public void organizeImports(EditorPartPresenter editor) { this.editor = editor; this.file = editor.getEditorInput().getFile(); if (file instanceof Resource) { final Optional<Resource> srcFolder = ((Resource) file).getParentWithMarker(SourceFolderMarker.ID); if (!srcFolder.isPresent()) { return; } clientServerEventService .sendFileTrackingSuspendEvent() .then( success -> { doOrganizeImports(file.getLocation().toString()); }); } }
Source:
<code>void persistentBackupFile(String filename, Map<String, Map<String, Long>> usage) throws IOException { if (filename == null || filename.isEmpty() || !filenamePattern.matcher(filename).matches()) { throw new IllegalArgumentException("Invalid filename :" + filename); } if (usage == null) { throw new IllegalArgumentException("Invalid usage map"); } if (backupFiles.contains(filename)) { return; } <START> logger.trace("Persist container usage for " + filename); <END> String tempFileName = filename + TEMP_FILE_SUFFIX; Path tempFilePath = backupDirPath.resolve(tempFileName); Path filePath = backupDirPath.resolve(filename); try (FileChannel channel = FileChannel.open(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { String usageMapInJson = objectMapper.writeValueAsString(usage); channel.write(ByteBuffer.wrap(usageMapInJson.getBytes(StandardCharsets.UTF_8))); Files.move(tempFilePath, filePath); } catch (Exception e) { logger.error("Failed to serialize and persist usage map to file {}", filePath, e); throw e; } backupFiles.add(filename); }</code><technical_language>nit: some remaining string concats in this class</technical_language>

Target:
void persistentBackupFile(String filename, Map<String, Map<String, Long>> usage) throws IOException { if (filename == null || filename.isEmpty() || !filenamePattern.matcher(filename).matches()) { throw new IllegalArgumentException("Invalid filename :" + filename); } if (usage == null) { throw new IllegalArgumentException("Invalid usage map"); } if (backupFiles.contains(filename)) { return; } logger.trace("Persist container usage for {}", filename); String tempFileName = filename + TEMP_FILE_SUFFIX; Path tempFilePath = backupDirPath.resolve(tempFileName); Path filePath = backupDirPath.resolve(filename); try (FileChannel channel = FileChannel.open(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { String usageMapInJson = objectMapper.writeValueAsString(usage); channel.write(ByteBuffer.wrap(usageMapInJson.getBytes(StandardCharsets.UTF_8))); Files.move(tempFilePath, filePath); } catch (Exception e) { logger.error("Failed to serialize and persist usage map to file {}", filePath, e); throw e; } backupFiles.add(filename); }
Source:
<code>public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<Serializable> query, QueryParameters queryParameters, TupleContext tupleContext) { List<String> queryHints = queryParameters.getQueryHints(); if ( queryHints.isEmpty() ) { <START> throw new HibernateException( "The query must have a hints!" ); <END> } else { if ( !queryHints.contains( DIALECT_SPECIFIED_HINT ) ) { throw new HibernateException( "The query not contains required hint! The query must contains hint \"" + DIALECT_SPECIFIED_HINT + "\"!" ); } } Tuple tuple = new Tuple(); tuple.put( "id", UUID.randomUUID().toString() ); tuple.put( "frequency", 1.0d ); return CollectionHelper.newClosableIterator( Collections.singletonList( tuple ) ); }</code><technical_language>"The query hint!"</technical_language>

Target:
public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<Serializable> query, QueryParameters queryParameters, TupleContext tupleContext) { List<String> queryHints = queryParameters.getQueryHints(); if ( queryHints.isEmpty() ) { throw new HibernateException( "The query must have at least one hint!" ); } else { if ( !queryHints.contains( DIALECT_SPECIFIED_HINT ) ) { throw new HibernateException( "The query does not contain the required hint \"" + DIALECT_SPECIFIED_HINT + "\"!" ); } } Tuple tuple = new Tuple(); tuple.put( "id", UUID.randomUUID().toString() ); tuple.put( "frequency", 1.0d ); return CollectionHelper.newClosableIterator( Collections.singletonList( tuple ) ); }
Source:
<code>public Set<String> getFreeVariables() { Set<String> freeVars = body.getFreeVariables(); <START> freeVars.remove(this.getName()); <END> for (FormalArg farg : formalArgs) { freeVars.remove(farg.getName()); } return freeVars; }</code><technical_language>name of definition is bound in body --- level of Core IL, recursive calls of form "this.mymethod(...)" "mymethod(...)" [there is a sugar this work source level in translation core]</technical_language>

Target:
public Set<String> getFreeVariables() { Set<String> freeVars = body.getFreeVariables(); for (FormalArg farg : formalArgs) { freeVars.remove(farg.getName()); } return freeVars; }
Source:
<code>private void testAutoCompleteUpstreamProjectName( String expectedValues, String value, AbstractProject project, DownstreamBuildSelector.DescriptorImpl d) { assertArrayEquals(expectedValues, d.doAutoCompleteUpstreamProjectName(value, project).getValues().toArray()); <START> assertArrayEquals(expectedValues, d.doAutoCompleteUpstreamProjectName(value, null).getValues().toArray()); <END> }</code><technical_language>sort list wrap Set. AutoCompleteCandidates ensure order of values (strange behavior!)</technical_language>

Target:
private void testAutoCompleteUpstreamProjectName( String expectedValues, String value, AbstractProject project, DownstreamBuildSelector.DescriptorImpl d) { Set<String> actualValues = new TreeSet<String>(d.doAutoCompleteUpstreamProjectName(value, project).getValues()); assertArrayEquals(expectedValues, actualValues.toArray(new String [actualValues.size()])); actualValues = new TreeSet<String>(d.doAutoCompleteUpstreamProjectName(value, null).getValues()); assertArrayEquals(new String[] {}, actualValues.toArray(new String [actualValues.size()])); }
Source:
<code>private void verifyStringParameterQueryInvocations() { Map<String, String> stringQueryParameters = getCompleteStringQueryParameters(); verify(mockedQuery).activityInstanceId(stringQueryParameters.get("activityInstanceId")); verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); verify(mockedQuery).executionId(stringQueryParameters.get("executionId")); verify(mockedQuery).activityId(stringQueryParameters.get("activityId")); verify(mockedQuery).activityName(stringQueryParameters.get("activityName")); <START> verify(mockedQuery).activityName(stringQueryParameters.get("activityNameLike")); <END> verify(mockedQuery).activityType(stringQueryParameters.get("activityType")); verify(mockedQuery).taskAssignee(stringQueryParameters.get("taskAssignee")); verify(mockedQuery).list(); }</code><technical_language>suggestion verify(mockedQuery).activityNameLike(stringQueryParameters.get("activityNameLike"));</technical_language>

Target:
private void verifyStringParameterQueryInvocations() { Map<String, String> stringQueryParameters = getCompleteStringQueryParameters(); verify(mockedQuery).activityInstanceId(stringQueryParameters.get("activityInstanceId")); verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); verify(mockedQuery).executionId(stringQueryParameters.get("executionId")); verify(mockedQuery).activityId(stringQueryParameters.get("activityId")); verify(mockedQuery).activityName(stringQueryParameters.get("activityName")); verify(mockedQuery).activityNameLike(stringQueryParameters.get("activityNameLike")); verify(mockedQuery).activityType(stringQueryParameters.get("activityType")); verify(mockedQuery).taskAssignee(stringQueryParameters.get("taskAssignee")); verify(mockedQuery).list(); }
Source:
<code>private void recvWants() throws IOException { boolean isFirst = true; for (;;) { String line; try { line = pckIn.readString(); } catch (EOFException eof) { if (isFirst) break; throw eof; } if (line == PacketLineIn.END) break; if (line.startsWith("deepen ")) { depth = Integer.parseInt(line.substring(7)); if (depth <= 0) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidDepth, Integer.valueOf(depth))); } continue; } if (line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8))); continue; } if (line.startsWith(OPTION_BLOB_MAX_BYTES + " ")) { blobMaxBytes = <START> Long.parseLong(line.substring(OPTION_BLOB_MAX_BYTES.length() <END> + 1)); continue; } if (!line.startsWith("want ") || line.length() < 45) throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); if (isFirst) { if (line.length() > 45) { FirstLine firstLine = new FirstLine(line); options = firstLine.getOptions(); line = firstLine.getLine(); } else options = Collections.emptySet(); } wantIds.add(ObjectId.fromString(line.substring(5))); isFirst = false; } }</code><technical_language>catch NumberFormatException throw PackProtocolException in case</technical_language>

Target:
private void recvWants() throws IOException { boolean isFirst = true; for (;;) { String line; try { line = pckIn.readString(); } catch (EOFException eof) { if (isFirst) break; throw eof; } if (line == PacketLineIn.END) break; if (line.startsWith("deepen ")) { depth = Integer.parseInt(line.substring(7)); if (depth <= 0) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidDepth, Integer.valueOf(depth))); } continue; } if (line.startsWith("shallow ")) { clientShallowCommits.add(ObjectId.fromString(line.substring(8))); continue; } if (line.startsWith(OPTION_BLOB_MAX_BYTES + " ")) { String arg = line.substring(OPTION_BLOB_MAX_BYTES.length() + 1); try { blobMaxBytes = Long.parseLong(arg); } catch (NumberFormatException e) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidBlobMaxBytes, arg)); } if (blobMaxBytes < 0) { throw new PackProtocolException( MessageFormat.format(JGitText.get().invalidBlobMaxBytes, arg)); } continue; } if (!line.startsWith("want ") || line.length() < 45) throw new PackProtocolException(MessageFormat.format(JGitText.get().expectedGot, "want", line)); if (isFirst) { if (line.length() > 45) { FirstLine firstLine = new FirstLine(line); options = firstLine.getOptions(); line = firstLine.getLine(); } else options = Collections.emptySet(); } wantIds.add(ObjectId.fromString(line.substring(5))); isFirst = false; } }
Source:
<code>public String getCurrentTaskTitles(ProcessDTO processDTO) { try { return ServiceManager.getProcessService().createProgressTooltip(processDTO); } catch (DAOException e) { <START> Helper.setErrorMessage("Unable to retrieve process with process ID " + processDTO.getId()); <END> return ""; } }</code><technical_language>Error message inserted translations: Helper.setErrorMessage(ERROR_LOADING_ONE, new Object[] {ObjectType.PROCESS.getTranslationSingular(), id }, logger, e);</technical_language>

Target:
public String getCurrentTaskTitles(ProcessDTO processDTO) { try { return ServiceManager.getProcessService().createProgressTooltip(processDTO); } catch (DAOException e) { Helper.setErrorMessage(ERROR_LOADING_ONE, new Object[] {ObjectType.PROCESS.getTranslationSingular(), processDTO.getId()}); return ""; } }
Source:
<code>public ValidationResult notManagementNetwork() { <START> String managementNetwork = Config.<String> GetValue(ConfigValues.ManagementNetwork); <END> return managementNetwork.equalsIgnoreCase(network.getName()) ? new ValidationResult(VdcBllMessages.NETWORK_CAN_NOT_REMOVE_DEFAULT_NETWORK) : ValidationResult.VALID; }</code><technical_language>If this patch pushed: <LINK_0> NetworkHelper.managementNetwork method save a couple repeating lines :)</technical_language>

Target:
public ValidationResult notManagementNetwork() { return NetworkUtils.isManagementNetwork(network) ? new ValidationResult(VdcBllMessages.NETWORK_CAN_NOT_REMOVE_DEFAULT_NETWORK) : ValidationResult.VALID; }
Source:
<code>private boolean needsClosing(Type type) { if (type.isSubtypeOf(STREAM_TOP_HIERARCHY)) { return false; } for (String ignoredTypes : IGNORED_CLOSEABLE_SUBTYPES) { if (type.isSubtypeOf(ignoredTypes)) { return false; } } <START> for (String excludedType : excludedTypesList) { <END> if (type.is(excludedType)) { return false; } } return isCloseable(type); }</code><technical_language>If list is static, remove static modifier everywhere. However, I prefer a dedicated getter lazily loading configuration of excluded types</technical_language>

Target:
private boolean needsClosing(Type type) { if (type.isSubtypeOf(STREAM_TOP_HIERARCHY)) { return false; } for (String ignoredTypes : IGNORED_CLOSEABLE_SUBTYPES) { if (type.isSubtypeOf(ignoredTypes)) { return false; } } for (String excludedType : loadExcludedTypesList()) { if (type.is(excludedType)) { return false; } } return isCloseable(type); }
Source:
<code>public List<StudyEntryDto> createStudyEntries(final Integer studyId, final Integer germplasmListId) { final GermplasmList germplasmList = this.germplasmListService.getGermplasmList(germplasmListId); this.germplasmListValidator.validateGermplasmList(germplasmListId); this.studyEntryValidator.validateStudyAlreadyHasStudyEntries(studyId); this.studyValidator.validate(studyId, true); final ModelMapper mapper = StudyEntryMapper.getInstance(); final List<StudyEntryDto> studyEntryDtoList = germplasmList.getListData().stream().map(l -> mapper.map(l, StudyEntryDto.class)).collect(Collectors.toList()); final Map<Integer, GermplasmListData> germplasmListDataMap = <START> germplasmList.getListData().stream().collect(Collectors.toMap(GermplasmListData::getGermplasmId, g -> g, (g1, g2) -> g1)); <END> final List<Integer> germplasmDescriptorIds = this.getEntryDescriptorColumns(studyId).stream() .map(measurementVariable -> measurementVariable.getTermId()).collect(Collectors.toList()); for(final StudyEntryDto studyEntryDto: studyEntryDtoList) { studyEntryDto.setProperties( StudyEntryPropertiesMapper.map(germplasmListDataMap.get(studyEntryDto.getGid()), germplasmDescriptorIds)); } return this.middlewareStudyEntryService.saveStudyEntries(studyId, studyEntryDtoList); }</code><technical_language>if GID map key duplicate GIDs a list. I entry number (entry ID) key. do @mderamos</technical_language>

Target:
public List<StudyEntryDto> createStudyEntries(final Integer studyId, final Integer germplasmListId) { final GermplasmList germplasmList = this.germplasmListService.getGermplasmList(germplasmListId); this.germplasmListValidator.validateGermplasmList(germplasmListId); this.studyEntryValidator.validateStudyAlreadyHasStudyEntries(studyId); this.studyValidator.validate(studyId, true); final ModelMapper mapper = StudyEntryMapper.getInstance(); final List<StudyEntryDto> studyEntryDtoList = germplasmList.getListData().stream().map(l -> mapper.map(l, StudyEntryDto.class)).collect(Collectors.toList()); final Map<Integer, GermplasmListData> germplasmListDataMap = germplasmList.getListData().stream().collect(Collectors.toMap(GermplasmListData::getEntryId, g -> g)); final List<Integer> germplasmDescriptorIds = this.getEntryDescriptorColumns(studyId).stream() .map(measurementVariable -> measurementVariable.getTermId()).collect(Collectors.toList()); for(final StudyEntryDto studyEntryDto: studyEntryDtoList) { studyEntryDto.setProperties( StudyEntryPropertiesMapper.map(germplasmListDataMap.get(studyEntryDto.getEntryId()), germplasmDescriptorIds)); } return this.middlewareStudyEntryService.saveStudyEntries(studyId, studyEntryDtoList); }
Source:
<code>public TradeOffer.Builder secondBuyingItem(final ItemStack item) { <START> Preconditions.checkNotNull(item, "Second buying item cannot be null"); <END> this.secondItem = item.createSnapshot(); return this; }</code><technical_language>item null? I thought allowed null implicitly</technical_language>

Target:
public TradeOffer.Builder secondBuyingItem(final ItemStack item) { this.secondItem = item != null ? item.createSnapshot() : ItemStackSnapshot.empty(); return this; }
Source:
<code>CloseDriverCommand(WebDriver webDriver, SelenideProxyServer selenideProxyServer) { this.webDriver = webDriver; this.selenideProxyServer = selenideProxyServer; <START> this.closeBrowserTimeoutMs = 5000; <END> }</code><technical_language>I suggest remove this field all. is need limit lifetime of CloseDriverCommand. work long takes</technical_language>

Target:
CloseDriverCommand(WebDriver webDriver, SelenideProxyServer selenideProxyServer) { this.webDriver = webDriver; this.selenideProxyServer = selenideProxyServer; }
Source:
<code>private AddBacklogMessage getAddBacklogMessage() { int backlog = subpartitionView.getAndResetUnannouncedBacklog(); if (backlog > 0) { return new AddBacklogMessage(receiverId, backlog, false); <START> } <END> return null; }</code><technical_language>I guess expect null return here. long code path enters getAddBacklogMessage, guarantee respective backlog more 0. add assert backlog instead</technical_language>

Target:
private AddBacklogMessage getAddBacklogMessage() { int backlog = subpartitionView.getAndResetUnannouncedBacklog(); if (backlog > 0) { return new AddBacklogMessage(receiverId, backlog); } return null; }
Source:
<code>public void checkMainTools() { <START> int sectionInsertTools = 17; <END> for (int i = 1; i < sectionInsertTools; i++) { clearSource(); clickMore(); String content = driver.findElement( By.xpath(" .getText(); driver.findElement( By.xpath(" .click(); waitForElementNotVisibleByElement(editorModal); waitForElementNotVisibleByElement(focusedMode); checkSourceContent(content); } }</code><technical_language>This name (for 21 65) unclear..</technical_language>

Target:
public void checkMainTools() { int wikitextShortcutsInsertSection = 17; for (int i = 1; i < wikitextShortcutsInsertSection; i++) { clearSource(); clickMore(); String content = driver.findElement( By.xpath(" .getText(); driver.findElement( By.xpath(" .click(); waitForElementNotVisibleByElement(editorModal); waitForElementNotVisibleByElement(focusedMode); checkSourceContent(content); } }
Source:
<code>public boolean equals(Object obj) { if(obj instanceof EnumValue) { return enumIdentifier.equals(((EnumValue) obj).enumIdentifier); } <START> return getValue().equals(obj); <END> }</code><technical_language>this comparison is sufficient. need of EnumTypeValue</technical_language>

Target:
public boolean equals(Object obj) { if(obj instanceof EnumValue) { EnumValue otherEnum = (EnumValue) obj; if(type.equals(otherEnum.type) && identifier.equals(otherEnum.identifier)) { return true; } } return getValue().equals(obj); }
Source:
<code>public File build() { File tmpFile = serializeRateMeterDefinitions(); <START> File configFile = new File("/tmp/ratemeters.json"); <END> try { deleteFileIfExists(configFile); renameFile(tmpFile, configFile); } catch (IOException ex) { throw new IllegalStateException(format("Could not create config file %s.", configFile.getAbsolutePath()), ex); } return configFile; }</code><technical_language>this is right supposed work *nix</technical_language>

Target:
public File build() { File tmpFile = serializeRateMeterDefinitions(); File configFile = Paths.get(getProperty("java.io.tmpdir"), "ratemeters.json").toFile(); try { deleteFileIfExists(configFile); renameFile(tmpFile, configFile); } catch (IOException ex) { throw new IllegalStateException(format("Could not create config file %s.", configFile.getAbsolutePath()), ex); } return configFile; }
Source:
<code>public SortedSet<String> getDependenciesAndSelf() { List<String> affectedCodeSystems = CoreTerminologyBroker.getInstance().getAffectedCodeSystemsForTeminology(terminologyComponentId); affectedCodeSystems.add(shortName); <START> return new TreeSet<String>(affectedCodeSystems); <END> }</code><technical_language>great return immutable SortedSet</technical_language>

Target:
public SortedSet<String> getDependenciesAndSelf() { ImmutableSortedSet.Builder<String> affectedCodeSystems = ImmutableSortedSet.naturalOrder(); affectedCodeSystems.addAll(CoreTerminologyBroker.getInstance().getAffectedCodeSystemsForTeminology(terminologyComponentId)); affectedCodeSystems.add(shortName); return affectedCodeSystems.build(); }
Source:
<code>public static String getFirstSelectedChineseVariant() { <START> if (FIRST_SELECTED_ZH_LANG_CODE == null) { <END> for (String langCode : WikipediaApp.getInstance().language().getAppLanguageCodes()) { if (langCode.startsWith(AppLanguageLookUpTable.CHINESE_LANGUAGE_CODE)) { FIRST_SELECTED_ZH_LANG_CODE = langCode; break; } } FIRST_SELECTED_ZH_LANG_CODE = StringUtils.defaultString(FIRST_SELECTED_ZH_LANG_CODE, AppLanguageLookUpTable.TRADITIONAL_CHINESE_LANGUAGE_CODE); } return FIRST_SELECTED_ZH_LANG_CODE; }</code><technical_language>if user changes selected Chinese variant while app is running? Is this expensive needs cached</technical_language>

Target:
public static String getFirstSelectedChineseVariant() { String firstSelectedChineseLangCode = null; for (String langCode : WikipediaApp.getInstance().language().getAppLanguageCodes()) { if (langCode.startsWith(AppLanguageLookUpTable.CHINESE_LANGUAGE_CODE)) { firstSelectedChineseLangCode = langCode; break; } } return StringUtils.defaultString(firstSelectedChineseLangCode, AppLanguageLookUpTable.TRADITIONAL_CHINESE_LANGUAGE_CODE); }
Source:
<code>public static String setFeedACL(String feed, String... ownerGroup) { FeedMerlin feedObject = null; try { feedObject = new FeedMerlin(feed); } catch (JAXBException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } ACL acl = feedObject.getACL(); if(ownerGroup.length > 0) { aclOwner = ownerGroup[0]; if (ownerGroup.length == 2) aclGroup = ownerGroup[1]; } acl.setOwner(aclOwner); acl.setGroup(aclGroup); <START> feedObject.setACL(acl); <END> return feedObject.toString(); }</code><technical_language>In current form this lead unpredictable behavior. give example, suppose tests: TestA TestB. Consider this order of execution: - TestA calls this setFeedACL(feed, "a" , "b") - mytest - TestB calls this setFeedACL(feed) In this case mytest aclOwner = "a", aclGroup = "b". consider another order of execution, - TestB calls this setFeedACL(feed) - mytest - TestA calls this setFeedACL(feed, "a" , "b") In this case mytest aclOwner = {value Merlin.properties}, aclGroup = {value Merlin.properties} Hence, mytest sees depends order of test execution</technical_language>

Target:
public static String setFeedACL(String feed, String... ownerGroup) { FeedMerlin feedObject = null; try { feedObject = new FeedMerlin(feed); } catch (JAXBException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } ACL acl = feedObject.getACL(); acl.setOwner(MerlinConstants.aclOwner); acl.setGroup(MerlinConstants.aclGroup); if(ownerGroup.length > 0) { acl.setOwner(ownerGroup[0]); if (ownerGroup.length == 2) acl.setGroup(ownerGroup[1]); } feedObject.setACL(acl); return feedObject.toString(); }
Source:
<code>public void convertGroupsToRichGroupsWithAttributesWithListOfNamesTest() throws Exception { <START> System.out.println("groupsManagerBl.convertGroupsToRichGroupsWithAttributes"); <END> vo = setUpVo(); attributesList = setUpGroupAttributes(); this.groupsManager.createGroup(sess, vo, group); attributesManager.setAttributes(sess, group, attributesList); this.groupsManager.createGroup(sess, vo, group2); attributesManager.setAttributes(sess, group2, attributesList); List<String> attrNames = new ArrayList<>(); RichGroup richGroup1 = new RichGroup(group, attributesList); RichGroup richGroup2 = new RichGroup(group2, attributesList); for (Attribute a : attributesList) { attrNames.add(a.getName()); } assertEquals("Both lists should be same", Arrays.asList(richGroup1, richGroup2), groupsManagerBl.convertGroupsToRichGroupsWithAttributes(sess, Arrays.asList(group, group2), attrNames)); }</code><technical_language>is name name of test</technical_language>

Target:
public void convertGroupsToRichGroupsWithAttributesWithListOfNamesTest() throws Exception { System.out.println("groupsManagerBl.convertGroupsToRichGroupsWithAttributesWithListOfNamesTest"); vo = setUpVo(); attributesList = setUpGroupAttributes(); this.groupsManager.createGroup(sess, vo, group); attributesManager.setAttributes(sess, group, attributesList); this.groupsManager.createGroup(sess, vo, group2); attributesManager.setAttributes(sess, group2, attributesList); List<String> attrNames = new ArrayList<>(); RichGroup richGroup1 = new RichGroup(group, attributesList); RichGroup richGroup2 = new RichGroup(group2, attributesList); for (Attribute a : attributesList) { attrNames.add(a.getName()); } assertEquals("Both lists should be same", Arrays.asList(richGroup1, richGroup2), groupsManagerBl.convertGroupsToRichGroupsWithAttributes(sess, Arrays.asList(group, group2), attrNames)); }
Source:
<code>private List<VariantEntity> findByComplexFiltersHelper(Query query, List<VariantEntityRepositoryFilter> filters, List<String> exclude, Pageable pageable) { if (filters.size() > 0){ List<Criteria> criteriaList = getFiltersCriteria(filters); for (Criteria criteria : criteriaList) { query.addCriteria(criteria); } <START> } <END> ArrayList<String> sortProperties = new ArrayList<String>(); sortProperties.add("chr"); sortProperties.add("start"); query.with(new Sort(Sort.Direction.ASC, sortProperties)); Pageable pageable1 = (pageable != null) ? pageable : new PageRequest(0, 10); query.with(pageable1); if (exclude != null && !exclude.isEmpty()) { exclude.forEach(e -> query.fields().exclude(e)); } return mongoTemplate.find(query, VariantEntity.class); }</code><technical_language>This block is part of building query. this encapsulated in another method</technical_language>

Target:
private List<VariantEntity> findByComplexFiltersHelper(Query query, List<VariantEntityRepositoryFilter> filters, List<String> exclude, Pageable pageable) { addFilterCriteriaToQuery(query, filters); ArrayList<String> sortProperties = new ArrayList<String>(); sortProperties.add("chr"); sortProperties.add("start"); query.with(new Sort(Sort.Direction.ASC, sortProperties)); Pageable pageable1 = (pageable != null) ? pageable : new PageRequest(0, 10); query.with(pageable1); if (exclude != null && !exclude.isEmpty()) { exclude.forEach(e -> query.fields().exclude(e)); } return mongoTemplate.find(query, VariantEntity.class); }
Source:
<code>protected void ExecuteVmCommand() { <START> lockVmWithCompensationIfNeeded(); <END> if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; boolean hasAsyncTasks = false; if (getImagesList().size() > 0) { for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (!returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } hasAsyncTasks = !getTaskIdList().isEmpty(); } removeSnapshotsFromDB(); if (hasAsyncTasks) { deleteOrphanedImages(); } else { EndVmCommand(); } setSucceeded(succeeded); }</code><technical_language>need lock VM if disks</technical_language>

Target:
protected void ExecuteVmCommand() { lockVmWithCompensationIfNeeded(); if (!isInternalExecution()) { freeLock(); } restoreSnapshotAndRemoveObsoleteSnapshots(); boolean succeeded = true; boolean hasAsyncTasks = false; if (getImagesList().size() > 0) { for (DiskImage image : getImagesList()) { if (image.getimageStatus() != ImageStatus.ILLEGAL) { ImagesContainterParametersBase params = new RestoreFromSnapshotParameters(image.getImageId(), getVmId(), targetSnapshot, removedSnapshotId); VdcReturnValueBase returnValue = runAsyncTask(VdcActionType.RestoreFromSnapshot, params); if (!returnValue.getSucceeded()) { succeeded = false; getReturnValue().setFault(returnValue.getFault()); } } } hasAsyncTasks = !getTaskIdList().isEmpty(); } removeSnapshotsFromDB(); if (hasAsyncTasks) { deleteOrphanedImages(); } else { endActionOnVmConfiguration(); } setSucceeded(succeeded); }
Source:
<code>private void initDBMaps(boolean firstAttempt) { close(); try { recordManager = createRecordManager(storeFile.getCanonicalPath()); persistedJobsLicenses = recordManager.hashMap(JOBS_LICENSES); persistedTasksLicenses = recordManager.hashMap(TASKS_LICENSES); remainingTokens = recordManager.hashMap(REMAINING_TOKENS); recordManager.commit(); if (!firstAttempt) { logger.info("Loading of job database successful after clean."); } <START> } catch (Throwable e) { <END> if (firstAttempt) { logger.error("Error occurred when loading the database " + storeFile.getAbsolutePath() + ", now cleaning it and retrying.", e); cleanDataBase(); initDBMaps(false); } else { close(); throw new IllegalStateException("Error when loading database (even after cleaning it): " + storeFile.getAbsolutePath(), e); } } }</code><technical_language>suggestion } catch (Exception e) {</technical_language>

Target:
private void initDBMaps(boolean firstAttempt) { close(); try { recordManager = createRecordManager(storeFile.getCanonicalPath()); persistedJobsLicenses = recordManager.hashMap(JOBS_LICENSES); persistedTasksLicenses = recordManager.hashMap(TASKS_LICENSES); remainingTokens = recordManager.hashMap(REMAINING_TOKENS); recordManager.commit(); if (!firstAttempt) { logger.info("Loading of job database successful after clean."); } } catch (Exception e) { if (firstAttempt) { logger.error("Error occurred when loading the database " + storeFile.getAbsolutePath() + ", now cleaning it and retrying.", e); cleanDataBase(); initDBMaps(false); } else { close(); throw new IllegalStateException("Error when loading database (even after cleaning it): " + storeFile.getAbsolutePath(), e); } } }
Source:
<code>public void testCancellationWhileWaitingOnRule() throws Exception { final Semaphore mainThreadSemaphore = new Semaphore(0); final Semaphore lockSemaphore = new Semaphore(0); final PathRule rule = new PathRule("testBeginRuleNoEnd"); final NullProgressMonitor rootMonitor = new NullProgressMonitor(); IProgressMonitor nestedMonitor = SubMonitor.convert(rootMonitor); nestedMonitor.setCanceled(false); Job job = Job.create("", monitor -> { mainThreadSemaphore.release(); try { lockSemaphore.acquire(); } catch (InterruptedException e) { } }); job.setRule(rule); job.schedule(); mainThreadSemaphore.acquire(); Job cancellationJob = Job.create("", monitor -> { rootMonitor.setCanceled(true); }); cancellationJob.schedule(100); boolean canceledExceptionThrown = false; try { manager.beginRule(rule, nestedMonitor); } catch (OperationCanceledException e) { canceledExceptionThrown = true; } <START> manager.endRule(rule); <END> lockSemaphore.release(); boolean interrupted = Thread.interrupted(); assertTrue("An OperationCancelledException was thrown", canceledExceptionThrown); assertFalse("The thread was not interrupted", interrupted); }</code><technical_language>endRule supposed a finally block</technical_language>

Target:
public void testCancellationWhileWaitingOnRule() throws Exception { final Semaphore mainThreadSemaphore = new Semaphore(0); final Semaphore lockSemaphore = new Semaphore(0); final PathRule rule = new PathRule("testBeginRuleNoEnd"); final NullProgressMonitor rootMonitor = new NullProgressMonitor(); IProgressMonitor nestedMonitor = SubMonitor.convert(rootMonitor); nestedMonitor.setCanceled(false); Job job = Job.create("", monitor -> { mainThreadSemaphore.release(); try { lockSemaphore.acquire(); } catch (InterruptedException e) { } }); job.setRule(rule); job.schedule(); mainThreadSemaphore.acquire(); Job cancellationJob = Job.create("", monitor -> { rootMonitor.setCanceled(true); }); cancellationJob.schedule(100); boolean canceledExceptionThrown = false; try { manager.beginRule(rule, nestedMonitor); } catch (OperationCanceledException e) { canceledExceptionThrown = true; } finally { manager.endRule(rule); } lockSemaphore.release(); boolean interrupted = Thread.interrupted(); assertTrue("An OperationCancelledException should have been thrown", canceledExceptionThrown); assertFalse("The THread.interrupted() state leaked", interrupted); }
Source:
<code>protected boolean authenticate(String realmName, String username, char[] password) throws HttpAuthenticationException { RealmCallback realmCallback = realmName != null ? new RealmCallback("User realm", realmName) : null; NameCallback nameCallback = new NameCallback("Remote Authentication Name", username); nameCallback.setName(username); final PasswordGuessEvidence evidence = new PasswordGuessEvidence(password); EvidenceVerifyCallback evidenceVerifyCallback = new EvidenceVerifyCallback(evidence); if (log.isDebugEnabled()) { <START> log.debug("Using UsernamePasswordAuthenticationMechanism for username authentication..."); <END> log.debugf("Realm => %s", realmName); log.debugf("Username => %s", username); } try { final Callback[] callbacks; if (realmCallback != null) { callbacks = new Callback[] { realmCallback, nameCallback, evidenceVerifyCallback }; } else { callbacks = new Callback[] { nameCallback, evidenceVerifyCallback }; } callbackHandler.handle(callbacks); return evidenceVerifyCallback.isVerified(); } catch (UnsupportedCallbackException e) { return false; } catch (IOException e) { throw new HttpAuthenticationException(e); } finally { evidence.destroy(); } }</code><technical_language>I suggest for logging this logging messages a single log.debugf contains additional parameters in one. In a server heavy load related messages split log file - elthough options pull is need rely them</technical_language>

Target:
protected boolean authenticate(String realmName, String username, char[] password) throws HttpAuthenticationException { RealmCallback realmCallback = realmName != null ? new RealmCallback("User realm", realmName) : null; NameCallback nameCallback = new NameCallback("Remote Authentication Name", username); nameCallback.setName(username); final PasswordGuessEvidence evidence = new PasswordGuessEvidence(password); EvidenceVerifyCallback evidenceVerifyCallback = new EvidenceVerifyCallback(evidence); log.debugf("Using UsernamePasswordAuthenticationMechanism for username authentication. Realm: [%s], Username: [%s].", realmName, username); try { final Callback[] callbacks; if (realmCallback != null) { callbacks = new Callback[] { realmCallback, nameCallback, evidenceVerifyCallback }; } else { callbacks = new Callback[] { nameCallback, evidenceVerifyCallback }; } callbackHandler.handle(callbacks); return evidenceVerifyCallback.isVerified(); } catch (UnsupportedCallbackException e) { return false; } catch (IOException e) { throw new HttpAuthenticationException(e); } finally { evidence.destroy(); } }
Source:
<code>private static int upgradeBarcodeScannerProperties(Map<String, JSONValue> componentProperties, int srcCompVersion) { if (srcCompVersion < 2) { srcCompVersion = 2; } if (srcCompVersion < 3) { if (componentProperties.containsKey("UseExternalScanner")){ String value = ((ClientJsonString)componentProperties.get("UseExternalScanner")).getString(); if (value.equals("True")){ componentProperties.remove("UseExternalScanner"); } <START> } <END> else { componentProperties.put("UseExternalScanner", new ClientJsonString("False")); } srcCompVersion = 3; } return srcCompVersion; }</code><technical_language>Code style: } else {</technical_language>

Target:
private static int upgradeBarcodeScannerProperties(Map<String, JSONValue> componentProperties, int srcCompVersion) { if (srcCompVersion < 2) { srcCompVersion = 2; } return srcCompVersion; }
Source:
<code>public String name() { <START> String name = ""; <END> if (job instanceof hudson.matrix.MatrixConfiguration) { name += ((hudson.matrix.MatrixProject) job.getParent()).getName(); name += ' ' + job.getDisplayName(); } else { name += (null != job.getDisplayNameOrNull()) ? job.getDisplayName() : job.getName(); } return name; }</code><technical_language>need instantiate String name "". In fact is need for this variable - This is calling getName for parent. Surely this getDisplayName() - is calling getDisplayName for child - if this works (i.e. falls getName) change !matrix branch do same</technical_language>

Target:
public String name() { if (job instanceof hudson.matrix.MatrixConfiguration) { return ((hudson.matrix.MatrixProject) job.getParent()).getDisplayName() + ' ' + job.getDisplayName(); } else { return (null != job.getDisplayNameOrNull()) ? job.getDisplayName() : job.getName(); } }
Source:
<code>private void parse() throws IOException, InterruptedException { try (InputStream is = dockerfilePath.read()) { <START> try (BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"))) { <END> String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith(ARG)) { String[] keyVal = parseDockerfileArg(line.substring(4)); args.put(keyVal[0], keyVal[1]); continue; } if (line.startsWith(FROM)) { froms.add(line.substring(5)); continue; } } } } }</code><technical_language>suggestion try (InputStream is = dockerfilePath.read(); BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"))) {</technical_language>

Target:
private void parse() throws IOException, InterruptedException { try (InputStream is = dockerfilePath.read(); BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"))) { String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith(ARG)) { String[] keyVal = parseDockerfileArg(line.substring(4)); args.put(keyVal[0], keyVal[1]); continue; } if (line.startsWith(FROM)) { froms.add(line.substring(5)); continue; } } } }
Source:
<code>public Visit getVisitByUuid(String configName, String uuid) { try { Config config = configService.getConfigByName(configName); return visitResource.getVisitById(config, uuid); } catch (HttpClientErrorException e) { <START> return null; <END> } }</code><technical_language>Log error here, similar other services</technical_language>

Target:
public Visit getVisitByUuid(String configName, String uuid) { try { Config config = configService.getConfigByName(configName); return visitResource.getVisitById(config, uuid); } catch (HttpClientErrorException e) { LOGGER.error("Error while fetching visit with UUID: " + uuid); return null; } }
Source:
<code>private VersionNumber versionOfPlugin(File p) throws IOException { if (!p.isFile()) { return new VersionNumber("0.0"); } <START> JarFile j = null; <END> try { try { j = new JarFile(p); } catch (IOException x) { throw new IOException("not a valid JarFile: " + p, x); } String v = j.getManifest().getMainAttributes().getValue("Plugin-Version"); if (v == null) { throw new IOException("no Plugin-Version in " + p); } try { return new VersionNumber(v); } catch (IllegalArgumentException x) { throw new IOException("malformed Plugin-Version in " + p + ": " + x, x); } } finally { if (j != null) { j.close(); } } }</code><technical_language>suggestion JarFile j; try { j = new JarFile(p); } catch (IOException x) { throw new IOException("not a valid JarFile: " + p, x); } do need null checks</technical_language>

Target:
private VersionNumber versionOfPlugin(File p) throws IOException { if (!p.isFile()) { return new VersionNumber("0.0"); } JarFile j; try { j = new JarFile(p); } catch (IOException x) { throw new IOException("not a valid JarFile: " + p, x); } try { String v = j.getManifest().getMainAttributes().getValue("Plugin-Version"); if (v == null) { throw new IOException("no Plugin-Version in " + p); } try { return new VersionNumber(v); } catch (IllegalArgumentException x) { throw new IOException("malformed Plugin-Version in " + p + ": " + x, x); } } finally { j.close(); } }