auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldNotSendEventIfActionEventParameterCanNotBeConvertedToInteger() throws Exception { setTriggerEvent(); setActionEvent(); <START> when(taskService.findActiveTasksForTriggerSubject(TRIGGER_SUBJECT)).thenReturn(tasks); <END> when(taskService.getActionEventFor(task.getActions().get(0))).thenReturn(actionEvent); task.getActions().get(0).getValues().put("phone", "1234 d"); handler.handle(createEvent()); ArgumentCaptor<TaskHandlerException> captor = ArgumentCaptor.forClass(TaskHandlerException.class); verify(taskService).save(task); verify(taskService).findActiveTasksForTriggerSubject(TRIGGER_SUBJECT); verify(taskService).getActionEventFor(task.getActions().get(0)); verify(taskActivityService).addError(eq(task), captor.capture()); ArgumentCaptor<MotechEvent> captorEvent = ArgumentCaptor.forClass(MotechEvent.class); verify(eventRelay).sendEventMessage(captorEvent.capture()); verify(taskActivityService, never()).addSuccess(task); assertEquals(createHandlerFailureSubject(task.getName(), TRIGGER), captorEvent.getValue().getSubject()); assertEquals("task.error.convertToInteger", captor.getValue().getMessage()); }</code><technical_language>happened formatting in this file</technical_language>

Target:
public void shouldNotSendEventIfActionEventParameterCanNotBeConvertedToInteger() throws Exception { setTriggerEvent(); setActionEvent(); when(taskService.findActiveTasksForTriggerSubject(TRIGGER_SUBJECT)).thenReturn(tasks); when(taskService.getActionEventFor(task.getActions().get(0))).thenReturn(actionEvent); task.getActions().get(0).getValues().put("phone", "1234 d"); handler.handle(createEvent()); verify(taskService).save(task); verify(taskService).findActiveTasksForTriggerSubject(TRIGGER_SUBJECT); verify(taskService).getActionEventFor(task.getActions().get(0)); verify(taskActivityService).addError(eq(task), exceptionCaptor.capture(), eq(createEventParameters())); ArgumentCaptor<MotechEvent> captorEvent = ArgumentCaptor.forClass(MotechEvent.class); verify(eventRelay).sendEventMessage(captorEvent.capture()); verify(taskActivityService, never()).addSuccess(task); assertEquals(createHandlerFailureSubject(task.getName(), TRIGGER), captorEvent.getValue().getSubject()); assertEquals("task.error.convertToInteger", exceptionCaptor.getValue().getMessage()); }
Source:
<code>HomeView( Binder uiBinder, PriceWidgetFactory priceWidgetFactory, PlaceManager placeManager, TokenFormatter tokenFormatter, AppMessages appMessages) { this.placeManager = placeManager; this.tokenFormatter = tokenFormatter; this.appMessages = appMessages; products = new ArrayList<>(); ProductDto shirt = new ProductDto(); <START> shirt.setBrandName(appMessages.brandName(Brand.ARCBEES)); <END> shirt.setPrice(55); shirt.setProductName("Shirt"); ProductDto bag = new ProductDto(); bag.setBrandName(appMessages.brandName(Brand.ARCBEES)); bag.setPrice(35); bag.setProductName("Bag"); shirtPrice = priceWidgetFactory.create(shirt); bagPrice = priceWidgetFactory.create(bag); products.add(shirtPrice); products.add(bagPrice); initWidget(uiBinder.createAndBindUi(this)); }</code><technical_language>Brand.default()</technical_language>

Target:
HomeView( Binder uiBinder, PriceWidgetFactory priceWidgetFactory, PlaceManager placeManager, TokenFormatter tokenFormatter, AppMessages appMessages) { this.priceWidgetFactory = priceWidgetFactory; this.placeManager = placeManager; this.tokenFormatter = tokenFormatter; this.appMessages = appMessages; products = new ArrayList<>(); createInitialProducts(Brand.getDefaultValue()); initWidget(uiBinder.createAndBindUi(this)); }
Source:
<code>public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int days = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_DAYS", 1); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ days +" day(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(days, false, false, DateType.DAY); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ days +" day(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); <START> } <END> } }</code><technical_language>Undo</technical_language>

Target:
public void run() { try { if(ESReindexationProcessStatus.inFullReindexation()) return; } catch (DotDataException e2) { Logger.warn(this, "can't determine if we're in full reindex",e2); } int days = Config.getIntProperty("DIST_REINDEX_JOURNAL_CLEANUP_DAYS", 1); try { Logger.debug(this, "About to delete dist_reindex_journal entries older than "+ days +" day(s)"); HibernateUtil.startTransaction(); APILocator.getDistributedJournalAPI().distReindexJournalCleanup(days, false, false, DateType.DAY); HibernateUtil.closeAndCommitTransaction(); } catch (Exception e) { Logger.error(this, "Error ocurred while trying to delete dist_reindex_journal entries older than "+ days +" day(s)", e); try { HibernateUtil.rollbackTransaction(); } catch (DotHibernateException e1) { Logger.error(this, e1.getMessage(), e1); } } finally { try { HibernateUtil.closeSession(); } catch (DotHibernateException e) { Logger.error(this, e.getMessage(), e); } DbConnectionFactory.closeConnection(); } }
Source:
<code>public void shouldExecuteStatements() throws Exception { TransitionalPeriodTransactionMessContainer kernel = mockKernel(); QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); Result executionResult = mock( Result.class ); TransactionalContext transactionalContext = prepareKernelWithQuerySession( kernel ); when( executionEngine.executeQuery( "query", map(), transactionalContext ) ).thenReturn( executionResult ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L ); TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output, mock( HttpServletRequest.class ) ); verify( executionEngine ).executeQuery( "query", map(), transactionalContext ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).notifications( anyCollection() ); outputOrder.verify( output ).transactionStatus( anyLong() ); <START> outputOrder.verify( output ).errors( MockitoHamcrest.argThat( hasNoErrors() ) ); <END> outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); }</code><technical_language>want a static import of argThat familiar Hamcrest function</technical_language>

Target:
public void shouldExecuteStatements() throws Exception { TransitionalPeriodTransactionMessContainer kernel = mockKernel(); QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class ); Result executionResult = mock( Result.class ); TransactionalContext transactionalContext = prepareKernelWithQuerySession( kernel ); when( executionEngine.executeQuery( "query", map(), transactionalContext ) ).thenReturn( executionResult ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L ); TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output, mock( HttpServletRequest.class ) ); verify( executionEngine ).executeQuery( "query", map(), transactionalContext ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).notifications( anyCollection() ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); }
Source:
<code>public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { try { Validate.isReadable(path, "Path to the pom.xml file must be defined and accessible"); } catch (IllegalArgumentException e) { path = this.getLocalResourcePathFromResourceName(path); <START> Validate.isReadable(path, "temp pom.xml file must be defined and accessible"); <END> } Model model = system.loadPom(new File(path), settings, session); ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); } return this; }</code><technical_language>Controlling execution flow exception is a good do it. if a path type qualifier classpath: similar</technical_language>

Target:
public MavenDependencyResolver includeDependenciesFromPom(String path) throws ResolutionException { path = resolvePathByQualifier(path); Validate.isReadable(path, "Path to the pom.xml file must be defined and accessible"); Model model = system.loadPom(new File(path), settings, session); ArtifactTypeRegistry stereotypes = system.getArtifactTypeRegistry(session); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { dependencies.push(MavenConverter.fromDependency(dependency, stereotypes)); } return this; }
Source:
<code>public void add(String nodeKey, String propertyName, Object[] values) { CheckArg.isNotNull(nodeKey, "nodeKey"); CheckArg.isNotNull(propertyName, "propertyName"); CheckArg.isNotNull(values, "values"); EsIndexColumn column = columns.column(propertyName); assert column != null : "Unexpected column for the index " + name(); try { EsDocument doc = findOrCreateDoc(nodeKey); putValues(doc, column, values); client.storeDocument(name(), workspace, nodeKey, doc); <START> client.refresh(name()); <END> } catch (IOException e) { throw new EsIndexException(e); } }</code><technical_language>@okulikov, explain client.refresh(...) is called add remove commit of changes index? I understand API enough, ES refresh a refresh of index changes refresh immediately visible</technical_language>

Target:
public void add(String nodeKey, String propertyName, Object[] values) { CheckArg.isNotNull(nodeKey, "nodeKey"); CheckArg.isNotNull(propertyName, "propertyName"); CheckArg.isNotNull(values, "values"); EsIndexColumn column = columns.column(propertyName); assert column != null : "Unexpected column for the index " + name(); try { EsRequest doc = findOrCreateDoc(nodeKey); putValues(doc, column, values); client.storeDocument(name(), workspace, nodeKey, doc); } catch (IOException e) { throw new EsIndexException(e); } }
Source:
<code>public String getUid() { <START> return dataHandler.getAsString(BlogXPath.contributorUserid); <END> }</code><technical_language>Change ForumXPath</technical_language>

Target:
public String getUid() { return dataHandler.getAsString(ForumsXPath.contributorUserid); }
Source:
<code>public String[] getSupportedTypes() { <START> return new String[] { SiteRest.CATEGORY + "." + SiteRest.NAME }; <END> }</code><technical_language>I suggest support EPersonRest object need a inform UI loginAs a specific user (You assume login of another admin in current version)</technical_language>

Target:
public String[] getSupportedTypes() { return new String[] {SiteRest.CATEGORY + "." + SiteRest.NAME, EPersonRest.CATEGORY + "." + EPersonRest.NAME}; }
Source:
<code>private void displayHeader(Collection<String> labels) { table.resizeColumns(2 + labels.size()); final CellFormatter fmt = table.getCellFormatter(); int col = 0; table.setText(0, col, Util.C.approvalTableReviewer()); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; table.clearCell(0, col); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; <START> List<String> sorted_labels = new ArrayList<String>(); <END> sorted_labels.addAll(labels); Collections.sort(sorted_labels); for (String name : sorted_labels) { table.setText(0, col, name); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; } fmt.addStyleName(0, col - 1, Gerrit.RESOURCES.css().rightmost()); }</code><technical_language>Lists.newArrayListWithCapacity(labels.size()) ArrayList need resize need large if number of elements is smaller default number of elements ArrayList hold</technical_language>

Target:
private void displayHeader(Collection<String> labels) { table.resizeColumns(2 + labels.size()); final CellFormatter fmt = table.getCellFormatter(); int col = 0; table.setText(0, col, Util.C.approvalTableReviewer()); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; table.clearCell(0, col); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; for (String name : labels) { table.setText(0, col, name); fmt.setStyleName(0, col, Gerrit.RESOURCES.css().header()); col++; } fmt.addStyleName(0, col - 1, Gerrit.RESOURCES.css().rightmost()); }
Source:
<code>protected void openLinkInNewTab(WebElement link) { String oldTab = driver.getWindowHandle(); waitForLinkOpenedInNewTab(link); <START> switchToNewTab(oldTab); <END> }</code><technical_language>oldTab -> currentTab</technical_language>

Target:
protected void openLinkInNewTab(WebElement link) { String currentTab = driver.getWindowHandle(); waitForLinkOpenedInNewTab(link); switchToNewTab(currentTab); }
Source:
<code>public void aboutToBeShown() { super.aboutToBeShown(); this.selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = radioGroupViewer.getStructuredSelection(); Object newValue = selection.getFirstElement(); controller.updateValue(newValue); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; this.radioGroup.addSelectionListener(this.selectionListener); this.controller.onNewValue(new IConsumer<Object>() { @Override public void apply(Object value) { if (!radioGroup.isDisposed()) { final ISelection selection; if (value != null) { selection = new StructuredSelection(value); } else { selection = null; } radioGroupViewer.setSelection(selection); if <START> (isEnabled() && !radioGroup.isEnabled()) <END> { radioGroup.setEnabled(true); } } } }); this.controller.onNewCandidates(new IConsumer<List<Object>>() { @Override public void apply(List<Object> candidates) { if (!radioGroup.isDisposed()) { if (candidates != null) { radioGroupViewer.setInput(candidates.toArray()); } else { radioGroupViewer.setInput(null); } if (isEnabled() && !radioGroup.isEnabled()) { radioGroup.setEnabled(true); } radioGroupViewer.refresh(true); } } }); }</code><technical_language>Why? If control is enabled, user modified this updated remotely (for example) thanks a computed value</technical_language>

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.selectionListener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = radioGroupViewer.getStructuredSelection(); Object newValue = selection.getFirstElement(); controller.updateValue(newValue); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; this.radioGroup.addSelectionListener(this.selectionListener); this.controller.onNewValue(new IConsumer<Object>() { @Override public void apply(Object value) { if (!radioGroup.isDisposed()) { final ISelection selection; if (value != null) { selection = new StructuredSelection(value); } else { selection = null; } radioGroupViewer.setSelection(selection); if (!radioGroup.isEnabled()) { radioGroup.setEnabled(true); } } } }); this.controller.onNewCandidates(new IConsumer<List<Object>>() { @Override public void apply(List<Object> candidates) { if (!radioGroup.isDisposed()) { if (candidates != null) { radioGroupViewer.setInput(candidates.toArray()); } else { radioGroupViewer.setInput(null); } if (!radioGroup.isEnabled()) { radioGroup.setEnabled(true); } radioGroupViewer.refresh(true); } } }); }
Source:
<code>public void shouldReflectChangesInASecretFile() throws Exception { Path temporarySecretFile = Files.createTempFile("vault", null); Path vaultDirectory = temporarySecretFile.getParent(); String secretName = temporarySecretFile.getFileName().toString(); PlainTextVaultProvider provider = new PlainTextVaultProvider(vaultDirectory); Files.write(temporarySecretFile, "secret1".getBytes()); VaultRawSecret secret1 = provider.obtainSecret(secretName); Files.write(temporarySecretFile, "secret2".getBytes()); VaultRawSecret secret2 = provider.obtainSecret(secretName); <START> assertEquals("secret1", new String(secret1.getRawSecret().get().array())); <END> assertEquals("secret2", new String(secret2.getRawSecret().get().array())); }</code><technical_language>Prefer hamcrest methods assertThat(new String(secret1.getRawSecret().get().array()), is("secret1"));</technical_language>

Target:
public void shouldReflectChangesInASecretFile() throws Exception { Path temporarySecretFile = Files.createTempFile("vault", null); Path vaultDirectory = temporarySecretFile.getParent(); String secretName = temporarySecretFile.getFileName().toString(); PlainTextVaultProvider provider = new PlainTextVaultProvider(vaultDirectory, "ignored") { @Override protected Path resolveSecretPath(String vaultSecretId) { return vaultDirectory.resolve(vaultSecretId); } }; String secret1AsString = null; String secret2AsString = null; Files.write(temporarySecretFile, "secret1".getBytes()); try (VaultRawSecret secret1 = provider.obtainSecret(secretName)) { secret1AsString = StandardCharsets.UTF_8.decode(secret1.getRawSecret().get()).toString(); } Files.write(temporarySecretFile, "secret2".getBytes()); try (VaultRawSecret secret2 = provider.obtainSecret(secretName)) { secret2AsString = StandardCharsets.UTF_8.decode(secret2.getRawSecret().get()).toString(); } assertEquals("secret1", secret1AsString); assertEquals("secret2", secret2AsString); }
Source:
<code>public void reportTrace(EvaluationTrace trace) { <START> traceRoot.reportSubtrace(trace); <END> }</code><technical_language>lifecycle of this traceRoot object dangerous - constructor allows this null this call expects instantiated</technical_language>

Target:
public void reportTrace(EvaluationTrace trace) { if (traceRoot != null) { traceRoot.reportSubtrace(trace); } }
Source:
<code>protected void handleArgumentCommand(String command, String parameter, Iterator<String> args) { switch (command) { case "-a": parameter = args.next(); case "--algorithms": algorithms = new ArrayList<>(); for (String algorithm : parameter.split(",")) { algorithms.add(algorithm); <START> } <END> break; case "-b": case "--batch-mode": batchMode = true; break; case "-f": parameter = args.next(); case "--users-file": usersFileName = parameter; break; case "-p": parameter = args.next(); case "--password": password = parameter; break; case "-c": case "--clear-text": plainText = true; break; case "-e": case "--encrypted": plainText = false; break; case "-g": parameter = args.next(); case "--groups": for (String group : parameter.split(",")) { addGroups.add(group); } break; case "-w": parameter = args.next(); case "--groups-file": groupsFileName = parameter; break; case "-r": parameter = args.next(); case "--realm": realm = parameter; break; case "-s": parameter = args.next(); case "--server-root": serverRoot = new File(parameter); break; case "-u": parameter = args.next(); case "--user": username = parameter; break; default: throw new IllegalArgumentException(); } }</code><technical_language>algorithms = Arrays.stream(parameter.split(",")).collect(Collectors.toList());</technical_language>

Target:
protected void handleArgumentCommand(String command, String parameter, Iterator<String> args) { switch (command) { case "-a": parameter = args.next(); case "--algorithms": algorithms = Arrays.stream(parameter.split(",")).collect(Collectors.toList()); break; case "-b": case "--batch-mode": batchMode = true; break; case "-f": parameter = args.next(); case "--users-file": usersFileName = parameter; break; case "-p": parameter = args.next(); case "--password": password = parameter; break; case "-c": case "--clear-text": plainText = true; break; case "-e": case "--encrypted": plainText = false; break; case "-g": parameter = args.next(); case "--groups": for (String group : parameter.split(",")) { addGroups.add(group); } break; case "-w": parameter = args.next(); case "--groups-file": groupsFileName = parameter; break; case "-r": parameter = args.next(); case "--realm": realm = parameter; break; case "-s": parameter = args.next(); case "--server-root": serverRoot = new File(parameter); break; case "-u": parameter = args.next(); case "--user": username = parameter; break; default: throw new IllegalArgumentException(); } }
Source:
<code>public final Session session( AccessMode mode ) { assertOpen(); Session session = sessionFactory.newInstance( mode ); if ( closed.get() ) { closeResources(); <START> throw new DriverClosedException(); <END> } return session; }</code><technical_language>a new exception type in driver for</technical_language>

Target:
public final Session session( AccessMode mode ) { assertOpen(); Session session = sessionFactory.newInstance( mode ); if ( closed.get() ) { closeResources(); throw driverCloseException(); } return session; }
Source:
<code>private void validateContractInput(String containerIdentifier, InputDefinition inputDefinition) { validateContractInputName(inputDefinition.getName()); if (inputDefinition.hasChildren() && (inputDefinition.getType() != null && !inputDefinition.getType().equals(Type.FILE))) { <START> addError("Can't have a type set on the contract input <" + inputDefinition.getName() + "> of contract of " + containerIdentifier <END> + " because it has children"); } if (!inputDefinition.hasChildren() && inputDefinition.getType() == null) { addError("Type not set on the contract input <" + inputDefinition.getName() + "> of contract of " + containerIdentifier); } if (inputDefinition.hasChildren()) { for (InputDefinition definition : inputDefinition.getInputs()) { validateContractInput(containerIdentifier, definition); } } }</code><technical_language>"of contract of" ??</technical_language>

Target:
private void validateContractInput(String containerIdentifier, InputDefinition inputDefinition) { validateContractInputName(inputDefinition.getName()); if (inputDefinition.hasChildren() && (inputDefinition.getType() != null && !inputDefinition.getType().equals(Type.FILE))) { addError("Can't have a type set on the contract input <" + inputDefinition.getName() + "> on " + containerIdentifier + " because it has children"); } if (!inputDefinition.hasChildren() && inputDefinition.getType() == null) { addError("Type not set on the contract input <" + inputDefinition.getName() + "> on " + containerIdentifier); } if (inputDefinition.hasChildren()) { for (InputDefinition definition : inputDefinition.getInputs()) { validateContractInput(containerIdentifier, definition); } } }
Source:
<code>public void hasMetrics() { List<MetricName> expected = Arrays.asList("nuxeo.cache.defaultCache.read", "nuxeo.cache.defaultCache.read-hit", "nuxeo.cache.defaultCache.read-hit-ratio", "nuxeo.cache.defaultCache.read-miss", "nuxeo.cache.defaultCache.write", "nuxeo.cache.defaultCache.invalidate-all", "nuxeo.cache.defaultCache.size").stream().map(MetricName::build).collect(Collectors.toList()); SharedMetricRegistries.getOrCreate(MetricsService.class.getName()).getNames() <START> .containsAll(expected); <END> }</code><technical_language>miss assertion</technical_language>

Target:
public void hasMetrics() { List<MetricName> expected = Arrays.asList("nuxeo.cache.read", "nuxeo.cache.hit", "nuxeo.cache.hit.ratio", "nuxeo.cache.invalidation", "nuxeo.cache.size") .stream() .map(name -> MetricName.build(name).tagged("cache", "default-test-cache")) .collect(Collectors.toList()); Assert.assertTrue( SharedMetricRegistries.getOrCreate(MetricsService.class.getName()).getNames().containsAll(expected)); }
Source:
<code>public QueryRequestSessionContext(CreateQuerySession createQuerySession, HttpServletRequest servletRequest) { this.createQuerySession = requireNonNull(createQuerySession, "createQuerySession is null"); checkArgument(!isNullOrEmpty(createQuerySession.getUser()), "User must be set"); this.identity = new Identity(createQuerySession.getUser(), Optional.ofNullable(servletRequest.getUserPrincipal())); this.remoteUserAddress = servletRequest.getRemoteAddr(); ImmutableMap.Builder<String, String> systemProperties = ImmutableMap.builder(); <START> Map<String, ImmutableMap.Builder<String, String>> catalogSessionProperties = new HashMap<>(); <END> if (createQuerySession.getProperties() != null && !createQuerySession.getProperties().isEmpty()) { for (Map.Entry<String, String> entry : createQuerySession.getProperties().entrySet()) { String fullPropertyName = entry.getKey(); String propertyValue = entry.getValue(); List<String> nameParts = PROPERTY_NAME_SPLITTER.splitToList(fullPropertyName); if (nameParts.size() == 1) { String propertyName = nameParts.get(0); checkArgument(!propertyName.isEmpty(), "propertyName is empty"); systemProperties.put(propertyName, propertyValue); } else if (nameParts.size() == 2) { String catalogName = nameParts.get(0); String propertyName = nameParts.get(1); checkArgument(!catalogName.isEmpty(), "catalogName is empty"); checkArgument(!propertyName.isEmpty(), "propertyName is empty"); catalogSessionProperties.computeIfAbsent(catalogName, id -> ImmutableMap.builder()).put(propertyName, propertyValue); } else { throw new IllegalArgumentException("Invalid property name: " + fullPropertyName); } } } this.systemProperties = systemProperties.build(); this.catalogSessionProperties = catalogSessionProperties.entrySet().stream() .collect(toImmutableMap(Map.Entry::getKey, entry -> entry.getValue().build())); }</code><technical_language>do need copy-paste code com.facebook.presto.server.HttpRequestSessionContext? extract some code (entity)</technical_language>

Target:
public QueryRequestSessionContext(CreateQuerySession createQuerySession, HttpServletRequest servletRequest) { assertRequest(createQuerySession != null, "createQuerySession is null"); this.createQuerySession = createQuerySession; assertRequest(!isNullOrEmpty(createQuerySession.getUser()), "User must be set"); this.identity = new Identity(createQuerySession.getUser(), Optional.ofNullable(servletRequest.getUserPrincipal())); this.remoteUserAddress = servletRequest.getRemoteAddr(); if (createQuerySession.getProperties() != null && !createQuerySession.getProperties().isEmpty()) { SystemAndCatalogProperties systemAndCatalogProperties = parseSessionProperties(createQuerySession.getProperties(), "Invalid properties object"); this.systemProperties = systemAndCatalogProperties.getSystemProperties(); this.catalogSessionProperties = systemAndCatalogProperties.getCatalogProperties(); } else { this.systemProperties = ImmutableMap.of(); this.catalogSessionProperties = ImmutableMap.of(); } this.transactionId = Optional.ofNullable(createQuerySession.getTransactionId()).map(TransactionId::valueOf); }
Source:
<code>private void blanketApproveDisbursementVoucherDocument(CuDisbursementVoucherDocument dv) throws WorkflowException { try { <START> getDocumentService().blanketApproveDocument(dv, "Auto blanket approve from Batch Job", null); <END> } catch (WorkflowException e) { LOG.error("approveDisbursementVoucherDocument: Unable to blanket approve DV Document ID::" + dv.getDocumentNumber() + "the exception was: ", e); throw e; } }</code><technical_language>sense this call in a separate method is</technical_language>

Target:
private void blanketApproveDisbursementVoucherDocument(CuDisbursementVoucherDocument dv) throws WorkflowException { try { getDocumentService().blanketApproveDocument(dv, "Auto blanket approve from Batch Job", null); } catch (WorkflowException e) { LOG.error("blanketApproveDisbursementVoucherDocument: Unable to blanket approve DV Document ID::" + dv.getDocumentNumber() + "the exception was: ", e); throw e; } }
Source:
<code>private SelectedGpxFile getSelectedFileByLoadedFileName(String path) { <START> List<SelectedGpxFile> newList = new ArrayList<>(selectedGPXFiles); <END> for (SelectedGpxFile s : newList) { if (path.endsWith("/" + s.getLoadedName())) { return s; } } return null; }</code><technical_language>This method strange</technical_language>

Target:
private SelectedGpxFile getSelectedFileByLoadedFileName(String path) { List<SelectedGpxFile> newList = new ArrayList<>(selectedGPXFiles); for (SelectedGpxFile s : newList) { if (path.endsWith("/" + s.getLoadingFileName())) { return s; } } return null; }
Source:
<code>public Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); <START> } <END></code><technical_language>This private plans class</technical_language>

Target:
private Map<String, Object> getQueueInfo(String queueName) throws JMSException { log.debug("Getting info about queue {}", queueName); List<Map<String, Object>> mm = runQuery("_object_id", singularMap("_object_name", queueName)); if (mm.size() == 0) { throw new RuntimeException("Couldn't find a queue in Qpid: " + queueName); } if (mm.size() > 1) { throw new RuntimeException("Found unexpected amount of information about queue: " + queueName); } return mm.get(0); }
Source:
<code>private static Termios convertToTermios(TerminalSettings settings) { Termios result = new Termios(); result.c_iflag = settings.c_iflag; result.c_oflag = settings.c_oflag; <START> result.c_cflag = settings.c_cflag; <END> System.arraycopy(settings.c_cc, 0, result.c_cc, 0, settings.c_cc.length); result.c_ispeed = settings.c_ispeed; result.c_ospeed = settings.c_ospeed; return result; }</code><technical_language>result.c_lflag = settings.c_lflag; missing</technical_language>

Target:
private static Termios convertToTermios(TerminalSettings settings) { Termios result = new Termios(); result.c_iflag = settings.c_iflag; result.c_oflag = settings.c_oflag; result.c_cflag = settings.c_cflag; result.c_lflag = settings.c_lflag; System.arraycopy(settings.c_cc, 0, result.c_cc, 0, settings.c_cc.length); result.c_ispeed = settings.c_ispeed; result.c_ospeed = settings.c_ospeed; return result; }
Source:
<code>public void handlePost(ActionParameters params) throws ActionException { <START> params.requireLoggedInUser(); <END> MyPlaceCategory category = new MyPlaceCategory(); category.setUuid(params.getUser().getUuid()); category.setName(params.getRequiredParam(PARAM_NAME)); category.getWFSLayerOptions() .setDefaultFeatureStyle(JSONHelper.createJSONObject(params.getHttpParam(PARAM_STYLE))); try { layerService.insert(Collections.singletonList(category)); LOG.info("Inserted category:", category.getId()); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to insert layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", category.getId()) .withParam("name", category.getName()) .added(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = toLayerJSON(category); ResponseHelper.writeResponse(params, 200, response); }</code><technical_language>This is unnecessary, preProcess(ActionParameters params) checks this</technical_language>

Target:
public void handlePost(ActionParameters params) throws ActionException { MyPlaceCategory category = new MyPlaceCategory(); category.setUuid(params.getUser().getUuid()); category.setName(params.getRequiredParam(PARAM_NAME)); category.getWFSLayerOptions() .setDefaultFeatureStyle(JSONHelper.createJSONObject(params.getHttpParam(PARAM_STYLE))); try { layerService.insert(Collections.singletonList(category)); LOG.info("Inserted category:", category.getId()); } catch (ServiceException e) { LOG.warn(e); throw new ActionException("Failed to insert layers"); } AuditLog.user(params.getClientIp(), params.getUser()) .withParam("id", category.getId()) .withParam("name", category.getName()) .added(AuditLog.ResourceType.MYPLACES_LAYER); JSONObject response = toLayerJSON(category); ResponseHelper.writeResponse(params, 200, response); }
Source:
<code>private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; <START> if (spmStatus == VdsSpmStatus.SPM) { <END> spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }</code><technical_language>check spmStatus != contending considered SPM well</technical_language>

Target:
private double calcTimeoutToFence(int vmCount, VdsSpmStatus spmStatus) { int spmIndicator = 0; if (spmStatus != VdsSpmStatus.None) { spmIndicator = 1; } return TimeUnit.SECONDS.toMillis((int)( Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds) + (Config.<Double> GetValue(ConfigValues.DelayResetForSpmInSeconds) * spmIndicator) + (Config.<Double> GetValue(ConfigValues.DelayResetPerVmInSeconds) * vmCount))); }
Source:
<code>public static void testFormula() { <START> try { <END> GeopointParser.parse("N 12° 23.345′ E 123° 34.5AB′"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ E 123° 3A′"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° E 12A°"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ 34″ E 123° 34′ 5A″"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("N 12° 23′ 34.56″ E 123° 34′ 56.7A″"); fail(); } catch (final Geopoint.ParseException e) { } try { GeopointParser.parse("-12.345678° 23.4ABCDE°"); fail(); } catch (final Geopoint.ParseException e) { } }</code><technical_language>expected failures a lot of duplicate code blocks. extract a assertParsingFails(final String geopointToParse) method</technical_language>

Target:
public static void testFormula() { assertParsingFails("N 12° 23.345′ E 123° 34.5AB′"); assertParsingFails("N 12° 23′ E 123° 3A′"); assertParsingFails("N 12° E 12A°"); assertParsingFails("N 12° 23′ 34″ E 123° 34′ 5A″"); assertParsingFails("N 12° 23′ 34.56″ E 123° 34′ 56.7A″"); assertParsingFails("-12.345678° 23.4ABCDE°"); }
Source:
<code>public void testWorkdirIsDotGit_CreateRepositoryFromWorkDirOnly() throws Exception { File workdir = getFile("workdir", "repo"); Repository repo = new Repository(null, workdir); <START> assertTrue(repo.getDirectory().getName().equals(Constants.DOT_GIT)); <END> }</code><technical_language>assertTrue(...equals()), assertEquals instead</technical_language>

Target:
public void testWorkdirIsDotGit_CreateRepositoryFromWorkDirOnly() throws Exception { File workdir = getFile("workdir", "repo"); Repository repo = new Repository(null, workdir); assertGitdirPath(repo, "workdir", "repo", Constants.DOT_GIT); }
Source:
<code>public boolean performNextOperation(int completedChildCount) { if (getParameters().getNextStep() == null) { return false; } switch (getParameters().getNextStep()) { case GEO_REP: GlusterVolumeGeoRepSessionParameters parameters = new GlusterVolumeGeoRepSessionParameters(getSession().getMasterVolumeId(), getSession().getId()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); <START> parameters.setParentParameters(getParameters()); <END> getParameters().setNextStep(DRStep.REMOVE_TMP_SNAPSHOTS); CommandCoordinatorUtil.executeAsyncCommand(VdcActionType.GlusterStorageGeoRepSyncInternal, parameters, cloneContextAndDetachFromParent()); persistCommandIfNeeded(); break; case REMOVE_TMP_SNAPSHOTS: removeDRSnapshots(); getParameters().setNextStep(null); persistCommandIfNeeded(); break; } return true; }</code><technical_language>this change is sufficient, executeAsync changes execution in a new thread</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getNextStep() == null) { return false; } switch (getParameters().getNextStep()) { case GEO_REP: GlusterVolumeGeoRepSessionParameters parameters = new GlusterVolumeGeoRepSessionParameters(getSession().getMasterVolumeId(), getSession().getId()); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); getParameters().setNextStep(DRStep.REMOVE_TMP_SNAPSHOTS); runInternalActionWithTasksContext(VdcActionType.GlusterStorageGeoRepSyncInternal, parameters); persistCommandIfNeeded(); break; case REMOVE_TMP_SNAPSHOTS: removeDRSnapshots(); getParameters().setNextStep(null); persistCommandIfNeeded(); break; } return true; }
Source:
<code>public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); <START> user.sendMessage(tl("jumpEasterDisable")); <END> } else { user.setRightClickJump(true); user.sendMessage(tl("jumpEasterEnable")); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); throw new NoChargeException(); }</code><technical_language>This easter egg functional. worth adding translations</technical_language>

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage(tl("jumpEasterDisable")); } else { user.setRightClickJump(true); user.sendMessage(tl("jumpEasterEnable")); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); }
Source:
<code>public List<Pool> createAndEnrichPools(Pool masterPool, List<Pool> existingPools) { List<Pool> pools = new LinkedList<Pool>(); masterPool.setQuantity(calculateQuantity(masterPool.getQuantity(), masterPool.getProduct(), masterPool.getUpstreamPoolId())); String virtOnly = masterPool.getProductAttribute(Product.Attributes.VIRT_ONLY); <START> if (virtOnly != null && !virtOnly.isEmpty()) { <END> masterPool.setAttribute(Pool.Attributes.VIRT_ONLY, virtOnly); } log.info("Checking if pools need to be created for: {}", masterPool); if (!hasMasterPool(existingPools)) { if (masterPool.getSourceSubscription() != null && masterPool.getSourceSubscription().getSubscriptionSubKey().contentEquals("derived")) { throw new IllegalStateException("Cannot create master pool from bonus pool"); } pools.add(masterPool); log.info("Creating new master pool: {}", masterPool); } Pool bonusPool = createBonusPool(masterPool, existingPools); if (bonusPool != null) { pools.add(bonusPool); } return pools; }</code><technical_language>StringUtils.isEmpty</technical_language>

Target:
public List<Pool> createAndEnrichPools(Pool masterPool, List<Pool> existingPools) { List<Pool> pools = new LinkedList<Pool>(); masterPool.setQuantity(calculateQuantity(masterPool.getQuantity(), masterPool.getProduct(), masterPool.getUpstreamPoolId())); String virtOnly = masterPool.getProductAttributeValue(Product.Attributes.VIRT_ONLY); if (virtOnly != null && !virtOnly.isEmpty()) { masterPool.setAttribute(Pool.Attributes.VIRT_ONLY, virtOnly); } log.info("Checking if pools need to be created for: {}", masterPool); if (!hasMasterPool(existingPools)) { if (masterPool.getSourceSubscription() != null && masterPool.getSourceSubscription().getSubscriptionSubKey().contentEquals("derived")) { throw new IllegalStateException("Cannot create master pool from bonus pool"); } pools.add(masterPool); log.info("Creating new master pool: {}", masterPool); } Pool bonusPool = createBonusPool(masterPool, existingPools); if (bonusPool != null) { pools.add(bonusPool); } return pools; }
Source:
<code>public void TestStartNewWikiButton_001 () { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki("muppet")); <START> homePage.getVenusGlobalNav().clickStartNewWiki(); <END> Assertion.assertTrue(driver.getCurrentUrl().contains("Special:CreateNewWiki")); }</code><technical_language>this action return a new pageobject</technical_language>

Target:
public void TestStartNewWikiButton_001 () { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki("muppet")); CreateNewWikiPageObjectStep1 createNewWikiPage = homePage.getVenusGlobalNav().clickStartNewWiki(); Assertion.assertTrue(createNewWikiPage.verifyPage()); }
Source:
<code>private void cacheServiceMetrics(Service srvc, String srvcName) { Map<GridServiceMethodReflectKey, HistogramMetricImpl> srvcHistograms = invocationHistograms.get(srvcName); if (srvcHistograms != null) return; srvcHistograms = new HashMap<>(); for (Class<?> itf : allInterfaces(srvc.getClass())) { for (Method mtd : itf.getMethods()) { if (metricIgnored(mtd.getDeclaringClass())) continue; HistogramMetricImpl histogram = createHistogram(srvcName, mtd); srvcHistograms.put(new GridServiceMethodReflectKey(mtd.getName(), mtd.getParameterTypes()), histogram); } } <START> invocationHistograms.put(srvcName, srvcHistograms); <END> }</code><technical_language>I suppose invocationHistograms.put(srvcName, Collections.unmodifiableMap(srvcHistograms)); is better</technical_language>

Target:
private void cacheServiceMetrics(Service srvc, String srvcName) { Map<GridServiceMethodReflectKey, HistogramMetricImpl> srvcHistograms = invocationHistograms.get(srvcName); if (srvcHistograms != null) return; srvcHistograms = new HashMap<>(); for (Class<?> itf : allInterfaces(srvc.getClass())) { for (Method mtd : itf.getMethods()) { if (metricIgnored(mtd.getDeclaringClass())) continue; HistogramMetricImpl histogram = createHistogram(srvcName, mtd); srvcHistograms.put(new GridServiceMethodReflectKey(mtd.getName(), mtd.getParameterTypes()), histogram); } } invocationHistograms.put(srvcName, Collections.unmodifiableMap(srvcHistograms)); }
Source:
<code>private TileMatrixSet getTileMatrixSet() throws IllegalArgumentException { List<TileMatrixSet> possibleTileMatrixSets = new ArrayList<>(); for (TileMatrixSet tms : capabilities.getTileMatrixSets()) { <START> String key = tms.getTileMatrixMap().keySet().iterator().next(); <END> possibleTileMatrixSets.add(tms); } if (possibleTileMatrixSets.isEmpty()) { throw new NullPointerException("Could not find any TileMatrixSets"); } if (possibleTileMatrixSets.size() == 1) { return possibleTileMatrixSets.get(0); } HashMap<String, String> alternativeTileMatrixSets = new HashMap<>(); JSONObject useThisTileMatrixSetInstead = layerService.find(layer.getId()).getOptions().optJSONObject("useThisAlternativeTileMatrixSet"); if (useThisTileMatrixSetInstead == null) { alternativeTileMatrixSets.put(srs, srs); } else if (useThisTileMatrixSetInstead.length() > 0) { Iterator iterator = useThisTileMatrixSetInstead.keys(); while (iterator.hasNext()) { String nextKey = (String) iterator.next(); alternativeTileMatrixSets.put(nextKey, useThisTileMatrixSetInstead.optString(nextKey)); } } TileMatrixSet setToReturn = null; for (TileMatrixSet tms : possibleTileMatrixSets) { String tileMatrixSetName = tms.getTileMatrixMap().keySet().iterator().next(); for (Map.Entry<String, String> entry : alternativeTileMatrixSets.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (tileMatrixSetName.contains(key) || tileMatrixSetName.contains(value)) { setToReturn = tms; break; } } } if (setToReturn != null) { return setToReturn; } throw new IllegalArgumentException("Could not find TileMatrixSet for the requested crs"); }</code><technical_language>This "first" identifier of a TileMatrix TileMatrixSet. "0" that. This for. Instead check TileMatrixSet supports CRS of request if (srs.equals(ProjectionHelper.shortSyntaxEpsg(tms.getCrs()))) if add possibleTileMatrixSets list</technical_language>

Target:
private TileMatrixSet getTileMatrixSet() throws IllegalArgumentException { List<TileMatrixSet> possibleTileMatrixSets = new ArrayList<>(); for (TileMatrixSet tms : capabilities.getTileMatrixSets()) { if (srs.equals(ProjectionHelper.shortSyntaxEpsg(tms.getCrs()))) { possibleTileMatrixSets.add(tms); } } if (possibleTileMatrixSets.isEmpty()) { throw new IllegalArgumentException("Could not find TileMatrixSet for the requested crs"); } if (possibleTileMatrixSets.size() == 1) { return possibleTileMatrixSets.get(0); } return determineTileMatrixSetToUse(possibleTileMatrixSets); }
Source:
<code>public int getMinimumValue() { switch (relation) { case LESS_THAN: case LESS_THAN_OR_EQUAL: return Integer.MIN_VALUE; case GREATER_THAN_OR_EQUAL: case EQUAL: return queryInt; case GREATER_THAN: <START> if (queryInt == Integer.MAX_VALUE) { <END> return queryInt; } else { return queryInt + 1; } default: throw new IllegalStateException("Unknown relation " + relation); } }</code><technical_language>Or: return Ints.saturatedCast(queryInt + 1L);</technical_language>

Target:
public int getMinimumValue() { return range.min; }