auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public BatchWriterConfig merge(BatchWriterConfig other) { BatchWriterConfig result = new BatchWriterConfig(); <START> if (this.maxMemory != null) { <END> result.maxMemory = this.maxMemory; } else if (other.maxMemory != null) { result.maxMemory = other.maxMemory; } if (this.maxLatency != null) { result.maxLatency = this.maxLatency; } else if (other.maxLatency != null) { result.maxLatency = other.maxLatency; } if (this.timeout != null) { result.timeout = this.timeout; } else if (other.timeout != null) { result.timeout = other.timeout; } if (this.maxWriteThreads != null) { result.maxWriteThreads = this.maxWriteThreads; } else if (other.timeout != null) { result.maxWriteThreads = other.maxWriteThreads; } if (this.isDurabilitySet) { result.durability = this.durability; } else if (other.isDurabilitySet) { result.durability = other.durability; } return result; }</code><technical_language>do java private static<T> T merge(T o1, T o2) { if(o1 != null) return o1; return o2; } public static BatchWriterConfig merge(BatchWriterConfig other) { BatchWriterConfig result = new BatchWriterConfig(); result.maxMemory = merge(this.maxMemory, other.maxMemory); }</technical_language>

Target:
public BatchWriterConfig merge(BatchWriterConfig other) { BatchWriterConfig result = new BatchWriterConfig(); result.maxMemory = merge(this.maxMemory, other.maxMemory); result.maxLatency = merge(this.maxLatency, other.maxLatency); result.timeout = merge(this.timeout, other.timeout); result.maxWriteThreads = merge(this.maxWriteThreads, other.maxWriteThreads); if (this.isDurabilitySet) { result.durability = this.durability; } else if (other.isDurabilitySet) { result.durability = other.durability; } return result; }
Source:
<code>public Response deleteMetadataStoreRealm(@PathParam("realm") String realm) { try { if (!_metadataStoreDirectory.deleteMetadataStoreRealm(_namespace, realm)) { return serverError(); } } catch (IllegalArgumentException ex) { return notFound(ex.getMessage()); <START> } catch (IllegalStateException ex) { return serverError(); <END> } return OK(); }</code><technical_language>Remove</technical_language>

Target:
public Response deleteMetadataStoreRealm(@PathParam("realm") String realm) { try { if (!_metadataStoreDirectory.deleteMetadataStoreRealm(_namespace, realm)) { return serverError(); } } catch (IllegalArgumentException ex) { return notFound(ex.getMessage()); } return OK(); }
Source:
<code>public Object visit(PropertyIsEqualTo filter, Object extraData) { helper.out = out; FilterFunction_pgNearest nearest = helper.getNearestFilter(filter); FilterFunction_arrayAnyMatch any = helper.getArrayAnyMatch(filter); if (nearest != null) { return helper.visit( nearest, extraData, new FilterToSqlHelper.NearestHelperContext( dialect, (a, b) -> { try { ((PostGISPSDialect) dialect) .encodeGeometryValue( a, helper.getFeatureTypeGeometryDimension(), helper.getFeatureTypeGeometrySRID(), b); } catch (IOException e) { throw new RuntimeException(e); } })); } else if (any != null) { <START> return helper.visit(any, extraData); <END> } else { return super.visit(filter, extraData); } }</code><technical_language>Feedback: A question this PR review - is duplication necessary? class extend other</technical_language>

Target:
public Object visit(PropertyIsEqualTo filter, Object extraData) { helper.out = out; FilterFunction_pgNearest nearest = helper.getNearestFilter(filter); InArrayFunction inArray = helper.getInArray(filter); if (nearest != null) { return helper.visit( nearest, extraData, new FilterToSqlHelper.NearestHelperContext( dialect, (a, b) -> { try { ((PostGISPSDialect) dialect) .encodeGeometryValue( a, helper.getFeatureTypeGeometryDimension(), helper.getFeatureTypeGeometrySRID(), b); } catch (IOException e) { throw new RuntimeException(e); } })); } else if (inArray != null) { return helper.visit(inArray, extraData); } else { return super.visit(filter, extraData); } }
Source:
<code><START> public GatewayResponse capture(CaptureGatewayRequest request) { <END> return sandboxCaptureHandler.capture(request); }</code><technical_language>Adding a generic type <BaseCaptureResponse> remove potential compile warnings</technical_language>

Target:
public GatewayResponse<BaseCaptureResponse> capture(CaptureGatewayRequest request) { return sandboxCaptureHandler.capture(request); }
Source:
<code>public void unregisterHandler(Thing thing) { ServiceRegistration<ThingHandler> thingHandlerServiceRegistration = thingHandlers .remove(thing.getUID().toString()); if (thingHandlerServiceRegistration != null) { logger.debug("Removing service registration for handler of thing " + thing.getUID().getAsString()); unregisterHandler(thingHandlerServiceRegistration); } else { <START> logger.error(MessageFormat.format("There is no service registration for a thing handler of thing {0}.", <END> thing.getUID().getAsString())); } ServiceRegistration<ConfigStatusProvider> configStatusProviderServiceRegistration = configStatusProviders .remove(thing.getUID().getAsString()); if (configStatusProviderServiceRegistration != null) { configStatusProviderServiceRegistration.unregister(); } ServiceRegistration<FirmwareUpdateHandler> firmwareUpdateHandlerServiceRegistration = firmwareUpdateHandlers .remove(thing.getUID().getAsString()); if (firmwareUpdateHandlerServiceRegistration != null) { firmwareUpdateHandlerServiceRegistration.unregister(); } }</code><technical_language>do need MessageFormat here</technical_language>

Target:
public void unregisterHandler(Thing thing) { ServiceRegistration<ThingHandler> thingHandlerServiceRegistration = thingHandlers .remove(thing.getUID().toString()); if (thingHandlerServiceRegistration != null) { logger.debug("Removing service registration for handler of thing '{}'.", thing.getUID().getAsString()); unregisterHandler(thingHandlerServiceRegistration); } else { logger.error("There is no service registration for a thing handler of thing '{}'.", thing.getUID().getAsString()); } ServiceRegistration<ConfigStatusProvider> configStatusProviderServiceRegistration = configStatusProviders .remove(thing.getUID().getAsString()); if (configStatusProviderServiceRegistration != null) { configStatusProviderServiceRegistration.unregister(); } ServiceRegistration<FirmwareUpdateHandler> firmwareUpdateHandlerServiceRegistration = firmwareUpdateHandlers .remove(thing.getUID().getAsString()); if (firmwareUpdateHandlerServiceRegistration != null) { firmwareUpdateHandlerServiceRegistration.unregister(); } }
Source:
<code>private void marshalCategories(Variable variable, VariableState variableState) { int categoryIndex = 0; for(Category c : variable.getCategories()) { CategoryState categoryState; int currentCategoryIndex = variableState.getCategoryIndex(c.getName()); if(currentCategoryIndex == -1) { categoryState = new CategoryState(c.getName(), c.getCode(), c.isMissing()); variableState.getCategories().add(categoryIndex, categoryState); } else { categoryState = variableState.getCategories().get(currentCategoryIndex); if(categoryIndex != currentCategoryIndex) { CategoryState previousCategory = variableState.getCategories().set(categoryIndex, categoryState); variableState.getCategories().set(currentCategoryIndex, previousCategory); } } setAttributes(c, categoryState); categoryIndex++; } if(categoryIndex < variableState.getCategories().size()) { Collection<CategoryState> toDelete = new ArrayList<CategoryState>(); <START> for(int i = categoryIndex; i < variableState.getCategories().size(); i++) { <END> toDelete.add(variableState.getCategories().get(i)); } variableState.getCategories().removeAll(toDelete); } }</code><technical_language>check size in loop</technical_language>

Target:
private void marshalCategories(Variable variable, VariableState variableState) { int categoryIndex = 0; for(Category c : variable.getCategories()) { CategoryState categoryState; int currentCategoryIndex = variableState.getCategoryIndex(c.getName()); if(currentCategoryIndex == -1) { categoryState = new CategoryState(c.getName(), c.getCode(), c.isMissing()); variableState.getCategories().add(categoryIndex, categoryState); } else { categoryState = variableState.getCategories().get(currentCategoryIndex); if(categoryIndex != currentCategoryIndex) { CategoryState previousCategory = variableState.getCategories().set(categoryIndex, categoryState); variableState.getCategories().set(currentCategoryIndex, previousCategory); } } setAttributes(c, categoryState); categoryIndex++; } int nbCategories = variableState.getCategories().size(); if(categoryIndex < nbCategories) { Collection<CategoryState> toDelete = new ArrayList<CategoryState>(); for(int i = categoryIndex; i < nbCategories; i++) { toDelete.add(variableState.getCategories().get(i)); } variableState.getCategories().removeAll(toDelete); } }
Source:
<code>private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String hadoopInputFormatClassName = in.readUTF(); String keyClassName = in.readUTF(); String valueClassName = in.readUTF(); if(jobConf == null) { jobConf = new JobConf(); } jobConf.readFields(in); try { <START> this.hadoopInputFormat = (org.apache.hadoop.mapred.InputFormat<K,V>) Class.forName(hadoopInputFormatClassName).newInstance(); <END> } catch (Exception e) { throw new RuntimeException("Unable to instantiate the hadoop input format", e); } try { this.keyClass = (Class<K>) Class.forName(keyClassName); } catch (Exception e) { throw new RuntimeException("Unable to find key class.", e); } try { this.valueClass = (Class<V>) Class.forName(valueClassName); } catch (Exception e) { throw new RuntimeException("Unable to find value class.", e); } ReflectionUtils.setConf(hadoopInputFormat, jobConf); }</code><technical_language>this work classes in lib folder? I in general need pass user code class loader (Thread.currentThread().getContextClassLoader())</technical_language>

Target:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String hadoopInputFormatClassName = in.readUTF(); String keyClassName = in.readUTF(); String valueClassName = in.readUTF(); if(jobConf == null) { jobConf = new JobConf(); } jobConf.readFields(in); try { this.mapredInputFormat = (org.apache.hadoop.mapred.InputFormat<K,V>) Class.forName(hadoopInputFormatClassName, true, Thread.currentThread().getContextClassLoader()).newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to instantiate the hadoop input format", e); } try { this.keyClass = (Class<K>) Class.forName(keyClassName, true, Thread.currentThread().getContextClassLoader()); } catch (Exception e) { throw new RuntimeException("Unable to find key class.", e); } try { this.valueClass = (Class<V>) Class.forName(valueClassName, true, Thread.currentThread().getContextClassLoader()); } catch (Exception e) { throw new RuntimeException("Unable to find value class.", e); } ReflectionUtils.setConf(mapredInputFormat, jobConf); }
Source:
<code>protected void setDirty(boolean dirty) { fDirty = fDirty || dirty; editorDirtyStateChanged(); <START> if (fDirty && getActivePage() == getPageCount() - 1) { <END> updateTargetDocumentEditor(); } }</code><technical_language>br reverse condition getActivePage() != getPageCount() - 1? I extract expression getActivePage() == getPageCount() - 1 a dedicated isActiveTabTextualEditor() method clearer. is occurence line 94</technical_language>

Target:
protected void setDirty(boolean dirty) { fDirty = fDirty || dirty; editorDirtyStateChanged(); if (fDirty && isActiveTabTextualEditor()) { updateTextualEditor(); } }
Source:
<code>public static FormValidation validateExecutable(String exe, FileValidator exeValidator) { if(!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) return ok(); final FormValidation[] result = {null}; try { DOSToUnixPathHelper.iteratePath(exe, new DOSToUnixPathHelper.Helper() { @Override public void ok() { result[0] = FormValidation.ok(); } @Override public void checkExecutable(File fexe) { result[0] = exeValidator.validate(fexe); } @Override public void error(String string) { result[0] = FormValidation.error(string); } @Override public void validate(File fexe) { result[0] = exeValidator.validate(fexe); } }); return result[0]; } catch (Exception e) { <START> return FormValidation.error(e, "Should not happen"); <END> } }</code><technical_language>statements include a link Murphy Law Wikipedia page</technical_language>

Target:
public static FormValidation validateExecutable(String exe, FileValidator exeValidator) { if(!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) return ok(); final FormValidation[] result = {null}; try { DOSToUnixPathHelper.iteratePath(exe, new DOSToUnixPathHelper.Helper() { @Override public void ok() { result[0] = FormValidation.ok(); } @Override public void checkExecutable(File fexe) { result[0] = exeValidator.validate(fexe); } @Override public void error(String string) { result[0] = FormValidation.error(string); } @Override public void validate(File fexe) { result[0] = exeValidator.validate(fexe); } }); return result[0]; } catch (Exception e) { return FormValidation.error(e, "Unexpected error"); } }
Source:
<code>public void accept(Map<String, Object> fieldMap) { <START> boolean alreadyExist = false; <END> Field schemaIdField = getSchemaFieldMap().get(getIdField()); String idFieldName = schemaIdField.getName().getPrefixedName(); Object rawId = fieldMap.get(idFieldName); if (rawId != null) { DocumentModel dm = session.getEntry(String.valueOf(rawId)); if (dm != null) { alreadyExist = true; switch (dataLoadingPolicy) { case IGNORE_DUPLICATE: return; case ERROR_ON_DUPLICATE: throw new DirectoryException(String.format("Entry with id %s already exists in directory %s", dm.getId(), getName())); case UPDATE_DUPLICATE: fieldMap.forEach((fieldName, value) -> dm.setProperty(getSchema(), fieldName, value)); ((BaseSession) session).updateEntryWithoutReferences(dm); break; default: throw new IllegalStateException("Unexpected value: " + dataLoadingPolicy); } } } if (!alreadyExist) { ((BaseSession) session).createEntryWithoutReferences(fieldMap); } }</code><technical_language>alreadyExist -> alreadyExists</technical_language>

Target:
public void accept(Map<String, Object> fieldMap) { if (DATA_LOADING_POLICY_REJECT_DUPLICATE.equals(dataLoadingPolicy) || DATA_LOADING_POLICY_LEGACY.equals(dataLoadingPolicy)) { ((BaseSession) session).createEntryWithoutReferences(fieldMap); } else { Object rawId = fieldMap.get(session.getIdField()); if (rawId == null) { throw new DirectoryException("A line is missing the entry id", SC_BAD_REQUEST); } String idValue = String.valueOf(rawId); if (session.hasEntry(idValue)) { if (DATA_LOADING_POLICY_UPDATE_DUPLICATE.equals(dataLoadingPolicy)) { DocumentModel dm = session.getEntry(idValue); fieldMap.forEach((fieldName, value) -> dm.setProperty(schema, fieldName, value)); ((BaseSession) session).updateEntryWithoutReferences(dm); } else { log.debug("Skip the entry with id: {}", idValue); } } else { ((BaseSession) session).createEntryWithoutReferences(fieldMap); } } }
Source:
<code>public Integer getAffectedNodeCount() { if (m_relatedAlarms == null || m_relatedAlarms.isEmpty()) { <START> return 1; <END> } Set<Integer> nodes = m_relatedAlarms.stream().map(OnmsAlarm::getNode).filter(Objects::nonNull).map(OnmsNode::getId).collect(Collectors.toSet()); if (m_node != null) { nodes.add(m_node.getId()); } return nodes.size(); }</code><technical_language>This 1 iff m_node != null, 0 otherwise</technical_language>

Target:
public Integer getAffectedNodeCount() { if (m_relatedAlarms == null || m_relatedAlarms.isEmpty()) { return m_node == null ? 0 : 1; } Set<Integer> nodes = m_relatedAlarms.stream().map(OnmsAlarm::getNode).filter(Objects::nonNull).map(OnmsNode::getId).collect(Collectors.toSet()); if (m_node != null) { nodes.add(m_node.getId()); } return nodes.size(); }
Source:
<code>void openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; void closeInventory(Cause cause) throws IllegalArgumentException; <START> boolean isViewingGui(); <END> Optional<Gui> getOpenGui(); boolean closeCurrentGui(); boolean showGui(Gui gui); int getViewDistance(); ChatVisibility getChatVisibility(); boolean isChatColorsEnabled(); Set<SkinPart> getDisplayedSkinParts(); @Override PlayerConnection getConnection(); void sendResourcePack(ResourcePack pack); TabList getTabList(); void kick(); void kick(Text reason); Scoreboard getScoreboard(); void setScoreboard(Scoreboard scoreboard); default JoinData getJoinData() { return get(JoinData.class).get(); }</code><technical_language>I remove this method getOpenGui().isPresent() is need</technical_language>

Target:
Optional<Container> openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; boolean closeInventory(Cause cause) throws IllegalArgumentException; Optional<Window> getActiveWindow(); default void closeActiveWindow() { Optional<Window> active = getActiveWindow(); if (active.isPresent()) { active.get().close(this); } }
Source:
<code>public OAuth2TokenValidatorResult validate(Jwt idToken) { <START> oAuth2Errors = validateRequiredClaims(idToken); <END> if (!oAuth2Errors.isEmpty()){ return OAuth2TokenValidatorResult.failure(oAuth2Errors); } if (!idToken.getAudience().contains(this.clientRegistration.getClientId())) { oAuth2Errors.add(invalidIdTokenError("Audience(au) claim must contain the client_id value")); } String authorizedParty = idToken.getClaimAsString(IdTokenClaimNames.AZP); if (idToken.getAudience().size() > 1 && authorizedParty == null) { oAuth2Errors.add(invalidIdTokenError("With multiple Audiences(aud), Authorized Party(azp) claim must be present")); } if (authorizedParty != null && !authorizedParty.equals(this.clientRegistration.getClientId())) { oAuth2Errors.add(invalidIdTokenError("With Authorized Party(azp) claim present, its value must match client_id")); } Instant now = Instant.now(); if (!now.isBefore(idToken.getExpiresAt())) { oAuth2Errors.add(invalidIdTokenError("Expiration(exp) claim cannot be before current time")); } Instant maxIssuedAt = now.plusSeconds(30); if (idToken.getIssuedAt().isAfter(maxIssuedAt)) { oAuth2Errors.add(invalidIdTokenError("The Issued At(iat) claim cannot be too far away from the current time")); } if (!oAuth2Errors.isEmpty()) { return OAuth2TokenValidatorResult.failure(oAuth2Errors); } return OAuth2TokenValidatorResult.success(); }</code><technical_language>Yes, is correct. OAuth2Error.description is built display follows: (null), ...other invalid claims</technical_language>

Target:
public OAuth2TokenValidatorResult validate(Jwt idToken) { Map<String, Object> invalidClaims = validateRequiredClaims(idToken); if (!invalidClaims.isEmpty()){ return OAuth2TokenValidatorResult.failure(invalidIdToken(invalidClaims)); } if (!idToken.getAudience().contains(this.clientRegistration.getClientId())) { invalidClaims.put(IdTokenClaimNames.AUD, idToken.getAudience()); } String authorizedParty = idToken.getClaimAsString(IdTokenClaimNames.AZP); if (idToken.getAudience().size() > 1 && authorizedParty == null) { invalidClaims.put(IdTokenClaimNames.AZP, authorizedParty); } if (authorizedParty != null && !authorizedParty.equals(this.clientRegistration.getClientId())) { invalidClaims.put(IdTokenClaimNames.AZP, authorizedParty); } Instant now = Instant.now(); if (!now.isBefore(idToken.getExpiresAt())) { invalidClaims.put(IdTokenClaimNames.EXP, idToken.getExpiresAt()); } Instant maxIssuedAt = now.plusSeconds(30); if (idToken.getIssuedAt().isAfter(maxIssuedAt)) { invalidClaims.put(IdTokenClaimNames.IAT, idToken.getIssuedAt()); } if (!invalidClaims.isEmpty()) { return OAuth2TokenValidatorResult.failure(invalidIdToken(invalidClaims)); } return OAuth2TokenValidatorResult.success(); }
Source:
<code>public void forceInsert_pickWinnerOfConflicts_TwoOfSameRoot_OneDeleted() throws Exception { DocumentRevision rev1a = createDbObject("1-x", bodyOne); DocumentRevision rev1b = createDbObject("1-x", bodyTwo); DocumentRevision rev2 = createDbObjectDeleted("2-x"); datastore.forceInsert(rev1a, "1-x"); datastore.forceInsert(rev1b, "1-x"); datastore.forceInsert(rev2, "1-x", "2-x"); DocumentRevision doc = datastore.getDocument(OBJECT_ID); Assert.assertEquals("The document winner should be the expected revision", "1-x", doc .getRevision()); <START> Assert.assertEquals("The document winner should have the expected body", bodyTwo.asMap(), <END> doc.getBody().asMap()); }</code><technical_language>long 9223372036854775807 entries in table :) <LINK_0></technical_language>

Target:
public void forceInsert_pickWinnerOfConflicts_TwoOfSameRoot_OneDeleted() throws Exception { DocumentRevision rev1a = createDbObject("1-x", bodyOne); DocumentRevision rev2 = createDbObjectDeleted("2-x"); datastore.forceInsert(rev1a, "1-x"); datastore.runOnDbQueue(new SQLQueueCallable<Long>() { @Override public Long call(SQLDatabase db) throws Exception { ContentValues args = new ContentValues(); args.put("doc_id", 1l); args.put("revid", "1-x"); args.put("json", bodyTwo.asBytes()); return db.insert("revs", args); } }); datastore.forceInsert(rev2, "1-x", "2-x"); DocumentRevision doc = datastore.getDocument(OBJECT_ID); Assert.assertEquals("The document winner should be the expected revision", "1-x", doc .getRevision()); Assert.assertEquals("The document winner should have the expected body", bodyTwo.asMap(), doc.getBody().asMap()); }
Source:
<code>private void checkProfileVersion(Match match) throws ProfileDefinitionException { EObject left = match.getLeft(); EObject right = match.getRight(); if (left instanceof ProfileApplication && right != null) { Collection<Match> annotationsMatches = Collections2.filter(match.getSubmatches(), ANNOTATION_REFERENCING_PROFILE_DEFINITION); for (Match annotationMatch : annotationsMatches) { <START> EAnnotation leftAnnot = (EAnnotation)annotationMatch.getLeft(); <END> EAnnotation rightAnnot = (EAnnotation)annotationMatch.getRight(); Collection<URI> leftUris = getURIs(ReferenceUtil.getAsList(leftAnnot, EcorePackage.Literals.EANNOTATION__REFERENCES)); Collection<URI> rightUris = getURIs(ReferenceUtil.getAsList(rightAnnot, EcorePackage.Literals.EANNOTATION__REFERENCES)); if (leftUris.size() != rightUris.size() || !leftUris.containsAll(rightUris)) { org.eclipse.uml2.uml.Package impactedPackage = ((ProfileApplication)left) .getApplyingPackage(); String message; if (impactedPackage != null) { message = UMLCompareMessages.getString("profile.definition.changed.on", "<" + impactedPackage.eClass().getName() + "> " + impactedPackage.getName()); } else { message = UMLCompareMessages.getString("profile.definition.changed"); } addDiagnostic(match.getComparison(), new BasicDiagnostic(Diagnostic.ERROR, null, 0, message, new Object[] {})); throw new ProfileDefinitionException(); } } } }</code><technical_language>this split in another method for clarity</technical_language>

Target:
private boolean checkProfileVersion(Match match) { EObject left = match.getLeft(); EObject right = match.getRight(); if (left instanceof ProfileApplication && right != null) { Collection<Match> annotationsMatches = Collections2.filter(match.getSubmatches(), ANNOTATION_REFERENCING_PROFILE_DEFINITION); for (Match annotationMatch : annotationsMatches) { EAnnotation leftAnnot = (EAnnotation)annotationMatch.getLeft(); EAnnotation rightAnnot = (EAnnotation)annotationMatch.getRight(); if (!checkProfileVersion(match.getComparison(), (ProfileApplication)left, leftAnnot, rightAnnot)) { return false; } } } return true; }
Source:
<code>public void handleSetPushSetupSmsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetPushSetupSmsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Push Setup Sms Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleSetPushSetupSmsResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSetPushSetupSmsResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Set Push Setup Sms Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public void unregisterService(ServiceDescription description) { if (mdnsClient != null) { <START> logger.debug("Unregistering service at port {}", description.serviceType, description.servicePort); <END> mdnsClient.unregisterService(description); } }</code><technical_language>remove this log message duplicates in mdnsClient</technical_language>

Target:
public void unregisterService(ServiceDescription description) { if (mdnsClient != null) { mdnsClient.unregisterService(description); } }
Source:
<code>List<PipelineTemplate> list(@RequestParam(required = false, value = "scopes", defaultValue = "global") List<String> scopes) { <START> if (pipelineTemplateDAO == null) { <END> throw PipelineTemplateFeatureUnsupportedException.build(); } return (List<PipelineTemplate>) pipelineTemplateDAO.getPipelineTemplatesByScope(scopes); }</code><technical_language>For consistency entity tags reason do ... throw new BadRequestException("Pipeline Templates supported storage backend") return a 400 (if ... I problems changing status code)</technical_language>

Target:
List<PipelineTemplate> list(@RequestParam(required = false, value = "scopes", defaultValue = "global") List<String> scopes) { return (List<PipelineTemplate>) getPipelineTemplateDAO().getPipelineTemplatesByScope(scopes); }
Source:
<code>public void enableDiversity() throws KuraException { <START> logger.warn("Not a LTE Modem"); <END> }</code><technical_language>I state this. Cell diversity is for HSPA modems. state is supported in generic modem implementation. In this case I, personally, prefer Unsupported exception</technical_language>

Target:
public void enableDiversity() throws KuraException { throw new KuraException(KuraErrorCode.OPERATION_NOT_SUPPORTED); }
Source:
<code>public static BookieSocketAddress getBookieAddress(ServerConfiguration conf) throws UnknownHostException { String iface = conf.getListeningInterface(); if (iface == null) { iface = "default"; } String hostName = DNS.getDefaultHost(iface); InetSocketAddress inetAddr = new InetSocketAddress(hostName, conf.getBookiePort()); if (inetAddr.isUnresolved()) { throw new UnknownHostException("Unable to resolve default hostname: " + hostName + " for interface: " + iface); } String hostAddress = inetAddr.getAddress().getHostAddress(); if (conf.getUseHostNameAsBookieID()) { hostAddress = inetAddr.getAddress().getCanonicalHostName(); } <START> if (conf.getAdvertisedAddress() != null && conf.getAdvertisedAddress().trim().length() > 0) { <END> hostAddress = conf.getAdvertisedAddress().trim(); } BookieSocketAddress addr = new BookieSocketAddress(hostAddress, conf.getBookiePort()); if (addr.getSocketAddress().getAddress().isLoopbackAddress() && !conf.getAllowLoopback()) { throw new UnknownHostException("Trying to listen on loopback address, " + addr + " but this is forbidden by default " + "(see ServerConfiguration#getAllowLoopback())"); } return addr; }</code><technical_language>rearrage code in order skip completely previous code, dns queries..</technical_language>

Target:
public static BookieSocketAddress getBookieAddress(ServerConfiguration conf) throws UnknownHostException { if (conf.getAdvertisedAddress() != null && conf.getAdvertisedAddress().trim().length() > 0) { String hostAddress = conf.getAdvertisedAddress().trim(); return new BookieSocketAddress(hostAddress, conf.getBookiePort()); } String iface = conf.getListeningInterface(); if (iface == null) { iface = "default"; } String hostName = DNS.getDefaultHost(iface); InetSocketAddress inetAddr = new InetSocketAddress(hostName, conf.getBookiePort()); if (inetAddr.isUnresolved()) { throw new UnknownHostException("Unable to resolve default hostname: " + hostName + " for interface: " + iface); } String hostAddress = inetAddr.getAddress().getHostAddress(); if (conf.getUseHostNameAsBookieID()) { hostAddress = inetAddr.getAddress().getCanonicalHostName(); } BookieSocketAddress addr = new BookieSocketAddress(hostAddress, conf.getBookiePort()); if (addr.getSocketAddress().getAddress().isLoopbackAddress() && !conf.getAllowLoopback()) { throw new UnknownHostException("Trying to listen on loopback address, " + addr + " but this is forbidden by default " + "(see ServerConfiguration#getAllowLoopback())"); } return addr; }
Source:
<code>private InstantiationException multipleMatchingConstructors(Class<?> cls, List<Constructor<?>> constructors) { return new InstantiationException(join("Unable to create instance of '" + cls.getSimpleName() + "'.", "Multiple constructors could be matched to arguments of types " + constructorArgTypes() + ":", <START> join("", " - ", constructors) <END> ), null); }</code><technical_language>extra information. I is useful to: - inform class pattern for working ambiguous constructors - ask for feedback - hurt do original modify if want. hint class</technical_language>

Target:
private InstantiationException multipleMatchingConstructors(Class<?> cls, List<Constructor<?>> constructors) { return new InstantiationException(join("Unable to create instance of '" + cls.getSimpleName() + "'.", "Multiple constructors could be matched to arguments of types " + constructorArgTypes() + ":", join("", " - ", constructors), "If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.", "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.", "See <LINK_0>" ), null); }
Source:
<code>protected boolean generateXML(AccountingXmlDocumentListWrapper documentWrapper, String masterAccountName) { boolean success = true; String fileNameBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_OUTPUT_FILE_NAME_FORMAT); String fileName = MessageFormat.format(fileNameBase, directoryPath, findProcessYear(), findMonthName(), masterAccountName, Calendar.getInstance().getTime().getTime()); try { cuMarshalService.marshalObjectToXML(documentWrapper, fileName); fileStorageService.createDoneFile(fileName); LOG.info("generateXML, successfully created an XML and DONE file for " + fileName); } catch (JAXBException | IOException e) { success = false; <START> LOG.error("generateDistributionOfIncomeDocumentsFromAWSService, unable to marshal documentWrapper to " + fileName, e); <END> } return success; }</code><technical_language>Wrong method name in logging statement</technical_language>

Target:
protected boolean generateXML(AccountingXmlDocumentListWrapper documentWrapper, String masterAccountName) { boolean success = true; String fileNameBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_OUTPUT_FILE_NAME_FORMAT); String fileName = MessageFormat.format(fileNameBase, directoryPath, findProcessYear(), findMonthName(), masterAccountName, Calendar.getInstance().getTime().getTime()); try { cuMarshalService.marshalObjectToXML(documentWrapper, fileName); fileStorageService.createDoneFile(fileName); LOG.info("generateXML, successfully created an XML and DONE file for " + fileName); } catch (JAXBException | IOException e) { success = false; LOG.error("generateXML, unable to marshal documentWrapper to " + fileName, e); } return success; }
Source:
<code>private Buffer.DataType getNextDataType(BufferAndBacklog bufferAndBacklog) { final Buffer.DataType nextDataType = bufferAndBacklog.getNextDataType(); if (numCreditsAvailable > 0 || (nextDataType != null && nextDataType.isEvent())) { return nextDataType; } <START> return null; <END> }</code><technical_language>hmmm, add another enum type for this purpose, instead of null? (I'm sure, brain storming)</technical_language>

Target:
private Buffer.DataType getNextDataType(BufferAndBacklog bufferAndBacklog) { final Buffer.DataType nextDataType = bufferAndBacklog.getNextDataType(); if (numCreditsAvailable > 0 || nextDataType.isEvent()) { return nextDataType; } return Buffer.DataType.NONE; }
Source:
<code>public ValidationResult validateDeletion(KitDescriptor object) throws IOException { ValidationResult result = new ValidationResult(); <START> switch (object.getKitType()) { <END> case LIBRARY: long libUsage = kitStore.getUsageByLibraries(object); if (libUsage > 0) { result.addError(ValidationError.forDeletionUsage(object, libUsage, Pluralizer.libraries(libUsage))); } break; case CLUSTERING: case MULTIPLEXING: long containerUsage = kitStore.getUsageByContainers(object); if (containerUsage > 0) { result.addError(ValidationError.forDeletionUsage(object, containerUsage, "sequencing " + Pluralizer.containers(containerUsage))); } break; default: break; } return result; }</code><technical_language>sense do checks in case some database shenanigans? Worst case, zero</technical_language>

Target:
public ValidationResult validateDeletion(KitDescriptor object) throws IOException { ValidationResult result = new ValidationResult(); long libUsage = kitStore.getUsageByLibraries(object); if (libUsage > 0) { result.addError(ValidationError.forDeletionUsage(object, libUsage, Pluralizer.libraries(libUsage))); } long containerUsage = kitStore.getUsageByContainers(object); if (containerUsage > 0) { result.addError(ValidationError.forDeletionUsage(object, containerUsage, "sequencing " + Pluralizer.containers(containerUsage))); } return result; }
Source:
<code>private void validateCreation(EnvironmentCreationDto creationDto, Environment environment) { LOGGER.info("Validating environment creation. CreationDto: '{}', Environment: '{}'.", creationDto, environment); ValidationResultBuilder validationBuilder = validatorService.validateNetworkCreation(environment, creationDto.getNetwork()); ValidationResult parentChildValidation = validatorService.validateParentChildRelation(environment, creationDto.getParentEnvironmentName()); validationBuilder.merge(parentChildValidation); validationBuilder.ifError(() -> isCloudPlatformInvalid(creationDto.getCreator(), creationDto.getCloudPlatform()), "Provisioning in Microsoft Azure is not enabled for this account."); ValidationResult freeIpaCreationValidation = validatorService.validateFreeIpaCreation(creationDto.getFreeIpaCreation()); validationBuilder.merge(freeIpaCreationValidation); ValidationResult validationResult = validationBuilder.build(); if (validationResult.hasError()) { throw new BadRequestException(validationResult.getFormattedErrors()); } <START> } <END></code><technical_language>I changed error message "Provisioning in " + creationDto.getCloudPlatform() + " is enabled for this account." locally</technical_language>

Target:
private void validateCreation(EnvironmentCreationDto creationDto, Environment environment) { LOGGER.info("Validating environment creation. CreationDto: '{}', Environment: '{}'.", creationDto, environment); ValidationResultBuilder validationBuilder = validatorService.validateNetworkCreation(environment, creationDto.getNetwork()); ValidationResult parentChildValidation = validatorService.validateParentChildRelation(environment, creationDto.getParentEnvironmentName()); validationBuilder.merge(parentChildValidation); validationBuilder.ifError(() -> isCloudPlatformInvalid(creationDto.getCreator(), creationDto.getCloudPlatform()), "Provisioning in " + creationDto.getCloudPlatform() + " is not enabled for this account."); ValidationResult freeIpaCreationValidation = validatorService.validateFreeIpaCreation(creationDto.getFreeIpaCreation()); validationBuilder.merge(freeIpaCreationValidation); ValidationResult validationResult = validationBuilder.build(); if (validationResult.hasError()) { throw new BadRequestException(validationResult.getFormattedErrors()); } }
Source:
<code>public static DenseLayer buildDenseLayer(Map<String,Object> kerasConfig) throws NotImplementedException { DenseLayer.Builder builder = new DenseLayer.Builder() <START> .nOut((int)kerasConfig.get("output_dim")); <END> finishLayerConfig(builder, kerasConfig); return builder.build(); }</code><technical_language>"magic strings" constants public final static SOME_VARIABLE_NAME</technical_language>

Target:
public static DenseLayer buildDenseLayer(Map<String,Object> kerasConfig) throws NotImplementedException { DenseLayer.Builder builder = new DenseLayer.Builder() .nOut((int)kerasConfig.get(KERAS_LAYER_PROPERTY_OUTPUT_DIM)); finishLayerConfig(builder, kerasConfig); return builder.build(); }
Source:
<code>protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); final String name = address.getLastElement().getValue(); final ModelNode bufferSizeModel = BufferPoolResourceDefinition.BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode bufferPerSliceModel = BufferPoolResourceDefinition.BUFFER_PER_SLICE.resolveModelAttribute(context, model); final ModelNode directModel = BufferPoolResourceDefinition.DIRECT_BUFFERS.resolveModelAttribute(context, model); final int bufferSize = bufferSizeModel.isDefined() ? bufferSizeModel.asInt() : BufferPoolResourceDefinition.defaultBufferSize; final int bufferPerSlice = bufferPerSliceModel.isDefined() ? bufferPerSliceModel.asInt() <START> : BufferPoolResourceDefinition.defaultBuffersPerRegion; <END> final boolean direct = directModel.isDefined() ? directModel.asBoolean() : BufferPoolResourceDefinition.defaultDirectBuffers; final BufferPoolService service = new BufferPoolService(bufferSize, bufferPerSlice, direct); context.getServiceTarget().addService(IOServices.BUFFER_POOL.append(name), service) .setInitialMode(ServiceController.Mode.ACTIVE).install(); }</code><technical_language>org.jboss.as.controller.OperationContext#getCurrentAddressValue</technical_language>

Target:
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); final String name = address.getLastElement().getValue(); final ModelNode bufferSizeModel = BufferPoolResourceDefinition.BUFFER_SIZE.resolveModelAttribute(context, model); final ModelNode bufferPerSliceModel = BufferPoolResourceDefinition.BUFFER_PER_SLICE.resolveModelAttribute(context, model); final ModelNode directModel = BufferPoolResourceDefinition.DIRECT_BUFFERS.resolveModelAttribute(context, model); final int bufferSize = bufferSizeModel.isDefined() ? bufferSizeModel.asInt() : BufferPoolResourceDefinition.defaultBufferSize; final int bufferPerSlice = bufferPerSliceModel.isDefined() ? bufferPerSliceModel.asInt() : BufferPoolResourceDefinition.defaultBuffersPerRegion; final boolean direct = directModel.isDefined() ? directModel.asBoolean() : BufferPoolResourceDefinition.defaultDirectBuffers; final BufferPoolService service = new BufferPoolService(bufferSize, bufferPerSlice, direct); context.getCapabilityServiceTarget().addCapability(BufferPoolResourceDefinition.IO_POOL_RUNTIME_CAPABILITY, service) .setInitialMode(ServiceController.Mode.ON_DEMAND) .install(); ByteBufferPoolService poolService = new ByteBufferPoolService(); context.getCapabilityServiceTarget().addCapability(BufferPoolResourceDefinition.IO_BYTE_BUFFER_POOL_RUNTIME_CAPABILITY, poolService) .addCapabilityRequirement(BufferPoolResourceDefinition.IO_POOL_RUNTIME_CAPABILITY.getDynamicName(address), Pool.class, poolService.bufferPool) .setInitialMode(ServiceController.Mode.ON_DEMAND) .install(); }
Source:
<code>private void setRGBAColor(String color) { String hexColor; <START> if(color != null && <END> X11ColorUtils.toHexColor(color) != null) { hexColor = X11ColorUtils.toHexColor(color); hexColor = hexColor.substring(1); } else { hexColor = DEFAULT_COLOR; } int intColor = Integer.parseInt(hexColor, HEX); RGBAColor rgbaColor = new RGBAColor(intColor); fRGBAColor = new RGBA(rgbaColor.getRed(), rgbaColor.getBlue(), rgbaColor.getGreen(), ALPHA); }</code><technical_language>If color null, color parameter of method @Nullable</technical_language>

Target:
private void setRGBAColor(String color) { String hexColor = color; if (hexColor != null && (hexColor = X11ColorUtils.toHexColor(hexColor)) != null) { hexColor = hexColor.substring(1); } else { hexColor = DEFAULT_COLOR; } int intColor = Integer.parseInt(hexColor, HEX); RGBAColor rgbaColor = new RGBAColor(intColor); fRGBAColor = new RGBA(rgbaColor.getRed(), rgbaColor.getGreen(), rgbaColor.getBlue(), ALPHA); }
Source:
<code>public CellWithElementId<C> getCell() { <START> return (CellWithElementId<C>) getCell(); <END> }</code><technical_language>return "super.getCell()" here</technical_language>

Target:
public CellWithElementId<C> getCell() { return (CellWithElementId<C>) super.getCell(); }
Source:
<code><START> private boolean validateAddressIfCheckPayment(ConcurRequestExtractRequestDetailFileLine detailFileLine) { <END> boolean valid = true; String employeeId = detailFileLine.getEmployeeId(); if (getConcurPersonValidationService().isPayeeSignedUpForACH(employeeId)) { LOG.info("validateAddressIfCheckPayment, the employee ID " + employeeId + " is signed up for ACH so no need to validdate address."); } else { valid = getConcurPersonValidationService().validPdpAddress(employeeId); if (!valid) { detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_INCOMPLETE_ADDRESS)); } LOG.info("validateAddressIfCheckPayment, Is the address valid: " + valid); } return valid; }</code><technical_language>This method is present in 2 services slight variations. I extract code validates address if check payment new validation service. call add error message</technical_language>

Target:
private boolean validateAddressIfCheckPayment(ConcurRequestExtractRequestDetailFileLine detailFileLine) { boolean valid = true; String validationMessage = getConcurEmployeeInfoValidationService().getAddressValidationMessageIfCheckPayment(detailFileLine.getEmployeeId()); if (StringUtils.isNotBlank(validationMessage)) { valid = false; detailFileLine.getValidationResult().addMessage(validationMessage); } return valid; }
Source:
<code>public static Datum createFromInt8(DataType type, long val) { switch (type.getType()) { case INT8: return new Int8Datum(val); case TIMESTAMP: return new TimestampDatum(val); case TIME: return createTime(val); default: <START> throw new TajoRuntimeException(Errors.ResultCode.UNSUPPORTED_DATATYPE, type.getType().name()); <END> } }</code><technical_language>new TajoRuntimeException(new UnsupportedDataType(...)</technical_language>

Target:
public static Datum createFromInt8(DataType type, long val) { switch (type.getType()) { case INT8: return new Int8Datum(val); case TIMESTAMP: return new TimestampDatum(val); case TIME: return createTime(val); default: throw new TajoRuntimeException(new UnsupportedDataTypeException(type.getType().name())); } }
Source:
<code>public static void greenTerraConvert(Player player, Block block) { Material type = block.getType(); if (Misc.blockBreakSimulate(block, player, false)) { if (Config.getInstance().getHerbalismGreenThumbSmoothbrickToMossy() && type == Material.SMOOTH_BRICK && block.getData() == 0) { block.setTypeIdAndData(block.getTypeId(), (byte) 1, false); } else if (Config.getInstance().getHerbalismGreenThumbDirtToGrass() && type == Material.DIRT) { block.setType(Material.GRASS); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLESTONE) { block.setType(Material.MOSSY_COBBLESTONE); mcMMO.placeStore.setTrue(block); } <START> else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLE_WALL && (block.getData() == 0) { <END> block.setData(1); } } }</code><technical_language>This line is missing a ) symbol</technical_language>

Target:
public static void greenTerraConvert(Player player, Block block) { Material type = block.getType(); if (Misc.blockBreakSimulate(block, player, false)) { if (Config.getInstance().getHerbalismGreenThumbSmoothbrickToMossy() && type == Material.SMOOTH_BRICK && block.getData() == 0) { block.setTypeIdAndData(block.getTypeId(), (byte) 1, false); } else if (Config.getInstance().getHerbalismGreenThumbDirtToGrass() && type == Material.DIRT) { block.setType(Material.GRASS); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLESTONE) { block.setType(Material.MOSSY_COBBLESTONE); mcMMO.placeStore.setTrue(block); } else if (Config.getInstance().getHerbalismGreenThumbCobbleToMossy() && type == Material.COBBLE_WALL && (block.getData() == 0)) { block.setData((Byte) 1); } } }