auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute() throws FluoCommandException { <START> getJars(); <END> }</code><technical_language>this inlined</technical_language>

Target:
public void execute() throws FluoCommandException { FluoConfiguration config = getConfig(); CommandUtil.verifyAppInitialized(config); config = FluoAdminImpl.mergeZookeeperConfig(config); if (config.getObserverJarsUrl().isEmpty()) { log.info("No observer jars found for the '{}' Fluo application!", getApplicationName()); return; } if (config.getObserverJarsUrl().startsWith("hdfs://")) { try (FileSystem fs = FileSystem.get(new URI(config.getDfsRoot()), new Configuration())) { File downloadPathFile = new File(getDownloadPath()); if (downloadPathFile.exists()) { FileUtils.deleteDirectory(downloadPathFile); } fs.copyToLocalFile(new Path(config.getObserverJarsUrl()), new Path(getDownloadPath())); } catch (URISyntaxException e) { throw new FluoCommandException( String.format("Error parsing DFS ROOT URI: %s", e.getMessage()), e); } catch (IOException e) { throw new FluoCommandException(e); } } else { throw new FluoCommandException(String.format("Unsupported url prefix for %s=%s", FluoConfiguration.OBSERVER_JARS_URL_PROP, config.getObserverJarsUrl())); } }
Source:
<code>public static final List<DateRange> sliceRange(DateTime fromDate, DateTime toDate, int rangeSize) { <START> List<DateRange> ranges = new ArrayList<>(); <END> while (true) { DateTime nextToDate = fromDate.plusDays(rangeSize); if (nextToDate.isAfter(toDate)) { ranges.add(new DateRange(fromDate, toDate)); break; } ranges.add(new DateRange(fromDate, nextToDate)); fromDate = nextToDate.plusSeconds(1); } return ranges; }</code><technical_language>If fromDate is 1 day toDate rangeSize is 1, this method returns 2 ranges is redundant</technical_language>

Target:
public static final List<DateRange> sliceRange(DateTime fromDate, DateTime toDate, int rangeSize) { List<DateRange> ranges = new ArrayList<>(); while (fromDate.isBefore(toDate)) { DateTime nextToDate = fromDate.plusDays(rangeSize); if (nextToDate.isAfter(toDate)) { ranges.add(new DateRange(fromDate, toDate)); break; } ranges.add(new DateRange(fromDate, nextToDate)); fromDate = nextToDate.plusSeconds(1); } return ranges; }
Source:
<code>public void fill(Control control, MouseEvent event, Point pt) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); IAxis yAxis = axisSet.getYAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); double yCoordinate = yAxis.getDataCoordinate(pt.y); ITmfChartTimeProvider viewer = getChartViewer(); ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + viewer.getTimeOffset()); <START> addTimeItem(null,"x", <END> time.toNanos(), time.toString()); addTimeItem(null, "y", null, Double.toString(yCoordinate)); }</code><technical_language>compile. name of method changed</technical_language>

Target:
public void fill(Control control, MouseEvent event, Point pt) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); IAxis yAxis = axisSet.getYAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); double yCoordinate = yAxis.getDataCoordinate(pt.y); ITmfChartTimeProvider viewer = getChartViewer(); ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + viewer.getTimeOffset()); addItem(null,"x", time.toString(), time.toNanos()); addItem(null, "y", Double.toString(yCoordinate), null); }
Source:
<code>private static LauncherStatus run(final String[] args) throws IOException, InjectionException { final Configuration commandLineConf = parseCommandLine(args); final Injector commandLineInjector = Tang.Factory.getTang().newInjector(commandLineConf); final Set<String> inputs = commandLineInjector.getNamedInstance(LineCountingDriver.Inputs.class); final boolean onLocal = commandLineInjector.getNamedInstance(Parameters.OnLocal.class); final int splits = commandLineInjector.getNamedInstance(Parameters.Splits.class); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(Parameters.OnLocal.class, Boolean.toString(onLocal)) .bindNamedParameter(Parameters.Splits.class, Integer.toString(splits)); inputs.forEach(input -> jcb.bindSetEntry(LineCountingDriver.Inputs.class, processInputDir(input, onLocal))); final Configuration paramConf = jcb.build(); final Configuration driverConf = getDriverConfiguration(paramConf); <START> final Configuration runTimeConf = onLocal ? <END> getLocalRuntimeConfiguration(splits) : getYarnRuntimeConfiguration(); final int timeout = commandLineInjector.getNamedInstance(Parameters.Timeout.class); return DriverLauncher.getLauncher(runTimeConf).run(driverConf, timeout); }</code><technical_language>nit: runTime -> runtime</technical_language>

Target:
private static LauncherStatus run(final String[] args) throws IOException, InjectionException { final Configuration commandLineConf = parseCommandLine(args); final Injector commandLineInjector = Tang.Factory.getTang().newInjector(commandLineConf); final Set<String> inputs = commandLineInjector.getNamedInstance(LineCountingDriver.Inputs.class); final boolean onLocal = commandLineInjector.getNamedInstance(Parameters.OnLocal.class); final int splits = commandLineInjector.getNamedInstance(Parameters.Splits.class); final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(Parameters.OnLocal.class, Boolean.toString(onLocal)) .bindNamedParameter(Parameters.Splits.class, Integer.toString(splits)); inputs.forEach(input -> jcb.bindSetEntry(LineCountingDriver.Inputs.class, processInputDir(input, onLocal))); final Configuration paramConf = jcb.build(); final Configuration driverConf = getDriverConfiguration(paramConf); final Configuration runtimeConf = onLocal ? getLocalRuntimeConfiguration(splits) : getYarnRuntimeConfiguration(); final int timeout = commandLineInjector.getNamedInstance(Parameters.Timeout.class); return DriverLauncher.getLauncher(runtimeConf).run(driverConf, timeout); }
Source:
<code>public void addingComponents() { <START> new SpecialInfoboxBuilderPageObject(driver).open("addingComponents") <END> .switchToIFrame() .verifyRowAdded() .verifyTitleAdded() .verifyImageAdded(); }</code><technical_language>longer need pass 'driver' object</technical_language>

Target:
public void addingComponents() { InfoboxBuilderPage builder = new InfoboxBuilderPage(); builder.open("addingComponents").switchToIFrame(); int rowComponents = builder.countRows(); int titleComponents = builder.countTitles(); int imageComponents = builder.countImages(); builder.addRowComponent().addImageComponent().addTitleComponent(); Assertion.assertEquals(rowComponents + 1, builder.countRows()); Assertion.assertEquals(titleComponents + 1, builder.countTitles()); Assertion.assertEquals(imageComponents + 1, builder.countImages()); }
Source:
<code>public String toString() { <START> return "OwnableReentrantStripedLockContainer{" + "sharedLocks=" + (Arrays.asList(sharedLocks)) + '}'; <END> }</code><technical_language>Redundant parenthesis. do this calling Arrays.toString</technical_language>

Target:
public String toString() { return "OwnableReentrantStripedLockContainer{" + "sharedLocks=" + Arrays.toString(sharedLocks) + '}'; }
Source:
<code>public Response getWorkflowZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); if (workflow.getIsPublished()) { <START> workflow = workflowDAO.findPublishedById(workflowId); <END> checkEntry(workflow); } else { checkEntry(workflow); if (user.isPresent()) { checkCanReadWorkflow(user.get(), workflow); } else { throw new CustomWebApplicationException("Forbidden: you do not have the credentials required to access this entry.", HttpStatus.SC_FORBIDDEN); } } WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); Set<SourceFile> sourceFiles = workflowVersion.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { throw new CustomWebApplicationException("no files found to zip", HttpStatus.SC_NO_CONTENT); } String fileName = workflow.getWorkflowPath().replaceAll("/", "-") + ".zip"; return Response.ok().entity((StreamingOutput)output -> writeStreamAsZip(sourceFiles, output)) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build(); }</code><technical_language>deal</technical_language>

Target:
public Response getWorkflowZip(@ApiParam(hidden = true) @Auth Optional<User> user, @ApiParam(value = "workflowId", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "workflowVersionId", required = true) @PathParam("workflowVersionId") Long workflowVersionId) { Workflow workflow = workflowDAO.findById(workflowId); if (workflow.getIsPublished()) { checkEntry(workflow); } else { checkEntry(workflow); if (user.isPresent()) { checkCanReadWorkflow(user.get(), workflow); } else { throw new CustomWebApplicationException("Forbidden: you do not have the credentials required to access this entry.", HttpStatus.SC_FORBIDDEN); } } WorkflowVersion workflowVersion = getWorkflowVersion(workflow, workflowVersionId); Set<SourceFile> sourceFiles = workflowVersion.getSourceFiles(); if (sourceFiles == null || sourceFiles.size() == 0) { throw new CustomWebApplicationException("no files found to zip", HttpStatus.SC_NO_CONTENT); } String fileName = workflow.getWorkflowPath().replaceAll("/", "-") + ".zip"; return Response.ok().entity((StreamingOutput)output -> writeStreamAsZip(sourceFiles, output)) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build(); }
Source:
<code>public Mono<CloseableChannel> start(ConnectionAcceptor acceptor, int mtu) { Objects.requireNonNull(acceptor, "acceptor must not be null"); ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor()); return server .doOnConnection( c -> { group.add(c.channel()); c.addHandlerLast(new RSocketLengthCodec()); DuplexConnection connection; if (mtu > 0) { connection = new FragmentationDuplexConnection( new TcpDuplexConnection(c, false), ByteBufAllocator.DEFAULT, mtu, true, "server"); } else { connection = new TcpDuplexConnection(c); } acceptor.apply(connection).then(Mono.<Void>never()).subscribe(c.disposeSubscriber()); }) .bind() <START> .doOnNext( <END> disposableChannel -> disposableChannel.channel().closeFuture().addListener(f -> group.close())) .map(CloseableChannel::new); }</code><technical_language>Do need do ? wondering opening door a new retain channels: - Is a case server life is shorter application life ? - If so, shutdown event loops force channels closed ? - Is this related OOM this is server is closed</technical_language>

Target:
public Mono<CloseableChannel> start(ConnectionAcceptor acceptor, int mtu) { Objects.requireNonNull(acceptor, "acceptor must not be null"); return server .doOnConnection( c -> { c.addHandlerLast(new RSocketLengthCodec()); DuplexConnection connection; if (mtu > 0) { connection = new FragmentationDuplexConnection( new TcpDuplexConnection(c, false), ByteBufAllocator.DEFAULT, mtu, true, "server"); } else { connection = new TcpDuplexConnection(c); } acceptor.apply(connection).then(Mono.<Void>never()).subscribe(c.disposeSubscriber()); }) .bind() .map(CloseableChannel::new); }
Source:
<code>public static EmptyMessage manageError(OSException e, Response response) { if (e == null) { LOGGER.error(Error.EXCEPTION_NULL); throw new NullPointerException(Error.EXCEPTION_NULL); } String errMess = e.getMessage(); if (errMess == null) { LOGGER.error(Error.ERROR_MESS_NULL); throw new NullPointerException(Error.ERROR_MESS_NULL); } if (!response.isConfirmable()) { LOGGER.error("An Empty Message will not be created"); return null; } <START> return EmptyMessage.newACK(response); <END> }</code><technical_language>OSCORE ACK (and RST) if message processing caused error</technical_language>

Target:
public static EmptyMessage manageError(OSException e, Response response) { if (e == null) { LOGGER.error(ErrorDescriptions.EXCEPTION_NULL); throw new NullPointerException(ErrorDescriptions.EXCEPTION_NULL); } String errMess = e.getMessage(); if (errMess == null) { LOGGER.error(ErrorDescriptions.ERROR_MESS_NULL); throw new NullPointerException(ErrorDescriptions.ERROR_MESS_NULL); } if (!response.isConfirmable()) { LOGGER.error("An Empty Message will not be created"); return null; } return EmptyMessage.newRST(response); }
Source:
<code>public Notification listByApplication( @PathVariable(value = "type") String type, @PathVariable(value = "name") String name) { HierarchicalLevel level = getLevel(type); final Notification notification = notificationDAO.get(level, name); if (level.equals(HierarchicalLevel.APPLICATION)) { final Object global = getGlobal(); NotificationDAO.NOTIFICATION_FORMATS.forEach( it -> { if (UntypedUtils.hasProperty(global, it)) { if (!UntypedUtils.hasProperty(notification, it)) { UntypedUtils.setProperty(notification, it, new ArrayList<>()); } <START> UntypedUtils.setProperty(notification, it, UntypedUtils.getProperty(global, it)); <END> } }); } return notification; }</code><technical_language>I this needs be: suggestion ((List<?>) UntypedUtils.getProperty(notification, it)).addAll((List<?>) UntypedUtils.getProperty(global, it))); replace list instead of adding</technical_language>

Target:
public Notification listByApplication( @PathVariable(value = "type") String type, @PathVariable(value = "name") String name) { HierarchicalLevel level = getLevel(type); final Notification notification = notificationDAO.get(level, name); if (level.equals(HierarchicalLevel.APPLICATION)) { final Object global = getGlobal(); NotificationDAO.NOTIFICATION_FORMATS.forEach( it -> { if (UntypedUtils.hasProperty(global, it)) { if (!UntypedUtils.hasProperty(notification, it)) { UntypedUtils.setProperty(notification, it, new ArrayList<>()); } ((List) UntypedUtils.getProperty(notification, it)) .addAll((List) UntypedUtils.getProperty(global, it)); } }); } return notification; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; <START> String[] allowOriginsA = System.getProperty("apiman-manager-ui.allowed-cors-origins", "*").split(","); <END> String allowOrigins = String.join(" ", allowOriginsA); if (isPreflightRequest(httpReq)) { httpResp.setHeader("Access-Control-Allow-Origin", allowOrigins); httpResp.setHeader("Access-Control-Allow-Credentials", "true"); httpResp.setHeader("Access-Control-Max-Age", "1800"); httpResp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,HEAD,DELETE"); httpResp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Accept,Origin,Authorization"); httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error"); } else { if (hasOriginHeader(httpReq)) { httpResp.setHeader("Access-Control-Allow-Origin", allowOrigins); httpResp.setHeader("Access-Control-Allow-Credentials", "true"); httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error"); } chain.doFilter(httpReq, httpResp); } }</code><technical_language>Please compare existing code: <LINK_0></technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; if (isPreflightRequest(httpReq) && originIsAllowed(httpReq)) { httpResp.setHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin")); if(!allowedCorsOrigins.contains("*")){ httpResp.setHeader("Vary", "Origin"); } httpResp.setHeader("Access-Control-Allow-Credentials", "true"); httpResp.setHeader("Access-Control-Max-Age", "1800"); httpResp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,HEAD,DELETE"); httpResp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Accept,Origin,Authorization"); httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error"); } else { if (hasOriginHeader(httpReq) && originIsAllowed(httpReq)) { httpResp.setHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin")); if(!allowedCorsOrigins.contains("*")){ httpResp.setHeader("Vary", "Origin"); } httpResp.setHeader("Access-Control-Allow-Credentials", "true"); httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error"); } chain.doFilter(httpReq, httpResp); } }
Source:
<code>private void parseSimpleLoadProvider(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress parent) throws XMLStreamException { PathAddress address = parent.append(SimpleLoadProviderResourceDefinition.PATH); ModelNode operation = Util.createAddOperation(address); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); <START> switch (attribute) { <END> case FACTOR: { readAttribute(reader, i, operation, SimpleLoadProviderResourceDefinition.Attribute.FACTOR); break; } default: { throw unexpectedAttribute(reader, i); } } } list.add(operation); }</code><technical_language>remove this? this element require content</technical_language>

Target:
private void parseSimpleLoadProvider(XMLExtendedStreamReader reader, List<ModelNode> list, PathAddress parent) throws XMLStreamException { PathAddress address = parent.append(SimpleLoadProviderResourceDefinition.PATH); ModelNode operation = Util.createAddOperation(address); int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { requireNoNamespaceAttribute(reader, i); XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case FACTOR: { readAttribute(reader, i, operation, SimpleLoadProviderResourceDefinition.Attribute.FACTOR); break; } default: { throw unexpectedAttribute(reader, i); } } } ParseUtils.requireNoContent(reader); list.add(operation); }
Source:
<code>private CloseableIterator<SupervisorStatus> getAuthorizedSupervisors( JsonParserIterator<SupervisorStatus> it, DataContext root ) { final AuthenticationResult authenticationResult = (AuthenticationResult) root.get(PlannerContext.DATA_CTX_AUTHENTICATION_RESULT); Function<SupervisorStatus, Iterable<ResourceAction>> raGenerator = supervisor -> Collections.singletonList( AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(supervisor.getSource())); <START> final Iterable<SupervisorStatus> authorizedTasks = AuthorizationUtils.filterAuthorizedResources( <END> authenticationResult, () -> it, raGenerator, authorizerMapper ); return wrap(authorizedTasks.iterator(), it); }</code><technical_language>authorizedTasks -> authorizedSupervisors</technical_language>

Target:
private CloseableIterator<SupervisorStatus> getAuthorizedSupervisors( JsonParserIterator<SupervisorStatus> it, DataContext root ) { final AuthenticationResult authenticationResult = (AuthenticationResult) root.get(PlannerContext.DATA_CTX_AUTHENTICATION_RESULT); Function<SupervisorStatus, Iterable<ResourceAction>> raGenerator = supervisor -> Collections.singletonList( AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(supervisor.getSource())); final Iterable<SupervisorStatus> authorizedSupervisors = AuthorizationUtils.filterAuthorizedResources( authenticationResult, () -> it, raGenerator, authorizerMapper ); return wrap(authorizedSupervisors.iterator(), it); }
Source:
<code>private Map<String, DbParameterAccessor> readIntoParams( String[] queryParameters, String query) throws SQLException { try (PreparedStatement dc = currentConnection.prepareStatement(query)) { for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) <START> paramName = ""; <END> String dataType = rs.getString(2); DbParameterAccessor dbp = new DbParameterAccessor(paramName, Direction.INPUT, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } }</code><technical_language>enclose if block in {}</technical_language>

Target:
private Map<String, DbParameterAccessor> readIntoParams( String[] queryParameters, String query) throws SQLException { try (PreparedStatement dc = currentConnection.prepareStatement(query)) { for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) { paramName = ""; } String dataType = rs.getString(2); DbParameterAccessor dbp = new DbParameterAccessor(paramName, Direction.INPUT, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } }
Source:
<code>public List<Datastream> getAllDatastreams() throws DatastreamException { GetAllRequest<Datastream> request = _builders.getAll().build(); <START> ResponseFuture<CollectionResponse<Datastream>> datastreamResponseFuture = _restClient.sendRequest(request); <END> try { return datastreamResponseFuture.getResponse().getEntity().getElements(); } catch (RemoteInvocationException e) { throw new DatastreamException("Get All Datastreams failed with error.", e); } }</code><technical_language>restli do paging automatically scenes? 10K datastreams of stored in memory? Whats memory usage</technical_language>

Target:
public List<Datastream> getAllDatastreams() throws DatastreamException { return getAllDatastreams(_builders.getAll().build()); }
Source:
<code>public void execScript(String id, String serviceName, String script) { <START> String scriptDockerLocalDir = "/opt/hawkular-apm-test-local"; <END> String[] command = new String[] { "docker-compose", "-f", id, "exec", serviceName, "bash", "-c", "mkdir " + scriptDockerLocalDir + " && " + "cp /opt/hawkular-apm-test/" + script + " " + scriptDockerLocalDir + " && " + "chmod +x " + scriptDockerLocalDir + "/" + script + " && " + scriptDockerLocalDir + "/" + script }; runShellCommand(command); }</code><technical_language>This externalized. For instance: System.getProperty("hawkular-apm-test-local-dir"), default</technical_language>

Target:
public void execScript(String id, String serviceName, String script) { String[] command = new String[] { "docker-compose", "-f", scenarioDirectory + File.separator + id, "exec", serviceName, "bash", "-c", scriptExecCommand(script), }; runShellCommand(command); }
Source:
<code>public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); IPath scriptPath = getScriptPath(); if (scriptPath == null) { setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_couldNotFindFile, scriptPathText.getText())); return false; } <START> if (!scriptPath.getFileExtension().equals("stp")) { END> setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp); } return true; }</code><technical_language>getFileExtension() null if scriptPath is a directory. I guess need extra check for this case</technical_language>

Target:
public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); IPath scriptPath = getScriptPath(); if (scriptPath == null) { setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_couldNotFindFile, scriptPathText.getText())); return false; } String extension = scriptPath.getFileExtension(); if (extension == null || !extension.equals("stp")) { setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp); return false; } return true; }
Source:
<code>public UserTuneElement build() { if (title != null) { return new UserTuneElement(this); } else { <START> throw new IllegalArgumentException("UserTune should atleast have 'title'"); <END> } }</code><technical_language>simplification improve readability of method above. Besides I a requirement in XEP-0118 user tune element's 'title' set (although appears sensible). I miss it</technical_language>

Target:
public UserTuneElement build() { return new UserTuneElement(this); }
Source:
<code>public LocalApplicationRunner(SamzaApplication app, Config config, MetadataStoreFactory metadataStoreFactory) { <START> this(app, config, getCoordinationUtils(config), metadataStoreFactory); <END> }</code><technical_language>In flow, getCoordinationUtils called full config. In new flow, getCoordinationUtils get called initial config, full config. Do need load config calling getCoordinationUtils</technical_language>

Target:
public LocalApplicationRunner(SamzaApplication app, Config config, MetadataStoreFactory metadataStoreFactory) { this(new LocalApplicationRunnerContext(app, config).setMetadataStoreFactory(metadataStoreFactory)); }
Source:
<code>public void setMessageBus(MessageBusSupport messageBus) { messageBus.setIntegrationEvaluationContext(new StandardEvaluationContext()); try { messageBus.afterPropertiesSet(); } catch (Exception e) { <START> e.printStackTrace(); <END> } this.messageBus = messageBus; }</code><technical_language>intend leave this</technical_language>

Target:
public void setMessageBus(MessageBusSupport messageBus) { messageBus.setIntegrationEvaluationContext(new StandardEvaluationContext()); try { messageBus.afterPropertiesSet(); } catch (Exception e) { throw new RuntimeException("Failed to initialize message bus", e); } this.messageBus = messageBus; }
Source:
<code>public void testLetTarget() { disableTypeCheck(); testEs6( LINE_JOINER.join( "let X = Polymer({", " is: 'x-element',", "});"), LINE_JOINER.join( " ", "var X = function() {};", "X = Polymer( {is:'x-element'});")); disableTypeCheck(); <START> testEs6( <END> LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get config() { return { properties: }; }", "};"), LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get config() { return { properties: }; }", "};")); }</code><technical_language>below..</technical_language>

Target:
public void testLetTarget() { disableTypeCheck(); testEs6( LINE_JOINER.join( "let X = Polymer({", " is: 'x-element',", "});"), LINE_JOINER.join( " ", "var X = function() {};", "X = Polymer( {is:'x-element'});")); disableTypeCheck(); testSameEs6( LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get properties() { return { }; }", "};")); }
Source:
<code>public void deletePerspectives(ArrayList<IPerspectiveDescriptor> perspToDelete) { for (IPerspectiveDescriptor <START> element : <END> perspToDelete) { deletePerspective(element); } }</code><technical_language>rename descriptor</technical_language>

Target:
public void deletePerspectives(ArrayList<IPerspectiveDescriptor> perspToDelete) { for (IPerspectiveDescriptor descriptor : perspToDelete) { deletePerspective(descriptor); } }
Source:
<code>private void handleByName(Context context, String name) throws Exception { if (name == null || "".equals(name) || DEFAULT_NAME_TOKEN.equals(name)) { context.clientError(404); return; } SortedMap<String, HealthCheck.Result> hcheckResults = new ConcurrentSkipListMap<>(); Optional<HealthCheck> hcheck = context.first(TypeToken.of(HealthCheck.class), hc -> hc.getName().equals(name)); if (!hcheck.isPresent()) { context.clientError(404); return; } try { Promise<HealthCheck.Result> promise = hcheck.get().check(context.getExecution().getControl()); promise.onError(throwable -> { hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(throwable)); <START> context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); <END> }).then(r -> { hcheckResults.put(hcheck.get().getName(), r); context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); }); } catch (Exception ex) { hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(ex)); context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); } }</code><technical_language>Collections.singletonMap instead of a concurrent map copying. similar lines</technical_language>

Target:
private void handleByName(Context context, String name) throws Exception { if (name == null || "".equals(name)) { context.clientError(404); return; } Optional<HealthCheck> hcheck = context.first(TypeToken.of(HealthCheck.class), hc -> { if (hc.getName().equals(name)) { return hc; } else { return null; } }); if (!hcheck.isPresent()) { context.clientError(404); return; } try { Promise<HealthCheck.Result> promise = hcheck.get().check(context.getExecution().getControl()); promise.onError(throwable -> { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), HealthCheck.Result.unhealthy(throwable)))); }).then(r -> { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), r))); }); } catch (Exception ex) { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), HealthCheck.Result.unhealthy(ex)))); } }
Source:
<code>synchronized void waitForCompletion() throws InterruptedException { while (finishCount < count) { wait(); } if (opts.keepalive > 0) { Thread.sleep(opts.keepalive); } eSvc.shutdown(); while (!eSvc.awaitTermination(5L, TimeUnit.SECONDS)) { System.err.println("Failed to close all threads, trying again..."); } for (ResultReporter r : reporters) { r.close(); } try { eSvc.awaitTermination(opts.keepalive, TimeUnit.MILLISECONDS); } finally { try { <START> if (opts.diffable != null) { <END> ResultFileSorter sorter = new ResultFileSorter(opts.diffable); sorter.sortFile(); } if (server != null) { server.stop(); } trf.close(); } catch (Exception e) { e.printStackTrace(); } } }</code><technical_language>Instead of altering this file, move this change LineFileReporterImpl.close()</technical_language>

Target:
synchronized void waitForCompletion() throws InterruptedException { while (finishCount < count) { wait(); } if (opts.keepalive > 0) { Thread.sleep(opts.keepalive); } eSvc.shutdown(); while (!eSvc.awaitTermination(5L, TimeUnit.SECONDS)) { System.err.println("Failed to close all threads, trying again..."); } for (ResultReporter r : reporters) { r.close(); } try { eSvc.awaitTermination(opts.keepalive, TimeUnit.MILLISECONDS); } finally { try { if (server != null) { server.stop(); } trf.close(); } catch (Exception e) { e.printStackTrace(); } } }
Source:
<code>private String perspToString(MPerspective persp) throws IOException { <START> Resource resource = new E4XMIResourceFactory().createResource(null); <END> resource.getContents().add((EObject) modelService.cloneElement(persp, null)); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { resource.save(output, null); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error(e, "Cannot close output stream"); } } } return new String(output.toByteArray(), StandardCharsets.US_ASCII); }</code><technical_language>I this leak resources. If create new ones, need destroy well</technical_language>

Target:
private String perspToString(MPerspective persp) throws IOException { Resource resource = new E4XMIResourceFactory().createResource(null); resource.getContents().add((EObject) modelService.cloneElement(persp, null)); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { resource.save(output, null); } finally { try { output.close(); } catch (IOException e) { logger.error(e, "Cannot close output stream"); } } resource.getContents().clear(); return new String(output.toByteArray(), ASCII_ENCODING); }
Source:
<code>private GitUser getCommitAuthor(RevCommit commit) { PersonIdent authorIdentity = commit.getAuthorIdent(); GitUser author = createDto(GitUser.class).withName(authorIdentity.getName()) .withEmail(authorIdentity.getEmailAddress()); <START> return author; <END> }</code><technical_language>return newDto(GitUser.class).withName(authorIdentity.getName()) .withEmail(authorIdentity.getEmailAddress());</technical_language>

Target:
private GitUser getCommitAuthor(RevCommit commit) { PersonIdent authorIdentity = commit.getAuthorIdent(); return newDto(GitUser.class).withName(authorIdentity.getName()) .withEmail(authorIdentity.getEmailAddress()); }
Source:
<code>protected boolean addedValid(IConfigurationElement element) { IConfigurationElement[] nsURIChildren = element.getChildren(TAG_NS_URI); IConfigurationElement[] resourceURIChildren = element.getChildren(TAG_RESOURCE_URI); Pattern nsURI = null; if (nsURIChildren.length > 0) { nsURI = Pattern.compile(nsURIChildren[0].getAttribute(ATT_VALUE)); } Pattern resourceURI = null; if (resourceURIChildren.length > 0) { resourceURI = Pattern.compile(resourceURIChildren[0].getAttribute(ATT_VALUE)); } String className = element.getAttribute(ATT_CLASS); IPostProcessor.Descriptor descriptor = new PostProcessorDescriptor(element, nsURI, resourceURI); descriptor.setOrdinal(Integer.parseInt(element.getAttribute(ATT_ORDINAL))); <START> StaticItemDescriptor<IPostProcessor.Descriptor> ddescriptor = new StaticItemDescriptor<IPostProcessor.Descriptor>( <END> element.getAttribute(ATT_LABEL), element.getAttribute(ATT_DESCRIPTION), descriptor .getOrdinal(), className, descriptor); IItemDescriptor<Descriptor> previous = registry.add(ddescriptor); if (previous != null) { EMFCompareRCPPlugin.getDefault().log(IStatus.WARNING, "The post processor factory '" + className + "' is registered twice."); } return true; }</code><technical_language>rename this a variable name. "descriptor" "ddescriptor" in context hinders readability</technical_language>

Target:
protected boolean addedValid(IConfigurationElement element) { IConfigurationElement[] nsURIChildren = element.getChildren(TAG_NS_URI); IConfigurationElement[] resourceURIChildren = element.getChildren(TAG_RESOURCE_URI); Pattern nsURI = null; if (nsURIChildren.length > 0) { nsURI = Pattern.compile(nsURIChildren[0].getAttribute(ATT_VALUE)); } Pattern resourceURI = null; if (resourceURIChildren.length > 0) { resourceURI = Pattern.compile(resourceURIChildren[0].getAttribute(ATT_VALUE)); } String className = element.getAttribute(ATT_CLASS); IPostProcessor.Descriptor postProcessorDescriptor = new PostProcessorDescriptor(element, nsURI, resourceURI); postProcessorDescriptor.setOrdinal(Integer.parseInt(element.getAttribute(ATT_ORDINAL))); WrapperItemDescriptor<IPostProcessor.Descriptor> postProcessorItemDescriptor = new WrapperItemDescriptor<IPostProcessor.Descriptor>( element.getAttribute(ATT_LABEL), element.getAttribute(ATT_DESCRIPTION), postProcessorDescriptor.getOrdinal(), className, postProcessorDescriptor); IItemDescriptor<Descriptor> previous = registry.add(postProcessorItemDescriptor); if (previous != null) { EMFCompareRCPPlugin.getDefault().log(IStatus.WARNING, "The post processor factory '" + className + "' is registered twice."); } return true; }
Source:
<code>public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); if (!PlayerListener19Spigot.isPlayerSpawnLocationEventCalled()) { teleportationService.teleportOnJoin(player); } if (quickCommandsProtectionManager.shouldSaveLogin(player)) { quickCommandsProtectionManager.setLogin(player.getName()); <START> } <END> management.performJoin(player); teleportationService.teleportNewPlayerToFirstSpawn(player); }</code><technical_language>I personally merge methods processLogin(player) (or saveLogin whatever) cmd protection manager takes care of checking permission node</technical_language>

Target:
public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); if (!PlayerListener19Spigot.isPlayerSpawnLocationEventCalled()) { teleportationService.teleportOnJoin(player); } quickCommandsProtectionManager.processJoin(player); management.performJoin(player); teleportationService.teleportNewPlayerToFirstSpawn(player); }
Source:
<code><START> public BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { <END> this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); this.blobBinder = checkNotNull(blobBinder, "blobBinder"); }</code><technical_language>Change signature package private, Guice injector (and test classes) instantiate class. remove redundant null checks</technical_language>

Target:
BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { this.azureBlob2Blob = azureBlob2Blob; this.blobBinder = blobBinder; }
Source:
<code>public static BlobProperties buildBlobProperties(Map<String, Object> args) throws RestServiceException { Account account = (Account) args.get(InternalKeys.TARGET_ACCOUNT_KEY); Container container = (Container) args.get(InternalKeys.TARGET_CONTAINER_KEY); <START> Objects.requireNonNull(account, "Target account object has not been injected into rest request"); <END> Objects.requireNonNull(container, "Target container object has not been injected into rest request"); String serviceId = getHeader(args, Headers.SERVICE_ID, true); String contentType = getHeader(args, Headers.AMBRY_CONTENT_TYPE, true); String ownerId = getHeader(args, Headers.OWNER_ID, false); long ttl = Utils.Infinite_Time; String ttlStr = getHeader(args, Headers.TTL, false); if (ttlStr != null) { try { ttl = Long.parseLong(ttlStr); if (ttl < -1) { throw new RestServiceException(Headers.TTL + "[" + ttl + "] is not valid (has to be >= -1)", RestServiceErrorCode.InvalidArgs); } } catch (NumberFormatException e) { throw new RestServiceException(Headers.TTL + "[" + ttlStr + "] could not parsed into a number", RestServiceErrorCode.InvalidArgs); } } return new BlobProperties(-1, serviceId, ownerId, contentType, getIsPrivateSetting(args), ttl, account.getId(), container.getId()); }</code><technical_language>I checks required - NullPointerException thrown chain anyway</technical_language>

Target:
public static BlobProperties buildBlobProperties(Map<String, Object> args) throws RestServiceException { Account account = (Account) args.get(InternalKeys.TARGET_ACCOUNT_KEY); Container container = (Container) args.get(InternalKeys.TARGET_CONTAINER_KEY); String serviceId = getHeader(args, Headers.SERVICE_ID, true); String contentType = getHeader(args, Headers.AMBRY_CONTENT_TYPE, true); String ownerId = getHeader(args, Headers.OWNER_ID, false); long ttl = Utils.Infinite_Time; String ttlStr = getHeader(args, Headers.TTL, false); if (ttlStr != null) { try { ttl = Long.parseLong(ttlStr); if (ttl < -1) { throw new RestServiceException(Headers.TTL + "[" + ttl + "] is not valid (has to be >= -1)", RestServiceErrorCode.InvalidArgs); } } catch (NumberFormatException e) { throw new RestServiceException(Headers.TTL + "[" + ttlStr + "] could not parsed into a number", RestServiceErrorCode.InvalidArgs); } } return new BlobProperties(-1, serviceId, ownerId, contentType, isPrivate(args), ttl, account.getId(), container.getId()); }
Source:
<code>public boolean onLongClick(View view) { switch (view.getId()) { case R.id.from: onAddAddressesToClipboard(mMessage.getFrom()); break; case R.id.to: <START> try { <END> onAddAddressesToClipboard(mMessage.getRecipients(Message.RecipientType.TO)); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get recipients address", e); } break; case R.id.cc: try { onAddAddressesToClipboard(mMessage.getRecipients(Message.RecipientType.CC)); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get recipients address", e); } break; } return true; }</code><technical_language>a try/catch block code harder read duplicates error handling code. I suggest creating a new method recipients a message handles exception</technical_language>

Target:
public boolean onLongClick(View view) { switch (view.getId()) { case R.id.from: onAddAddressesToClipboard(mMessage.getFrom()); break; case R.id.to: onAddRecipientsToClipboard(Message.RecipientType.TO); break; case R.id.cc: onAddRecipientsToClipboard(Message.RecipientType.CC); break; } return true; }
Source:
<code>protected Object readResolve() { if (containers == null) { containers = new ArrayList<>(); ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image); containerTemplate.setCommand(command); containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args); containerTemplate.setPrivileged(privileged); containerTemplate.setAlwaysPullImage(alwaysPullImage); containerTemplate.setEnvVars(envVars); containerTemplate.setResourceRequestMemory(resourceRequestMemory); containerTemplate.setResourceLimitCpu(resourceLimitCpu); containerTemplate.setResourceLimitMemory(resourceLimitMemory); containerTemplate.setResourceRequestCpu(resourceRequestCpu); containerTemplate.setWorkingDir(remoteFs); containers.add(containerTemplate); } if (podRetention == null) { podRetention = PodRetention.getPodTemplateDefault(); } if (annotations == null) { annotations = new ArrayList<>(); } yaml = Util.fixEmpty(yaml); if (yamls != null) { setYamls(yamls); if (!yamls.isEmpty()) { <START> yaml = yamls.get(0); <END> } yamls = null; } if (showRawYaml == null) { showRawYaml = Boolean.TRUE; } if (yamlMergeStrategy == null) { yamlMergeStrategy = YamlMergeStrategy.defaultStrategy(); } return this; }</code><technical_language>this verifying yamls.size() == 1</technical_language>

Target:
protected Object readResolve() { if (containers == null) { containers = new ArrayList<>(); ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image); containerTemplate.setCommand(command); containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args); containerTemplate.setPrivileged(privileged); containerTemplate.setAlwaysPullImage(alwaysPullImage); containerTemplate.setEnvVars(envVars); containerTemplate.setResourceRequestMemory(resourceRequestMemory); containerTemplate.setResourceLimitCpu(resourceLimitCpu); containerTemplate.setResourceLimitMemory(resourceLimitMemory); containerTemplate.setResourceRequestCpu(resourceRequestCpu); containerTemplate.setWorkingDir(remoteFs); containers.add(containerTemplate); } if (podRetention == null) { podRetention = PodRetention.getPodTemplateDefault(); } if (annotations == null) { annotations = new ArrayList<>(); } yaml = Util.fixEmpty(yaml); if (yamls != null) { setYamls(yamls); if (!yamls.isEmpty()) { if (yamls.size() > 1) { LOGGER.log(Level.WARNING, "Found several persisted YAML fragments in pod template " + name + ". Only the first fragment will be considered, others will be ignored."); } yaml = yamls.get(0); } yamls = null; } if (showRawYaml == null) { showRawYaml = Boolean.TRUE; } if (yamlMergeStrategy == null) { yamlMergeStrategy = YamlMergeStrategy.defaultStrategy(); } return this; }
Source:
<code>public void testNonPartition() throws Exception { prepareTables(false); createTable("source", source.toURI().toString(), false); createTable("sink", sink.toURI().toString(), false); tEnv().executeSql("insert into sink select * from source").await(); <START> CloseableIterator<Row> iter = tEnv().executeSql("select * from sink").collect(); <END> List<String> results = CollectionUtil.iteratorToList(iter).stream() .map(row -> row.getKind().shortString() + "(" + row.toString() + ")") .collect(Collectors.toList()); iter.close(); Assert.assertEquals(EXPECTED, results); }</code><technical_language>Select some fields trigger projection push down? write more column sink, e.g UPPER(name), select out upper_name instead of name</technical_language>

Target:
public void testNonPartition() throws Exception { prepareTables(false); createTable(false, source.toURI().toString(), false); createTable(true, sink.toURI().toString(), false); tEnv().executeSql("insert into sink select id,name,UPPER(name),description,weight from source").await(); CloseableIterator<Row> iter = tEnv() .executeSql("select id,upper_name,description,weight from sink").collect(); List<String> results = CollectionUtil.iteratorToList(iter).stream() .map(row -> row.getKind().shortString() + "(" + row.toString() + ")") .collect(Collectors.toList()); iter.close(); Assert.assertEquals(EXPECTED, results); }
Source:
<code>public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long endTimeNanos = System.nanoTime() + unit.toNanos(timeout); <START> Counter counter = getActiveChannelCounter(); <END> for (ChannelAndMetrics channelWrapper : channels.get()) { ManagedChannel channel = channelWrapper.channel; if (channel.isTerminated()) { continue; } long awaitTimeNanos = endTimeNanos - System.nanoTime(); if (awaitTimeNanos <= 0) { break; } channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS); counter.dec(); } return isTerminated(); }</code><technical_language>NB: logic is slightly strange, I fine. potentially spend entire time budget awaiting for termination non-terminated channel find. Of implementation of awaitTermination do other sleeping for entire allotted time, I guess of this matters, weird me. read more natural IMO if checked for non-terminated channels, if find any, slept for some increment, checking of again, I imagine this is worth worrying about</technical_language>

Target:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long endTimeNanos = System.nanoTime() + unit.toNanos(timeout); for (InstrumentedChannel channel : channels.get()) { if (channel.isTerminated()) { continue; } long awaitTimeNanos = endTimeNanos - System.nanoTime(); if (awaitTimeNanos <= 0) { break; } channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS); } return isTerminated(); }
Source:
<code>protected boolean checkDisksNotInBackupStorage() { <START> for (Disk disk : getVm().getDiskMap().values()) { <END> StorageDomainStatic destDomain = storageDomainStaticDao.get(disk.getId()); if (destDomain.isBackup()) { return false; } } return true; }</code><technical_language>For disk check is image not. check. if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { backup storage domain images. Direct LUN disks part of backup storage domain</technical_language>

Target:
protected boolean checkDisksNotInBackupStorage() { for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { StorageDomainStatic destDomain = storageDomainStaticDao.get(((DiskImage)disk).getStorageIds().get(0)); if (getVm().getDiskMap().values().stream().anyMatch(destDomain.isBackup())) { return false; } } } return true; }