auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void saveResourceWithNoOptions() throws IOException, SAXException, ParserConfigurationException { final EClass class1 = setupClass("package1", "class1"); final URI resourceURI = URI.createURI("MyResource.xmi"); final XMIResource resource = new XMIResourceImpl(resourceURI); resource.getContents().add(class1); resource.save(null); final ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResources().add(resource); class1.setName("test"); <START> Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() <END> .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "class1"); ResourceSetHelpers.save(resourceSet, null); document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "test"); }</code><technical_language>I reorder modify assert, assert modify</technical_language>

Target:
public void saveResourceWithNoOptions() throws IOException, SAXException, ParserConfigurationException { final EClass class1 = setupClass("package1", "class1"); final URI resourceURI = URI.createURI("MyResource.xmi"); final XMIResource resource = createResource(resourceURI); resource.getContents().add(class1); resource.save(null); final ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResources().add(resource); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "class1"); class1.setName("test"); ResourceSetHelpers.save(resourceSet, null); document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse("MyResource.xmi"); assertEquals(document.getDocumentElement().getAttribute("name"), "test"); }
Source:
<code>private List<Branch> getBranchesOfCommit(RevCommit commit, ListMode mode) throws GitAPIException { List<Branch> branchList = new ArrayList<Branch>(); List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); branches.forEach(ref->branchList.add(newDto(Branch.class).withName(ref.getName()))); <START> return branchList; <END> }</code><technical_language>I rewrite return branches.stream() .map(branch -> newDto(Branch.class).withName(branch.getName)) .collect(Collectors.toList());</technical_language>

Target:
private List<Branch> getBranchesOfCommit(RevCommit commit, ListMode mode) throws GitAPIException { List<Ref> branches = getGit().branchList() .setListMode(mode) .setContains(commit.getName()) .call(); return branches.stream() .map(branch -> newDto(Branch.class).withName(branch.getName())) .collect(Collectors.toList()); }
Source:
<code>public T value() { if (m_value == null) { m_value = restoreParameter(); } else if(!isPerInstance()) { m_value = restoreParameter(); } <START> return (m_value!=null)? m_value : m_defaultValue; <END> }</code><technical_language>check for null instead of !null logic new class PersistentListParameter</technical_language>

Target:
public T value() { if (m_value == null) { m_value = restoreParameter(); } else if(!isPerInstance()) { m_value = restoreParameter(); } return (m_value == null)? m_defaultValue : m_value; }
Source:
<code>@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { if (!(e instanceof TypeElement)) { error("@Module applies to a type, " + e.getSimpleName() + " is a " + e.getKind(), e); continue; } delayedModuleNames.add(((TypeElement) e).getQualifiedName().toString()); } return true; } Set<Element> modules = new LinkedHashSet<Element>(); for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); try { new ProblemDetector().detectProblems(bindings.values()); } catch (IllegalStateException e) { error("Graph validation failed: " + e.getMessage(), moduleType); continue; } try { writeDotFile(moduleType, bindings); } catch (IOException e) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.WARNING, <START> "Graph visualization failed. Please report this as a bug.\n\n" + e, moduleType); <END> } } return true; }</code><technical_language>Mind busywork get full stacktrace string for e ? NullPointerExceptions brutal diagnose. Pastable snippet in answer 2 here: <LINK_0></technical_language>

Target:
@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { if (!(e instanceof TypeElement)) { error("@Module applies to a type, " + e.getSimpleName() + " is a " + e.getKind(), e); continue; } delayedModuleNames.add(((TypeElement) e).getQualifiedName().toString()); } return true; } Set<Element> modules = new LinkedHashSet<Element>(); for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); try { new ProblemDetector().detectProblems(bindings.values()); } catch (IllegalStateException e) { error("Graph validation failed: " + e.getMessage(), moduleType); continue; } try { writeDotFile(moduleType, bindings); } catch (IOException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); processingEnv.getMessager() .printMessage(Diagnostic.Kind.WARNING, "Graph visualization failed. Please report this as a bug.\n\n" + sw, moduleType); } } return true; }
Source:
<code>private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); int keyOffset = readKeyOffset( cursor ); if ( keyOffset > pageSize ) { <START> cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); <END> } cursor.setOffset( keyOffset ); }</code><technical_language>PageCursor checks bounds, propagated in checkAndClearBoundsFlag() it? Do need do this specifically anyway</technical_language>

Target:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); int keyOffset = readKeyOffset( cursor ); if ( keyOffset > pageSize || keyOffset < 0 ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } cursor.setOffset( keyOffset ); }
Source:
<code>protected String retrieveAPISwaggerFromRegistry(API api, String requestURI) throws RegistryException { String resourcePath = api.getSwaggerResourcePath(); if (resourcePath == null) { StringBuilder resourcePathBuilder = new StringBuilder(); resourcePathBuilder.append(SwaggerConstants.DEFAULT_SWAGGER_REGISTRY_PATH).append(api.getAPIName()); if (!(api.getVersionStrategy() instanceof DefaultStrategy)) { resourcePathBuilder.append(":v").append(api.getVersion()); } resourcePathBuilder.append("/swagger.json"); <START> resourcePath = CONFIG_REG_PREFIX + resourcePathBuilder.toString(); <END> } return SwaggerUtils.fetchSwaggerFromRegistry(requestURI, resourcePath); }</code><technical_language>refactor removing this "CONFIG_REG_PREFIX" constant defined in SwaggerProcessorConstants.java. refactor usage of CONFIG_REG_PREFIX in SwaggerGenerator.java</technical_language>

Target:
protected String retrieveAPISwaggerFromRegistry(API api, String requestURI) throws RegistryException { String resourcePath = api.getSwaggerResourcePath(); if (resourcePath == null) { StringBuilder resourcePathBuilder = new StringBuilder(); resourcePathBuilder.append(SwaggerConstants.DEFAULT_SWAGGER_REGISTRY_PATH).append(api.getAPIName()); if (!(api.getVersionStrategy() instanceof DefaultStrategy)) { resourcePathBuilder.append(":v").append(api.getVersion()); } resourcePathBuilder.append("/swagger.json"); resourcePath = SwaggerProcessorConstants.CONFIG_REG_PREFIX + resourcePathBuilder.toString(); } return SwaggerUtils.fetchSwaggerFromRegistry(requestURI, resourcePath); }
Source:
<code>public static InputClauseLiteralExpression wbFromDMN(final org.kie.dmn.model.api.LiteralExpression dmn) { if (dmn == null) { return null; } Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef(), dmn); Text text = new Text(dmn.getText()); ImportedValues importedValues = ImportedValuesConverter.wbFromDMN(dmn.getImportedValues()); <START> InputClauseLiteralExpression result = new InputClauseLiteralExpression(id, <END> description, typeRef, text, importedValues); if (importedValues != null) { importedValues.setParent(result); } return result; }</code><technical_language>please declare local variables final</technical_language>

Target:
public static InputClauseLiteralExpression wbFromDMN(final org.kie.dmn.model.api.LiteralExpression dmn) { if (dmn == null) { return null; } final Id id = new Id(dmn.getId()); final Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); final QName typeRef = QNamePropertyConverter.wbFromDMN(dmn.getTypeRef(), dmn); final Text text = new Text(dmn.getText()); final ImportedValues importedValues = ImportedValuesConverter.wbFromDMN(dmn.getImportedValues()); final InputClauseLiteralExpression result = new InputClauseLiteralExpression(id, description, typeRef, text, importedValues); if (importedValues != null) { importedValues.setParent(result); } return result; }
Source:
<code>private void testUpdateWhenNearlyOutOfMemory() throws Exception { if (config.memory) { return; } deleteDb("outOfMemory"); String url = getURL("outOfMemory", true); / Child.main(url); try (Connection conn = getConnection("outOfMemory")) { Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT count(*) FROM stuff"); assertTrue(rs.next()); assertEquals(3000, rs.getInt(1)); rs = stat.executeQuery("SELECT * FROM stuff WHERE id = 3000"); assertTrue(rs.next()); String text = rs.getString(2); assertFalse(rs.wasNull()); assertEquals(1004, text.length()); } finally { deleteDb("outOfMemory"); } }</code><technical_language>plain "java" work for TestKillRestart</technical_language>

Target:
private void testUpdateWhenNearlyOutOfMemory() throws Exception { if (config.memory) { return; } deleteDb(DB_NAME); ProcessBuilder processBuilder = buildChild( DB_NAME + ";MAX_OPERATION_MEMORY=1000000", MyChild.class, "-XX:+UseParallelGC", "-Xmx128m"); / List<String> args = processBuilder.command(); for (Iterator<String> iter = args.iterator(); iter.hasNext(); ) { String arg = iter.next(); if(arg.equals(MyChild.class.getName())) { iter.remove(); break; } iter.remove(); } MyChild.main(args.toArray(new String[0])); try (Connection conn = getConnection(DB_NAME)) { Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT count(*) FROM stuff"); assertTrue(rs.next()); assertEquals(3000, rs.getInt(1)); rs = stat.executeQuery("SELECT * FROM stuff WHERE id = 3000"); assertTrue(rs.next()); String text = rs.getString(2); assertFalse(rs.wasNull()); assertEquals(1004, text.length()); rs = stat.executeQuery("SELECT sum(length(text)) FROM stuff"); assertTrue(rs.next()); int totalSize = rs.getInt(1); if (3010893 > totalSize) { TestBase.logErrorMessage("Durability failure - expected: 3010893, actual: " + totalSize); } } finally { deleteDb(DB_NAME); } }
Source:
<code>public HostMetrics(TaggedMetricRegistry registry, String serviceName, String hostname) { <START> informational = registry.meter(name(serviceName, hostname, "1xx")); <END> successful = registry.meter(name(serviceName, hostname, "2xx")); redirection = registry.meter(name(serviceName, hostname, "3xx")); clientError = registry.meter(name(serviceName, hostname, "4xx")); serverError = registry.meter(name(serviceName, hostname, "5xx")); other = registry.meter(name(serviceName, hostname, "other")); }</code><technical_language>*xx constants</technical_language>

Target:
public HostMetrics(TaggedMetricRegistry registry, String serviceName, String hostname) { informational = registry.meter(name(serviceName, hostname, INFORMATIONAL)); successful = registry.meter(name(serviceName, hostname, SUCCESSFUL)); redirection = registry.meter(name(serviceName, hostname, REDIRECTION)); clientError = registry.meter(name(serviceName, hostname, CLIENT_ERROR)); serverError = registry.meter(name(serviceName, hostname, SERVER_ERROR)); other = registry.meter(name(serviceName, hostname, OTHER)); }
Source:
<code>public void eventsControllerTest() throws Exception { <START> <END> Event event = new Event( "Test", "test", "test", 10, 10, "path/to/files", LocalDateTime.now(), LocalDateTime.now().plusHours(1), "Short description" ); when(eventService.getByKey(event.getKey())).thenReturn(event); mockMvc.perform(get("/sales/stats/event/" + event.getKey())) .andExpect(status().isOk()) .andExpect(view().name("sales/stats/event/index")) .andExpect(model().attributeExists("event", "moneyEarned", "ticketsSold", "orders", "key")); }</code><technical_language>remove</technical_language>

Target:
public void eventsControllerTest() throws Exception { Event event = createEvent(); mockMvc.perform(get("/sales/stats/event/" + event.getKey())) .andExpect(status().isOk()) .andExpect(view().name("sales/stats/event/index")) .andExpect(model().attributeExists("event", "moneyEarned", "ticketsSold", "orders")); }
Source:
<code>private void init() { if (jp == null) { try { long timeLeftMillis = timeoutAt - System.currentTimeMillis(); if (hasTimeout && timeLeftMillis < 1) { throw new TimeoutException(); } InputStream is = hasTimeout ? future.get(timeLeftMillis, TimeUnit.MILLISECONDS) : future.get(); if (responseHandler != null && responseHandler.getStatus() != HttpServletResponse.SC_OK) { throw new RE( "Unexpected response status [%s] description [%s] from request url [%s]", responseHandler.getStatus(), responseHandler.getDescription(), url ); } if (is == null) { throw new QueryInterruptedException( new ResourceLimitExceededException( "query[%s] url[%s] timed out or max bytes limit reached.", query != null ? query.getId() : null, url ), host ); } else { jp = objectMapper.getFactory().createParser(is); } final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_OBJECT) { QueryInterruptedException cause = jp.getCodec().readValue(jp, QueryInterruptedException.class); throw new QueryInterruptedException(cause, host); } else if (nextToken != JsonToken.START_ARRAY) { throw new IAE("Next token wasn't a START_ARRAY, was[%s] from url [%s]", jp.getCurrentToken(), url); } else { jp.nextToken(); objectCodec = jp.getCodec(); } } catch (TimeoutException ignored) { throw new QueryInterruptedException( <START> new ResourceLimitExceededException( <END> "query[%s] url[%s] timed out.", query != null ? query.getId() : null, url ), host ); } catch (IOException | InterruptedException | ExecutionException e) { throw new RE( e, "Failure getting results for query[%s] url[%s] because of [%s]", query == null ? null : query.getId(), url, e.getMessage() ); } catch (CancellationException e) { throw new QueryInterruptedException(e, host); } } }</code><technical_language>I TimeoutException is more ResourceLimitExceededException here. supposed for physical resources memory</technical_language>

Target:
private void init() { if (jp == null) { try { long timeLeftMillis = timeoutAt - System.currentTimeMillis(); if (hasTimeout && timeLeftMillis < 1) { throw new TimeoutException(StringUtils.format("url[%s] timed out", url)); } InputStream is = hasTimeout ? future.get(timeLeftMillis, TimeUnit.MILLISECONDS) : future.get(); if (responseHandler != null && responseHandler.getStatus() != HttpServletResponse.SC_OK) { interruptQuery( new RE( "Unexpected response status [%s] description [%s] from request url[%s]", responseHandler.getStatus(), responseHandler.getDescription(), url ) ); } if (is != null) { jp = objectMapper.getFactory().createParser(is); } else { interruptQuery( new ResourceLimitExceededException( "url[%s] timed out or max bytes limit reached.", url ) ); } final JsonToken nextToken = jp.nextToken(); if (nextToken == JsonToken.START_ARRAY) { jp.nextToken(); objectCodec = jp.getCodec(); } else if (nextToken == JsonToken.START_OBJECT) { interruptQuery(jp.getCodec().readValue(jp, QueryInterruptedException.class)); } else { interruptQuery( new IAE("Next token wasn't a START_ARRAY, was[%s] from url[%s]", jp.getCurrentToken(), url) ); } } catch (IOException | InterruptedException | ExecutionException | CancellationException | TimeoutException e) { interruptQuery(e); } } }
Source:
<code>public void testRegexMatchesTopicsAWhenCreated() throws Exception { <START> final String outputTopic = createTopic(topicSuffixGenerator.incrementAndGet()); <END> final Serde<String> stringSerde = Serdes.String(); final List<String> expectedFirstAssignment = Collections.singletonList("TEST-TOPIC-1"); final List<String> expectedSecondAssignment = Arrays.asList("TEST-TOPIC-1", "TEST-TOPIC-2"); CLUSTER.createTopic("TEST-TOPIC-1"); final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> pattern1Stream = builder.stream(Pattern.compile("TEST-TOPIC-\\d")); pattern1Stream.to(outputTopic, Produced.with(stringSerde, stringSerde)); final List<String> assignedTopics = new CopyOnWriteArrayList<>(); streams = new KafkaStreams(builder.build(), streamsConfiguration, new DefaultKafkaClientSupplier() { @Override public Consumer<byte[], byte[]> getConsumer(final Map<String, Object> config) { return new KafkaConsumer<byte[], byte[]>(config, new ByteArrayDeserializer(), new ByteArrayDeserializer()) { @Override public void subscribe(final Pattern topics, final ConsumerRebalanceListener listener) { super.subscribe(topics, new TheConsumerRebalanceListener(assignedTopics, listener)); } }; } }); streams.start(); TestUtils.waitForCondition(() -> assignedTopics.equals(expectedFirstAssignment), STREAM_TASKS_NOT_UPDATED); CLUSTER.createTopic("TEST-TOPIC-2"); TestUtils.waitForCondition(() -> assignedTopics.equals(expectedSecondAssignment), STREAM_TASKS_NOT_UPDATED); }</code><technical_language>I this counter, this in setUp() method outputTopic a class member</technical_language>

Target:
public void testRegexMatchesTopicsAWhenCreated() throws Exception { final Serde<String> stringSerde = Serdes.String(); final List<String> expectedFirstAssignment = Collections.singletonList("TEST-TOPIC-1"); final List<String> expectedSecondAssignment = Arrays.asList("TEST-TOPIC-1", "TEST-TOPIC-2"); CLUSTER.createTopic("TEST-TOPIC-1"); final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> pattern1Stream = builder.stream(Pattern.compile("TEST-TOPIC-\\d")); pattern1Stream.to(outputTopic, Produced.with(stringSerde, stringSerde)); final List<String> assignedTopics = new CopyOnWriteArrayList<>(); streams = new KafkaStreams(builder.build(), streamsConfiguration, new DefaultKafkaClientSupplier() { @Override public Consumer<byte[], byte[]> getConsumer(final Map<String, Object> config) { return new KafkaConsumer<byte[], byte[]>(config, new ByteArrayDeserializer(), new ByteArrayDeserializer()) { @Override public void subscribe(final Pattern topics, final ConsumerRebalanceListener listener) { super.subscribe(topics, new TheConsumerRebalanceListener(assignedTopics, listener)); } }; } }); streams.start(); TestUtils.waitForCondition(() -> assignedTopics.equals(expectedFirstAssignment), STREAM_TASKS_NOT_UPDATED); CLUSTER.createTopic("TEST-TOPIC-2"); TestUtils.waitForCondition(() -> assignedTopics.equals(expectedSecondAssignment), STREAM_TASKS_NOT_UPDATED); }
Source:
<code><START> protected Button getAddButton() { <END> final Optional<Control> control = getControlForAction(AddRowAction.ACTION_ID); if (control.isPresent()) { return (Button) control.get(); } return null; }</code><technical_language>move get null return method code duplication, method private</technical_language>

Target:
protected Button getAddButton() { final Optional<Control> control = getControlForAction( org.eclipse.emfforms.spi.swt.table.action.AddRowAction.ACTION_ID); if (control.isPresent()) { return (Button) control.get(); } return null; }
Source:
<code>public void onBackPressed() { if (referencesViewPager.getCurrentItem() > 0) { referencesViewPager.setCurrentItem(referencesViewPager.getCurrentItem() - 1, true); <START> } <END> }</code><technical_language>This correctly cycles pager button is pressed. However, position is reached, button effect (i.e. dialog close is pressed). handle final case, add else following: else { super.onBackPressed(); }</technical_language>

Target:
public void onBackPressed() { if (referencesViewPager.getCurrentItem() > 0) { referencesViewPager.setCurrentItem(referencesViewPager.getCurrentItem() - 1, true); } else { super.onBackPressed(); } }
Source:
<code>public List<FuturesPosition> getFuturesPositions() throws IOException { FuturesPositionsResponse res = okex.getFuturesPositions(apikey, digest, timestamp(), passphrase); res.checkResult(); List<List<FuturesPosition>> holding = res.getHolding(); <START> return holding == null || holding.isEmpty() ? new ArrayList<>() : holding.get(0); <END> }</code><technical_language>Collections.EMPTY_LIST instead of new ArrayList<>()</technical_language>

Target:
public List<FuturesPosition> getFuturesPositions() throws IOException { FuturesPositionsResponse res = okex.getFuturesPositions(apikey, digest, timestamp(), passphrase); res.checkResult(); List<List<FuturesPosition>> holding = res.getHolding(); return holding == null || holding.isEmpty() ? Collections.emptyList() : holding.get(0); }
Source:
<code>public void init() { post( "/list/import", (request, response) -> { MultipartConfigElement multipartConfigElement = new MultipartConfigElement(""); request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement); String listType = request.headers(LIST_TYPE_HEADER); if (StringUtils.isBlank(listType)) { String exceptionMessage = String.format("The header %s must be set.", LIST_TYPE_HEADER); LOGGER.info(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } List<Part> parts = new ArrayList<>(request.raw().getParts()); AttachmentInfo attachmentInfo = parseAttachments(parts); if (attachmentInfo == null) { String exceptionMessage = "Unable to parse the attachments."; LOGGER.debug(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) { IOUtils.copy(attachmentInfo.getStream(), temporaryFileBackedOutputStream); for (Splitter splitter : lookupSplitters(attachmentInfo.getContentType())) { try { if (attemptToSplitAndStore( response, listType, attachmentInfo, temporaryFileBackedOutputStream, splitter)) break; } catch (StopSplitterExecutionException e) { <START> String exceptionMessage = "Attached files do not contain the correct mimetypes"; <END> LOGGER.debug(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } } } IOUtils.closeQuietly(attachmentInfo.getStream()); return ""; }); }</code><technical_language>This message pretty specific for exception. print stack trace code threw convey reason failed</technical_language>

Target:
public void init() { post( "/list/import", (request, response) -> { MultipartConfigElement multipartConfigElement = new MultipartConfigElement(""); request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement); String listType = request.headers(LIST_TYPE_HEADER); if (StringUtils.isBlank(listType)) { String exceptionMessage = String.format("The header %s must be set.", LIST_TYPE_HEADER); LOGGER.info(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } List<Part> parts = new ArrayList<>(request.raw().getParts()); AttachmentInfo attachmentInfo = parseAttachments(parts); if (attachmentInfo == null) { String exceptionMessage = "Unable to parse the attachments."; LOGGER.debug(exceptionMessage); createBadRequestResponse(exceptionMessage, response); return null; } try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) { IOUtils.copy(attachmentInfo.getStream(), temporaryFileBackedOutputStream); for (Splitter splitter : lookupSplitters(attachmentInfo.getContentType())) { try { if (attemptToSplitAndStore( response, listType, attachmentInfo, temporaryFileBackedOutputStream, splitter)) break; } catch (StopSplitterExecutionException e) { LOGGER.debug("Failed to split file.", e); createBadRequestResponse( "Attached files do not contain the correct mimetypes", response); return null; } } } IOUtils.closeQuietly(attachmentInfo.getStream()); return ""; }); }
Source:
<code>private void declaration(@Nullable IBinding binding, Tree node) { if (binding == null) { return; } <START> sema.declarations.put(sema.declarationBinding(binding), node); <END> }</code><technical_language>IMO for declarations binding == sema.declarationBinding(binding) already</technical_language>

Target:
private void declaration(@Nullable IBinding binding, Tree node) { if (binding == null) { return; } sema.declarations.put(binding, node); }
Source:
<code>public void adjustBaseTableCost(ResultSetNode rsn) throws StandardException { if (fetchFirst==-1 && offset ==-1) return; CostEstimate costEstimate = rsn.getFinalCostEstimate(false); long totalRowCount = costEstimate.getEstimatedRowCount(); long currentOffset = offset==-1?0:offset; long currentFetchFirst = fetchFirst==-1?totalRowCount:fetchFirst; scaleFactor = (double) currentFetchFirst/(double) totalRowCount; if (scaleFactor >= 1.0d) { } else { costEstimate.setEstimatedRowCount(currentFetchFirst); costEstimate.setSingleScanRowCount(currentFetchFirst); costEstimate.setRowCount(currentFetchFirst); costEstimate.setProjectionRows(currentFetchFirst); costEstimate.setIndexLookupRows(costEstimate.getIndexLookupRows()*scaleFactor); costEstimate.setEstimatedHeapSize((long)(costEstimate.getEstimatedHeapSize()*scaleFactor)); costEstimate.setRemoteCost((long)(costEstimate.getRemoteCost()*scaleFactor)); costEstimate.setFromBaseTableCost(costEstimate.getFromBaseTableCost()*scaleFactor); costEstimate.setFromBaseTableRows(costEstimate.getFromBaseTableRows()*scaleFactor); costEstimate.setScannedBaseTableRows(costEstimate.getScannedBaseTableRows()*scaleFactor); costEstimate.setEstimatedCost(costEstimate.getEstimatedCost()*scaleFactor); int numPartitions = costEstimate.partitionCount(); if (numPartitions <= 0) numPartitions = 1; <START> costEstimate.setRemoteCostPerPartition(costEstimate.remoteCost()/numPartitions); <END> } }</code><technical_language>a copy paste, creating a private method do calculation, e.g. private void setRemoteCostPerPartition(...)</technical_language>

Target:
public void adjustBaseTableCost(ResultSetNode rsn) throws StandardException { if (fetchFirst==-1 && offset ==-1) return; CostEstimate costEstimate = rsn.getFinalCostEstimate(false); long totalRowCount = costEstimate.getEstimatedRowCount(); long currentOffset = offset==-1?0:offset; long currentFetchFirst = fetchFirst==-1?totalRowCount:fetchFirst; scaleFactor = (double) currentFetchFirst/(double) totalRowCount; if (scaleFactor >= 1.0d) { } else { costEstimate.setEstimatedRowCount(currentFetchFirst); costEstimate.setSingleScanRowCount(currentFetchFirst); costEstimate.setRowCount(currentFetchFirst); costEstimate.setProjectionRows(currentFetchFirst); costEstimate.setIndexLookupRows(costEstimate.getIndexLookupRows()*scaleFactor); costEstimate.setEstimatedHeapSize((long)(costEstimate.getEstimatedHeapSize()*scaleFactor)); costEstimate.setRemoteCost((long)(costEstimate.getRemoteCost()*scaleFactor)); costEstimate.setFromBaseTableCost(costEstimate.getFromBaseTableCost()*scaleFactor); costEstimate.setFromBaseTableRows(costEstimate.getFromBaseTableRows()*scaleFactor); costEstimate.setScannedBaseTableRows(costEstimate.getScannedBaseTableRows()*scaleFactor); costEstimate.setEstimatedCost(costEstimate.getEstimatedCost()*scaleFactor); costEstimate.setRemoteCostPerPartition(costEstimate.remoteCost(), costEstimate.partitionCount()); } }
Source:
<code>private void onMessage(final String message, final String file, final String details, final int line) { if (message == "sourcefile") { <START> server_.profileSources(file, new ServerRequestCallback<String>() <END> { @Override public void onResponseReceived(String response) { selectedPath_ = file; selectedLine_ = line; hasValidPath_ = !StringUtil.isNullOrEmpty(response); commands_.gotoProfileSource().setEnabled(hasValidPath_); if (details == "open") { if (hasValidPath_) { FilePosition filePosition = FilePosition.create(line, 0); CodeNavigationTarget navigationTarget = new CodeNavigationTarget(file, filePosition); fileTypeRegistry_.editFile( FileSystemItem.createFile(navigationTarget.getFile()), filePosition); } else { globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening profiler source", "Could not find reference to: " + selectedPath_); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } }</code><technical_language>this RPC do more check a file exists. RPC this -- FilesServerOperations.stat; returns a FileSystemItem call exists()</technical_language>

Target:
private void onMessage(final String message, final String file, final String details, final int line) { if (message == "sourcefile") { server_.profileSources(file, new ServerRequestCallback<String>() { @Override public void onResponseReceived(String response) { selectedPath_ = file; selectedLine_ = line; hasValidPath_ = !StringUtil.isNullOrEmpty(response); commands_.gotoProfileSource().setEnabled(hasValidPath_); if (details == "open") { if (hasValidPath_) { FilePosition filePosition = FilePosition.create(line, 0); CodeNavigationTarget navigationTarget = new CodeNavigationTarget(file, filePosition); fileTypeRegistry_.editFile( FileSystemItem.createFile(navigationTarget.getFile()), filePosition); } else { globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening profiler source", "The source file " + selectedPath_ + " does not exist."); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } }
Source:
<code>public final boolean preventCommit () { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("BasicAction::preventCommit( " + this + ")"); } boolean res = false; { synchronized (this) { if (actionStatus == ActionStatus.RUNNING) actionStatus = ActionStatus.ABORT_ONLY; } res = ((actionStatus == ActionStatus.ABORT_ONLY) || (actionStatus == ActionStatus.ABORTED) || (actionStatus == ActionStatus.ABORTING)); } <START> createPreparedLists(); <END> return res; }</code><technical_language>this need done in arjunaCore guarded in XTS alone? is fine if is arjunaCore issue code fix I need arjunacore test case shows this reasoning sole change in XTS</technical_language>

Target:
public final boolean preventCommit () { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("BasicAction::preventCommit( " + this + ")"); } boolean res = false; { synchronized (this) { if (actionStatus == ActionStatus.RUNNING) actionStatus = ActionStatus.ABORT_ONLY; } res = ((actionStatus == ActionStatus.ABORT_ONLY) || (actionStatus == ActionStatus.ABORTED) || (actionStatus == ActionStatus.ABORTING)); } return res; }
Source:
<code>public void onMultipleActionsTest() { assertEquals(0, receiver.multipleActionCall); <START> Intent intent = new Intent("ACTION_MULTIPLE_TEST_1"); <END> receiver.onReceive(Robolectric.application, intent); assertEquals(1, receiver.multipleActionCall); intent = new Intent("ACTION_MULTIPLE_TEST_2"); receiver.onReceive(Robolectric.application, intent); assertEquals(2, receiver.multipleActionCall); }</code><technical_language>Move strings constants</technical_language>

Target:
public void onMultipleActionsTest() { assertEquals(0, receiver.multipleActionCall); Intent intent = new Intent(ReceiverWithActions.ACTION_MULTIPLE_TEST_1); receiver.onReceive(Robolectric.application, intent); assertEquals(1, receiver.multipleActionCall); intent = new Intent(ReceiverWithActions.ACTION_MULTIPLE_TEST_2); receiver.onReceive(Robolectric.application, intent); assertEquals(2, receiver.multipleActionCall); }
Source:
<code>private void postDescription(@NonNull String editToken) { final String description = StringUtil.emptyIfNull(editView.getDescription()); descriptionEditCall = new DescriptionEditClient().request(wikiData, pageTitle, description, editToken, new DescriptionEditClient.Callback() { @Override <START> @SuppressWarnings("checkstyle:magicnumber") <END> public void success(@NonNull Call<DescriptionEdit> call) { if (getActivity() == null) { return; } DeviceUtil.hideSoftKeyboard(getActivity()); editView.setSaveState(false); startActivityForResult(DescriptionEditSuccessActivity.newIntent(getContext(), description), Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS); } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, String info) { editView.setSaveState(false); editView.setError(info); } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editFailed(caught); } }); }</code><technical_language>I literal numbers in this method. is @SuppressWarnings("checkstyle:magicnumber") needed</technical_language>

Target:
private void postDescription(@NonNull String editToken) { final String description = StringUtil.emptyIfNull(editView.getDescription()); descriptionEditCall = new DescriptionEditClient().request(wikiData, pageTitle, description, editToken, new DescriptionEditClient.Callback() { @Override public void success(@NonNull Call<DescriptionEdit> call) { if (getActivity() == null) { return; } DeviceUtil.hideSoftKeyboard(getActivity()); editView.setSaveState(false); startActivityForResult(DescriptionEditSuccessActivity.newIntent(getContext(), description), Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS); } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, String info) { editView.setSaveState(false); editView.setError(info); } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editFailed(caught); } }); }
Source:
<code>public void init() throws IOException { final Properties producerConfig = new Properties(); final Dictionary<String, Object> properties = configAdmin.getConfiguration(KAFKA_CLIENT_PID).getProperties(); if (properties != null) { final Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { final String key = keys.nextElement(); producerConfig.put(key, properties.get(key)); } } producerConfig.put("key.serializer", StringSerializer.class.getCanonicalName()); producerConfig.put("value.serializer", ByteArraySerializer.class.getCanonicalName()); final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(null); producer = new KafkaProducer<>(producerConfig); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } if(kafkaSendQueueCapacity <= 0) { kafkaSendQueueCapacity = 1000; <START> Log.info("Defaulted the 'kafkaSendQueueCapacity' to 1000 since no property was set"); <END> } kafkaSendQueue = new LinkedBlockingQueue<>(kafkaSendQueueCapacity); kafkaSendQueueExecutor.execute(this::processKafkaSendQueue); if (forwardEvents) { eventSubscriptionService.addEventListener(this); } }</code><technical_language>LOG Log (currently org.jline.utils.Log)</technical_language>

Target:
public void init() throws IOException { final Properties producerConfig = new Properties(); final Dictionary<String, Object> properties = configAdmin.getConfiguration(KAFKA_CLIENT_PID).getProperties(); if (properties != null) { final Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { final String key = keys.nextElement(); producerConfig.put(key, properties.get(key)); } } producerConfig.put("key.serializer", StringSerializer.class.getCanonicalName()); producerConfig.put("value.serializer", ByteArraySerializer.class.getCanonicalName()); final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(null); producer = new KafkaProducer<>(producerConfig); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } if(kafkaSendQueueCapacity <= 0) { kafkaSendQueueCapacity = 1000; LOG.info("Defaulted the 'kafkaSendQueueCapacity' to 1000 since no property was set"); } kafkaSendQueue = new LinkedBlockingQueue<>(kafkaSendQueueCapacity); kafkaSendQueueExecutor.execute(this::processKafkaSendQueue); if (forwardEvents) { eventSubscriptionService.addEventListener(this); } }
Source:
<code>OrientDB orientDB() throws IOException { OrientDB orientDB = new OrientDB(StringUtils.substringBeforeLast(connectionConfig.getUrl(), "/"), connectionConfig.getUsername(), connectionConfig.getPassword(), getOrientDBConfig()); String database = connectionConfig.getDatabase(); if (!orientDB.exists(database)) { logger.info(String.format("Unpacking database from snapshot [%s]...", database)); <START> try (InputStream is = new ClassPathResource("db/snapshot/strongbox-db-snapshot.zip").getInputStream()) <END> { ZipUtil.unpack(is, new File(EmbeddedOrientDbServer.getDatabasePath() + "/strongbox")); } } else { logger.info("Re-using existing database " + database + "."); } return orientDB; }</code><technical_language>java.util.zip.ZipInputStream instead of ZipUtil</technical_language>

Target:
OrientDB orientDB() throws IOException { OrientDB orientDB = new OrientDB(StringUtils.substringBeforeLast(connectionConfig.getUrl(), "/"), connectionConfig.getUsername(), connectionConfig.getPassword(), getOrientDBConfig()); String database = connectionConfig.getDatabase(); if (!orientDB.exists(database)) { logger.info(String.format("Database does not exist. Copying fresh database snapshot from [%s]...", databaseSnapshotResource.getURI())); Path snapshotPath = Paths.get(databaseSnapshotResource.getURI()); FileSystemUtils.copyRecursively(snapshotPath, Paths.get(databasePath)); } else { logger.info("Re-using existing database " + database + "."); } return orientDB; }
Source:
<code>public void singleAtomicCallFieldTest() { String functionName = "singleAtomic"; CallManager.CallableEndpoint callableEndpoint = endpointUtil.makeCallableEndpoint(functionName); CallManager.OneCaller<Double> caller = endpointUtil.makeOneCaller(callableEndpoint, Double.class); class Output { Double expectedOutput = 0.0; } final Output output = new Output(); CallBatcher<CallArgs, OneCallEvent<Double>> batcher = caller .batcher() .forArgs() .withDefaultArgs(caller.args().param("param1", 1.2)) .onCallSuccess(event -> { output.expectedOutput = event.getItem(); }) .onCallFailure((event, throwable) -> { throwable.printStackTrace(); fail("atomic batcher failed"); }); <START> batcher.getDataMovementManager().startJob(batcher); <END> batcher.add(caller.args()); batcher.flushAndWait(); batcher.getDataMovementManager().stopJob(batcher); assertEquals("for single atomic callField, output not equal to input", Double.valueOf(1.2), output.expectedOutput); }</code><technical_language>start() in previous version of line 101 is supported (and revision simpler). Also, know, adding arguments implicitly starts a job</technical_language>

Target:
public void singleAtomicCallFieldTest() { String functionName = "singleAtomic"; CallManager.CallableEndpoint callableEndpoint = endpointUtil.makeCallableEndpoint(functionName); CallManager.OneCaller<Double> caller = endpointUtil.makeOneCaller(callableEndpoint, Double.class); class Output { Double expectedOutput = 0.0; } final Output output = new Output(); CallBatcher<CallArgs, OneCallEvent<Double>> batcher = caller .batcher() .forArgs() .withDefaultArgs(caller.args().param("param1", 1.2)) .onCallSuccess(event -> { output.expectedOutput = event.getItem(); }) .onCallFailure((event, throwable) -> { throwable.printStackTrace(); fail("atomic batcher failed"); }); batcher.add(caller.args()); batcher.flushAndWait(); assertEquals("for single atomic callField, output not equal to input", Double.valueOf(1.2), output.expectedOutput); batcher.add(caller.args().param("param1", 1.1)); batcher.flushAndWait(); assertEquals("for single atomic callField, output not equal to input", Double.valueOf(1.1), output.expectedOutput); batcher.getDataMovementManager().stopJob(batcher); }
Source:
<code>public static void runBlockingActionWithMessageBoxDefaultResult(IRunnable runnable, int messageBoxResult) { ClientRunContexts.copyCurrent() <START> .withThreadLocal(ClientSessionProviderWithCache.MESSAGE_BOX_HANDLER_STRATEGY, (t) -> messageBoxResult) <END> .run(runnable); }</code><technical_language>mbox easier read instead of t single-argument lamda expressions do require braces, style currently in scout</technical_language>

Target:
public static void runBlockingActionWithMessageBoxDefaultResult(IRunnable runnable, int messageBoxResult) { ClientRunContexts.copyCurrent() .withThreadLocal(ClientSessionProviderWithCache.MESSAGE_BOX_HANDLER_STRATEGY, mBox -> messageBoxResult) .run(runnable); }
Source:
<code>private void pushUpstream(final RevCommit commit, final PushMode pushTo) { RemoteConfig config = SimpleConfigurePushDialog .getConfiguredRemote(repository); if (pushTo == PushMode.GERRIT) { final Wizard pushWizard = new PushToGerritWizard(repository); openPushWizard(pushWizard); } else <START> { <END> if (config == null) { try { Wizard pushWizard = null; String fullBranch = repository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { Ref ref = repository.getRef(fullBranch); pushWizard = new PushBranchWizard(repository, ref); } else { pushWizard = new PushBranchWizard(repository, commit.getId()); } openPushWizard(pushWizard); } catch (IOException e) { Activator.handleError( NLS.bind(UIText.CommitUI_pushFailedMessage, e), e, true); } } else { PushOperationUI op = new PushOperationUI(repository, config.getName(), false); op.start(); } } }</code><technical_language>unnecessary braces</technical_language>

Target:
private void pushUpstream(final RevCommit commit, final PushMode pushTo) { RemoteConfig config = SimpleConfigurePushDialog .getConfiguredRemote(repository); if (pushTo == PushMode.GERRIT) { final Wizard pushWizard = new PushToGerritWizard(repository); openPushWizard(pushWizard); } else if (config == null) { try { Wizard pushWizard = null; String fullBranch = repository.getFullBranch(); if (fullBranch != null && fullBranch.startsWith(Constants.R_HEADS)) { Ref ref = repository.getRef(fullBranch); pushWizard = new PushBranchWizard(repository, ref); } else { pushWizard = new PushBranchWizard(repository, commit.getId()); } openPushWizard(pushWizard); } catch (IOException e) { Activator.handleError( NLS.bind(UIText.CommitUI_pushFailedMessage, e), e, true); } } else { PushOperationUI op = new PushOperationUI(repository, config.getName(), false); op.start(); } }
Source:
<code><START> public static boolean isValidEmailFormat ( String email ) { <END> return isValidEmailFormat(email, VALID_EMAIL_ADDRESS_REGEX); }</code><technical_language>I favour of external library handles email validations, including regex here. a [JavaMail](<LINK_0> [Apache Commons Validator](<LINK_1> for some ideas</technical_language>

Target:
public static boolean isValidEmailFormat ( String email ) { boolean isValid = false; try { InternetAddress emailAddress = new InternetAddress(email); emailAddress.validate(); isValid = true; } catch (AddressException ex) { isValid = false; logger.warn("Email " + email + " is invalid"); } return isValid; }
Source:
<code>private void initialiseAndValidateDefaultErrorHandler() { String defaultErrorHandler = getDefaultErrorHandlerName(); if (defaultErrorHandler != null) { FlowExceptionHandler messagingExceptionHandler = registry.<FlowExceptionHandler>lookupByName(defaultErrorHandler) .orElseThrow(() -> new MuleRuntimeException(createStaticMessage(format("No global error handler defined with name '%s'.", defaultErrorHandler)))); if (messagingExceptionHandler instanceof MessagingExceptionHandlerAcceptor) { MessagingExceptionHandlerAcceptor messagingExceptionHandlerAcceptor = (MessagingExceptionHandlerAcceptor) messagingExceptionHandler; if (!messagingExceptionHandlerAcceptor.acceptsAll()) { <START> throw new MuleRuntimeException(createStaticMessage("Default exception strategy must not have expression attribute. It must accept any message.")); <END> } } } }</code><technical_language>this throw InitialisationException</technical_language>

Target:
private void initialiseAndValidateDefaultErrorHandler() throws InitialisationException { String defaultErrorHandler = getDefaultErrorHandlerName(); if (defaultErrorHandler != null) { FlowExceptionHandler messagingExceptionHandler = registry.<FlowExceptionHandler>lookupByName(defaultErrorHandler) .orElseThrow(() -> new InitialisationException(createStaticMessage(format("No global error handler defined with name '%s'.", defaultErrorHandler)), this)); if (messagingExceptionHandler instanceof MessagingExceptionHandlerAcceptor) { MessagingExceptionHandlerAcceptor messagingExceptionHandlerAcceptor = (MessagingExceptionHandlerAcceptor) messagingExceptionHandler; if (!messagingExceptionHandlerAcceptor.acceptsAll()) { throw new InitialisationException(createStaticMessage("Default exception strategy must not have expression attribute. It must accept any message."), this); } } } }
Source:
<code>public Call<Captcha> request(@NonNull WikiSite wiki, @NonNull Callback cb) { Service service = <START> new MwCachedService<>(Service.class).service(wiki); <END> return request(service, cb); }</code><technical_language>this create a new Service a new Service cache request</technical_language>

Target:
public Call<Captcha> request(@NonNull WikiSite wiki, @NonNull Callback cb) { Service service = cachedService.service(wiki); return request(service, cb); }
Source:
<code>public void deleteAllAllergies() throws Exception { handle(newDeleteRequest(getURI(), new Parameter("reason", "unit test"))); Allergy allergy = Context.getPatientService().getAllergy(AALLERGY_ID); Assert.assertTrue(allergy.isVoided()); <START> Assert.assertEquals("unit test", allergy.getVoidReason()); <END> }</code><technical_language>need assert status is Unknown</technical_language>

Target:
public void deleteAllAllergies() throws Exception { handle(newDeleteRequest(getURI(), new Parameter("reason", "unit test"))); Allergy allergy = Context.getPatientService().getAllergyByUuid(getUuid()); Allergies allergies = Context.getPatientService().getAllergies(allergy.getPatient()); Assert.assertTrue(allergy.isVoided()); Assert.assertEquals("unit test", allergy.getVoidReason()); Assert.assertEquals(Allergies.UNKNOWN, allergies.getAllergyStatus()); }
Source:
<code>public void setSpacing(int spacing) { <START> this.spacing = spacing; <END> }</code><technical_language>happen if calls setSpacing showing CTabFolder? I expect this redrawing new setting</technical_language>

Target:
public void setSpacing(int spacing) { if(spacing < 0 || spacing > 3) SWT.error(SWT.ERROR_INVALID_ARGUMENT); this.spacing = spacing; updateFolder(REDRAW_TABS); }