auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private HashMap<String, String> buildConfirmationEmailPersonalisationFrom(ChargeEntity charge) { GatewayAccountEntity gatewayAccount = charge.getGatewayAccount(); EmailNotificationEntity emailNotification = gatewayAccount .getEmailNotifications().get(EmailNotificationType.PAYMENT_CONFIRMED); String customParagraph = emailNotification != null ? emailNotification.getTemplateBody() : ""; HashMap<String, String> map = new HashMap<>(); map.put("serviceReference", charge.getReference().toString()); map.put("date", DateTimeUtils.toUserFriendlyDate(charge.getCreatedDate())); Long amount = charge.getCorporateSurcharge() .map(corporateSurcharge -> CorporateCardSurchargeCalculator.getTotalAmountFor(charge)) <START> .orElse(charge.getAmount()); <END> map.put("amount", formatToPounds(amount)); map.put("description", charge.getDescription()); map.put("customParagraph", isBlank(customParagraph) ? "" : "^ " + customParagraph); map.put("serviceName", StringUtils.defaultString(gatewayAccount.getServiceName())); String corporateSurchargeMsg = charge.getCorporateSurcharge() .map(corporateSurcharge -> String.format("Your payment includes a fee of £%s for using a corporate credit or debit card.", formatToPounds(corporateSurcharge))) .orElse(""); map.put("corporateCardSurcharge", corporateSurchargeMsg); return map; }</code><technical_language>I do CorporateCardSurchargeCalculator.getTotalAmountFor(charge): return correct total if a surcharge</technical_language>

Target:
private HashMap<String, String> buildConfirmationEmailPersonalisationFrom(ChargeEntity charge) { GatewayAccountEntity gatewayAccount = charge.getGatewayAccount(); EmailNotificationEntity emailNotification = gatewayAccount .getEmailNotifications().get(EmailNotificationType.PAYMENT_CONFIRMED); String customParagraph = emailNotification != null ? emailNotification.getTemplateBody() : ""; HashMap<String, String> map = new HashMap<>(); map.put("serviceReference", charge.getReference().toString()); map.put("date", DateTimeUtils.toUserFriendlyDate(charge.getCreatedDate())); map.put("amount", formatToPounds(CorporateCardSurchargeCalculator.getTotalAmountFor(charge))); map.put("description", charge.getDescription()); map.put("customParagraph", isBlank(customParagraph) ? "" : "^ " + customParagraph); map.put("serviceName", StringUtils.defaultString(gatewayAccount.getServiceName())); String corporateSurchargeMsg = charge.getCorporateSurcharge() .map(corporateSurcharge -> String.format("Your payment includes a fee of £%s for using a corporate credit or debit card.", formatToPounds(corporateSurcharge))) .orElse(""); map.put("corporateCardSurcharge", corporateSurchargeMsg); return map; }
Source:
<code>protected DefaultHttpRequestRetryStrategy( final int maxRetries, final TimeValue defaultRetryInterval, final Collection<Class<? extends IOException>> clazzes, final Collection<Integer> codes) { Args.notNegative(maxRetries, "maxRetries"); Args.positive(defaultRetryInterval.getDuration(), "defaultRetryInterval"); this.maxRetries = maxRetries; this.defaultRetryInterval = defaultRetryInterval; <START> this.nonRetriableClasses = new HashSet<>(); <END> this.nonRetriableClasses.addAll(clazzes); this.retriableCodes = new HashSet<>(); this.retriableCodes.addAll(codes); }</code><technical_language>this.coll = new HashSet<>(); this.coll.addAll(input) -> this.coll = new HashSet<>(input);</technical_language>

Target:
protected DefaultHttpRequestRetryStrategy( final int maxRetries, final TimeValue defaultRetryInterval, final Collection<Class<? extends IOException>> clazzes, final Collection<Integer> codes) { Args.notNegative(maxRetries, "maxRetries"); Args.positive(defaultRetryInterval.getDuration(), "defaultRetryInterval"); this.maxRetries = maxRetries; this.defaultRetryInterval = defaultRetryInterval; this.nonRetriableIOExceptionClasses = new HashSet<>(clazzes); this.retriableCodes = new HashSet<>(codes); }
Source:
<code>public void validate(IValidatable<String> iv) { String name = (String) iv.getValue(); LayerGroupInfo other = getCatalog().getLayerGroupByName(name); if(other != null && (layerGroupId == null || !other.getId().equals(layerGroupId))) { <START> iv.error(new ValidationError("duplicateGroupNameError")); <END> } }</code><technical_language>Error message parameter "name" lost in conversion</technical_language>

Target:
public void validate(IValidatable<String> iv) { String name = (String) iv.getValue(); LayerGroupInfo other = getCatalog().getLayerGroupByName(name); if(other != null && (layerGroupId == null || !other.getId().equals(layerGroupId))) { iv.error(new ValidationError("duplicateGroupNameError").setVariable("name", name)); } }
Source:
<code>private String getLocalHCID() { String localHCID = null; try { localHCID = propertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.HOME_COMMUNITY_ID_PROPERTY); } catch (PropertyAccessException ex) { LOG.error("Exception while retrieving home community ID", ex); <START> } <END> return localHCID; }</code><technical_language>update code exception logging convention now. LOG.error("Exception while retrieving home community ID: " + ex.getLocalizedMessage(), ex);</technical_language>

Target:
private String getLocalHCID() { String localHCID = null; try { localHCID = propertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.HOME_COMMUNITY_ID_PROPERTY); } catch (PropertyAccessException ex) { LOG.error("Exception while retrieving home community ID : " + ex.getLocalizedMessage(), ex); } return localHCID; }
Source:
<code>void assignExclusiveSegments() throws IOException { <START> bufferManager.requestExclusiveBuffers(); <END> }</code><technical_language>is supplement similar check avoid this action is called multiple times in practice. check exclusive buffers 0 in BufferManager instead</technical_language>

Target:
void assignExclusiveSegments() throws IOException { checkState(bufferManager.unsynchronizedGetAvailableExclusiveBuffers() == 0, "Bug in input channel setup logic: exclusive buffers have already been set for this input channel."); if (initialCredit > 0) { bufferManager.requestExclusiveBuffers(); } }
Source:
<code><START> public void designDocSync() throws MalformedURLException { <END> DesignDocument designDoc = DesignDocumentManager.fromFile(designDocExample); db.getDesignDocumentManager().put(designDoc); }</code><technical_language>this throws a MalformedURLException more. is a test, Exception, test fail if exception propagates out</technical_language>

Target:
public void designDocSync() throws Exception { DesignDocument designDoc = DesignDocumentManager.fromFile(designDocExample); db.getDesignDocumentManager().put(designDoc); }
Source:
<code>public ObaStopResponse getStopDetails(String stopId) { <START> ObaStopResponse response = new ObaStopRequest.Builder(stopId).build().call(); <END> log.debug("ObaStopRequest returned " + response.toString()); return response; }</code><technical_language>Is for this null</technical_language>

Target:
public ObaStopResponse getStopDetails(String stopId) throws SpeechletException { ObaStopResponse response = new ObaStopRequest.Builder(stopId).build().call(); log.debug("ObaStopRequest returned " + response.toString()); if (response.getCode() == ObaApi.OBA_OK) { return response; } else { throw new SpeechletException(String.format("Error getting stop details for %s", stopId)); } }
Source:
<code>public void test_evaluate_array_strings () { final AtomicReferenceArray<String> atomicStringArray = new AtomicReferenceArray<>(3); atomicStringArray.set(0, "executing"); browser.addProgressListener(new ProgressListener() { @Override public void changed(ProgressEvent event) { } @Override public void completed(ProgressEvent event) { Object[] evalResult = (Object[]) browser.evaluate("return new Array(\"str1\", \"str2\", \"str3\")"); atomicStringArray.set(0, (String) evalResult[0]); atomicStringArray.set(1, (String) evalResult[1]); atomicStringArray.set(2, (String) evalResult[2]); if (browser_debug) System.out.println("Node value: "+ evalResult); } }); browser.setText("<html><body><p id='myid'>HelloWorld</p></body></html>"); shell.open(); for (int i = 0; i < (loopMultipier * secondsToWaitTillFail); i++) { runLoopTimer(waitMS); if (! "executing".equals(atomicStringArray.get(0))) { if (atomicStringArray.get(0).equals("str1") && atomicStringArray.get(1).equals("str2") && atomicStringArray.get(2).equals("str3")) { return; } else { <START> System.err.println("ERROR: test_evaluate_array_strings, resulting strings not as expected"); <END> } } } fail(name.getMethodName() + " failed. Excpected an array of strings, but did not receive array or got the wrong result."); }</code><technical_language>fail again</technical_language>

Target:
public void test_evaluate_array_strings () { assumeFalse(webkit1SkipMsg(), isWebkit1); final AtomicReferenceArray<String> atomicStringArray = new AtomicReferenceArray<>(3); atomicStringArray.set(0, "executing"); browser.addProgressListener(new ProgressListener() { @Override public void changed(ProgressEvent event) { } @Override public void completed(ProgressEvent event) { Object[] evalResult = (Object[]) browser.evaluate("return new Array(\"str1\", \"str2\", \"str3\")"); atomicStringArray.set(0, (String) evalResult[0]); atomicStringArray.set(1, (String) evalResult[1]); atomicStringArray.set(2, (String) evalResult[2]); if (browser_debug) System.out.println("Node value: "+ evalResult); } }); browser.setText("<html><body><p id='myid'>HelloWorld</p></body></html>"); shell.open(); for (int i = 0; i < (loopMultipier * secondsToWaitTillFail); i++) { runLoopTimer(waitMS); if (! "executing".equals(atomicStringArray.get(0))) { if (atomicStringArray.get(0).equals("str1") && atomicStringArray.get(1).equals("str2") && atomicStringArray.get(2).equals("str3")) { return; } else { fail("Resulting strings in array are not as expected"); } } } fail("Expected an array of strings, but did not receive array or got the wrong result."); }
Source:
<code>protected String getRequestParameterAsString( String parameter, String defaultValue, String encoding ) throws UnsupportedEncodingException { String enc = StringUtils.isEmpty( encoding ) ? CharsetHelper.getEncoding() : encoding; <START> <END> if( getRequestParameters() != null && getRequestParameters().hasParameter( parameter ) ){ return URLDecoder.decode( getRequestParameters().getStringParameter( parameter, defaultValue ) ); } return defaultValue; }</code><technical_language>@pedrofvteixeira , enc is in decode call. Is purpose</technical_language>

Target:
protected String getRequestParameterAsString( String parameter, String defaultValue, String encoding ) throws UnsupportedEncodingException { String enc = StringUtils.isEmpty( encoding ) ? CharsetHelper.getEncoding() : encoding; if( getRequestParameters() != null && getRequestParameters().hasParameter( parameter ) ){ return URLDecoder.decode( getRequestParameters().getStringParameter( parameter, defaultValue ), enc ); } return defaultValue; }
Source:
<code>public KlvNumericalDataElement( final byte[] key, final String name, Optional<T> errorIndicatorValue) { super(key, name); Preconditions.checkArgument( <START> errorIndicatorValue.isPresent(), "The errorIndicatorValue cannot be null."); <END> this.errorIndicatorValue = errorIndicatorValue; }</code><technical_language>I this change. Optional a parameter a method/ctor is problematic for reasons, of reasons fact easily check for null ifPresent. a cursory examination of code, I preventing invoking this ctor a null errorIndicatorValue, in case throw NPE this isPresent check</technical_language>

Target:
public KlvNumericalDataElement( final byte[] key, final String name, Optional<T> errorIndicatorValue) { super(key, name); this.errorIndicatorValue = errorIndicatorValue; }
Source:
<code>public void updateUploadItem(int index, UploadItem uploadItem) { UploadItem uploadItem1 = items.get(index); uploadItem1.setDescriptions(uploadItem.descriptions); uploadItem1.setTitle(uploadItem.title); <START> store.putString("Title", uploadItem.place.getName()); <END> }</code><technical_language>if pass this data, setting/retrieving a in sharedprefences is a bit surprising</technical_language>

Target:
public void updateUploadItem(int index, UploadItem uploadItem) { UploadItem uploadItem1 = items.get(index); uploadItem1.setDescriptions(uploadItem.descriptions); uploadItem1.setTitle(uploadItem.title); }
Source:
<code>public void zap(Entity entity, Charge.DamageOrigin origin, float damage) { if (Game.isClient(entity.world)) return; if (!RCEntitySelectors.KILLABLE.test(entity)) return; double chargeCost = damage * CHARGE_PER_DAMAGE; if (hasCapacity(chargeCost)) { float remainingDamage = damage; if (entity instanceof EntityLivingBase) { EntityLivingBase livingEntity = (EntityLivingBase) entity; EnumMap<EntityEquipmentSlot, IChargeProtectionItem> protections = new EnumMap<>(EntityEquipmentSlot.class); EnumSet.allOf(EntityEquipmentSlot.class).forEach(slot -> { IChargeProtectionItem protection = getChargeProtection(livingEntity, slot); if (protection != null) protections.put(slot, protection); } ); for (Map.Entry<EntityEquipmentSlot, IChargeProtectionItem> e : protections.entrySet()) { if (remainingDamage > 0.1) { IChargeProtectionItem.ZapResult result = e.getValue().zap(livingEntity.getItemStackFromSlot(e.getKey()), livingEntity, remainingDamage); entity.setItemStackToSlot(e.getKey(), result.stack); remainingDamage -= result.damagePrevented; } else break; } } if (remainingDamage > 0.1 && entity.attackEntityFrom(origin == Charge.DamageOrigin.BLOCK ? RailcraftDamageSource.ELECTRIC : RailcraftDamageSource.TRACK_ELECTRIC, remainingDamage)) { removeCharge(chargeCost); <START> HostEffects.INSTANCE.zapEffectDeath(entity.world, entity); <END> } } }</code><technical_language>This needs remain unchanged, if API is working</technical_language>

Target:
public void zap(Entity entity, Charge.DamageOrigin origin, float damage) { if (Game.isClient(entity.world)) return; if (!RCEntitySelectors.KILLABLE.test(entity)) return; double chargeCost = damage * CHARGE_PER_DAMAGE; if (hasCapacity(chargeCost)) { float remainingDamage = damage; if (entity instanceof EntityLivingBase) { EntityLivingBase livingEntity = (EntityLivingBase) entity; EnumMap<EntityEquipmentSlot, IChargeProtectionItem> protections = new EnumMap<>(EntityEquipmentSlot.class); EnumSet.allOf(EntityEquipmentSlot.class).forEach(slot -> { IChargeProtectionItem protection = getChargeProtection(livingEntity, slot); if (protection != null) protections.put(slot, protection); } ); for (Map.Entry<EntityEquipmentSlot, IChargeProtectionItem> e : protections.entrySet()) { if (remainingDamage > 0.1) { IChargeProtectionItem.ZapResult result = e.getValue().zap(livingEntity.getItemStackFromSlot(e.getKey()), livingEntity, remainingDamage); entity.setItemStackToSlot(e.getKey(), result.stack); remainingDamage -= result.damagePrevented; } else break; } } if (remainingDamage > 0.1 && entity.attackEntityFrom(origin == Charge.DamageOrigin.BLOCK ? RailcraftDamageSource.ELECTRIC : RailcraftDamageSource.TRACK_ELECTRIC, remainingDamage)) { removeCharge(chargeCost); Charge.hostEffects().zapEffectDeath(entity.world, entity); } } }
Source:
<code>public byte[] toByteArray() { if (rawMessage != null) { return rawMessage; } if (byteArray == null) { <START> DatagramWriter writer = new DatagramWriter(); <END> writer.write(getMessageType().getCode(), MESSAGE_TYPE_BITS); writer.write(getMessageLength(), MESSAGE_LENGTH_BITS); writer.write(messageSeq, MESSAGE_SEQ_BITS); writer.write(getFragmentOffset(), FRAGMENT_OFFSET_BITS); writer.write(getFragmentLength(), FRAGMENT_LENGTH_BITS); byte[] fragmentByteArray = fragmentToByteArray(); writer.writeBytes(fragmentByteArray); byteArray = writer.toByteArray(); } return byteArray; }</code><technical_language>initialize DatagramWriter a size</technical_language>

Target:
public byte[] toByteArray() { if (rawMessage != null) { return rawMessage; } if (byteArray == null) { int fragmentLength = getFragmentLength(); DatagramWriter writer = new DatagramWriter(fragmentLength + MESSAGE_HEADER_LENGTH_BYTES); writer.write(getMessageType().getCode(), MESSAGE_TYPE_BITS); writer.write(getMessageLength(), MESSAGE_LENGTH_BITS); writer.write(messageSeq, MESSAGE_SEQ_BITS); writer.write(getFragmentOffset(), FRAGMENT_OFFSET_BITS); writer.write(fragmentLength, FRAGMENT_LENGTH_BITS); writer.writeBytes(fragmentToByteArray()); byteArray = writer.toByteArray(); } return byteArray; }
Source:
<code>public Docs docs() { <START> return new MkDocs(this.dir, this.name.replace("[^a-z0-9]", "/")); <END> }</code><technical_language>Lets replace return new MkDocs(this.dir, this.name.replaceAll("[^a-z0-9]", "/"));</technical_language>

Target:
public Docs docs() { return new MkDocs(this.dir, this.name.replaceAll("[^a-z0-9]", "/")); }
Source:
<code>public void dispose() { super.dispose(); <START> fBuildThreadMap.values().forEach(buildThread -> { <END> buildThread.cancel(); }); if (fZoomThread != null) { fZoomThread.cancel(); } ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); }</code><technical_language>this needs synchronized. I a java.util.ConcurrentModificationException closing view while right opening a trace</technical_language>

Target:
public void dispose() { super.dispose(); synchronized (fBuildThreadMap) { fBuildThreadMap.values().forEach(buildThread -> { buildThread.cancel(); }); } if (fZoomThread != null) { fZoomThread.cancel(); } ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); }
Source:
<code>public static void createDatanodeIdFile(DatanodeDetails datanodeDetails, File path) throws IOException { <START> Preconditions.checkNotNull(path); <END> DumperOptions options = new DumperOptions(); options.setPrettyFlow(true); options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); Yaml yaml = new Yaml(options); try (Writer writer = new OutputStreamWriter( new FileOutputStream(path), "UTF-8")) { yaml.dump(getDatanodeDetailsYaml(datanodeDetails), writer); } }</code><technical_language>This is anti-pattern, crash NPE if path null</technical_language>

Target:
public static void createDatanodeIdFile(DatanodeDetails datanodeDetails, File path) throws IOException { DumperOptions options = new DumperOptions(); options.setPrettyFlow(true); options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); Yaml yaml = new Yaml(options); try (Writer writer = new OutputStreamWriter( new FileOutputStream(path), "UTF-8")) { yaml.dump(getDatanodeDetailsYaml(datanodeDetails), writer); } }
Source:
<code>private Entity toEntity(EntityType entityType, Entity emxEntity) { Entity entity = entityManager.create(entityType, POPULATE); for (Attribute attr : entityType.getAtomicAttributes()) { if (attr.getExpression() == null && !attr.isMappedBy()) { String attrName = attr.getName(); Object emxValue = emxEntity.get(attrName); AttributeType attrType = attr.getDataType(); switch (attrType) { case BOOL: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case HTML: case HYPERLINK: case INT: case LONG: case SCRIPT: case STRING: case TEXT: Object value = emxValue != null ? DataConverter.convert(emxValue, attr) : null; if ((!attr.isAuto() || value != null) && (!attr.hasDefaultValue() || value != null)) { entity.set(attrName, value); } break; case CATEGORICAL: case FILE: case XREF: Entity refEntity = toRefEntity(attr, emxValue); if ((!attr.isAuto() || refEntity != null) && (!attr.hasDefaultValue() || refEntity != null)) { entity.set(attrName, refEntity); } break; case CATEGORICAL_MREF: case MREF: List<Entity> refEntities = toRefEntities(attr, emxValue); if (!refEntities.isEmpty()) { entity.set(attrName, refEntities); } break; <START> case COMPOUND://Since this is inside a "atomic attributes" loop this should not be possible <END> default: throw new UnexpectedEnumException(attrType); } } } return entity; }</code><technical_language>IllegalStateException</technical_language>

Target:
private Entity toEntity(EntityType entityType, Entity emxEntity) { Entity entity = entityManager.create(entityType, POPULATE); for (Attribute attr : entityType.getAtomicAttributes()) { if (attr.getExpression() == null && !attr.isMappedBy()) { String attrName = attr.getName(); Object emxValue = emxEntity.get(attrName); AttributeType attrType = attr.getDataType(); switch (attrType) { case BOOL: case DATE: case DATE_TIME: case DECIMAL: case EMAIL: case ENUM: case HTML: case HYPERLINK: case INT: case LONG: case SCRIPT: case STRING: case TEXT: Object value = emxValue != null ? DataConverter.convert(emxValue, attr) : null; if ((!attr.isAuto() || value != null) && (!attr.hasDefaultValue() || value != null)) { entity.set(attrName, value); } break; case CATEGORICAL: case FILE: case XREF: Entity refEntity = toRefEntity(attr, emxValue); if ((!attr.isAuto() || refEntity != null) && (!attr.hasDefaultValue() || refEntity != null)) { entity.set(attrName, refEntity); } break; case CATEGORICAL_MREF: case MREF: List<Entity> refEntities = toRefEntities(attr, emxValue); if (!refEntities.isEmpty()) { entity.set(attrName, refEntities); } break; case COMPOUND://Since this is inside a "atomic attributes" loop this should not be possible throw new IllegalStateException("COMPOUND should never occur inside a 'atomic' loop"); default: throw new UnexpectedEnumException(attrType); } } } return entity; }
Source:
<code>private static PatternCondition<PsiElement> positionInTuple(final int position) { return new PatternCondition<PsiElement>("positionInTuple") { @Override public boolean accepts(@NotNull PsiElement element, ProcessingContext context) { ErlangTupleExpression tuple = PsiTreeUtil.getParentOfType(element, ErlangTupleExpression.class); ErlangExpression expression = PsiTreeUtil.getParentOfType(element, ErlangExpression.class); List<ErlangExpression> expressions = tuple != null ? tuple.getExpressionList() : ContainerUtil.<ErlangExpression>emptyList(); <START> return expressions.size() > position && expressions.get(position).equals(expression); <END> } }; }</code><technical_language>Do equals - reference equality is need here</technical_language>

Target:
private static PatternCondition<PsiElement> positionInTuple(final int position) { return new PatternCondition<PsiElement>("positionInTuple") { @Override public boolean accepts(@NotNull PsiElement element, ProcessingContext context) { ErlangTupleExpression tuple = PsiTreeUtil.getParentOfType(element, ErlangTupleExpression.class); ErlangExpression expression = PsiTreeUtil.getParentOfType(element, ErlangExpression.class); List<ErlangExpression> expressions = tuple != null ? tuple.getExpressionList() : ContainerUtil.<ErlangExpression>emptyList(); return expressions.size() > position && expressions.get(position) == expression; } }; }
Source:
<code>private synchronized void loadConfig() throws IOException { Resource configFile = findConfigFile(); checkNotNull(configFile, "gwc config file does not exist: ", GWC_CONFIG_FILE); XStreamPersister xmlPersister = this.persisterFactory.createXMLPersister(); configureXstream(xmlPersister.getXStream()); try { InputStream in = configFile.in(); try { this.config = xmlPersister.load(in, GWCConfig.class); <START> } finally { <END> in.close(); } LOGGER.fine("GWC GeoServer specific configuration loaded from " + GWC_CONFIG_FILE); } catch (Exception e) { LOGGER.log( Level.WARNING, "Error loading GWC GeoServer specific " + "configuration from " + configFile.path() + ". Applying defaults.", e); this.config = new GWCConfig(); } }</code><technical_language>This try-with-resources</technical_language>

Target:
private synchronized void loadConfig() throws IOException { Resource configFile = findConfigFile(); checkNotNull(configFile, "gwc config file does not exist: ", GWC_CONFIG_FILE); XStreamPersister xmlPersister = this.persisterFactory.createXMLPersister(); configureXstream(xmlPersister.getXStream()); try { try (InputStream in = configFile.in()) { this.config = xmlPersister.load(in, GWCConfig.class); } LOGGER.fine("GWC GeoServer specific configuration loaded from " + GWC_CONFIG_FILE); } catch (Exception e) { LOGGER.log( Level.WARNING, "Error loading GWC GeoServer specific " + "configuration from " + configFile.path() + ". Applying defaults.", e); this.config = new GWCConfig(); } }
Source:
<code>public void exit() { mOffload.stop(); mUpstreamNetworkMonitor.stop(); notifyDownstreamsOfNewUpstreamIface(null); handleNewUpstreamNetworkState(null); if (mTetherUpstream != null) { mTetherUpstream = null; reportUpstreamChanged(null); } <START> mBpfTetheringCoordinator.stop(); <END> }</code><technical_language>this stop command is run, IpServers tethering coordinator stopped? If not, running - is safe stop coordinator</technical_language>

Target:
public void exit() { mOffload.stop(); mUpstreamNetworkMonitor.stop(); notifyDownstreamsOfNewUpstreamIface(null); handleNewUpstreamNetworkState(null); if (mTetherUpstream != null) { mTetherUpstream = null; reportUpstreamChanged(null); } mBpfCoordinator.stop(); }
Source:
<code>private Class<?> loadPdxClass(String className) { try { <START> return loadClass(className); <END> } catch (ClassNotFoundException ex) { throw new JdbcConnectorException( "The pdx class \"" + className + "\" could not be loaded because: " + ex); } }</code><technical_language>implementation is line, inline it</technical_language>

Target:
private Class<?> loadPdxClass(String className) { try { return ClassPathLoader.getLatest().forName(className); } catch (ClassNotFoundException ex) { throw new JdbcConnectorException( "The pdx class \"" + className + "\" could not be loaded because: " + ex); } }
Source:
<code>private Boolean compareValues(Session session, Object left, Object right) { if (left == null) { if (right == null && opType == OpTypes.NOT_DISTINCT) { return Boolean.TRUE; } return null; } <START> if (right == null) { <END> return null; } int result = nodes[LEFT].dataType.compare(left, right); switch (opType) { case OpTypes.EQUAL : case OpTypes.NOT_DISTINCT : return result == 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.NOT_EQUAL : return result != 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.GREATER : return result > 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.GREATER_EQUAL : return result >= 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.SMALLER_EQUAL : return result <= 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.SMALLER : return result < 0 ? Boolean.TRUE : Boolean.FALSE; default : throw Error.runtimeError(ErrorCode.U_S0500, "Expression"); } }</code><technical_language>DISTINCT return NULL FALSE if side of op is NULL</technical_language>

Target:
private Boolean compareValues(Session session, Object left, Object right) { if (left == null) { if (opType == OpTypes.NOT_DISTINCT) { return right == null; } return null; } if (right == null) { return (opType == OpTypes.NOT_DISTINCT) ? Boolean.FALSE : null; } int result = nodes[LEFT].dataType.compare(left, right); switch (opType) { case OpTypes.EQUAL : case OpTypes.NOT_DISTINCT : return result == 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.NOT_EQUAL : return result != 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.GREATER : return result > 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.GREATER_EQUAL : return result >= 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.SMALLER_EQUAL : return result <= 0 ? Boolean.TRUE : Boolean.FALSE; case OpTypes.SMALLER : return result < 0 ? Boolean.TRUE : Boolean.FALSE; default : throw Error.runtimeError(ErrorCode.U_S0500, "Expression"); } }
Source:
<code>public HypervisorUpdateJobConfig() { this.setJobKey(JOB_KEY) <START> .setJobName(JOB_NAME); <END> }</code><technical_language>This job is currently configured unique-by-entity & other constraints. checking jobs 1) extend UniqueByEntityJob, 2) explicitly define methods isSchedulable & scheduleJob. HypervisorUpdateJob is #2, target owner, is a custom query isSchedulable method checks for non-terminal jobs of type owner, checks & schedules jobs in order received. allow job run if is oldest of type this owner (see change f15807dde0e4ca0f08fcee7b94e7b4b29327e478 for details). Currently, new do constraints is add constraint here, in similar ImportJob/ExportJob: .addConstraint(JobConstraints.uniqueByArgument(OWNER_KEY));. This needs done a minimum, care requirement of preserving order. This is another topic in list of need discuss @Ceiu I think</technical_language>

Target:
public HypervisorUpdateJobConfig() { this.setJobKey(JOB_KEY) .setJobName(JOB_NAME) .addConstraint(JobConstraints.uniqueByArgument(OWNER_KEY)); }
Source:
<code>public Response setRoutingData(String jsonContent) { try { <START> Map<String, List<String>> routingData = new ObjectMapper() <END> .readValue(jsonContent, new TypeReference<HashMap<String, List<String>>>() { }); _metadataStoreDirectory.setNamespaceRoutingData(_namespace, routingData); } catch (JsonMappingException | JsonParseException | IllegalArgumentException e) { return badRequest(e.getMessage()); } catch (IOException e) { return serverError(e); } return created(); }</code><technical_language>above. create ObjectMapper over</technical_language>

Target:
public Response setRoutingData(String jsonContent) { try { Map<String, List<String>> routingData = OBJECT_MAPPER.readValue(jsonContent, new TypeReference<HashMap<String, List<String>>>() { }); _metadataStoreDirectory.setNamespaceRoutingData(_namespace, routingData); } catch (JsonMappingException | JsonParseException | IllegalArgumentException e) { return badRequest(e.getMessage()); } catch (IOException e) { return serverError(e); } return created(); }
Source:
<code>public void findMetrics( @Suspended final AsyncResponse asyncResponse, @ApiParam(value = "Queried metric type", required = false, allowableValues = "[gauge, availability, counter]") @QueryParam("type") MetricType metricType, @ApiParam(value = "List of tags", required = false) @QueryParam ("tags") Tags tags) { <START> if(metricType != null && !MetricType.userTypes().stream().filter(t -> metricType == t) <END> .findAny().isPresent()) { asyncResponse.resume(badRequest(new ApiError("Incorrect type param"))); return; } Observable<Metric> metricObservable = (tags == null) ? metricsService.findMetrics(tenantId, metricType) : metricsService.findMetricsWithTags(tenantId, tags.getTags(), metricType); metricObservable .map(MetricDefinition::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); }</code><technical_language>userTypes().contains(metricType) ? This stream+filter+findAny construct a bit convoluted in this case</technical_language>

Target:
public void findMetrics( @Suspended final AsyncResponse asyncResponse, @ApiParam(value = "Queried metric type", required = false, allowableValues = "[gauge, availability, counter]") @QueryParam("type") MetricType metricType, @ApiParam(value = "List of tags", required = false) @QueryParam ("tags") Tags tags) { if(metricType != null && !MetricType.userTypes().contains(metricType)) { asyncResponse.resume(badRequest(new ApiError("Incorrect type param"))); return; } Observable<Metric> metricObservable = (tags == null) ? metricsService.findMetrics(tenantId, metricType) : metricsService.findMetricsWithTags(tenantId, tags.getTags(), metricType); metricObservable .map(MetricDefinition::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); }
Source:
<code>public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval ret = super.doSingularQuery(t, attributeQuark); if (ret != null) { return ret; } <START> fRwl.readLock().lock(); <END> for (HTInterval interval : fCurrentChunk) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } fRwl.readLock().unlock(); for (Iterable<HTInterval> intervals : intervalQueue) { for (HTInterval interval : intervals) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } } return super.doSingularQuery(t, attributeQuark); }</code><technical_language>try / finally</technical_language>

Target:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval ret = super.doSingularQuery(t, attributeQuark); if (ret != null) { return ret; } List<HTInterval> currentIntervals = fCurrentChunk; int size = currentIntervals.size(); for (int i = 0; i < size; i++) { HTInterval interval = currentIntervals.get(i); if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } for (Iterable<HTInterval> intervals : intervalQueue) { for (HTInterval interval : intervals) { if (interval.getAttribute() == attributeQuark && interval.intersects(t)) { return interval; } } } return super.doSingularQuery(t, attributeQuark); }
Source:
<code>public void processingInstruction(final String target, final String data) { final ProcessingInstruction pi = new ProcessingInstruction(); if (isBeforeRoot()) { nodesBeforeRoot.add(pi); } else if (isAfterRoot()) { nodesAfterRoot.add(pi); } else { final Element parent = stack.getLast().element; parent.addChild(pi); appendChars(false); } final int startOffset = content.length(); content.insertTagMarker(content.length()); <START> content.insertText(content.length(), target + " " + data); <END> content.insertTagMarker(content.length()); pi.associate(content, new ContentRange(startOffset, content.length() - 1)); trimLeading = false; }</code><technical_language>In opinion target a member of ProcessingInstruction part of textual content. is equivalent element name. is possibility formally define PIs NOTATION. easier handle this if target edited normal content. some formal requirements target fulfill validated easier if target is isolated content. getText() include target. Users of API remove target text. insert/edit/change target of existing PI provide a special action dialog</technical_language>

Target:
public void processingInstruction(final String target, final String data) { final ProcessingInstruction pi = new ProcessingInstruction(target); if (isBeforeRoot()) { nodesBeforeRoot.add(pi); } else if (isAfterRoot()) { nodesAfterRoot.add(pi); } else { final Element parent = stack.getLast().element; parent.addChild(pi); appendChars(false); } final int startOffset = content.length(); content.insertTagMarker(content.length()); content.insertText(content.length(), data); content.insertTagMarker(content.length()); pi.associate(content, new ContentRange(startOffset, content.length() - 1)); trimLeading = false; }
Source:
<code>public int getInt(int length, boolean signed) { if (length == 0) { return 0; } if (!canRead(length)) { throw new BufferOverflowException(); } int val = 0; boolean gotIt = false; <START> if (this.pos % BitBuffer.BIT_CHAR == 0) { <END> switch (length) { case BitBuffer.BIT_CHAR: val = this.buf.get((int) (this.pos / 8)); if (!signed) { val = val & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: val = this.buf.getShort((int) (this.pos / 8)); if (!signed) { val = val & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }</code><technical_language>this is a candidate for a faster alignment detection (pos & (BIT_CHAR-1)) != 0 compiler able optimize proves 'pos' is a positive number</technical_language>

Target:
private int getInt(int length, boolean signed) throws CTFReaderException { if (length == 0) { return 0; } if (!canRead(length)) { throw new CTFReaderException("Cannot read the integer, the buffer does not have enough remaining space. Requested:" + length); } int val = 0; boolean gotIt = false; if ((this.pos & (BitBuffer.BIT_CHAR - 1)) == 0) { switch (length) { case BitBuffer.BIT_CHAR: val = this.buf.get((int) (this.pos / 8)); if (!signed) { val = val & 0xff; } gotIt = true; break; case BitBuffer.BIT_SHORT: val = this.buf.getShort((int) (this.pos / 8)); if (!signed) { val = val & 0xffff; } gotIt = true; break; case BitBuffer.BIT_INT: val = this.buf.getInt((int) (this.pos / 8)); gotIt = true; break; default: break; } } if (!gotIt) { if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { val = getIntLE(this.pos, length, signed); } else { val = getIntBE(this.pos, length, signed); } } this.pos += length; return val; }
Source:
<code>public void addColumn(long tableId, ColumnInfo column) { String columnType = sqlColumnType(column.getType()); if (columnType == null) { <START> throw metadataError(new UnsupportedDataTypeException(column.getType().getDisplayName())); <END> } String sql = format("ALTER TABLE %s ADD COLUMN (%s %s, %s %s)", shardIndexTable(tableId), minColumn(column.getColumnId()), columnType, maxColumn(column.getColumnId()), columnType); int attempts = 0; while (true) { attempts++; try (Handle handle = dbi.open()) { handle.execute(sql); } catch (DBIException e) { if (isSyntaxOrAccessError(e)) { return; } if (attempts >= MAX_ADD_COLUMN_ATTEMPTS) { throw metadataError(e); } log.warn(e, "Failed to alter table on attempt %s, will retry. SQL: %s", attempts, sql); try { SECONDS.sleep(3); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw metadataError(ie); } } } }</code><technical_language>This change is needed. Please restore changes DatabaseShardManager.java</technical_language>

Target:
public void addColumn(long tableId, ColumnInfo column) { String columnType = sqlColumnType(column.getType()); if (columnType == null) { return; } String sql = format("ALTER TABLE %s ADD COLUMN (%s %s, %s %s)", shardIndexTable(tableId), minColumn(column.getColumnId()), columnType, maxColumn(column.getColumnId()), columnType); int attempts = 0; while (true) { attempts++; try (Handle handle = dbi.open()) { handle.execute(sql); } catch (DBIException e) { if (isSyntaxOrAccessError(e)) { return; } if (attempts >= MAX_ADD_COLUMN_ATTEMPTS) { throw metadataError(e); } log.warn(e, "Failed to alter table on attempt %s, will retry. SQL: %s", attempts, sql); try { SECONDS.sleep(3); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw metadataError(ie); } } } }
Source:
<code>public void removeContext(IUndoContext context) { boolean recompute = false; if (triggeringOperation != null && triggeringOperation.hasContext(context)) { if (triggeringOperation.getContexts().length == 1) { remove(triggeringOperation); return; } triggeringOperation.removeContext(context); recompute = true; } ArrayList<IUndoableOperation> toBeRemoved = new ArrayList<>(); for (IUndoableOperation child : children) { if (child.hasContext(context)) { if (child.getContexts().length == 1) { toBeRemoved.add(child); } else { child.removeContext(context); } recompute = true; } } for (IUndoableOperation <START> element : <END> toBeRemoved) { remove(element); } if (recompute) { recomputeContexts(); } }</code><technical_language>rename operation</technical_language>

Target:
public void removeContext(IUndoContext context) { boolean recompute = false; if (triggeringOperation != null && triggeringOperation.hasContext(context)) { if (triggeringOperation.getContexts().length == 1) { remove(triggeringOperation); return; } triggeringOperation.removeContext(context); recompute = true; } ArrayList<IUndoableOperation> toBeRemoved = new ArrayList<>(); for (IUndoableOperation child : children) { if (child.hasContext(context)) { if (child.getContexts().length == 1) { toBeRemoved.add(child); } else { child.removeContext(context); } recompute = true; } } for (IUndoableOperation operation : toBeRemoved) { remove(operation); } if (recompute) { recomputeContexts(); } }
Source:
<code>public static Object[] data() { <START> if (Objects.equals(System.getenv().get("SKIP_BINARY_GENERATION"), "true")) { <END> return new TestPlatform[]{TestPlatform.NATIVE, TestPlatform.ALPINE, TestPlatform.CENTOS, TestPlatform.UBUNTU, TestPlatform.NO_INIT, TestPlatform.SLIM}; } else { return TestPlatform.values(); } }</code><technical_language>system properties instead of environment variables? is easy for PCT system properties? I BourneShellScript.class.GetName() + ". SKIP_BINARY_GENERATION" property/env var name for traceability needs used</technical_language>

Target:
public static Object[] data() { if (Objects.equals(System.getenv().get("SKIP_DURABLE_TASK_BINARY_GENERATION"), "true")) { return new TestPlatform[]{TestPlatform.NATIVE, TestPlatform.ALPINE, TestPlatform.CENTOS, TestPlatform.UBUNTU, TestPlatform.NO_INIT, TestPlatform.SLIM}; } else { return TestPlatform.values(); } }
Source:
<code>public boolean shouldSendEvent(Event event) { <START> return event.getId().getLeastSignificantBits() % RATE_MULTIPLIER < sampleRate; <END> }</code><technical_language>frequently people a UUID generation scheme default UUID4, sense compare sample rate Random.nextFloat instead. If UUID1 get a suitable distribution here</technical_language>

Target:
public boolean shouldSendEvent(Event event) { return Math.abs(random.nextInt()) % RATE_MULTIPLIER < sampleRate; }
Source:
<code>private List<ContainerId> previouslyAllocatedContainers(List<Container> containersListByYarn) { List<ContainerId> containersToRelease = new ArrayList<>(); if (containersListByYarn.size() != 0) { Map<String, Container> fromYarn = new HashMap<>(); Set<String> fromStreamingContainerManager = new HashSet<>(); LOG.debug("Containers list by YARN - {}", containersListByYarn); LOG.debug("Containers list by Streaming Container Manger - {}", dnmgr.getPhysicalPlan().getContainers()); for (Container container : containersListByYarn) { fromYarn.put(container.getId().toString(), container); } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { if (ptContainer.getExternalId() != null) { fromStreamingContainerManager.add(ptContainer.getExternalId()); } } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { <START> String containerId = ptContainer.getExternalId(); <END> Container container = fromYarn.get(containerId); if (container != null) { allocatedContainers.put(containerId, new AllocatedContainer(container)); fromYarn.remove(containerId); fromStreamingContainerManager.remove(containerId); } } for (Container container : fromYarn.values()) { containersToRelease.add(container.getId()); } if (fromYarn.size() != 0) { LOG.info("YARN returned has container(s) {}, with no corresponding container(s) in Physical Plan", fromYarn); } for (String containerId : fromStreamingContainerManager) { dnmgr.scheduleContainerRestart(containerId); } } else { dnmgr.deployAfterRestart(); } return containersToRelease; }</code><technical_language>is containerId is null well. handle containers ExternalId null in this loop only</technical_language>

Target:
private List<ContainerId> previouslyAllocatedContainers(List<Container> containersListByYarn) { List<ContainerId> containersToRelease = new ArrayList<>(); if (containersListByYarn.size() != 0) { LOG.debug("Containers list by YARN - {}", containersListByYarn); LOG.debug("Containers list by Streaming Container Manger - {}", dnmgr.getPhysicalPlan().getContainers()); Map<String, Container> fromYarn = new HashMap<>(); for (Container container : containersListByYarn) { fromYarn.put(container.getId().toString(), container); } for (PTContainer ptContainer : dnmgr.getPhysicalPlan().getContainers()) { String containerId = ptContainer.getExternalId(); if (containerId == null) { continue; } Container container = fromYarn.get(containerId); if (container != null) { allocatedContainers.put(containerId, new AllocatedContainer(container)); fromYarn.remove(containerId); } else { dnmgr.scheduleContainerRestart(containerId); } } for (Container container : fromYarn.values()) { containersToRelease.add(container.getId()); } if (fromYarn.size() != 0) { LOG.info("Containers list returned by YARN, has the following container(s) which are not present in PhysicalPlan {}", fromYarn); } } else { dnmgr.deployAfterRestart(); } return containersToRelease; }
Source:
<code>@After public void teardown() throws IOException { <START> File rootExpectedOutputDirectory = new File( "./" + absoluteManagedResource.substring( 2 ).split( "/" )[ 0 ] ); <END> FileUtils.deleteDirectory( rootExpectedOutputDirectory ); File toDelete = new File( "./" + fileUrl.substring( 2 ).split( "/" )[ 0 ] ); FileUtils.deleteDirectory( toDelete ); }</code><technical_language>File separators need correct in tests too, in case of windows</technical_language>

Target:
@After public void teardown() throws IOException { File rootExpectedOutputDirectory = Paths.get( "." + File.separator + absoluteManagedResource.substring( 2 ).split( File.separator )[ 0 ] ).toFile(); FileUtils.deleteDirectory( rootExpectedOutputDirectory ); File toDelete = Paths.get( "." + File.separator + fileUrl.substring( 2 ).split( File.separator )[ 0 ] ).toFile(); FileUtils.deleteDirectory( toDelete ); }
Source:
<code>private HttpResponse invokeService(String endpoint) throws IOException, ArtifactSynchronizerException { HttpGet method = new HttpGet(endpoint); URL synapseGetURL = new URL(endpoint); APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); String password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD); byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes (APIConstants.DigestAuthConstants.CHARSET)); int synapsePort = synapseGetURL .getPort(); String synapseProtocol = synapseGetURL .getProtocol(); method.setHeader("Authorization", "Basic " + new String(credentials, <START> APIConstants.DigestAuthConstants.CHARSET)); <END> HttpClient httpClient = APIUtil.getHttpClient(synapsePort, synapseProtocol); HttpResponse httpResponse = null; int retryCount = 0; boolean retry = false; do { try { httpResponse = httpClient.execute(method); retry = false; } catch (IOException ex) { retryCount++; if (retryCount < retrievalRetries) { retry = true; log.warn("Failed retrieving " + endpoint + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + retrievalTimeoutInSeconds + " seconds."); try { Thread.sleep(retrievalTimeoutInSeconds * 1000); } catch (InterruptedException e) { } } else { throw ex; } } } while (retry); if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) { log.error("Retrieving artifacts is unsuccessful"); throw new ArtifactSynchronizerException("Error while retrieving artifacts"); } return httpResponse; }</code><technical_language>line exceeding row width</technical_language>

Target:
private CloseableHttpResponse invokeService(String endpoint) throws IOException { HttpGet method = new HttpGet(endpoint); URL url = new URL(endpoint); String username = eventHubConfigurationDto.getUsername(); String password = eventHubConfigurationDto.getPassword(); byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password). getBytes(APIConstants.DigestAuthConstants.CHARSET)); int port = url.getPort(); String protocol = url.getProtocol(); method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT , APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET)); HttpClient httpClient = APIUtil.getHttpClient(port, protocol); return APIUtil.executeHTTPRequest(method, httpClient); }