auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Set<Symbol>> context) { Set<Symbol> expectedFilterInputs = ImmutableSet.<Symbol>builder() .addAll(SymbolsExtractor.extractUnique(node.getFilter())) .addAll(context.get()) .build(); PlanNode left = context.rewrite(node.getLeft(), expectedFilterInputs); PlanNode right = context.rewrite(node.getRight(), expectedFilterInputs); Set<Symbol> seenSymbol = new HashSet<>(); List<Symbol> outputSymbols = node.getOutputSymbols().stream() .filter(context.get()::contains) .filter(seenSymbol::add) <START> .collect(toImmutableList()); <END> return new SpatialJoinNode(node.getId(), node.getType(), left, right, outputSymbols, node.getFilter()); }</code><technical_language>distinct</technical_language>

Target:
public PlanNode visitSpatialJoin(SpatialJoinNode node, RewriteContext<Set<Symbol>> context) { Set<Symbol> requiredInputs = ImmutableSet.<Symbol>builder() .addAll(SymbolsExtractor.extractUnique(node.getFilter())) .addAll(context.get()) .build(); PlanNode left = context.rewrite(node.getLeft(), requiredInputs); PlanNode right = context.rewrite(node.getRight(), requiredInputs); List<Symbol> outputSymbols = node.getOutputSymbols().stream() .filter(context.get()::contains) .distinct() .collect(toImmutableList()); return new SpatialJoinNode(node.getId(), node.getType(), left, right, outputSymbols, node.getFilter()); }
Source:
<code>public void customExhangeTestBean() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, CustomExchangeTestBean.class); final Collection<org.springframework.amqp.core.Exchange> exchanges = context .getBeansOfType(org.springframework.amqp.core.Exchange.class).values(); assertThat(exchanges, hasSize(1)); assertThat(exchanges.iterator().next(), instanceOf(CustomExchange.class)); final CustomExchange customExchange = (CustomExchange) exchanges.iterator().next(); assertEquals("my_custom_exchange", customExchange.getName()); <START> assertEquals("custom_type", customExchange.getType()); <END> context.close(); }</code><technical_language>big height fix reasonable for me. work real Broker? curious if CustomExchange is robust. But, yeah, thank @panchenko for effort support community improve Framework</technical_language>

Target:
public void customExhangeTestBean() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class, CustomExchangeTestBean.class); final Collection<CustomExchange> exchanges = context.getBeansOfType(CustomExchange.class).values(); assertThat(exchanges, hasSize(1)); final CustomExchange exchange = exchanges.iterator().next(); assertEquals("my_custom_exchange", exchange.getName()); assertEquals("custom_type", exchange.getType()); context.close(); }
Source:
<code>public Tag build() { validate(); if (tagBytes != null) { return new ArrayBackedTag(tagType, tagBytes); } else { <START> return new ByteBufferTag(tagType, tagBuffer, -Tag.INFRASTRUCTURE_SIZE, <END> tagBuffer.capacity() + Tag.INFRASTRUCTURE_SIZE); } }</code><technical_language>Pls... Ya in builder lets byte[] create ArrayBackedTags</technical_language>

Target:
public Tag build() { validate(); return new ArrayBackedTag(tagType, tagBytes); }
Source:
<code>public SuccessResponse addTable(String tableConfigStr) { TableConfig tableConfig; try { tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class); TableConfigUtils.validate(tableConfig); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.BAD_REQUEST, e); } String tableName = tableConfig.getTableName(); try { ensureMinReplicas(tableConfig); verifyTableConfigs(tableConfig); _pinotHelixResourceManager.addTable(tableConfig); <START> return new SuccessResponse("Table " + tableName + " Successfully added"); <END> } catch (Exception e) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.CONTROLLER_TABLE_ADD_ERROR, 1L); if (e instanceof PinotHelixResourceManager.InvalidTableConfigException) { String errStr = String.format("Invalid table config for table %s: %s", tableName, e.getMessage()); throw new ControllerApplicationException(LOGGER, errStr, Response.Status.BAD_REQUEST, e); } else if (e instanceof PinotHelixResourceManager.TableAlreadyExistsException) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.CONFLICT, e); } else { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR, e); } } }</code><technical_language>do need change this</technical_language>

Target:
public SuccessResponse addTable(String tableConfigStr) { TableConfig tableConfig; try { tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class); TableConfigUtils.validate(tableConfig); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.BAD_REQUEST, e); } String tableName = tableConfig.getTableName(); try { ensureMinReplicas(tableConfig); verifyTableConfigs(tableConfig); _pinotHelixResourceManager.addTable(tableConfig); return new SuccessResponse("Table " + tableName + " succesfully added"); } catch (Exception e) { _controllerMetrics.addMeteredGlobalValue(ControllerMeter.CONTROLLER_TABLE_ADD_ERROR, 1L); if (e instanceof PinotHelixResourceManager.InvalidTableConfigException) { String errStr = String.format("Invalid table config for table %s: %s", tableName, e.getMessage()); throw new ControllerApplicationException(LOGGER, errStr, Response.Status.BAD_REQUEST, e); } else if (e instanceof PinotHelixResourceManager.TableAlreadyExistsException) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.CONFLICT, e); } else { throw new ControllerApplicationException(LOGGER, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR, e); } } }
Source:
<code>public void startBackgroundTasks() { scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.ALL) .withName("Five Updater") <START> , DAILY <END> ); log.info("Installed Five updater"); scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.TODAY) .withName("Five Today Updater") , RepetitionRules.NEVER ); log.info("Installed FiveToday updater"); scheduler.schedule( fiveUpdater(FiveUpdater.TimeFrame.PLUS_MINUS_7_DAYS) .withName("Five +-7 Days Updater") , RepetitionRules.NEVER ); log.info("Installed FivePlusMinusSevenDays updater"); }</code><technical_language>change this 1/week Friday night</technical_language>

Target:
public void startBackgroundTasks() { scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.ALL) .withName("Five Updater"), DAILY ); log.info("Installed Five updater"); scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.TODAY) .withName("Five Today Updater"), RepetitionRules.NEVER ); log.info("Installed FiveToday updater"); scheduler.schedule( fiveUpdaterDelegate(FiveUpdater.TimeFrame.PLUS_MINUS_7_DAYS) .withName("Five +-7 Days Updater"), RepetitionRules.NEVER ); log.info("Installed FivePlusMinusSevenDays updater"); }
Source:
<code>public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); <START> DocumentModel lastVersion = session.getLastDocumentVersion(idRef); <END> return lastVersion; }</code><technical_language>return this</technical_language>

Target:
public DocumentModel run(DocumentModel input) { IdRef idRef = new IdRef(input.getId()); return session.getLastDocumentVersion(idRef); }
Source:
<code>public static void handleRequest(RestRequestInfo restRequestInfo) throws RestServiceException { RestResponseHandler responseHandler = restRequestInfo.getRestResponseHandler(); if (restRequestInfo.getRestRequestContent() == null) { String echoStr = echo(restRequestInfo.getRestRequestMetadata()).toString(); responseHandler.setContentType("text/plain"); responseHandler.addToResponseBody(echoStr.getBytes(), true); } else if (restRequestInfo.getRestRequestContent().isLast()) { responseHandler.flush(); <START> responseHandler.close(); <END> } }</code><technical_language>do need close connection here</technical_language>

Target:
public static void handleRequest(RestRequestInfo restRequestInfo) throws RestServiceException { RestResponseHandler responseHandler = restRequestInfo.getRestResponseHandler(); if (restRequestInfo.getRestRequestContent() == null) { String echoStr = echo(restRequestInfo.getRestRequestMetadata()).toString(); responseHandler.setContentType("application/json"); responseHandler.addToResponseBody(echoStr.getBytes(), true); } else if (restRequestInfo.getRestRequestContent().isLast()) { responseHandler.flush(); responseHandler.onRequestComplete(null, false); } }
Source:
<code>public void execute(DiagnosticContext context) { logger.info("Getting Elasticsearch Version."); try { DiagnosticInputs diagnosticInputs = context.getDiagnosticInputs(); RestClient restClient = context.getEsRestClient(); RestResult res = restClient.execQuery("/"); if(res.getStatus() != 200)){ <START> throw new DiagnosticException("Unrecoverable ES query error."); <END> } String result = res.toString(); JsonNode root = JsonYamlUtils.createJsonNodeFromString(result); String versionNumber = root.path("version").path("number").asText(); Version version = new Version(versionNumber); context.setVersion(version); } catch (Exception e) { logger.error("Could not retrieve the Elasticsearch version - unable to continue."); throw new DiagnosticException("Undetermined error", e); } }</code><technical_language>suggestion throw new DiagnosticException("Unable fetch [GET /]"); this is in try / catch, this info error output</technical_language>

Target:
public void execute(DiagnosticContext context) { logger.info("Getting Elasticsearch Version."); try { RestClient restClient = context.getEsRestClient(); RestResult res = restClient.execQuery("/"); if (! res.isValid()) { throw new DiagnosticException( res.formatStatusMessage( "Could not retrieve the Elasticsearch version - unable to continue.")); } String result = res.toString(); JsonNode root = JsonYamlUtils.createJsonNodeFromString(result); String versionNumber = root.path("version").path("number").asText(); Version version = new Version(versionNumber); context.setVersion(version); } catch (DiagnosticException de) { throw de; } catch (Throwable t) { logger.log(SystemProperties.DIAG, "Unanticipated error:", t); throw new DiagnosticException(String.format("Could not retrieve the Elasticsearch version due to a system or network error - unable to continue. %s", Constants.CHECK_LOG)); } }
Source:
<code>public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) <START> .map(r -> (r.getMethod() != null ? r.getMethod() : Mono.empty())) <END> .filter(m -> ALLOWED_METHODS.contains(m)) .flatMap(m -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); }</code><technical_language>This right me. map a publisher. a .flatMap code paths need a Publisher suggestion .flatMap(r -> Mono.justOrEmpty(r.getMethod()))</technical_language>

Target:
public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap(r -> Mono.justOrEmpty(r.getMethod())) .filter(m -> ALLOWED_METHODS.contains(m)) .flatMap(m -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); }
Source:
<code>protected String doIntercept(ActionInvocation invocation) throws Exception { Validator validator = this.beanValidationManager.getValidator(); if (validator == null) { LOG.debug("There is no Bean Validator configured in class path. Skipping Bean validation.."); return invocation.invoke(); } LOG.debug("Starting bean validation using validator: {}", validator.getClass()); Object action = invocation.getAction(); ActionProxy actionProxy = invocation.getProxy(); String methodName = actionProxy.getMethod(); if (LOG.isDebugEnabled()) { LOG.debug("Validating [{}/{}] with method [{}]", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName(), methodName); } <START> Class<?>[] validationGroup = getValidationGroups(action, methodName); <END> if (null == MethodUtils.getAnnotation(getActionMethod(action.getClass(), methodName), SkipValidation.class, true, true)) { performBeanValidation(action, validator, validationGroup); } return invocation.invoke(); }</code><technical_language>remove this line line#104 (i.e. required user skips validation)</technical_language>

Target:
protected String doIntercept(ActionInvocation invocation) throws Exception { Validator validator = this.beanValidationManager.getValidator(); if (validator == null) { LOG.debug("There is no Bean Validator configured in class path. Skipping Bean validation.."); return invocation.invoke(); } LOG.debug("Starting bean validation using validator: {}", validator.getClass()); Object action = invocation.getAction(); ActionProxy actionProxy = invocation.getProxy(); String methodName = actionProxy.getMethod(); LOG.debug("Validating [{}/{}] with method [{}]", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName(), methodName); if (null == MethodUtils.getAnnotation(getActionMethod(action.getClass(), methodName), SkipValidation.class, true, true)) { Class<?>[] validationGroup = getValidationGroups(action, methodName); performBeanValidation(action, validator, validationGroup); } return invocation.invoke(); }
Source:
<code>public Response getDeviceInformation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { DeviceInformationManager informationManager; DeviceInfo deviceInfo; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); } catch (DeviceDetailsMgtException e) { <START> String msg = "Error occurred while getting the device information."; <END> log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); }</code><technical_language>Add deviceId type parameters msg. give enough context for logs</technical_language>

Target:
public Response getDeviceInformation( @PathParam("type") @Size(max = 45) String type, @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { DeviceInformationManager informationManager; DeviceInfo deviceInfo; try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(id); deviceIdentifier.setType(type); informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService(); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while getting the device information of id : " + id + " type : " + type ; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(deviceInfo).build(); }
Source:
<code>public long getMinEnd() { <START> return fMinEnd != null ? fMinEnd : getNodeEnd(); <END> }</code><technical_language>getNodeEnd() return Long.Max_Value is node is disk... brings original state. expected, assert in benchmark fails</technical_language>

Target:
public long getMinEnd() { return fMinEnd != null ? fMinEnd : getNodeStart(); }
Source:
<code>public TabularData getRouteProperties() { try { final Map<String, Object> properties = route.getProperties(); final TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.camelRoutePropertiesTabularType()); final CompositeType ct = CamelOpenMBeanTypes.camelRoutePropertiesCompositeType(); for (Map.Entry<String, Object> entry : properties.entrySet()) { final String key = entry.getKey(); final String val = context.getTypeConverter().convertTo(String.class, entry.getValue()); CompositeData data = new CompositeDataSupport( ct, <START> new String[]{ "name", "value"}, <END> new Object[]{ key, val } ); answer.put(data); } return answer; } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }</code><technical_language>key instead of name</technical_language>

Target:
public TabularData getRouteProperties() { try { final Map<String, Object> properties = route.getProperties(); final TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.camelRoutePropertiesTabularType()); final CompositeType ct = CamelOpenMBeanTypes.camelRoutePropertiesCompositeType(); for (Map.Entry<String, Object> entry : properties.entrySet()) { final String key = entry.getKey(); final String val = context.getTypeConverter().convertTo(String.class, entry.getValue()); CompositeData data = new CompositeDataSupport( ct, new String[]{"key", "value"}, new Object[]{key, val} ); answer.put(data); } return answer; } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
Source:
<code>private Schema getOutputSchema(FailureCollector collector) { List<Schema.Field> fields = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { collector.addFailure("Field name cannot be null or empty.", null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { collector.addFailure(String.format("A type must be provided for field '%s'.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { <START> Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(Schema.of(Schema.Type.valueOf( <END> params[1].trim().toUpperCase())))); if (fieldNames.contains(field.getName())) { collector.addFailure(String.format("Field '%s' already has a type specified.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { fields.add(field); fieldNames.add(field.getName()); } } } collector.getOrThrowException(); return Schema.recordOf("record", fields); }</code><technical_language>function calls function calls, hard read. Break this 2 statements</technical_language>

Target:
private Schema getOutputSchema(FailureCollector collector) { List<Schema.Field> fields = new ArrayList<>(); List<String> fieldNames = new ArrayList<>(); String[] mappings = fieldTypeMapping.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); String fieldName = params[0].trim(); if (Strings.isNullOrEmpty(fieldName)) { collector.addFailure("Field name cannot be null or empty.", null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else if (params.length < 2 || Strings.isNullOrEmpty(params[1])) { collector.addFailure(String.format("A type must be provided for field '%s'.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { Schema fieldSchema = Schema.of(Schema.Type.valueOf(params[1].trim().toUpperCase())); Schema.Field field = Schema.Field.of(fieldName, Schema.nullableOf(fieldSchema)); if (fieldNames.contains(field.getName())) { collector.addFailure(String.format("Field '%s' already has a type specified.", fieldName), null) .withConfigElement(FIELD_TYPE_MAPPING, mapping); } else { fields.add(field); fieldNames.add(field.getName()); } } } collector.getOrThrowException(); return Schema.recordOf("record", fields); }
Source:
<code>public void consumerChangeDetection() { Consumer existing = getFakeConsumer(); Set<ConsumerCapability> caps1 = new HashSet<ConsumerCapability>(); Set<ConsumerCapability> caps2 = new HashSet<ConsumerCapability>(); ConsumerCapability cca = new ConsumerCapability(existing, "capability_a"); ConsumerCapability ccb = new ConsumerCapability(existing, "capability_b"); ConsumerCapability ccc = new ConsumerCapability(existing, "capability_c"); caps1.add(cca); caps1.add(ccb); caps1.add(ccc); caps2.add(ccb); existing.setCapabilities(caps1); Consumer toUpdate = getFakeConsumer(); toUpdate.setCapabilities(caps1); assertFalse(resource.performConsumerUpdates(existing, toUpdate, null)); toUpdate.setCapabilities(caps2); assertTrue(resource.performConsumerUpdates(existing, toUpdate, null)); <START> toUpdate.setCapabilities(null); <END> assertFalse(resource.performConsumerUpdates(existing, toUpdate, null)); }</code><technical_language>Consumer.setCapabilities checks null is set Consumer.capabilities field. I intention of this part of test test this path: java if (update.getCapabilities() != null) { do that</technical_language>

Target:
public void consumerChangeDetection() { Consumer existing = getFakeConsumer(); Set<ConsumerCapability> caps1 = new HashSet<ConsumerCapability>(); Set<ConsumerCapability> caps2 = new HashSet<ConsumerCapability>(); ConsumerCapability cca = new ConsumerCapability(existing, "capability_a"); ConsumerCapability ccb = new ConsumerCapability(existing, "capability_b"); ConsumerCapability ccc = new ConsumerCapability(existing, "capability_c"); caps1.add(cca); caps1.add(ccb); caps1.add(ccc); caps2.add(ccb); existing.setCapabilities(caps1); Consumer update = getFakeConsumer(); update.setCapabilities(caps1); assertFalse(resource.performConsumerUpdates(update, existing, null)); update.setCapabilities(caps2); assertTrue(resource.performConsumerUpdates(update, existing, null)); update = getFakeConsumer(); assertFalse(resource.performConsumerUpdates(update, existing, null)); }
Source:
<code>public final boolean getBoolean(final String property) { final String val = this.properties.getProperty(property).toUpperCase(); <START> if (val == null) <END> throw new NullPointerException(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }</code><technical_language>I this necessary. If property set, NPE thrown code attempts call .toUpperCase(). This line next removed</technical_language>

Target:
public final boolean getBoolean(final String property) { final String val = this.properties.get(property).toUpperCase(); if (val.equals("1")) return true; if (val.equals("TRUE")) return true; if (val.equals("YES")) return true; return false; }
Source:
<code>private String formatLine(String str) { <START> if (str.isEmpty()) { <END> return ""; } else { String safeString = SafeHtmlUtils.htmlEscape(str); return "<nobr>" + safeString +"</nobr><br>"; } }</code><technical_language>I write str.trim().isEmpty()</technical_language>

Target:
private String formatLine(String str) { if (str.trim().isEmpty()) { return ""; } else { String safeString; if (str.matches("\\[.*\\].*")) { safeString = SafeHtmlUtils.htmlEscape(str).replaceFirst("]", "]</span>"); return "<nobr><span style='color:gray;'>" + safeString +"</nobr><br>"; } else { safeString = SafeHtmlUtils.htmlEscape(str); return "<nobr>" + safeString +"</nobr><br>"; } } }
Source:
<code>static public String sendHttpPutRequest(String url) { String response = null; try { <START> return HttpUtil.executeUrl("PUT", url, 1000); <END> } catch (IOException e) { logger.error("Fatal transport error: {}",e); } return response; }</code><technical_language>response = instead of return</technical_language>

Target:
static public String sendHttpPutRequest(String url) { String response = null; try { response = HttpUtil.executeUrl("PUT", url, 1000); } catch (IOException e) { logger.error("Fatal transport error: {}", e); } return response; }
Source:
<code>private ArrayList<Integer> getAvailableSeasons() { <START> final ArrayList<Integer> availableSeasons = new ArrayList<>(); <END> for (Episode episode : show.episodes) { if (!availableSeasons.contains(episode.season)) { availableSeasons.add(episode.season); } } Collections.sort(availableSeasons); return availableSeasons; }</code><technical_language>for method signature</technical_language>

Target:
private List<Integer> getAvailableSeasons() { final List<Integer> availableSeasons = new ArrayList<>(); for (Episode episode : show.episodes) { if (!availableSeasons.contains(episode.season)) { availableSeasons.add(episode.season); } } Collections.sort(availableSeasons); return availableSeasons; }
Source:
<code>public static synchronized void startAsynchronousLogging(){ <START> if (m_asynchLoggerPool == null) { <END> m_asynchLoggerPool = Boolean.getBoolean("DISABLE_ASYNC_LOGGING") ? null : new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new LoggerThreadFactory()); if (m_asynchLoggerPool != null) { try { m_asynchLoggerPool.submit(new Runnable() { @Override public void run() }).get(); } catch (InterruptedException | ExecutionException e) { } } } }</code><technical_language>java if (m_asynchLoggerPool == null && !Boolean.getBoolean("DISABLE_ASYNC_LOGGING")) { m_asynchLoggerPool = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new LoggerThreadFactory()); try { m_asynchLoggerPool.submit(new Runnable() { @Override public void run )).get(); catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Unable prime asynchronous logging", e); } }</technical_language>

Target:
public static synchronized void startAsynchronousLogging(){ if (m_asynchLoggerPool == null && !Boolean.getBoolean("DISABLE_ASYNC_LOGGING")) { m_asynchLoggerPool = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new LoggerThreadFactory()); try { m_asynchLoggerPool.submit(new Runnable() { @Override public void run() }).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Unable to prime asynchronous logging", e); } } }
Source:
<code>public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } try { String addrString = InetAddresses.toAddrString(InetAddress.getByAddress(getSlice(block, position).getBytes(0, 2 * Long.BYTES))); String prefixString = Integer.toString(getSlice(block, position).getByte(2 * Long.BYTES) & 0xff); return addrString + "/" + prefixString; } catch (UnknownHostException e) { <START> throw new IllegalArgumentException(); <END> } }</code><technical_language>nit: new IllegalArgumentException(e) stackstrace in UnknownHostException well</technical_language>

Target:
public Object getObjectValue(ConnectorSession session, Block block, int position) { if (block.isNull(position)) { return null; } try { String addrString = InetAddresses.toAddrString(InetAddress.getByAddress(getSlice(block, position).getBytes(0, 2 * Long.BYTES))); String prefixString = Integer.toString(getSlice(block, position).getByte(2 * Long.BYTES) & 0xff); return addrString + "/" + prefixString; } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } }
Source:
<code>public String getForegroundWindowTitle() { if (!isOnWindows) { return null; } HWND window = User32.INSTANCE.GetForegroundWindow(); if (window != null) { char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); } else { return null; <START> } <END> }</code><technical_language>if (window == null) { return null; } char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); Reduces nesting favors "guards" method returns invalid conditions, leaving "actual" code end</technical_language>

Target:
private String getForegroundWindowTitle() { if (!isWindows) { return null; } HWND window = User32.INSTANCE.GetForegroundWindow(); if (window == null) { return null; } char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MultiSourceTrackingToken that = (MultiSourceTrackingToken) o; if (this.trackingTokens.size() != that.trackingTokens.size()) { return false; } for (Map.Entry<String, TrackingToken> trackingTokenEntry : trackingTokens.entrySet()) { try { <START> if ( trackingTokenEntry.getValue() == null && that.trackingTokens.get(trackingTokenEntry.getKey()) == null) { <END> return true; } if (!trackingTokenEntry.getValue().equals(that.trackingTokens.get(trackingTokenEntry.getKey()))) { return false; } } catch (NullPointerException ex) { logger.warn("A constituent token has not been initialized"); return false; } } return true; }</code><technical_language>This lead a NPE, trackingTokenEntry is null, a non-null entry. Consider Object.equals(x, y) in existing if statement, instead of x.equals(y)</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MultiSourceTrackingToken that = (MultiSourceTrackingToken) o; if (this.trackingTokens.size() != that.trackingTokens.size()) { return false; } return trackingTokens.entrySet() .stream() .allMatch(trackingTokenEntry -> Objects.equals(trackingTokenEntry.getValue(), that.trackingTokens.get(trackingTokenEntry.getKey()))); }
Source:
<code>public static void setupRegionReplicaReplication(Configuration conf) throws IOException { if (!isRegionReplicaReplicationEnabled(conf)) { return; } try (Connection connection = ConnectionFactory.createConnection(conf); Admin admin = connection.getAdmin()) { ReplicationPeerConfig peerConfig = null; peerConfig = admin.getReplicationPeerConfig(REGION_REPLICA_REPLICATION_PEER); if (peerConfig == null) { LOG.info("Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist. Creating..."); peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(ZKConfig.getZooKeeperClusterKey(conf)); peerConfig.setReplicationEndpointImpl(RegionReplicaReplicationEndpoint.class.getName()); admin.addReplicationPeer(REGION_REPLICA_REPLICATION_PEER, peerConfig); } <START> } catch (ReplicationPeerNotFoundException e) { LOG.warn( "Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist", e); <END> } }</code><technical_language>If catch this Exception, want create replication peer id? model this with: try(closeables){ try{ peerConfig = admin.getReplicationPeerConfig(REGION_REPLICA_REPLICATION_PEER); } catch (ReplicationPeerNotFoundException e){ } if (peerConfig == null) { ..... } }</technical_language>

Target:
public static void setupRegionReplicaReplication(Configuration conf) throws IOException { if (!isRegionReplicaReplicationEnabled(conf)) { return; } try (Connection connection = ConnectionFactory.createConnection(conf); Admin admin = connection.getAdmin()) { ReplicationPeerConfig peerConfig = null; try { peerConfig = admin.getReplicationPeerConfig(REGION_REPLICA_REPLICATION_PEER); } catch (ReplicationPeerNotFoundException e) { LOG.warn( "Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist", e); } if (peerConfig == null) { LOG.info("Region replica replication peer id=" + REGION_REPLICA_REPLICATION_PEER + " not exist. Creating..."); peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(ZKConfig.getZooKeeperClusterKey(conf)); peerConfig.setReplicationEndpointImpl(RegionReplicaReplicationEndpoint.class.getName()); admin.addReplicationPeer(REGION_REPLICA_REPLICATION_PEER, peerConfig); } } }
Source:
<code>public void beginFunction() { <START> collectSet = new HashSet<>(); <END> }</code><technical_language>a Set final create in constructor, clear here</technical_language>

Target:
public void beginFunction() { collectSet.clear(); }
Source:
<code>public ResourceCounter freeReservedSlot(AllocationID allocationId, @Nullable Throwable cause, long currentTime) { <START> LOG.debug("Release slot {}.", allocationId); <END> final Optional<AllocatedSlot> releasedSlot = slotPool.freeReservedSlot(allocationId, currentTime); Optional<ResourceCounter> previouslyFulfilledRequirement = releasedSlot.map(Collections::singleton).map(this::getFulfilledRequirements); releasedSlot.ifPresent(allocatedSlot -> { releasePayload(Collections.singleton(allocatedSlot), cause); tryToFulfillResourceRequirement(allocatedSlot); notifyNewSlots.accept(Collections.singletonList(allocatedSlot)); }); return previouslyFulfilledRequirement.orElseGet(ResourceCounter::empty); }</code><technical_language>consistent terms Free reserved slot {}. here</technical_language>

Target:
public ResourceCounter freeReservedSlot(AllocationID allocationId, @Nullable Throwable cause, long currentTime) { LOG.debug("Free reserved slot {}.", allocationId); final Optional<AllocatedSlot> freedSlot = slotPool.freeReservedSlot(allocationId, currentTime); Optional<ResourceCounter> previouslyFulfilledRequirement = freedSlot.map(Collections::singleton).map(this::getFulfilledRequirements); freedSlot.ifPresent(allocatedSlot -> { releasePayload(Collections.singleton(allocatedSlot), cause); tryToFulfillResourceRequirement(allocatedSlot); notifyNewSlots.accept(Collections.singletonList(allocatedSlot)); }); return previouslyFulfilledRequirement.orElseGet(ResourceCounter::empty); }
Source:
<code>public long readFrom(ReadableByteChannel channel) throws IOException { long bytesRead = 0; if (buffer == null) { if (sizeBuffer == null) { <START> sizeBuffer = ByteBufAllocator.DEFAULT.heapBuffer(8); <END> } try { bytesRead = readBytesFromReadableByteChannel(channel, sizeBuffer); if (bytesRead < 0) { throw new EOFException(); } } catch (IOException e) { sizeBuffer.release(); sizeBuffer = null; throw e; } if (sizeBuffer.writerIndex() == sizeBuffer.capacity()) { sizeToRead = sizeBuffer.readLong(); sizeRead += 8; sizeBuffer.release(); buffer = ByteBufAllocator.DEFAULT.heapBuffer((int) sizeToRead - 8); } } if (buffer != null && sizeRead < sizeToRead) { long bytesReadFromChannel; try { bytesReadFromChannel = readBytesFromReadableByteChannel(channel, buffer); if (bytesReadFromChannel < 0) { throw new EOFException(); } } catch (IOException e) { buffer.release(); buffer = null; throw e; } sizeRead += bytesReadFromChannel; bytesRead += bytesReadFromChannel; } logger.trace("size read from channel {}", sizeRead); return bytesRead; }</code><technical_language>replace 8 Long.BYTES</technical_language>

Target:
public long readFrom(ReadableByteChannel channel) throws IOException { long bytesRead = 0; if (buffer == null) { if (sizeBuffer == null) { sizeBuffer = ByteBufAllocator.DEFAULT.heapBuffer(Long.BYTES); } try { bytesRead = readBytesFromReadableByteChannel(channel, sizeBuffer); if (bytesRead < 0) { throw new EOFException(); } } catch (IOException e) { sizeBuffer.release(); sizeBuffer = null; throw e; } if (sizeBuffer.writerIndex() == sizeBuffer.capacity()) { sizeToRead = sizeBuffer.readLong(); sizeRead += Long.BYTES; sizeBuffer.release(); buffer = ByteBufAllocator.DEFAULT.heapBuffer((int) sizeToRead - Long.BYTES); } } if (buffer != null && sizeRead < sizeToRead) { long bytesReadFromChannel; try { bytesReadFromChannel = readBytesFromReadableByteChannel(channel, buffer); if (bytesReadFromChannel < 0) { throw new EOFException(); } } catch (IOException e) { buffer.release(); buffer = null; throw e; } sizeRead += bytesReadFromChannel; bytesRead += bytesReadFromChannel; } logger.trace("size read from channel {}", sizeRead); return bytesRead; }
Source:
<code>private JMenuItem createItemForUser(User user) { String userName = ModelFormatUtils.getDisplayName(user); String userNameShort = userName; int index = userNameShort.indexOf("@"); if (index > -1) { userNameShort = userNameShort.substring(0, index); } <START> JMenuItem menuItem = new JMenuItem(menuItemPrefix + userNameShort); <END> menuItem.setForeground(FOREGROUND_COLOR); menuItem.setBackground(BACKGROUND_COLOR); FollowModeManager currentFollowModeManager = followModeManager; User currentlyFollowedUser = null; if (currentFollowModeManager != null) { currentlyFollowedUser = currentFollowModeManager.getFollowedUser(); } if (currentlyFollowedUser != null) { String currentUserName = ModelFormatUtils.getDisplayName(currentlyFollowedUser); if (currentUserName.equalsIgnoreCase(userNameShort)) { menuItem.setEnabled(false); } } menuItem.setActionCommand(userName); menuItem.addActionListener(e -> followModeAction.execute(e.getActionCommand())); return menuItem; }</code><technical_language>In other class a JBMenuItem. special reason a JMenuItem</technical_language>

Target:
private JMenuItem createItemForUser(User user) { String userName = ModelFormatUtils.getDisplayName(user); String userNameShort = userName; int index = userNameShort.indexOf("@"); if (index > -1) { userNameShort = userNameShort.substring(0, index); } JMenuItem menuItem = new JBMenuItem(menuItemPrefix + userNameShort); menuItem.setForeground(FOREGROUND_COLOR); menuItem.setBackground(BACKGROUND_COLOR); FollowModeManager currentFollowModeManager = followModeManager; User currentlyFollowedUser = null; if (currentFollowModeManager != null) { currentlyFollowedUser = currentFollowModeManager.getFollowedUser(); } if (currentlyFollowedUser != null) { String currentUserName = ModelFormatUtils.getDisplayName(currentlyFollowedUser); if (currentUserName.equalsIgnoreCase(userNameShort)) { menuItem.setEnabled(false); } } menuItem.setActionCommand(userName); menuItem.addActionListener(e -> followModeAction.execute(e.getActionCommand())); return menuItem; }
Source:
<code>public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); <START> if (phoneNumber != null) { <END> return PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164); } return null; }</code><technical_language>ternary operator result in nicer code: return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null</technical_language>

Target:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null; }
Source:
<code>protected @NonNull List<@NonNull TimeGraphEntryModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { Builder<@NonNull TimeGraphEntryModel> builder = new Builder<>(); int quark = ITmfStateSystem.ROOT_ATTRIBUTE; long parentId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); builder.add(new TimeGraphEntryModel(parentId, -1, getTrace().getName(), <START> getTrace().getStartTime().toNanos(), Long.MAX_VALUE)); <END> addChildren(ss, builder, quark, parentId); return builder.build(); }</code><technical_language>ss.getStart / ss.getCurrentEnd</technical_language>

Target:
protected @NonNull List<@NonNull TimeGraphEntryModel> getTree(@NonNull ITmfStateSystem ss, @NonNull TimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { Builder<@NonNull TimeGraphEntryModel> builder = new Builder<>(); long parentId = getId(ITmfStateSystem.ROOT_ATTRIBUTE); builder.add(new TimeGraphEntryModel(parentId, -1, getTrace().getName(), ss.getStartTime(), ss.getCurrentEndTime())); addChildren(ss, builder, ITmfStateSystem.ROOT_ATTRIBUTE, parentId); return builder.build(); }
Source:
<code>public void parseMethodsInLike() throws Exception { this.assertTranslate("SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj where obj.first_name like LOWER('%DMIN%')", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 where ( obj_first_name1.value like LOWER ( '%DMIN%' ) ) and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); <START> this.assertTranslate( <END> "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj where obj.first_name like LOWER(CONCAT('%', 'DMIN%'))", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 where ( obj_first_name1.value like LOWER ( CONCAT ( '%' , 'DMIN%' ) ) ) and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); }</code><technical_language>small detail, "this" for methods in general</technical_language>

Target:
public void parseMethodsInLike() throws Exception { assertTranslate( "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj " + "where obj.first_name like LOWER('%DMIN%')", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 " + "where ( obj_first_name1.value like LOWER ( '%DMIN%' ) ) " + "and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' " + "and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); assertTranslate( "SELECT doc.fullName FROM Document doc, doc.object(XWiki.XWikiUsers) obj " + "where obj.first_name like LOWER(CONCAT('%', 'DMIN%'))", "SELECT doc.fullName FROM XWikiDocument as doc , BaseObject as obj , StringProperty as obj_first_name1 " + "where ( obj_first_name1.value like LOWER ( CONCAT ( '%' , 'DMIN%' ) ) ) " + "and doc.fullName=obj.name and obj.className='XWiki.XWikiUsers' " + "and obj_first_name1.id.id=obj.id and obj_first_name1.id.name='first_name'"); }
Source:
<code>private SchedulingManager mockScheduler() { SchedulingManager mock = Mockito.mock(SchedulingManager.class); <START> Mockito.when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); <END> return mock; }</code><technical_language>please static import for Mockito</technical_language>

Target:
private SchedulingManager mockScheduler() { SchedulingManager mock = mock(SchedulingManager.class); when(mock.getClusterPolicies()).thenReturn(Collections.<ClusterPolicy>emptyList()); return mock; }
Source:
<code>public long blah(FContext ctx, int num, String Str, Event event) throws TException, AwesomeException, actual_base.java.api_exception { FBoundableMemoryOutputBuffer memoryBuffer = new FBoundableMemoryOutputBuffer(transport.getMaxRequestSize()); FProtocol oprot = this.protocolFactory.getProtocol(memoryBuffer); BlockingQueue<Object> result = new ArrayBlockingQueue<>(1); transport.register(ctx, recvBlahHandler(ctx, result)); try { oprot.writeRequestHeader(ctx); oprot.writeMessageBegin(new TMessage("blah", TMessageType.CALL, 0)); blah_args args = new blah_args(); args.setNum(num); args.setStr(Str); args.setEvent(event); args.write(oprot); oprot.writeMessageEnd(); transport.send(memoryBuffer.getWriteBytes()); Object res = null; try { res = result.poll(ctx.getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new TApplicationException(TApplicationException.INTERNAL_ERROR, "blah interrupted: " + e.getMessage()); } if (res == null) { throw new FTimeoutException("blah timed out"); } if (res instanceof TException) { throw (TException) res; } blah_result r = (blah_result) res; if (r.isSetSuccess()) { return r.success; } if (r.awe != null) { throw r.awe; } if (r.api != null) { throw r.api; } throw new TApplicationException(TApplicationException.MISSING_RESULT, "blah failed: unknown result"); } finally { <START> transport.unregister(ctx); <END> } }</code><technical_language>IMO protocols "reset" initial state if error is encountered reused. a number of fixes Thrift address this issue in Java. Other languages similar problems addressed</technical_language>

Target:
public long blah(FContext ctx, int num, String Str, Event event) throws TException, AwesomeException, actual_base.java.api_exception { TMemoryOutputBuffer memoryBuffer = new TMemoryOutputBuffer(transport.getRequestSizeLimit()); FProtocol oprot = this.protocolFactory.getProtocol(memoryBuffer); BlockingQueue<Object> result = new ArrayBlockingQueue<>(1); transport.register(ctx, recvBlahHandler(ctx, result)); try { oprot.writeRequestHeader(ctx); oprot.writeMessageBegin(new TMessage("blah", TMessageType.CALL, 0)); blah_args args = new blah_args(); args.setNum(num); args.setStr(Str); args.setEvent(event); args.write(oprot); oprot.writeMessageEnd(); transport.send(memoryBuffer.getWriteBytes()); Object res = null; try { res = result.poll(ctx.getTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new TApplicationException(TApplicationException.INTERNAL_ERROR, "blah interrupted: " + e.getMessage()); } if (res == null) { throw new FTimeoutException("blah timed out"); } if (res instanceof TException) { throw (TException) res; } blah_result r = (blah_result) res; if (r.isSetSuccess()) { return r.success; } if (r.awe != null) { throw r.awe; } if (r.api != null) { throw r.api; } throw new TApplicationException(TApplicationException.MISSING_RESULT, "blah failed: unknown result"); } finally { transport.unregister(ctx); } }
Source:
<code>private AnnotationPainter initializeCommentColoring(ISourceViewer viewer) { AnnotationPainter commentPainter = new AnnotationPainter(viewer, null) { @Override protected IAnnotationModel findAnnotationModel(ISourceViewer sourceViewer) { if (sourceViewer.getDocument() instanceof CommentableCompareItem) { return ((CommentableCompareItem) sourceViewer.getDocument()).getEditableComments(); } return null; } @Override <START> public void applyTextPresentation(TextPresentation tp) { <END> AnnotationModel originalCommentsModel = ((CommentableCompareItem) viewer.getDocument()) .getEditableComments(); Iterator<?> it = originalCommentsModel.getAnnotationIterator(); while (it.hasNext()) { GerritCommentAnnotation object = (GerritCommentAnnotation) it.next(); Position positingExistingComment = originalCommentsModel.getPosition(object); StyleRange range; if (isToggle) { range = new StyleRange(positingExistingComment.getOffset(), positingExistingComment.getLength(), Display.getCurrent().getSystemColor(SWT.COLOR_BLACK), Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW)); setAnnotationTypeColor(GerritCommentAnnotation.TYPE, Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW)); isToggle = false; } else { range = new StyleRange(positingExistingComment.getOffset(), positingExistingComment.getLength(), Display.getCurrent().getSystemColor(SWT.COLOR_BLACK), Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW)); setAnnotationTypeColor(GerritCommentAnnotation.TYPE, Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW)); isToggle = true; } tp.mergeStyleRange(range); } super.applyTextPresentation(tp); } }; Object strategyID = new Object(); HighlightingStrategy paintingStrategy = new AnnotationPainter.HighlightingStrategy(); commentPainter.addTextStyleStrategy(strategyID, paintingStrategy); commentPainter.addAnnotationType(GerritCommentAnnotation.TYPE, strategyID); commentPainter.addHighlightAnnotationType(strategyID); return commentPainter; }</code><technical_language>I this. this point character I type, color changes :) This is disturbing</technical_language>

Target:
private AnnotationPainter initializeCommentColoring(ISourceViewer viewer) { return new CommentAnnotationPainter(viewer, null); }