auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static String interpolateLine(String line, Properties properties, String[] delimiters) { if (delimiters == null) { return line; } Pattern propertyPattern = Pattern.compile("(?<variable>" + Pattern.quote(delimiters[0]) + "(?<prop>.*?)" + Pattern.quote(delimiters[1]) + ")"); Matcher matcher = propertyPattern.matcher(line); <START> StringBuffer ret = new StringBuffer(); <END> while (matcher.find()) { String prop = matcher.group("prop"); String value = properties.containsKey(prop) ? properties.getProperty(prop) : matcher.group("variable"); matcher.appendReplacement(ret, value.replace("$","\\$")); } matcher.appendTail(ret); return ret.toString(); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Replace synchronized class "StringBuffer" unsynchronized "StringBuilder". [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private static String interpolateLine(String line, Properties properties, String[] delimiters) { if (delimiters == null || delimiters.length == 0) { return line; } Pattern propertyPattern = Pattern.compile("(?<variable>" + Pattern.quote(delimiters[0]) + "(?<prop>.*?)" + Pattern.quote(delimiters[1]) + ")"); Matcher matcher = propertyPattern.matcher(line); StringBuffer ret = new StringBuffer(); while (matcher.find()) { String prop = matcher.group("prop"); String value = properties.containsKey(prop) ? properties.getProperty(prop) : matcher.group("variable"); matcher.appendReplacement(ret, value.replace("$","\\$")); } matcher.appendTail(ret); return ret.toString(); }
Source:
<code>public Collection<ITemplate> getTemplates() { Collection<ITemplate> all = new ArrayList<ITemplate>(); try { all.addAll(client.<ITemplate>list(ResourceKind.Template, DEFAULT_NAMESPACE)); }catch(UnauthorizedException e) { <START> LOG.warn("Unauthorized to list templates in the default namespace", DEFAULT_NAMESPACE, e); <END> }catch(OpenShiftException e) { LOG.error("Error getting templates from the default namespace", DEFAULT_NAMESPACE, e); } all.addAll(client.<ITemplate>list(ResourceKind.Template, project.getNamespace())); return all; }</code><technical_language>Shouldnt exceptions bubble caller "interrupt" call</technical_language>

Target:
public Collection<ITemplate> getTemplates() { return client.<ITemplate>list(ResourceKind.Template, project.getNamespace()); }
Source:
<code>public EmailLogEntry(AppLogLine appLog) { time = appLog.getTimeUsec() / 1000; String[] tokens = appLog.getLogMessage() .split(Pattern.quote(Const.EmailLog.FIELD_SEPARATOR), -1); try { receiver = tokens[1]; subject = tokens[2]; content = tokens[3]; } catch (ArrayIndexOutOfBoundsException e) { receiver = ""; subject = ""; <START> content = ""; <END> } }</code><technical_language>if related add some logging if exception occurs</technical_language>

Target:
public EmailLogEntry(AppLogLine appLog) { time = appLog.getTimeUsec() / 1000; String[] tokens = appLog.getLogMessage() .split(Pattern.quote(Const.EmailLog.FIELD_SEPARATOR), -1); try { receiver = tokens[1]; subject = tokens[2]; content = tokens[3]; } catch (ArrayIndexOutOfBoundsException e) { receiver = ""; subject = ""; content = ""; log.severe(String.format(Const.EmailLog.ERROR_LOG_FORMAT, appLog.getLogMessage())); } }
Source:
<code>public void announceSegment(DataSegment segment) throws IOException { int newBytesLen = jsonMapper.writeValueAsBytes(segment).length; if (newBytesLen > config.getMaxBytesPerNode()) { throw new ISE("byte size %,d exceeds %,d", newBytesLen, config.getMaxBytesPerNode()); } synchronized (lock) { boolean done = false; if (!availableZNodes.isEmpty()) { Iterator<SegmentZNode> iter = availableZNodes.iterator(); while (iter.hasNext() && !done) { SegmentZNode availableZNode = iter.next(); if (availableZNode.getBytes().length + newBytesLen < config.getMaxBytesPerNode()) { availableZNode.addSegment(segment); log.info("Announcing segment[%s] at path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.update(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); if (availableZNode.getCount() >= config.getSegmentsPerNode()) { availableZNodes.remove(availableZNode); } done = true; } else { <START> availableZNodes.remove(availableZNode); <END> } } } if (!done) { assert (availableZNodes.isEmpty()); SegmentZNode availableZNode = new SegmentZNode(makeServedSegmentPath()); availableZNode.addSegment(segment); log.info("Announcing segment[%s] at path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.announce(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); availableZNodes.add(availableZNode); } } }</code><technical_language>technically need remove node, is for another segment announcement fit in there, this specific one</technical_language>

Target:
public void announceSegment(DataSegment segment) throws IOException { int newBytesLen = jsonMapper.writeValueAsBytes(segment).length; if (newBytesLen > config.getMaxBytesPerNode()) { throw new ISE("byte size %,d exceeds %,d", newBytesLen, config.getMaxBytesPerNode()); } synchronized (lock) { boolean done = false; if (!availableZNodes.isEmpty()) { Iterator<SegmentZNode> iter = availableZNodes.iterator(); while (iter.hasNext() && !done) { SegmentZNode availableZNode = iter.next(); if (availableZNode.getBytes().length + newBytesLen < config.getMaxBytesPerNode()) { availableZNode.addSegment(segment); log.info("Announcing segment[%s] at existing path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.update(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); if (availableZNode.getCount() >= config.getSegmentsPerNode()) { availableZNodes.remove(availableZNode); } done = true; } else { availableZNodes.remove(availableZNode); } } } if (!done) { assert (availableZNodes.isEmpty()); SegmentZNode availableZNode = new SegmentZNode(makeServedSegmentPath()); availableZNode.addSegment(segment); log.info("Announcing segment[%s] at new path[%s]", segment.getIdentifier(), availableZNode.getPath()); announcer.announce(availableZNode.getPath(), availableZNode.getBytes()); segmentLookup.put(segment, availableZNode); availableZNodes.add(availableZNode); } } }
Source:
<code><START> public void convertDevicePropertiesToMap() { <END> String customDevPropSpec = "{type=interface;prop={speed=[0-9]{1,5};duplex=^(full|half)$}}"; DevicePropertiesUtils utils = mockDevicePropertiesUtils(customDevPropSpec); assertTrue(utils.isDevicePropertiesDefinitionValid(customDevPropSpec)); VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.INTERFACE); device.setCustomProperties("speed=1024;duplex=half"); Map<String, String> map = utils.getDeviceProperties(Version.v3_3, device); String value; assertNotNull(map); assertTrue(map.size() == 2); value = map.get("speed"); assertNotNull(value); assertTrue(value.equals("1024")); value = map.get("duplex"); assertNotNull(value); assertTrue(value.equals("half")); }</code><technical_language>Thanks for test</technical_language>

Target:
public void convertDevicePropertiesToMap() { String customDevPropSpec = "{type=interface;prop={speed=[0-9]{1,5};duplex=^(full|half)$}}"; DevicePropertiesUtils utils = mockDevicePropertiesUtils(customDevPropSpec); assertTrue(utils.isDevicePropertiesDefinitionValid(customDevPropSpec)); VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.INTERFACE); device.setCustomProperties("speed=1024;duplex=half"); Map<String, String> map = utils.getDeviceProperties(Version.v3_3, device); String value; assertNotNull(map); assertEquals(2, map.size()); value = map.get("speed"); assertNotNull(value); assertEquals("1024", value); value = map.get("duplex"); assertNotNull(value); assertEquals("half", value); }
Source:
<code>protected String enumValueToSchemaString(Enum<?> value) { StringBuilder serialized = new StringBuilder(); serialized.append(value.name()); <START> serialized.append("::"); <END> if(value instanceof HasName) { serialized.append(((HasName)value).getName()); } else { serialized.append(String.valueOf(value)); } if(value instanceof HasAliases) { String[] aliases = ((HasAliases)value).getAliases(); if(aliases != null) { for(String alias: aliases) { if(alias != null && !alias.isEmpty()) { serialized.append("::").append(alias); } } } } return serialized.toString(); }</code><technical_language>"::" is referred in JsonSchemaConfiguredPropertyDescriptorImpl, I suggest share a common constant out of sync</technical_language>

Target:
protected String enumValueToSchemaString(Enum<?> value) { StringBuilder serialized = new StringBuilder(); serialized.append(value.name()); serialized.append(ENUM_ALIAS_SEPARATOR); if(value instanceof HasName) { serialized.append(((HasName)value).getName()); } else { serialized.append(String.valueOf(value)); } if(value instanceof HasAliases) { String[] aliases = ((HasAliases)value).getAliases(); if(aliases != null) { for(String alias: aliases) { if(alias != null && !alias.isEmpty()) { serialized.append(ENUM_ALIAS_SEPARATOR).append(alias); } } } } return serialized.toString(); }
Source:
<code>public void expand(IProgressMonitor monitor) { <START> this.progressMonitor = monitor; <END> item.setExpanded(true); refreshContent(); }</code><technical_language>useful monitor in field, pass refreshContent() in parameter useful for refresh</technical_language>

Target:
public void expand(IProgressMonitor monitor) { item.setExpanded(true); refreshContent(); }
Source:
<code>public void metadataExportToCsvTest() throws Exception { context.turnOffAuthorisationSystem(); Community community = communityService.create(null, context); Collection collection = collectionService.create(context, community); WorkspaceItem wi = workspaceItemService.create(context, collection, true); Item item = wi.getItem(); itemService.addMetadata(context, item, "dc", "contributor", "author", null, "Donald, Smith"); item = installItemService.installItem(context, wi); String fileLocation = configurationService.getProperty("dspace.dir") + testProps.get("test.exportcsv") .toString(); String[] args = new String[] {"metadata-export", "-i", String.valueOf(item.getHandle()), "-f", fileLocation}; TestDSpaceRunnableHandler testDSpaceRunnableHandler = new TestDSpaceRunnableHandler(); ScriptLauncher.handleScript(args, ScriptLauncher.getConfig(kernelImpl), testDSpaceRunnableHandler, kernelImpl); File file = new File(fileLocation); String fileContent = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8); assertTrue(fileContent.contains("Donald, Smith")); <START> assertTrue(fileContent.contains(String.valueOf(item.getID()))); <END> }</code><technical_language>This test cleaning itself. deleting test Community/Collection/Item end of this test? Otherwise, remain in test database impact tests run later</technical_language>

Target:
public void metadataExportToCsvTest() throws Exception { context.turnOffAuthorisationSystem(); Community community = communityService.create(null, context); Collection collection = collectionService.create(context, community); WorkspaceItem wi = workspaceItemService.create(context, collection, true); Item item = wi.getItem(); itemService.addMetadata(context, item, "dc", "contributor", "author", null, "Donald, Smith"); item = installItemService.installItem(context, wi); context.restoreAuthSystemState(); String fileLocation = configurationService.getProperty("dspace.dir") + testProps.get("test.exportcsv") .toString(); String[] args = new String[] {"metadata-export", "-i", String.valueOf(item.getHandle()), "-f", fileLocation}; TestDSpaceRunnableHandler testDSpaceRunnableHandler = new TestDSpaceRunnableHandler(); ScriptLauncher.handleScript(args, ScriptLauncher.getConfig(kernelImpl), testDSpaceRunnableHandler, kernelImpl); File file = new File(fileLocation); String fileContent = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8); assertTrue(fileContent.contains("Donald, Smith")); assertTrue(fileContent.contains(String.valueOf(item.getID()))); context.turnOffAuthorisationSystem(); itemService.delete(context, itemService.find(context, item.getID())); collectionService.delete(context, collectionService.find(context, collection.getID())); communityService.delete(context, communityService.find(context, community.getID())); context.restoreAuthSystemState(); }
Source:
<code>private void reinsertFailed(List<VoltBulkLoaderRow> rows) throws Exception { VoltTable tmpTable = new VoltTable(m_columnInfo); for (final VoltBulkLoaderRow row : rows) { try { Object row_args[] = new Object[row.m_rowData.length]; for (int i = 0; i < row_args.length; i++) { final VoltType type = m_columnTypes[i]; row_args[i] = ParameterConverter.tryToMakeCompatible(type.classFromType(), row.m_rowData[i]); } tmpTable.addRow(row_args); } catch (VoltTypeException ex) { loaderLog.error("Type conversion exception", ex); assert false: "Type conversion exception" + ex.getMessage(); continue; } ProcedureCallback callback = new ProcedureCallback() { @Override public void clientCallback(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) { row.m_loader.m_notificationCallBack.failureCallback(row.m_rowHandle, row.m_rowData, response); } row.m_loader.m_loaderCompletedCnt.incrementAndGet(); row.m_loader.m_outstandingRowCount.decrementAndGet(); } }; <START> loadTableWithRetry(callback, tmpTable); <END> } }</code><technical_language>places loadTable() is called switched this</technical_language>

Target:
private void reinsertFailed(List<VoltBulkLoaderRow> rows) throws Exception { VoltTable tmpTable = new VoltTable(m_columnInfo); for (final VoltBulkLoaderRow row : rows) { try { Object row_args[] = new Object[row.m_rowData.length]; for (int i = 0; i < row_args.length; i++) { final VoltType type = m_columnTypes[i]; row_args[i] = ParameterConverter.tryToMakeCompatible(type.classFromType(), row.m_rowData[i]); } tmpTable.addRow(row_args); } catch (VoltTypeException ex) { loaderLog.error("Type conversion exception", ex); assert false: "Type conversion exception" + ex.getMessage(); continue; } ProcedureCallback callback = new ProcedureCallback() { @Override public void clientCallback(ClientResponse response) throws Exception { if (response.getStatus() == ClientResponse.CONNECTION_LOST && m_autoReconnect) { m_es.execute(new Runnable() { @Override public void run() { try { reinsertFailed(Arrays.asList(row)); } catch (Exception e) { loaderLog.error("Failed to re-insert failed batch", e); } } }); return; } else if (response.getStatus() != ClientResponse.SUCCESS) { row.m_loader.m_notificationCallBack.failureCallback(row.m_rowHandle, row.m_rowData, response); } row.m_loader.m_loaderCompletedCnt.incrementAndGet(); row.m_loader.m_outstandingRowCount.decrementAndGet(); } }; loadTable(callback, tmpTable); } }
Source:
<code>public UndertowJaxrsServer deploy(ResteasyDeployment deployment, String contextPath, Map<String, String> contextParams, Map<String, String> initParams) { if (contextPath == null) contextPath = "/"; if (!contextPath.startsWith("/")) contextPath = "/" + contextPath; DeploymentInfo builder = undertowDeployment(deployment); builder.setContextPath(contextPath); builder.setDeploymentName("Resteasy" + contextPath); builder.setClassLoader(deployment.getApplication().getClass().getClassLoader()); if (contextParams != null) { for (Iterator<String> it = contextParams.keySet().iterator(); it.hasNext(); ) { String key = it.next(); <START> builder.addInitParameter(key, contextParams.get(key)); <END> } } if (initParams != null) { ServletInfo servletInfo = builder.getServlets().get("ResteasyServlet"); for (Iterator<String> it = initParams.keySet().iterator(); it.hasNext(); ) { String key = it.next(); servletInfo.addInitParam(key, initParams.get(key)); } } return deploy(builder); }</code><technical_language>For performances, practice be: for (Entry<String, String> e : contextParams.entrySet()) { builder.addInitParameter(e.getKey(), e.getValue()); } avoids accessing map key</technical_language>

Target:
public UndertowJaxrsServer deploy(ResteasyDeployment deployment, String contextPath, Map<String, String> contextParams, Map<String, String> initParams) { if (contextPath == null) contextPath = "/"; if (!contextPath.startsWith("/")) contextPath = "/" + contextPath; DeploymentInfo builder = undertowDeployment(deployment); builder.setContextPath(contextPath); builder.setDeploymentName("Resteasy" + contextPath); builder.setClassLoader(deployment.getApplication().getClass().getClassLoader()); if (contextParams != null) { for (Entry<String, String> e : contextParams.entrySet()) { builder.addInitParameter(e.getKey(), e.getValue()); } } if (initParams != null) { ServletInfo servletInfo = builder.getServlets().get("ResteasyServlet"); for (Entry<String, String> e : initParams.entrySet()) { servletInfo.addInitParam(e.getKey(), e.getValue()); } } return deploy(builder); }
Source:
<code>private void saveQuestion(final Long accountId, final Question question, final DateTime today, final DateTime expireDate) { <START> LOGGER.debug("action=saved_question processor=question_survey account_id={} question_id={} today={} expireDate={}", accountId, question.id, today, expireDate); <END> this.questionResponseDAO.insertAccountQuestion(accountId, question.id, today, expireDate); }</code><technical_language>expireDate is consistent rest of keys</technical_language>

Target:
private void saveQuestion(final Long accountId, final Question question, final DateTime today, final DateTime expireDate) { LOGGER.debug("action=saved_question processor=question_survey account_id={} question_id={} today={} expire_date={}", accountId, question.id, today, expireDate); this.questionResponseDAO.insertAccountQuestion(accountId, question.id, today, expireDate); }
Source:
<code>public static Object handleNonNull(boolean arg) { <START> throw new AssertionError("value of unknown type should all be NULL"); <END> }</code><technical_language>throw new IllegalArgumentException("value of unknown type null")</technical_language>

Target:
public static Object handleNonNull(boolean arg) { throw new IllegalArgumentException("value of unknown type should always be null"); }
Source:
<code>public GC(FileRepository repo) { <START> ProgressMonitor pm = NullProgressMonitor.INSTANCE; <END> this.repo = repo; this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm; this.expireAgeMillis = 14 * 24 * 60 * 60 * 1000l; }</code><technical_language>inline this drop ?: operator initializing pm</technical_language>

Target:
public GC(FileRepository repo) { this.repo = repo; this.pm = NullProgressMonitor.INSTANCE; this.expireAgeMillis = 14 * 24 * 60 * 60 * 1000L; }
Source:
<code><START> public static void main(final String args) throws IOException, XMLStreamException { <END> final ApplicationContext context = new ClassPathXmlApplicationContext("spring/migration-bean.xml"); final Migrator m = (Migrator)context.getBean("migrator"); System.out.println("After creating bean..."); m.run(); ((ConfigurableApplicationContext)context).close(); }</code><technical_language>Thanks for this clean-up code! I start enforcing fcrepo4 code style rules sooner later..</technical_language>

Target:
public static void main(final String args) throws IOException, XMLStreamException { final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/migration-bean.xml"); final Migrator m = context.getBean("migrator", Migrator.class); m.run(); context.close(); }
Source:
<code>protected static CommonProfile getUserProfile() { final String sessionId = session(Constants.SESSION_ID); logger.debug("sessionId for profile : {}", sessionId); CommonProfile profile = null; if (StringUtils.isNotBlank(sessionId)) { profile = StorageHelper.getProfile(sessionId); } <START> profile = (profile != null) ? profile : (CommonProfile) ctx().args.get(HttpConstants.USER_PROFILE); <END> logger.debug("profile : {}", profile); return profile; }</code><technical_language>a big fan of this _compressed syntax_</technical_language>

Target:
protected static CommonProfile getUserProfile() { final String sessionId = session(Pac4jConstants.SESSION_ID); logger.debug("sessionId for profile : {}", sessionId); CommonProfile profile = null; if (StringUtils.isNotBlank(sessionId)) { profile = StorageHelper.getProfile(sessionId); } if (profile == null) { return (CommonProfile) ctx().args.get(Pac4jConstants.USER_PROFILE); } else { return profile; } }
Source:
<code><START> public static String convertDateToEventTimestamp(Date date) throws ParseException { <END> return dateFormat.format(date).replaceAll(" ", "T") + "Z"; }</code><technical_language>ParseException thrown</technical_language>

Target:
public static String convertDateToEventTimestamp(Date date) { return dateFormat.format(date); }
Source:
<code>public void clickToSignInForm(){ <START> switchToAuthModalHandle(); <END> linkToSignInForm.click(); }</code><technical_language>wait.forElementClickable nice</technical_language>

Target:
public void clickToSignInForm(){ switchToAuthModalHandle(); wait.forElementClickable(linkToSignInForm); linkToSignInForm.click(); }
Source:
<code>public HashSet<T> removeAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); HashArrayMappedTrie<T, Object> trie = tree; for (T element : elements) { trie = trie.remove(element); } <START> return trie.size() == list.get().length() ? this : new HashSet<>(trie); <END> }</code><technical_language>here. if true.remove(element) returns instance, test == instead of size length</technical_language>

Target:
public HashSet<T> removeAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); HashArrayMappedTrie<T, Object> trie = tree; for (T element : elements) { trie = trie.remove(element); } return trie == tree ? this : new HashSet<>(trie); }
Source:
<code>public void testSetDutyCycleSuccess() throws Exception { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); try { <START> xbeeDevice.setPWMDutyCycle(IOLine.DIO10_PWM0, 75); <END> } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } }</code><technical_language>Do catch exceptions throw them, if this occurs test case is failing is need</technical_language>

Target:
public void testSetDutyCycleSuccess() throws InvalidOperatingModeException, XBeeException { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); xbeeDevice.setPWMDutyCycle(IOLine.DIO10_PWM0, DUTY_CYCLE_VALID_VALUE); }
Source:
<code><START> public void configure(ServerHttpSecurity http) { <END> HttpsRedirectWebFilter transportSecurityFilter = new HttpsRedirectWebFilter(); if (this.serverWebExchangeMatcher != null) { transportSecurityFilter.setRequiresHttpsRedirectMatcher(this.serverWebExchangeMatcher); } http.addFilterAt(transportSecurityFilter, SecurityWebFiltersOrder.HTTPS_REDIRECT); }</code><technical_language>this public exposes unnecessary method users</technical_language>

Target:
protected void configure(ServerHttpSecurity http) { HttpsRedirectWebFilter httpsRedirectWebFilter = new HttpsRedirectWebFilter(); if (this.serverWebExchangeMatcher != null) { httpsRedirectWebFilter.setRequiresHttpsRedirectMatcher(this.serverWebExchangeMatcher); } if (this.portMapper != null) { httpsRedirectWebFilter.setPortMapper(this.portMapper); } http.addFilterAt(httpsRedirectWebFilter, SecurityWebFiltersOrder.HTTPS_REDIRECT); }
Source:
<code>public OutputStream create(String filename, HdfsSinkConnectorConfig conf, boolean overwrite) { final Path path = new Path(filename); try { return new OutputStream() { FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); OutputStream file = fs.create(new Path(filename), overwrite); @Override public void write(final int b) throws IOException { file.write(b); } @Override public void write(final byte[] b) throws IOException { file.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); } @Override public void flush() throws IOException { file.flush(); } @Override public void close() throws IOException { file.close(); <START> fs.close(); <END> } }; } catch (IOException e) { throw new ConnectException(e); } }</code><technical_language>fs.close() in a finally block. that, for file.close() method fail leave open FileSystem created for this stream, resulting in a memory leak. a bit tricky, properly handle potential exception in finally block (which overrides exception in try block), want return _first_ exception for file.close() fs.close()</technical_language>

Target:
public OutputStream create(String filename, HdfsSinkConnectorConfig conf, boolean overwrite) { final Path path = new Path(filename); try { return new OutputStream() { FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); OutputStream file = fs.create(new Path(filename), overwrite); @Override public void write(final int b) throws IOException { file.write(b); } @Override public void write(final byte[] b) throws IOException { file.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); } @Override public void flush() throws IOException { file.flush(); } @Override public void close() throws IOException { try { file.close(); } finally { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } } }; } catch (IOException e) { throw new ConnectException(e); } }
Source:
<code>public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } <START> Helper.setMeldung(null, "ExportFinished", ""); <END> logger.info(Helper.getTranslation("ExportFinished")); }</code><technical_language>If add a log message logged user get information. Please move this log call in front of Helper.setMeldung() call</technical_language>

Target:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } logger.info(Helper.getTranslation("ExportFinished")); Helper.setMeldung(null, "ExportFinished", ""); }
Source:
<code>public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { <START> LogGetHandle handle = dockerAccess.getLogAsync(containerId, createLogCallback(spec)); <END> logHandles.put(containerId, handle); }</code><technical_language>a a fan of static imports dilute real locations I search in current class review. refer static method class (LogCallbackFactory.createLogBack()) ? saves some lines</technical_language>

Target:
public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { LogGetHandle handle = dockerAccess.getLogAsync(containerId, new DefaultLogCallback(spec)); logHandles.put(containerId, handle); }
Source:
<code>private static CloseableHttpClient createClient() { return HttpClientBuilder.create() .useSystemProperties() .disableConnectionState() .setConnectionManager( httpClientConnectionManager ) .setRetryHandler( createRetryHandler() ) .setServiceUnavailableRetryStrategy( <START> new SimpleServiceUnavailableRetryStrategy( 10, 1000 ) ) <END> .setDefaultAuthSchemeRegistry( createAuthSchemeRegistry() ) .build(); }</code><technical_language>if implement this optional retry number/time retry configurable</technical_language>

Target:
private static CloseableHttpClient createClient() { return HttpClientBuilder.create() .useSystemProperties() .disableConnectionState() .setConnectionManager( httpClientConnectionManager ) .setRetryHandler( createRetryHandler() ) .setServiceUnavailableRetryStrategy( createServiceUnavailableRetryStrategy() ) .setDefaultAuthSchemeRegistry( createAuthSchemeRegistry() ) .build(); }
Source:
<code>public static boolean setRequestSchema(String schema) { <START> if(schema!=null && schema.trim().length() > 0) { <END> ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes.getRequest() != null) { HttpServletRequest request = requestAttributes.getRequest(); request.setAttribute("requestSchema", schema); return true; } else { CoreResources.tenantSchema.set(schema); } } return false; }</code><technical_language>instead of adding a null check here, calling method is passing a non-null schema. This is masking root of problem</technical_language>

Target:
public static boolean setRequestSchema(String schema) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes.getRequest() != null) { HttpServletRequest request = requestAttributes.getRequest(); request.setAttribute("requestSchema", schema); return true; } else { CoreResources.tenantSchema.set(schema); } return false; }
Source:
<code>public SimpleMessage(String message, String key, String topic) { if (topic == null) <START> throw new IllegalArgumentException("topic==null"); <END> if (message == null) throw new IllegalArgumentException("message==null"); this.topic = topic; this.key = key; this.message = message; }</code><technical_language>inconsistent topic is checked for null key is, definition optional</technical_language>

Target:
public SimpleMessage(String message, String key, String topic) { if (message == null) throw new IllegalArgumentException("message==null"); this.topic = topic; this.key = key; this.message = message; }
Source:
<code>public Map<String, Object> getStats() { try { return getCurrentTotalStats(); } <START> catch (Exception e) { <END> throw new RuntimeException(e); } }</code><technical_language>this need catch exceptions</technical_language>

Target:
public Map<String, Map<String, Object>> getStats() { try { return getCurrentTotalStats(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error(ie, "getStats() interrupted."); throw new RuntimeException(ie); } catch (ExecutionException | TimeoutException eete) { throw new RuntimeException(eete); } }
Source:
<code>private List<Long> replOpenTxnForTest(long startId, int numTxn, String replPolicy) throws Exception { conf.setIntVar(HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH, numTxn); long lastId = startId + numTxn - 1; OpenTxnRequest rqst = new OpenTxnRequest(numTxn, "me", "localhost"); rqst.setReplPolicy(replPolicy); rqst.setReplSrcTxnIds(LongStream.rangeClosed(startId, lastId) .boxed().collect(Collectors.toList())); int numTxnPresentStart = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS"); OpenTxnsResponse openedTxns = txnHandler.openTxns(rqst); List<Long> txnList = openedTxns.getTxn_ids(); assertEquals(txnList.size(), numTxn); <START> int numTxnPresentNow = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS"); <END> assertEquals(numTxn + numTxnPresentStart, numTxnPresentNow); checkReplTxnForTest(startId, lastId, replPolicy, txnList); return txnList; }</code><technical_language>Instead of 2 queries TXNS table, add clause for range of txnids allocated</technical_language>

Target:
private List<Long> replOpenTxnForTest(long startId, int numTxn, String replPolicy) throws Exception { conf.setIntVar(HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH, numTxn); long lastId = startId + numTxn - 1; OpenTxnRequest rqst = new OpenTxnRequest(numTxn, "me", "localhost"); rqst.setReplPolicy(replPolicy); rqst.setReplSrcTxnIds(LongStream.rangeClosed(startId, lastId) .boxed().collect(Collectors.toList())); OpenTxnsResponse openedTxns = txnHandler.openTxns(rqst); List<Long> txnList = openedTxns.getTxn_ids(); assertEquals(txnList.size(), numTxn); int numTxnPresentNow = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS where TXN_ID >= " + txnList.get(0) + " and TXN_ID <= " + txnList.get(numTxn - 1)); assertEquals(numTxn, numTxnPresentNow); checkReplTxnForTest(startId, lastId, replPolicy, txnList); return txnList; }
Source:
<code>public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } <START> if(upCount > 1 && downCount > 1) { <END> return downCount; } } return downCount; }</code><technical_language>0 ? a volume 6 bricks 2 down. In this scenario, loop executed 4 times 3 is enough get expected result</technical_language>

Target:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 0 && downCount > 0) { return downCount; } } return downCount; }
Source:
<code><START> public void close() throws IOException { <END> tarArchiveOutputStream.close(); }</code><technical_language>please remove this patch</technical_language>

Target:
public void close() throws Exception { tarArchiveOutputStream.close(); }
Source:
<code>public void testNoWorkHomeSpecifier_EMAIL() throws Throwable { final String request = "<iq id='v1' to='user@igniterealtime.org/mobile' type='result'>" + "<vCard xmlns='vcard-temp'><EMAIL><USERID>foo@fee.www.bar</USERID></EMAIL></vCard>" + "</iq>"; IQ iqRequest = (IQ) PacketParserUtils.parseStanza(request); assertTrue(iqRequest instanceof VCard); <START> VCard vCard = (VCard) iqRequest; <END> assertEquals("foo@fee.www.bar", vCard.getEmailHome()); }</code><technical_language>VCard vCard = PakcetParserUtils.parseStanza(request) enough</technical_language>

Target:
public void testNoWorkHomeSpecifier_EMAIL() throws Throwable { final String request = "<iq id='v1' to='user@igniterealtime.org/mobile' type='result'>" + "<vCard xmlns='vcard-temp'><EMAIL><USERID>foo@fee.www.bar</USERID></EMAIL></vCard>" + "</iq>"; VCard vCard = (VCard) PacketParserUtils.parseStanza(request); assertEquals("foo@fee.www.bar", vCard.getEmailHome()); }
Source:
<code>public void handle(LoginSuccess loginSuccess) throws Exception { Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not expecting LOGIN_SUCCESS" ); ch.setProtocol( Protocol.GAME ); thisState = State.LOGIN; <START> if ( user.getServer() != null && user.getForgeClientHandler().isHandshakeComplete() && !user.getForgeClientHandler().isForgeOutdated() ) <END> { user.getForgeClientHandler().resetHandshake(); } throw CancelSendSignal.INSTANCE; }</code><technical_language>This work. if Forge client is outdated this point</technical_language>

Target:
public void handle(LoginSuccess loginSuccess) throws Exception { Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not expecting LOGIN_SUCCESS" ); ch.setProtocol( Protocol.GAME ); thisState = State.LOGIN; if ( user.getServer() != null && user.getForgeClientHandler().isForgeClient() && !user.getForgeClientHandler().isForgeOutdated() ) { user.getForgeClientHandler().resetHandshake(); } throw CancelSendSignal.INSTANCE; }
Source:
<code>public WorkspaceAndPluginsResourceDialog(Shell parent, boolean allowMultiple, List<String> extensions) { super(parent, WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(), new DeferredWorkbenchContentProvider()); this.extensions = extensions; setAllowMultiple(allowMultiple); if (allowMultiple) { <START> setTitle("Select files"); <END> } else { setTitle("Select a file"); } setInput(new WorkbenchProxyObject()); addFilter(new FileExtensionFilter()); }</code><technical_language>in .properties file</technical_language>

Target:
public WorkspaceAndPluginsResourceDialog(Shell parent, boolean allowMultiple, List<String> extensions) { super(parent, WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(), new DeferredWorkbenchContentProvider()); this.extensions = extensions; setAllowMultiple(allowMultiple); if (allowMultiple) { setTitle(SiriusTransPlugin.INSTANCE.getString("titleSelectFiles")); } else { setTitle(SiriusTransPlugin.INSTANCE.getString("titleSelectAFile")); } setInput(new WorkbenchProxyObject()); addFilter(new FileExtensionFilter()); }
Source:
<code>public double getStdDev() { return fNbSegments > 2 ? Math.sqrt(fVariance / <START> fNbSegments) : <END> Double.NaN; }</code><technical_language>(fNbSegments - 1)</technical_language>

Target:
public double getStdDev() { return fNbSegments > 2 ? Math.sqrt(fVariance / (fNbSegments - 1)) : Double.NaN; }
Source:
<code>@Override public void updateInitial(long start, long delta) { try { update(start + delta); } <START> catch (IgniteCheckedException e) { <END> } initCntr = get(); }</code><technical_language>Declared exception update method removed this try-catch block</technical_language>

Target:
@Override public synchronized void updateInitial(long start, long delta) { update(start + delta); initCntr = get(); }
Source:
<code>public Optional<EventMessage<?>> readKafkaMessage(ConsumerRecord<String, byte[]> consumerRecord) { try { Headers headers = consumerRecord.headers(); if (isAxonMessage(headers)) { byte[] messageBody = consumerRecord.value(); SerializedMessage<?> message = extractSerializedMessage(headers, messageBody); long timestamp = valueAsLong(headers, MESSAGE_TIMESTAMP); <START> return headers.lastHeader(AGGREGATE_ID) != null ? <END> domainEvent(headers, message, timestamp) : event(message, timestamp); } } catch (Exception e) { logger.trace("Error converting to axon, {}", consumerRecord, e); } return Optional.empty(); }</code><technical_language>I move this if method constructs EventMessage out of Kafka message</technical_language>

Target:
public Optional<EventMessage<?>> readKafkaMessage(ConsumerRecord<String, byte[]> consumerRecord) { try { Headers headers = consumerRecord.headers(); if (isAxonMessage(headers)) { byte[] messageBody = consumerRecord.value(); SerializedMessage<?> message = extractSerializedMessage(headers, messageBody); return buildMessage(headers, message); } } catch (Exception e) { logger.trace("Error converting to axon", consumerRecord, e); } return Optional.empty(); }
Source:
<code>public void junit_assert_that() { <START> assertThat("aaa", org.junit.matchers.JUnitMatchers.containsString("a")); <END> }</code><technical_language>Do change that. explicit show a junit assert</technical_language>

Target:
public void junit_assert_that() { org.junit.Assert.assertThat("aaa", org.junit.matchers.JUnitMatchers.containsString("a")); }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; BlockTree block = methodTree.block(); if (block != null) { NpeVisitor visitor = new NpeVisitor(methodTree.parameters()); block.accept(visitor); for (Tree issueTree : visitor.getIssueTrees()) { <START> addIssue(issueTree, "NPE!"); <END> } } }</code><technical_language>a reminder forget managing message</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; BlockTree block = methodTree.block(); if (block != null) { NpeVisitor visitor = new NpeVisitor(methodTree.parameters()); block.accept(visitor); for (Tree issueTree : visitor.getIssueTrees()) { String name = getNameFrom(issueTree); String methodName = visitor.isTreeMethodParam(issueTree); if (StringUtils.isNotBlank(methodName)) { if (issueTree.is(Tree.Kind.NULL_LITERAL)) { addIssue(issueTree, "method '" + methodName + "' does not accept nullable argument"); } else { addIssue(issueTree, "'" + name + "' is nullable here and method '" + methodName + "' does not accept nullable argument"); } } else { addIssue(issueTree, "NullPointerException might be thrown as '" + name + "' is nullable here"); } } } }
Source:
<code>public InstanceMonitor(String clusterName, String participantName, ObjectName objectName) throws JMException { _clusterName = clusterName; _participantName = participantName; _tags = ImmutableList.of(ClusterStatusMonitor.DEFAULT_TAG); _initObjectName = objectName; createMetrics(); <START> register(); <END> }</code><technical_language>follow convention, please register in constructor. Trigger register instantiation in caller method</technical_language>

Target:
public InstanceMonitor(String clusterName, String participantName, ObjectName objectName) { _clusterName = clusterName; _participantName = participantName; _tags = ImmutableList.of(ClusterStatusMonitor.DEFAULT_TAG); _initObjectName = objectName; createMetrics(); }
Source:
<code><START> public static <E> AbstractGroupExpression<E, Set<E>> sortedSet(Expression<E> expression, Comparator<? super E> comparator) { <END> return GSet.createSorted(expression, comparator); }</code><technical_language>this sound good? 'Create a new aggregating set expression a backing TreeSet comparator'</technical_language>

Target:
public static <E> AbstractGroupExpression<E, SortedSet<E>> sortedSet(Expression<E> expression, Comparator<? super E> comparator) { return GSet.createSorted(expression, comparator); }
Source:
<code>private Jar getSources(Tool tool, Processor context, String path) throws Exception { Jar jar = toJar(context, path); if (path != null && jar == null) { logger.warn( "A sources path was set in the -maven-release instuction, but no sources could be found in (base path: {}) ", <START> path, context.getBaseURI() <END> .toString()); } if (jar != null) { tool.setSources(jar, ""); } else { jar = tool.doSource(); } jar.ensureManifest(); jar.setName(Archive.SOURCES_CLASSIFIER); tool.addClose(jar); return jar; }</code><technical_language>I 2nd arg options.context.getBase(). I want a URI here. toString() in case logging happen. Leave toString() call logging code</technical_language>

Target:
private Jar getSources(Tool tool, Processor context, String path) throws Exception { Jar jar = toJar(context, path); if (path != null && jar == null) { logger.warn( "A sources path was set in the -maven-release instuction, but no sources could be found in (base path: {}) ", path, context.getBase()); } if (jar != null) { tool.setSources(jar, ""); } else { jar = tool.doSource(); } jar.ensureManifest(); jar.setName(Archive.SOURCES_CLASSIFIER); tool.addClose(jar); return jar; }
Source:
<code>private void handleIdentifyResults(List<IdentifyLayerResult> identifyLayerResults) { String message = ""; int totalCount = 0; for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) { int count = geoElementsCountFromResult(identifyLayerResult); String layerName = identifyLayerResult.getLayerContent().getName(); <START> message += layerName + ": " + count; <END> if (!identifyLayerResult.equals(identifyLayerResults.get(identifyLayerResults.size() - 1))) { message += "\n"; } totalCount += count; } if (totalCount > 0) { showAlertDialog(message); } else { Toast.makeText(this, "No element found", Toast.LENGTH_SHORT).show(); Log.i(TAG, "No element found."); } }</code><technical_language>is instance StringBuilder used: java StringBuilder message = new StringBuilder(); ... message.append(layerName).append(": ").append(count);</technical_language>

Target:
private void handleIdentifyResults(List<IdentifyLayerResult> identifyLayerResults) { StringBuilder message = new StringBuilder(); int totalCount = 0; for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) { int count = geoElementsCountFromResult(identifyLayerResult); String layerName = identifyLayerResult.getLayerContent().getName(); message.append(layerName).append(": ").append(count); if (!identifyLayerResult.equals(identifyLayerResults.get(identifyLayerResults.size() - 1))) { message.append("\n"); } totalCount += count; } if (totalCount > 0) { showAlertDialog(message); } else { Toast.makeText(this, "No element found", Toast.LENGTH_SHORT).show(); Log.i(TAG, "No element found."); } }
Source:
<code><START> public void deleteNodeTestNodeException_puppet_1() throws NodeExecutionException, Exception { <END> HttpResponse httpResponse = mock(HttpResponse.class); StatusLine statusLine = mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(500); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testError", "token"); verify(httpResponse, times(1)).getStatusLine(); }</code><technical_language>NTC</technical_language>

Target:
public void deleteNodeTestNodeException_puppet_1() throws Exception { HttpResponse httpResponse = mock(HttpResponse.class); StatusLine statusLine = mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(500); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testError", "token"); }
Source:
<code>private Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); if (root == null) { return e; } else { while(true) { <START> if (root.getCause() == null) { <END> return root; } else { root = root.getCause(); } } } }</code><technical_language>I cases a Throwable return this for getCause() infinite loops in code this. I want: java while (true) { Throwable = root.getCause(); if (cause == null || == root) { return root; } root = cause; } a result instead</technical_language>

Target:
private Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); if (root == null || root == e) { return e; } else { while(true) { Throwable cause = root.getCause(); if (cause == null || cause == root) { return root; } root = root.getCause(); } } }
Source:
<code>public void testFindAndDeleteGarbage() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().active(true); injectTestSystemOut(); ignite.createCaches(Arrays.asList( new CacheConfiguration<>("garbage1").setGroupName("groupGarbage"), new CacheConfiguration<>("garbage2").setGroupName("groupGarbage"))); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); <START> assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); <END> assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", ignite(0).localNode().id().toString(), "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "groupGarbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); }</code><technical_language>Do call command purpose</technical_language>

Target:
public void testFindAndDeleteGarbage() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().active(true); injectTestSystemOut(); ignite.createCaches(Arrays.asList( new CacheConfiguration<>("garbage1").setGroupName("groupGarbage"), new CacheConfiguration<>("garbage2").setGroupName("groupGarbage"))); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", ignite(0).localNode().id().toString(), "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "groupGarbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); }