auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private GrouperMetadataImpl getGrouperMetadata(String jobModelVersion, List<ProcessorNode> processorNodes) { Map<TaskName, String> taskToProcessorId = new HashMap<>(); Map<TaskName, List<SystemStreamPartition>> taskToSSPs = new HashMap<>(); if (jobModelVersion != null) { JobModel jobModel = readJobModelFromMetadataStore(jobModelVersion); if (jobModel != null) { for (ContainerModel containerModel : jobModel.getContainers().values()) { for (TaskModel taskModel : containerModel.getTasks().values()) { taskToProcessorId.put(taskModel.getTaskName(), containerModel.getId()); for (SystemStreamPartition partition : taskModel.getSystemStreamPartitions()) { <START> taskToSSPs.computeIfAbsent(taskModel.getTaskName(), k -> new ArrayList<>()); <END> taskToSSPs.get(taskModel.getTaskName()).add(partition); } } } } } Map<String, LocationId> processorLocality = new HashMap<>(); for (ProcessorNode processorNode : processorNodes) { ProcessorData processorData = processorNode.getProcessorData(); processorLocality.put(processorData.getProcessorId(), processorData.getLocationId()); } Map<TaskName, LocationId> taskLocality = zkUtils.readTaskLocality(); return new GrouperMetadataImpl(processorLocality, taskLocality, taskToSSPs, taskToProcessorId); }</code><technical_language>replace taskToSSPs.putIfAbsent(taskModel.getTaskName(), new ArrayList<>());</technical_language>

Target:
private GrouperMetadataImpl getGrouperMetadata(String jobModelVersion, List<ProcessorNode> processorNodes) { Map<TaskName, String> taskToProcessorId = new HashMap<>(); Map<TaskName, List<SystemStreamPartition>> taskToSSPs = new HashMap<>(); if (jobModelVersion != null) { JobModel jobModel = readJobModelFromMetadataStore(jobModelVersion); for (ContainerModel containerModel : jobModel.getContainers().values()) { for (TaskModel taskModel : containerModel.getTasks().values()) { taskToProcessorId.put(taskModel.getTaskName(), containerModel.getId()); for (SystemStreamPartition partition : taskModel.getSystemStreamPartitions()) { taskToSSPs.computeIfAbsent(taskModel.getTaskName(), k -> new ArrayList<>()); taskToSSPs.get(taskModel.getTaskName()).add(partition); } } } } Map<String, LocationId> processorLocality = new HashMap<>(); for (ProcessorNode processorNode : processorNodes) { ProcessorData processorData = processorNode.getProcessorData(); processorLocality.put(processorData.getProcessorId(), processorData.getLocationId()); } Map<TaskName, LocationId> taskLocality = zkUtils.readTaskLocality(); return new GrouperMetadataImpl(processorLocality, taskLocality, taskToSSPs, taskToProcessorId); }
Source:
<code>public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { return type instanceof Class && supportedTypes.contains(type) <START> ? Optional.of(new LoggableBinderArgument<>(value, (p, i, v) -> p.setObject(i, value))) <END> : Optional.empty(); }</code><technical_language>this ObjectArgument.of</technical_language>

Target:
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { return Optional.of(type) .filter(Class.class::isInstance) .map(Class.class::cast) .map(supportedTypes::get) .map(sqlType -> ObjectArgument.of(value, sqlType)); }
Source:
<code>public void destroy() { if (origin instanceof TemporaryVertex) ((TemporaryVertex) origin).dispose(); if (target instanceof TemporaryVertex) ((TemporaryVertex) target).dispose(); LOG.debug("ms Cleaning up temporary edges", temporaryEdges.size()); <START> temporaryEdges.forEach(TemporaryEdge::dispose); <END> temporaryEdges.clear(); temporaryVertices.forEach(graph::remove); temporaryVertices.clear(); }</code><technical_language>this mechanism for rest of temporary edges, added request addressed #2655? I @t2gran a lot of effort automated cleanup search, simpler record created temporary object clear out context teardown</technical_language>

Target:
public void destroy() { TemporaryVertex.disposeAll(temporaryVertices); temporaryVertices.clear(); }
Source:
<code>public void endBlock() throws IOException { state = state.endBlock(); LOG.debug("{}: end block", out.getPos()); currentBlock.setRowCount(currentRecordCount); <START> int blockSize = blocks.size(); <END> if (fileEncryptor != null && blockSize > Short.MAX_VALUE) { throw new IOException("Number of row groups exceeds short max. Can't set ordinal"); } currentBlock.setOrdinal((short) blockSize); blocks.add(currentBlock); columnIndexes.add(currentColumnIndexes); offsetIndexes.add(currentOffsetIndexes); bloomFilters.add(currentBloomFilters); currentColumnIndexes = null; currentOffsetIndexes = null; currentBloomFilters = null; currentBlock = null; }</code><technical_language>blockSize is a bit misleading. is ordinal rowGroupOrdinal similar</technical_language>

Target:
STATE endBlock() { return STARTED; }
Source:
<code>NeoStores( File neoStoreFileName, Config config, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, final LogProvider logProvider, FileSystemAbstraction fileSystemAbstraction, VersionContextSupplier versionContextSupplier, RecordFormats recordFormats, boolean createIfNotExist, StoreType[] storeTypes, OpenOption[] openOptions ) { this.neoStoreFileName = neoStoreFileName; this.config = config; this.idGeneratorFactory = idGeneratorFactory; this.pageCache = pageCache; this.logProvider = logProvider; this.fileSystemAbstraction = fileSystemAbstraction; this.versionContextSupplier = versionContextSupplier; this.recordFormats = recordFormats; this.createIfNotExist = createIfNotExist; this.openOptions = openOptions; this.storeDir = neoStoreFileName.getParentFile(); verifyRecordFormat(); stores = new Object[StoreType.values().length]; try { for ( StoreType type : storeTypes ) { getOrCreateStore( type ); } } <START> catch ( Exception initException ) <END> { try { close(); } catch ( Exception closeException ) { initException.addSuppressed( closeException ); } throw initException; } initializedStores = storeTypes; }</code><technical_language>RuntimeException</technical_language>

Target:
NeoStores( File neoStoreFileName, Config config, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, final LogProvider logProvider, FileSystemAbstraction fileSystemAbstraction, VersionContextSupplier versionContextSupplier, RecordFormats recordFormats, boolean createIfNotExist, StoreType[] storeTypes, OpenOption[] openOptions ) { this.neoStoreFileName = neoStoreFileName; this.config = config; this.idGeneratorFactory = idGeneratorFactory; this.pageCache = pageCache; this.logProvider = logProvider; this.fileSystemAbstraction = fileSystemAbstraction; this.versionContextSupplier = versionContextSupplier; this.recordFormats = recordFormats; this.createIfNotExist = createIfNotExist; this.openOptions = openOptions; this.storeDir = neoStoreFileName.getParentFile(); verifyRecordFormat(); stores = new Object[StoreType.values().length]; try { for ( StoreType type : storeTypes ) { getOrCreateStore( type ); } } catch ( RuntimeException initException ) { try { close(); } catch ( RuntimeException closeException ) { initException.addSuppressed( closeException ); } throw initException; } initializedStores = storeTypes; }
Source:
<code>public static <P extends PolicyConfiguration> P getCurrentPolicyConfiguration() throws PolicyContextException { String contextID; if (WildFlySecurityManager.isChecking()) { contextID = doPrivileged(new GetContextIDAction()); } else { contextID = PolicyContext.getContextID(); } try { <START> ElytronPolicyConfigurationFactory policyConfigurationFactory = (ElytronPolicyConfigurationFactory) PolicyConfigurationFactory.getPolicyConfigurationFactory(); <END> P policyConfiguration = (P) policyConfigurationFactory.getPolicyConfiguration(contextID); if (policyConfiguration == null) { throw log.authzInvalidPolicyContextIdentifier(contextID); } if (!policyConfiguration.inService()) { throw log.authzPolicyConfigurationNotInService(contextID); } return policyConfiguration; } catch (Exception e) { throw log.authzUnableToObtainPolicyConfiguration(contextID, e); } }</code><technical_language>this static/global? this prevent (for example) WildFly EE containers running JVM</technical_language>

Target:
static <P extends PolicyConfiguration> P getCurrentPolicyConfiguration() throws PolicyContextException { String contextID; if (WildFlySecurityManager.isChecking()) { contextID = doPrivileged(GET_CONTEXT_ID); } else { contextID = PolicyContext.getContextID(); } if (contextID == null) { throw log.authzContextIdentifierNotSet(); } try { P policyConfiguration = (P) configurationRegistry.get(contextID); if (policyConfiguration == null) { throw log.authzInvalidPolicyContextIdentifier(contextID); } if (!policyConfiguration.inService()) { throw log.authzPolicyConfigurationNotInService(contextID); } return policyConfiguration; } catch (Exception e) { throw log.authzUnableToObtainPolicyConfiguration(contextID, e); } }
Source:
<code>public SpanElement renderNodeContents(ProcessTreeNode node) { ProcessTreeNode.ProcessNodeType type = node.getType(); switch (type) { case MACHINE_NODE: return createMachineElement((MachineDto)node.getData()); case COMMAND_NODE: return createCommandElement(node); case TERMINAL_NODE: return createTerminalElement(node); <START> case GIT_NODE: <END> return createGitElement(node); default: return Elements.createSpanElement(); } }</code><technical_language>good hardcode git</technical_language>

Target:
public SpanElement renderNodeContents(ProcessTreeNode node) { ProcessTreeNode.ProcessNodeType type = node.getType(); switch (type) { case MACHINE_NODE: return createMachineElement((MachineDto)node.getData()); case COMMAND_NODE: return createCommandElement(node); case TERMINAL_NODE: return createTerminalElement(node); default: return Elements.createSpanElement(); } }
Source:
<code>public ResponseEntity addOrUpdateRepository(@ApiParam(value = "The storageId", required = true) @PathVariable String storageId, @ApiParam(value = "The repositoryId", required = true) @PathVariable String repositoryId, @ApiParam(value = "The repository object", required = true) @RequestBody Repository repository) throws IOException, JAXBException { try { logger.debug("Creating repository " + storageId + ":" + repositoryId + "..."); repository.setStorage(configurationManagementService.getStorage(storageId)); configurationManagementService.saveRepository(storageId, repository); final File repositoryBaseDir = new File(repository.getBasedir()); if (!repositoryBaseDir.exists()) { repositoryManagementService.createRepository(storageId, repository.getId()); } <START> return ResponseEntity.ok(ResponseStatusEnum.OK.value()); <END> } catch (IOException | JAXBException | RepositoryManagementStrategyException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ResponseStatusEnum.FAILED.value()); } }</code><technical_language>removed actual text response here</technical_language>

Target:
public ResponseEntity addOrUpdateRepository(@ApiParam(value = "The storageId", required = true) @PathVariable String storageId, @ApiParam(value = "The repositoryId", required = true) @PathVariable String repositoryId, @ApiParam(value = "The repository object", required = true) @RequestBody Repository repository) throws IOException, JAXBException { try { logger.debug("Creating repository " + storageId + ":" + repositoryId + "..."); repository.setStorage(configurationManagementService.getStorage(storageId)); configurationManagementService.saveRepository(storageId, repository); final File repositoryBaseDir = new File(repository.getBasedir()); if (!repositoryBaseDir.exists()) { repositoryManagementService.createRepository(storageId, repository.getId()); } return ResponseEntity.ok("The repository was updated successfully."); } catch (IOException | JAXBException | RepositoryManagementStrategyException e) { logger.error(e.getMessage(), e); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } }
Source:
<code>private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); <START> vmInterfaceManager.removeAll(vm.getId()); <END> for (VmNetworkInterface vmInterface : vm.getInterfaces()) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.add(vmInterface, compensationContext, true, false, vm.getOs(), vm.getCompatibilityVersion()); } vnicProfileHelper.auditInvalidInterfaces(vm.getName()); }</code><technical_language>macs 'marked' removed, 'commit' removed pool</technical_language>

Target:
private void synchronizeNics(VM vm, CompensationContext compensationContext, DbUser user, VmInterfaceManager vmInterfaceManager) { VnicProfileHelper vnicProfileHelper = new VnicProfileHelper(vm.getClusterId(), vm.getStoragePoolId(), AuditLogType.IMPORTEXPORT_SNAPSHOT_VM_INVALID_INTERFACES); MacPool macPool = vmInterfaceManager.getMacPool(); List<VmNic> dbNics = vmNicDao.getAllForVm(vm.getId()); List<VmNetworkInterface> newNics = vm.getInterfaces(); Map<String, Long> preexistingMacsUsageFrequency = countMacUsageFrequency(dbNics); Map<String, Long> macsFromRequestUsageFrequency = countMacUsageFrequency(newNics); vmInterfaceManager.removeAll(dbNics); releaseExtraMacs(macPool, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); for (VmNetworkInterface vmInterface : newNics) { vmInterface.setVmId(vm.getId()); if (vmInterface.getId() == null) { vmInterface.setId(Guid.newGuid()); } vnicProfileHelper.updateNicWithVnicProfileForUser(vmInterface, user); vmInterfaceManager.persistIface(vmInterface, compensationContext); } allocateMacsMissingInMacPool(macPool, preexistingMacsUsageFrequency, macsFromRequestUsageFrequency); vnicProfileHelper.auditInvalidInterfaces(vm.getName()); }
Source:
<code>public Map<PlanNodeId, SplitSource> visitTableScan(TableScanNode node, Context context) { <START> TableHandle table = node.getIsDelete() ? context.tableWriteInfo.getDeleteScanTableHandle().orElseThrow(() -> new IllegalStateException("deletesScanTableHandle is absent")) : node.getTable(); <END> Supplier<SplitSource> splitSourceSupplier = () -> splitSourceProvider.getSplits( session, table, getSplitSchedulingStrategy(stageExecutionDescriptor, node.getId())); SplitSource splitSource = new LazySplitSource(splitSourceSupplier); splitSources.add(splitSource); return ImmutableMap.of(node.getId(), splitSource); }</code><technical_language>nit: IllegalStateException -> IllegalArgumentException/VerifyException</technical_language>

Target:
public Map<PlanNodeId, SplitSource> visitTableScan(TableScanNode node, Context context) { TableHandle table; Optional<DeleteScanInfo> deleteScanInfo = context.getTableWriteInfo().getDeleteScanInfo(); if (deleteScanInfo.isPresent() && deleteScanInfo.get().getId() == node.getId()) { table = deleteScanInfo.get().getTableHandle(); } else { table = node.getTable(); } Supplier<SplitSource> splitSourceSupplier = () -> splitSourceProvider.getSplits( session, table, getSplitSchedulingStrategy(stageExecutionDescriptor, node.getId())); SplitSource splitSource = new LazySplitSource(splitSourceSupplier); splitSources.add(splitSource); return ImmutableMap.of(node.getId(), splitSource); }
Source:
<code>public void addCursorBlock(String streamName, byte[] opaque) { m_checksumLock.writeLock().lock(); m_lastestOpaque = opaque; boolean expandCursorBuff = m_slotManager.addStream(streamName); m_staleSlotMapper = true; if (expandCursorBuff) { BBContainer newCursorBuff = DBBPool.allocateDirect(m_slotManager.m_cursorSpace); ByteBuffer b = m_cursorBuffer.b(); assert(b.position() == 0); newCursorBuff.b().put(b); newCursorBuff.b().position(0); m_lb = newCursorBuff.bD().asLongBuffer(); m_cursorBuffer.discard(); m_cursorBuffer = newCursorBuff; } <START> m_checksumLock.writeLock().unlock(); <END> }</code><technical_language>If throws in this method this lock left locked a deadlock if another thread lock this lock. This in a finally block. for other methods</technical_language>

Target:
public void addCursorBlock(String streamName, byte[] opaque) { try { m_checksumLock.writeLock().lock(); boolean expandCursorBuff = m_slotMapper.addStream(streamName, opaque); if (expandCursorBuff) { BBContainer newCursorBuff = DBBPool.allocateDirect(m_slotMapper.m_cursorSpace); ByteBuffer b = m_cursorBuffer.b(); assert(b.position() == 0); newCursorBuff.b().put(b); newCursorBuff.b().position(0); m_lb = newCursorBuff.bD().asLongBuffer(); m_cursorBuffer.discard(); m_cursorBuffer = newCursorBuff; } } finally { m_checksumLock.writeLock().unlock(); } }
Source:
<code>private void addMpTermData(String mpId, StatisticalResultDTO doc) throws SQLException { if (mpId != null) { OntologyTermBean mpTerm = mpOntologyService.getTerm(mpId); if (mpTerm != null) { doc.setMpTermId(mpTerm.getId()); doc.setMpTermName(mpTerm.getName()); doc.setTopLevelMpTermId(mpOntologyService.getTopLevelDetail(mpId).getIds()); doc.setTopLevelMpTermName(mpOntologyService.getTopLevelDetail(mpId).getNames()); doc.setIntermediateMpTermId(mpOntologyService.getIntermediatesDetail(mpId).getIds()); doc.setIntermediateMpTermName(mpOntologyService.getIntermediatesDetail(mpId).getNames()); if (mpOntologyService.getAnatomyMappings(mpId) != null){ List<String> anatomyIds = mpOntologyService.getAnatomyMappings(mpId); for (String id: anatomyIds){ OntologyDAO currentOntologyService = null; if (id.startsWith("EMAPA")){ currentOntologyService = emapaOntologyService; } else if (id.startsWith("MA")){ currentOntologyService = maOntologyService; } <START> doc.addAnatomyTermId(id); <END> doc.addAnatomyTermName(currentOntologyService.getTerm(id).getName()); OntologyDetail maAncestors = currentOntologyService.getIntermediatesDetail(id); doc.setIntermediateAnatomyTermId(maAncestors.getIds()); doc.setIntermediateAnatomyTermName(maAncestors.getNames()); OntologyDetail maTopLevels = currentOntologyService.getSelectedTopLevelDetails(id); doc.setTopLevelAnatomyTermId(maTopLevels.getIds()); doc.setTopLevelAnatomyTermName(maTopLevels.getNames()); } } } } }</code><technical_language>currentOntologyService null if is a term start MA EMAPA</technical_language>

Target:
private void addMpTermData(String mpId, StatisticalResultDTO doc) throws SQLException { if (mpId != null) { OntologyTermBean mpTerm = mpOntologyService.getTerm(mpId); if (mpTerm != null) { doc.setMpTermId(mpTerm.getId()); doc.setMpTermName(mpTerm.getName()); doc.setTopLevelMpTermId(mpOntologyService.getTopLevelDetail(mpId).getIds()); doc.setTopLevelMpTermName(mpOntologyService.getTopLevelDetail(mpId).getNames()); doc.setIntermediateMpTermId(mpOntologyService.getIntermediatesDetail(mpId).getIds()); doc.setIntermediateMpTermName(mpOntologyService.getIntermediatesDetail(mpId).getNames()); if (mpOntologyService.getAnatomyMappings(mpId) != null){ List<String> anatomyIds = mpOntologyService.getAnatomyMappings(mpId); for (String id: anatomyIds){ OntologyDAO currentOntologyService = null; if (id.startsWith("EMAPA")){ currentOntologyService = emapaOntologyService; } else if (id.startsWith("MA")){ currentOntologyService = maOntologyService; } if (currentOntologyService != null){ doc.addAnatomyTermId(id); doc.addAnatomyTermName(currentOntologyService.getTerm(id).getName()); OntologyDetail anatomyIntermediateTerms = currentOntologyService.getIntermediatesDetail(id); doc.setIntermediateAnatomyTermId(anatomyIntermediateTerms.getIds()); doc.setIntermediateAnatomyTermName(anatomyIntermediateTerms.getNames()); OntologyDetail anatomyTopLevels = currentOntologyService.getSelectedTopLevelDetails(id); doc.setTopLevelAnatomyTermId(anatomyTopLevels.getIds()); doc.setTopLevelAnatomyTermName(anatomyTopLevels.getNames()); } } } } } }
Source:
<code>public void unblockAllServicesOnDestination(PerunSession sess, String destinationName) throws FacilityNotExistsException, PrivilegeException { <START> List<Destination> destinations = ((PerunBlImpl) sess.getPerun()).getServicesManagerBl().getDestinations(sess); <END> for(Destination destination: destinations) { if(destination.getDestination().equals(destinationName)) { List<Facility> destinationFacilities = perunBl.getFacilitiesManager().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { log.warn("Trying to unblock services on destination by a user who is neither perunadmin nor admin of the facility"); continue; } getServicesManagerBl().unblockAllServicesOnDestination(sess, destination.getId()); } } }</code><technical_language>getServicesManagerBl() instead of ((PerunBlImpl) sess.getPerun()).getServicesManagerBl()</technical_language>

Target:
public void unblockAllServicesOnDestination(PerunSession sess, String destinationName) throws FacilityNotExistsException, PrivilegeException { List<Destination> destinations = getServicesManagerBl().getDestinations(sess); for(Destination destination: destinations) { if(destination.getDestination().equals(destinationName)) { List<Facility> destinationFacilities = perunBl.getFacilitiesManagerBl().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNADMIN)) { log.warn("Trying to unblock services on destination by a user who is neither perunadmin nor admin of the facility"); continue; } getServicesManagerBl().unblockAllServicesOnDestination(sess, destination.getId()); } } }
Source:
<code>protected com.mongodb.client.model.IndexOptions convert(final IndexOptions options, final boolean background) { if (options.dropDups()) { <START> throw new MappingException("dropDups value has been desupported by the server. Please set this value to false and " <END> + "validate your system behaves as expected."); } com.mongodb.client.model.IndexOptions indexOptions = new com.mongodb.client.model.IndexOptions() .background(options.background() || background) .sparse(options.sparse()) .unique(options.unique()); if (!options.language().equals("")) { indexOptions.defaultLanguage(options.language()); } if (!options.languageOverride().equals("")) { indexOptions.languageOverride(options.languageOverride()); } if (!options.name().equals("")) { indexOptions.name(options.name()); } if (options.expireAfterSeconds() != -1) { indexOptions.expireAfter((long) options.expireAfterSeconds(), TimeUnit.SECONDS); } if (!options.collation().locale().equals("")) { indexOptions.collation(convert(options.collation())); } return indexOptions; }</code><technical_language>desupported => longer supported</technical_language>

Target:
private com.mongodb.client.model.IndexOptions convert(final IndexOptions options, final boolean background) { if (options.dropDups()) { LOG.warning("dropDups value is no longer supported by the server. Please set this value to false and " + "validate your system behaves as expected."); } com.mongodb.client.model.IndexOptions indexOptions = new com.mongodb.client.model.IndexOptions() .background(options.background() || background) .sparse(options.sparse()) .unique(options.unique()); if (!options.language().equals("")) { indexOptions.defaultLanguage(options.language()); } if (!options.languageOverride().equals("")) { indexOptions.languageOverride(options.languageOverride()); } if (!options.name().equals("")) { indexOptions.name(options.name()); } if (options.expireAfterSeconds() != -1) { indexOptions.expireAfter((long) options.expireAfterSeconds(), TimeUnit.SECONDS); } if (!options.collation().locale().equals("")) { indexOptions.collation(convert(options.collation())); } return indexOptions; }
Source:
<code>public void checkExecutorHealth() { final Map<Optional<Executor>, List<ExecutableFlow>> exFlowMap = getFlowToExecutorMap(); for (final Map.Entry<Optional<Executor>, List<ExecutableFlow>> entry : exFlowMap.entrySet()) { final Optional<Executor> executorOption = entry.getKey(); if (!executorOption.isPresent()) { final String finalizeReason = "Executor id of this execution doesn't exist."; for (final ExecutableFlow flow : entry.getValue()) { this.logger.warn( String.format("Finalizing execution %s, %s", flow.getExecutionId(), finalizeReason)); ExecutionControllerUtils .finalizeFlow(this.executorLoader, this.alerterHolder, flow, finalizeReason, null); } continue; } final Executor executor = executorOption.get(); try { <START> final Map<String, Object> results = this.apiGateway <END> .callWithExecutionId(executor.getHost(), executor.getPort(), ConnectorParams.PING_ACTION, null, null); if (results == null || results.containsKey(ConnectorParams.RESPONSE_ERROR) || !results .containsKey(ConnectorParams.STATUS_PARAM) || !results.get(ConnectorParams.STATUS_PARAM) .equals(ConnectorParams.RESPONSE_ALIVE)) { throw new ExecutorManagerException("Status of executor " + executor.getId() + " is " + "not alive."); } } catch (final ExecutorManagerException e) { handleExecutorNotAliveCase(entry, executor, e); } } }</code><technical_language>return for callWithExecutionId more specific? Map<String, Object>, stored a value, is difficult for callers expect, parse handle</technical_language>

Target:
public void checkExecutorHealth() { final Map<Optional<Executor>, List<ExecutableFlow>> exFlowMap = getFlowToExecutorMap(); for (final Map.Entry<Optional<Executor>, List<ExecutableFlow>> entry : exFlowMap.entrySet()) { final Optional<Executor> executorOption = entry.getKey(); if (!executorOption.isPresent()) { final String finalizeReason = "Executor id of this execution doesn't exist."; for (final ExecutableFlow flow : entry.getValue()) { logger.warn( String.format("Finalizing execution %s, %s", flow.getExecutionId(), finalizeReason)); ExecutionControllerUtils .finalizeFlow(this.executorLoader, this.alerterHolder, flow, finalizeReason, null); } continue; } final Executor executor = executorOption.get(); try { final Map<String, Object> results = this.apiGateway .callWithExecutionId(executor.getHost(), executor.getPort(), ConnectorParams.PING_ACTION, null, null); if (results == null || results.containsKey(ConnectorParams.RESPONSE_ERROR) || !results .containsKey(ConnectorParams.STATUS_PARAM) || !results.get(ConnectorParams.STATUS_PARAM) .equals(ConnectorParams.RESPONSE_ALIVE)) { throw new ExecutorManagerException("Status of executor " + executor.getId() + " is " + "not alive."); } else { if (this.executorFailureCount.containsKey(executor.getId())) { this.executorFailureCount.put(executor.getId(), 0); } } } catch (final ExecutorManagerException e) { handleExecutorNotAliveCase(entry, executor, e); } } }
Source:
<code><START> private boolean canDirectEdit() { <END> boolean valid = !isInLayoutingModeDiagram(labeled); valid = valid && checkPrecondition(); return valid; }</code><technical_language>This method in public</technical_language>

Target:
public boolean canDirectEdit() { boolean valid = !isInLayoutingModeDiagram(labeled); valid = valid && checkPrecondition((DDiagramElement) labeled, directEditTool); return valid; }
Source:
<code>public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions() : other; return new ParallelTransferOptions() .setBlockSize(other.getBlockSizeLong() == null <START> ? Long.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) <END> : other.getBlockSizeLong()) .setNumBuffers(other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers()) .setProgressReceiver(other.getProgressReceiver()) .setMaxSingleUploadSize(other.getMaxSingleUploadSizeLong() == null ? Long.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG) : other.getMaxSingleUploadSizeLong()); }</code><technical_language>need Long.valueOf</technical_language>

Target:
public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions() : other; Long blockSize = other.getBlockSizeLong(); if (blockSize == null) { blockSize = (long) BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE; } Integer numBuffers = other.getNumBuffers(); if (numBuffers == null) { numBuffers = BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS; } Long maxSingleUploadSize = other.getMaxSingleUploadSizeLong(); if (maxSingleUploadSize == null) { maxSingleUploadSize = BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES_LONG; } return new ParallelTransferOptions() .setBlockSizeLong(blockSize) .setNumBuffers(numBuffers) .setProgressReceiver(other.getProgressReceiver()) .setMaxSingleUploadSizeLong(maxSingleUploadSize); }
Source:
<code>public LockException(Throwable cause, int statusCode) { super(cause); this.statusCode = statusCode; <START> } <END></code><technical_language>set statusCode in this class, delegate super takes a statusCode</technical_language>

Target:
public LockException(Throwable cause, int statusCode) { super(cause, statusCode); }
Source:
<code>public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { private final List<PartitionStateChangeListener> listeners = new LinkedList<>(); @Override public void participate(List<AmbryHealthReport> ambryHealthReports, DataNodeId currentNode) { Set<String> partitionsOnNode = getClusterMap().getReplicaIds(currentNode) .stream() .map(r -> r.getPartitionId().toPathString()) .collect(Collectors.toSet()); for (PartitionStateChangeListener listener : listeners) { <START> for (String partitionName : partitionsOnNode) { <END> listener.onPartitionBecomeLeaderFromStandby(partitionName); } } } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { return false; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean markStop) { return false; } @Override public List<String> getSealedReplicas() { return Collections.emptyList(); } @Override public List<String> getStoppedReplicas() { return Collections.emptyList(); } @Override public void registerPartitionStateChangeListener(StateModelListenerType listenerType, PartitionStateChangeListener partitionStateChangeListener) { listeners.add(partitionStateChangeListener); } }; } return clusterParticipant; }</code><technical_language>get currentNode, code: DataNodeId currentNode = getClusterMap().getDataNodeId(clusterMapConfig.clusterMapHostName, clusterMapConfig.clusterMapPort);</technical_language>

Target:
public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { private final List<PartitionStateChangeListener> listeners = new LinkedList<>(); @Override public void participate(List<AmbryHealthReport> ambryHealthReports) { DataNodeId currentNode = getClusterMap().getDataNodeId(clusterMapConfig.clusterMapHostName, clusterMapConfig.clusterMapPort); Set<String> partitionsOnNode = getClusterMap().getReplicaIds(currentNode) .stream() .map(r -> r.getPartitionId().toPathString()) .collect(Collectors.toSet()); for (PartitionStateChangeListener listener : listeners) { for (String partitionName : partitionsOnNode) { listener.onPartitionBecomeLeaderFromStandby(partitionName); } } } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { return false; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean markStop) { return false; } @Override public List<String> getSealedReplicas() { return Collections.emptyList(); } @Override public List<String> getStoppedReplicas() { return Collections.emptyList(); } @Override public void registerPartitionStateChangeListener(StateModelListenerType listenerType, PartitionStateChangeListener partitionStateChangeListener) { listeners.add(partitionStateChangeListener); } }; } return clusterParticipant; }
Source:
<code>public static Map<String, String> getFormatSettingsFromFile(File file) { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLParser parserXML = new XMLParser(); try { SAXParser parser = factory.newSAXParser(); <START> parser.parse(new FileInputStream(file), parserXML); <END> } catch (ParserConfigurationException | SAXException | IOException e) { LOG.error("It is not possible to parse file " + file.getName(), e); } return parserXML.getSettings(); }</code><technical_language>Stream closing</technical_language>

Target:
public static Map<String, String> getFormatSettingsFromFile(File file) { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLParser parserXML = new XMLParser(); try (FileInputStream fis = new FileInputStream(file)) { SAXParser parser = factory.newSAXParser(); parser.parse(fis, parserXML); } catch (ParserConfigurationException | SAXException | IOException e) { LOG.error("It is not possible to parse file " + file.getName(), e); } return parserXML.getSettings(); }
Source:
<code>public static ProcessBatchResult processBatchSuccess(Page page) { <START> return new ProcessBatchResult(ProcessBatchState.SUCCESS, page); <END> }</code><technical_language>requireNonNull</technical_language>

Target:
public static ProcessBatchResult processBatchSuccess(Page page) { return new ProcessBatchResult(ProcessBatchState.SUCCESS, requireNonNull(page)); }
Source:
<code>public void testXLSXFileImport() throws Exception { MockMultipartFile multipartFile = getTestMultipartFile("/simple-valid.xlsx", CONTENT_TYPE_EXCEL); Sheet sheet = mock(Sheet.class); DataCollection dataCollection = mock(DataCollection.class); EntityType table = mock(EntityType.class); String tableId = "generated_table_id"; File file = mock(File.class); when(fileStore.store(any(InputStream.class), anyString())).thenReturn(file); when(excelService.buildExcelSheetFromFile(file)).thenReturn(sheet); when(oneClickImporterService.buildDataCollection("simple-valid", sheet)).thenReturn(dataCollection); when(entityService.createEntityType(dataCollection)).thenReturn(tableId); when(table.getId()).thenReturn(tableId); mockMvc.perform(fileUpload(OneClickImporterController.URI + "/upload").file(multipartFile)) <START> .andExpect(status().isOk()); <END> verify(oneClickImporterService).buildDataCollection("simple-valid", sheet); }</code><technical_language>is creating a entity return created, setting Location is a nice a usable web api</technical_language>

Target:
public void testXLSXFileImport() throws Exception { MockMultipartFile multipartFile = getTestMultipartFile("/simple-valid.xlsx", CONTENT_TYPE_EXCEL); Sheet sheet = mock(Sheet.class); DataCollection dataCollection = mock(DataCollection.class); EntityType table = mock(EntityType.class); String tableId = "generated_table_id"; File file = mock(File.class); String fileName = "file-name"; when(file.getName()).thenReturn(fileName); when(fileStore.store(any(InputStream.class), anyString())).thenReturn(file); when(excelService.buildExcelSheetFromFile(file)).thenReturn(sheet); when(oneClickImporterService.buildDataCollection("simple-valid", sheet)).thenReturn(dataCollection); when(entityService.createEntityType(dataCollection)).thenReturn(table); when(table.getId()).thenReturn(tableId); mockMvc.perform(fileUpload(OneClickImporterController.URI + "/upload").file(multipartFile)) .andExpect(status().isCreated()) .andExpect(header().string("Location", StringEndsWith.endsWith(tableId))) .andExpect(jsonPath("$.entityId").value(tableId)) .andExpect(jsonPath("$.baseFileName").value(fileName)); verify(oneClickImporterService).buildDataCollection("simple-valid", sheet); }
Source:
<code>public List<Action> resolve(List<Diagnosis> diagnosis) { for (Diagnosis diagnoses : diagnosis) { Symptom bpSymptom = diagnoses.getSymptoms().get(DIAGNOSIS_SLOW_INSTANCE.text()); if (bpSymptom == null || bpSymptom.getComponents().isEmpty()) { continue; } if (bpSymptom.getComponents().size() > 1) { throw new UnsupportedOperationException("Multiple components with back pressure symptom"); } String stmgrId = bpSymptom.getComponents().get(0).getId(); <START> String urlStr = "http://" + physicalPlanProvider.getShellUrl(stmgrId) + "/killexecutor"; <END> URL url = new URL(urlStr); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.writeBytes("secret=" + topologyName); out.flush(); out.close(); int status = con.getResponseCode(); LOG.info("Restarting container: " + url.toString() + "; result: " + status); con.disconnect(); ContainerRestart action = new ContainerRestart(); LOG.info("Broadcasting container restart event"); eventManager.onEvent(action); List<Action> actions = new ArrayList<>(); actions.add(action); return actions; } return null; }</code><technical_language>getShellUrl return null. A safety check is required here. Otherwise, debug hard</technical_language>

Target:
public List<Action> resolve(List<Diagnosis> diagnosis) { List<Action> actions = new ArrayList<>(); for (Diagnosis diagnoses : diagnosis) { Symptom bpSymptom = diagnoses.getSymptoms().get(DIAGNOSIS_SLOW_INSTANCE.text()); if (bpSymptom == null || bpSymptom.getComponents().isEmpty()) { continue; } if (bpSymptom.getComponents().size() > 1) { throw new UnsupportedOperationException("Multiple components with back pressure symptom"); } String stmgrId = bpSymptom.getComponent().getName(); boolean b = schedulerClient.restartTopology( RestartTopologyRequest.newBuilder().setContainerIndex(Integer.valueOf(stmgrId)).build()); LOG.info("Restarted container: " + stmgrId + "; result: " + b); ContainerRestart action = new ContainerRestart(); LOG.info("Broadcasting container restart event"); eventManager.onEvent(action); actions.add(action); return actions; } return actions; }
Source:
<code>protected C getUiHandlers() { if (uiHandlers == null) { <START> logger.severe("uiHandlers are not set. You should call setUiHandlers() from your presenter's constructor."); <END> } return uiHandlers; }</code><technical_language>add setUiHandlers called ctor in order instance available</technical_language>

Target:
protected C getUiHandlers() { if (uiHandlers == null) { logger.severe("uiHandlers are not set. You should call " + "setUiHandlers() from your presenter's constructor to make " + "the UiHandlers instance available."); } return uiHandlers; }
Source:
<code>protected PowerDogLocalApiBindingConfig parseInnerBindingConfig(Item item, String bindingConfig, PowerDogLocalApiBindingConfig config, Command key) throws BindingConfigParseException { logger.debug("PowerDogLocalAPI:parseInnerBindingConfig called"); PowerDogLocalApiBindingConfigElement configElement; Matcher matcher = INNER_BINDING_PATTERN.matcher(bindingConfig); if (!matcher.matches()) { throw new BindingConfigParseException( "bindingConfig '" + bindingConfig + "' doesn't represent a valid binding-configuration. A valid configuration is matched by the RegExp '" + INNER_BINDING_PATTERN + "'"); } matcher.reset(); while (matcher.find()) { configElement = new PowerDogLocalApiBindingConfigElement(); configElement.serverId = matcher.group(1); configElement.valueId = matcher.group(2); configElement.refreshInterval = Integer.valueOf(matcher.group(3)); if (matcher.group(4).isEmpty()) configElement.name = "Current_Value"; else configElement.name = matcher.group(4).substring(1); <START> logger.debug("PowerDogLocalAPI: " + configElement); <END> config.put(key, configElement); } return config; }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
protected PowerDogLocalApiBindingConfig parseInnerBindingConfig(Item item, String bindingConfig, PowerDogLocalApiBindingConfig config, Command key) throws BindingConfigParseException { logger.debug("PowerDogLocalAPI:parseInnerBindingConfig called"); PowerDogLocalApiBindingConfigElement configElement; Matcher matcher = INNER_BINDING_PATTERN.matcher(bindingConfig); if (!matcher.matches()) { throw new BindingConfigParseException("bindingConfig '" + bindingConfig + "' doesn't represent a valid binding-configuration. A valid configuration is matched by the RegExp '" + INNER_BINDING_PATTERN + "'"); } matcher.reset(); while (matcher.find()) { configElement = new PowerDogLocalApiBindingConfigElement(); configElement.serverId = matcher.group(1); configElement.valueId = matcher.group(2); configElement.refreshInterval = Integer.valueOf(matcher.group(3)); if (matcher.group(4).isEmpty()) { configElement.name = "Current_Value"; } else { configElement.name = matcher.group(4).substring(1); } logger.debug("PowerDogLocalAPI: {}", configElement); config.put(key, configElement); } return config; }
Source:
<code>public static RootedPath getWorkspaceRootedFile(RootedPath directory, Environment env) throws IOException, InterruptedException { RootedPath workspaceRootedFile = RootedPath.toRootedPath( directory.getRoot(), directory .getRootRelativePath() .getRelative(LabelConstants.WORKSPACE_DOT_BAZEL_FILE_NAME)); SkyKey workspaceFileKey = FileValue.key(workspaceRootedFile); FileValue value; value = (FileValue) env.getValueOrThrow(workspaceFileKey, IOException.class); if (value == null) { return null; } <START> if (value.exists() && !value.isDirectory()) { <END> return workspaceRootedFile; } return RootedPath.toRootedPath( directory.getRoot(), directory .getRootRelativePath() .getRelative(LabelConstants.WORKSPACE_FILE_NAME)); }</code><technical_language>This check is insufficient: is a file, a special file. about: if (value.isFile() && !value.isSpecialFile())</technical_language>

Target:
public static RootedPath getWorkspaceRootedFile(RootedPath directory, Environment env) throws IOException, InterruptedException { RootedPath workspaceRootedFile = RootedPath.toRootedPath( directory.getRoot(), directory .getRootRelativePath() .getRelative(LabelConstants.WORKSPACE_DOT_BAZEL_FILE_NAME)); SkyKey workspaceFileKey = FileValue.key(workspaceRootedFile); FileValue value; value = (FileValue) env.getValueOrThrow(workspaceFileKey, IOException.class); if (value == null) { return null; } if (value.isFile() && !value.isSpecialFile()) { return workspaceRootedFile; } return RootedPath.toRootedPath( directory.getRoot(), directory .getRootRelativePath() .getRelative(LabelConstants.WORKSPACE_FILE_NAME)); }
Source:
<code>private SpecificDatumWriter getDatumWriter(Schema fieldSchema) { <START> SpecificDatumWriter writer = writerMap.get(fieldSchema); <END> if (writer == null) { writer = new SpecificDatumWriter(fieldSchema); writerMap.put(fieldSchema, writer); } return writer; }</code><technical_language>Consider Map.computeIfAbsent()</technical_language>

Target:
private SpecificDatumWriter getDatumWriter(Schema fieldSchema) { SpecificDatumWriter writer = writerMap.computeIfAbsent(fieldSchema, (t) -> { return new SpecificDatumWriter(t); }); return writer; }
Source:
<code>public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { List<TServerStatus> tservers; final InstanceOperations instanceOps = shellState.getConnector().instanceOperations(); final boolean paginate = !cl.hasOption(disablePaginationOpt.getOpt()); if (cl.hasOption(tserverOption.getOpt())) { tservers = new ArrayList<>(); for (TServerStatus ts : instanceOps.getTabletServerStatus()) { if (ts.getName().equals(cl.getOptionValue(tserverOption.getOpt()))) { tservers.add(ts); } } } else if (cl.hasOption(allOption.getOpt())) { tservers = instanceOps.getTabletServerStatus(); } else { throw new MissingOptionException("Missing options"); } if (tservers.isEmpty()) { <START> throw new TabletServerNotFoundException("Tablet Servers not found"); <END> } shellState.printLines(new TabletServerStatusIterator(tservers, shellState), paginate); return 0; }</code><technical_language>I need throw exception here. print nothing, if status available</technical_language>

Target:
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { List<Map<String,String>> tservers; final InstanceOperations instanceOps = shellState.getConnector().instanceOperations(); final boolean paginate = !cl.hasOption(disablePaginationOpt.getOpt()); if (cl.hasOption(tserverOption.getOpt())) { tservers = new ArrayList<>(); for (Map<String,String> ts : instanceOps.getTabletServerStatus()) { if (ts.get("server").equals(cl.getOptionValue(tserverOption.getOpt()))) { tservers.add(ts); } } } else if (cl.hasOption(allOption.getOpt())) { tservers = instanceOps.getTabletServerStatus(); } else { throw new MissingOptionException("Missing options"); } shellState.printLines(new TabletServerStatusIterator(tservers, shellState), paginate); return 0; }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TaskPropertyType)) { return false; } TaskPropertyType that = (TaskPropertyType) o; <START> if (!name.equals(that.name)) { <END> return false; } return true; }</code><technical_language>This is FALSE. name is static final</technical_language>

Target:
public boolean equals(Object o) { return this == o || o instanceof TaskPropertyType; }
Source:
<code>public ChangeInfo getChangeInfo(final int reviewId, IProgressMonitor monitor) throws GerritException { return execute(monitor, new Operation<ChangeInfo>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { try { <START> Request<ChangeInfo> request = new Request<ChangeInfo>() { <END> @Override public HttpMethodBase createMethod() throws IOException { GetMethod method = new GetMethod(client.getUrl() + "/changes/" + reviewId + "/revisions/current/review"); method.setRequestHeader("Accept", "application/json"); return method; } @Override public ChangeInfo process(HttpMethodBase method) throws IOException { return ChangeInfo.fromJson(method.getResponseBodyAsString()); } }; ChangeInfo result = client.execute(request, monitor); onSuccess(result); } catch (Exception e) { onFailure(e); } } }); }</code><technical_language>This extracted pattern postRestRequest()</technical_language>

Target:
public ChangeInfo getChangeInfo(final int reviewId, IProgressMonitor monitor) throws GerritException { final String uri = "/changes/" + reviewId + "/revisions/current/review"; return executeGetRestRequest(uri, ChangeInfo.class, monitor); }
Source:
<code>public void setUp() throws Exception { <START> setBrickPosition = 1; <END> Script script = BrickTestUtils.createProjectAndGetStartScript("askBricksTest"); script.addBrick(new AskBrick(getResourcesString(R.string.brick_ask_default_question))); baseActivityTestRule.launchActivity(null); }</code><technical_language>setBrickPosition do brickPosition in other brick tests? if not, please rename brickPosition</technical_language>

Target:
public void setUp() throws Exception { brickPosition = 1; Script script = BrickTestUtils.createProjectAndGetStartScript("askBricksTest"); script.addBrick(new AskBrick(getResourcesString(R.string.brick_ask_default_question))); instrument = getInstrumentation(); baseActivityTestRule.launchActivity(null); project = ProjectManager.getInstance().getCurrentProject(); }