auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean removeTimestampedSnapshot(String basePath, Repository repository, int numberToKeep, int keepPeriod) throws ProviderImplementationException, IOException, XmlPullParserException, ParseException { String storageId = repository.getStorage() .getId(); File file = new File(basePath); LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); Metadata metadata = mavenMetadataManager.readMetadata(Paths.get(basePath)); if (metadata != null && metadata.getVersioning() != null) { Map<Integer, String> mapToRemove = getRemovingSnapshots(metadata, numberToKeep, keepPeriod); if (!mapToRemove.isEmpty()) { List<String> removingSnapshots = new ArrayList<>(); new ArrayList<>(mapToRemove.values()).forEach(e -> removingSnapshots.add(metadata.getArtifactId() .concat("-") .concat(e) .concat(".jar")) ); List<File> list = Arrays.asList(file.listFiles()); list.stream() .filter(File::isFile) .filter(e -> ArtifactUtils.isArtifact(e.getPath()) && removingSnapshots.contains(e.getName())) .forEach(e -> { try { layoutProvider.delete(storageId, repository.getId(), e.getPath(), true); String artifactName = e.getName(); <START> artifactName = artifactName.substring(0, artifactName.lastIndexOf(".")); <END> String pomPath = Paths.get(e.getParent(), artifactName) .toString() .concat(".pom"); layoutProvider.delete(storageId, repository.getId(), pomPath, true); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } }); return true; } } return false; }</code><technical_language>Please, fix</technical_language>

Target:
private boolean removeTimestampedSnapshot(String basePath, Repository repository, int numberToKeep, int keepPeriod) throws ProviderImplementationException, IOException, XmlPullParserException, ParseException { String storageId = repository.getStorage() .getId(); File file = new File(basePath); LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); Metadata metadata = mavenMetadataManager.readMetadata(Paths.get(basePath)); if (metadata != null && metadata.getVersioning() != null) { Map<Integer, String> mapToRemove = getRemovableTimestampedSnapshots(metadata, numberToKeep, keepPeriod); if (!mapToRemove.isEmpty()) { List<String> removingSnapshots = new ArrayList<>(); new ArrayList<>(mapToRemove.values()).forEach(e -> removingSnapshots.add(metadata.getArtifactId() .concat("-") .concat(e) .concat(".jar")) ); List<File> list = Arrays.asList(file.listFiles()); list.stream() .filter(File::isFile) .filter(e -> ArtifactUtils.isArtifact(e.getPath()) && removingSnapshots.contains(e.getName())) .forEach(e -> { try { layoutProvider.delete(storageId, repository.getId(), e.getPath(), true); String artifactName = e.getName(); artifactName = artifactName.substring(0, artifactName.lastIndexOf('.')); String pomPath = Paths.get(e.getParent(), artifactName) .toString() .concat(".pom"); layoutProvider.delete(storageId, repository.getId(), pomPath, true); } catch (IOException e1) { logger.error(e1.getMessage(), e1); } }); return true; } } return false; }
Source:
<code>public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { XWikiDocument doc = context.getDoc(); if (doc != null) { XWikiDocumentArchive documentArchive = doc.getDocumentArchive(); if (documentArchive == null) { <START> doc.setDocumentArchive(new XWikiDocumentArchive()); <END> } } this.getVersioningStore(context).resetRCSArchive(this, true, context); } }</code><technical_language>I understand this</technical_language>

Target:
public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { this.loadArchive(context); this.getVersioningStore(context).resetRCSArchive(this, true, context); } }
Source:
<code>private void validateMeasurementHasNotBeenCreated(final Observation observation, final Observation existingObservation, final List<ObjectError> errors) { final List<Measurement> measurements = observation.getMeasurements(); int counter = 0; for (final Measurement measurement : measurements) { final Measurement existingMeasurement = existingObservation.getMeasurement(measurement.getMeasurementIdentifier()); if (existingMeasurement == null) { <START> final String []array = {"measurement.already.inserted"}; <END> final List<String> object = new ArrayList<>(); final ObjectMapper objectMapper = new ObjectMapper(); try { object.add(objectMapper.writeValueAsString(measurement)); } catch (final JsonProcessingException e) { throw new ApiRuntimeException("Error mapping measurement to JSON", e); } final FieldError objectError = new FieldError("Observation", "Measurements [" + counter + "]", null, false, array, object.toArray(), "Error processing measurement"); errors.add(objectError); counter++; } } }</code><technical_language>format final String[] array. Rename errorMessage if</technical_language>

Target:
private void validateMeasurementHasNotBeenCreated(final Observation observation, final Observation existingObservation, final List<ObjectError> errors) { final List<Measurement> measurements = observation.getMeasurements(); int counter = 0; for (final Measurement measurement : measurements) { final Measurement existingMeasurement = existingObservation.getMeasurement(measurement.getMeasurementIdentifier()); if (existingMeasurement == null) { final String []errorMessage = {"measurement.already.inserted"}; final List<String> object = new ArrayList<>(); final ObjectMapper objectMapper = new ObjectMapper(); try { object.add(objectMapper.writeValueAsString(measurement)); } catch (final JsonProcessingException e) { throw new ApiRuntimeException("Error mapping measurement to JSON", e); } final FieldError objectError = new FieldError("Observation", "Measurements [" + counter + "]", null, false, errorMessage, object.toArray(), "Error processing measurement"); errors.add(objectError); counter++; } } }
Source:
<code>public void testAccessControl() throws Exception{ String iDOfCourseOfStudent = dataBundle.students.get("student1InCourse1").course; String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; verifyAccessibleForStudentsOfTheSameCourse(submissionParams); <START> verifyAccessibleForStudentsOfDifferentCourse(submissionParams); <END> }</code><technical_language>verifyUnaccessibleForStudentsOfOtherCourses in parent class</technical_language>

Target:
public void testAccessControl() throws Exception { String iDOfCourseOfStudent = dataBundle.students .get("student1InCourse1").course; String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of same course can access"); verifyAccessibleForStudentsOfTheSameCourse(submissionParams); ______TS("Admin can access to Masquerade as student"); verifyAccessibleForAdminToMasqueradeAsStudent(submissionParams); ______TS("Unaccessible without login"); verifyUnaccessibleWithoutLogin(submissionParams); iDOfCourseOfStudent = dataBundle.students.get("student2InCourse1").course; submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of different course can not access"); verifyUnaccessibleForStudentsOfOtherCourses(submissionParams); ______TS("UnregisteredUsers cannot access"); verifyUnaccessibleForUnregisteredUsers(submissionParams); }
Source:
<code>public void status(ObjectNode obj) { countSuccesses++; assertNotNull(obj); assertNotNull(obj.path("Timestamp")); <START> assertNotNull(obj.path("Current status")); <END> }</code><technical_language>"Current status" property logging batch success, test verify expected properties for a batch status message null? motivation confirm status logging is providing a progress indicator need</technical_language>

Target:
public void status(ObjectNode obj) { countSuccesses++; assertNotNull(obj); assertNotNull(obj.get("Timestamp")); assertNotNull(obj.get("Current status")); if (!obj.path("Current status").isMissingNode() && obj.get("Current status").textValue().equals("Batch Success Recorded.")) { assertNotNull(obj.get("Estimated total bytes in the CSV file")); assertNotNull(obj.get("Bytes read so far")); assertNotNull(obj.get("Success Batch Number")); assertNotNull(obj.get("Batch running since last log")); assertNotNull(obj.get("Total successes")); } }
Source:
<code>private void collided(SolGame game) { shouldBeRemoved = true; Vector2 position = body.getPosition(); buildEffect(game, config.collisionEffect, DrawableLevel.PART_FG_1, position, false); buildEffect(game, config.collisionEffectBackground, DrawableLevel.PART_FG_0, position, false); if (config.collisionEffectBackground != null) { game.getPartMan().blinks(position, game, config.collisionEffectBackground.size); } <START> if(ship.getPilot().isPlayer() && obstacle instanceof SolShip) <END> ship.changeDisposition(((SolShip) obstacle).getFactionID()); game.getSoundManager().play(game, config.collisionSound, null, this); }</code><technical_language>Braces</technical_language>

Target:
private void collided(SolGame game) { shouldBeRemoved = true; Vector2 position = body.getPosition(); buildEffect(game, config.collisionEffect, DrawableLevel.PART_FG_1, position, false); buildEffect(game, config.collisionEffectBackground, DrawableLevel.PART_FG_0, position, false); if (config.collisionEffectBackground != null) { game.getPartMan().blinks(position, game, config.collisionEffectBackground.size); } if (ship.getPilot().isPlayer() && obstacle instanceof SolShip) { ship.changeDisposition(((SolShip) obstacle).getFactionID()); } game.getSoundManager().play(game, config.collisionSound, null, this); }
Source:
<code>protected void executeCommand() { final VDS vds = getVds(); EngineLock monitoringLock = new EngineLock(Collections.singletonMap(getParameters().getVdsId().toString(), new Pair<String, String>(LockingGroup.VDS_INIT.name(), "")), null); log.infoFormat("Before acquiring lock in order to prevent monitoring for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); getLockManager().acquireLockWait(monitoringLock); <START> log.infoFormat("Lock acquired, from now a monitoring of host will be skipped for host {0} from data-center {1}", <END> vds.getName(), vds.getStoragePoolName()); try { ResourceManager.getInstance().GetVdsManager(getVdsId()).refreshCapabilities(new AtomicBoolean(), getVds()); setSucceeded(true); } catch (Exception e) { setSucceeded(false); } finally { getLockManager().releaseLock(monitoringLock); log.infoFormat("Get Capabilities finished. Lock released. Monitoring can run now for host {0} from data-center {1}", vds.getName(), vds.getStoragePoolName()); } }</code><technical_language>I this code is shared ActivateVdsCommand, extract this some static method</technical_language>

Target:
protected void executeCommand() { EngineLock monitoringLock = aquireMonitorLock(); try { ResourceManager.getInstance().GetVdsManager(getVdsId()).refreshHost(getVds()); setSucceeded(true); } finally { releaseMonitorLock(monitoringLock, "Get Capabilities"); } }
Source:
<code>public synchronized V getValue() { <START> if (value.get() == null || isExpired()) { <END> return refreshValue(); } return value.get(); }</code><technical_language>soft reference freed calls get()? a safe programming style safe current reference? Java final V valueCur = value.get(); if (valueCur == null || isExpired()) { return refreshValue(); } else { retturn valueCur; }</technical_language>

Target:
public synchronized V getValue() { V cachedValue = value.get(); if (cachedValue == null || isExpired()) { return refreshValue(); } return cachedValue; }
Source:
<code>protected String generateNewIdOfLength(ConfigBag setup, int len) { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) entity = (Entity) context; StringShortener shortener = Strings.shortener().separator("-"); shortener.append("system", "brooklyn"); <START> shortener.append("timeStamp", Long.toString(System.currentTimeMillis() / 1000L, 16)); <END> String user = System.getProperty("user.name"); if (!"brooklyn".equals(user)) shortener.append("user", user); if (entity!=null) { Application app = entity.getApplication(); if (app!=null) { shortener.append("app", shortName(app)) .append("appId", app.getId()); } shortener.append("entity", shortName(entity)) .append("entityId", entity.getId()); } else if (context!=null) { shortener.append("context", context.toString()); } shortener.truncate("user", 12) .truncate("app", 16) .truncate("entity", 16) .truncate("appId", 4) .truncate("entityId", 4) .truncate("context", 12); shortener.canTruncate("user", 8) .canTruncate("app", 5) .canTruncate("entity", 5) .canTruncate("system", 2) .canTruncate("app", 3) .canTruncate("entity", 3) .canRemove("app") .canTruncate("user", 4) .canRemove("entity") .canTruncate("context", 4) .canTruncate("timeStamp", 8) .canRemove("user") .canTruncate("appId", 2) .canRemove("appId"); String s = shortener.getStringOfMaxLength(len); return sanitize(s).toLowerCase(); }</code><technical_language>Long.toString(1440680387, Character.MAX_RADIX) more explicitly Long.toString(l, 36) (keep of this constant in brooklyn instead of realying java.util) This narrows required string length for timestamp 6</technical_language>

Target:
protected String generateNewIdOfLength(ConfigBag setup, int len) { Object context = setup.peek(CloudLocationConfig.CALLER_CONTEXT); Entity entity = null; if (context instanceof Entity) entity = (Entity) context; StringShortener shortener = Strings.shortener().separator("-"); shortener.append("system", "brooklyn"); shortener.append("timeStamp", Long.toString(System.currentTimeMillis() / 1000L, Character.MAX_RADIX)); String user = System.getProperty("user.name"); if (!"brooklyn".equals(user)) shortener.append("user", user); if (entity!=null) { Application app = entity.getApplication(); if (app!=null) { shortener.append("app", shortName(app)) .append("appId", app.getId()); } shortener.append("entity", shortName(entity)) .append("entityId", entity.getId()); } else if (context!=null) { shortener.append("context", context.toString()); } shortener.truncate("user", 12) .truncate("app", 16) .truncate("entity", 16) .truncate("appId", 4) .truncate("entityId", 4) .truncate("context", 12); shortener.canTruncate("user", 8) .canTruncate("app", 5) .canTruncate("entity", 5) .canTruncate("system", 2) .canTruncate("app", 3) .canTruncate("entity", 3) .canRemove("app") .canTruncate("user", 4) .canRemove("entity") .canTruncate("context", 4) .canTruncate("timeStamp", 6) .canRemove("user") .canTruncate("appId", 2) .canRemove("appId"); String s = shortener.getStringOfMaxLength(len); return sanitize(s).toLowerCase(); }
Source:
<code>private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { <START> numbers.add(Double.parseDouble(matcher.group())); <END> } if (numbers.isEmpty() || numbers.size() == 1) { return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); return new LiteralSuggestion("LITERAL", name, latLonList); }</code><technical_language>This throw a NumberFormatException. Typically, protect it</technical_language>

Target:
private LiteralSuggestion getLatLonSuggestions(String query) { Matcher matcher = PATTERN_LAT_LON.matcher(query); List<Double> numbers = new ArrayList<>(); while (matcher.find()) { numbers.add(Double.parseDouble(matcher.group())); } if (numbers.size() <= 1) { return null; } List<LatLon> latLonList = getLatLonList(numbers); String name = "Lat/Lon: " + latLonList.stream().map(LatLon::toString).collect(Collectors.joining(", ")); return new LiteralSuggestion("LITERAL", name, latLonList); }
Source:
<code>public Collection<E> getValues() { if (parts == null) { <START> ArrayList<E> sortedParts = new ArrayList<>(globalContext.getParts(type)); <END> sortedParts.sort((o1, o2) -> { if (o1 == o2) { return 0; } if (o2 == null) { return -1; } if (o1 == null) { return 1; } return o1.getPriority() - o2.getPriority(); }); parts = sortedParts; } return Collections.unmodifiableCollection(parts); }</code><technical_language>suggestion List<E> sortedParts = new ArrayList<>(globalContext.getParts(type));</technical_language>

Target:
public Collection<E> getValues() { if (parts == null) { List<E> sortedParts = new ArrayList<>(globalContext.getParts(type)); sortedParts.sort(Comparator.comparingInt(Priorized::getPriority)); parts = sortedParts; } return Collections.unmodifiableCollection(parts); }
Source:
<code><START> public boolean isEmpty() { <END> return this.shadow$isEmpty(); }</code><technical_language>Needs @Implements @Intrinsic</technical_language>

Target:
public boolean itemstack$isEmpty() { return this.shadow$isEmpty(); }
Source:
<code>public void faultySoftwareInfoFormsTest() { final DataForm dataForm = new DataForm(Type.result); FormField.Builder builder = FormField.builder(FormField.FORM_TYPE); builder.setType(FormField.Type.hidden); builder.addValue("faulty_formtype"); dataForm.addField(builder.build()); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(dataForm).build(); }); final DataForm dataFormWithoutFormType = new DataForm(Type.result); assertThrows(IllegalArgumentException.class, () -> { <START> SoftwareInfoForm.getBuilder().setDataForm(dataFormWithoutFormType).build(); <END> }); }</code><technical_language>This method static</technical_language>

Target:
public void faultySoftwareInfoFormsTest() { DataForm.Builder dataFormbuilder = DataForm.builder(Type.result); TextSingleFormField formField = FormField.buildHiddenFormType("faulty_formtype"); dataFormbuilder.addField(formField); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(dataFormbuilder.build()).build(); }); DataForm.Builder builderWithoutFormType = DataForm.builder(Type.result); assertThrows(IllegalArgumentException.class, () -> { SoftwareInfoForm.getBuilder().setDataForm(builderWithoutFormType.build()).build(); }); }
Source:
<code>public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { String mimeType = mimeTypeDetector.normalize(contentType, content); if (mimeTypeDetector.isXml(mimeType)) { return processXml(url, content); } else if (mimeTypeDetector.isText(mimeType)) { return processText(url, content); } else if (mimeTypeDetector.isGzip(mimeType)) { try (InputStream decompressed = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(content)))) { String compressedType = mimeTypeDetector.detect(decompressed); if (mimeTypeDetector.isXml(compressedType)) { return processGzippedXML(url, content); } else if (mimeTypeDetector.isText(compressedType)) { return processText(url, decompressed); } } catch (Exception e) { <START> String msg = String.format("Failed to detect embedded MediaType of gzipped sitemap '%s'", url); <END> throw new UnknownFormatException(msg, e); } } String msg = String.format("Can't parse a sitemap with MediaType '%s' from '%s'", contentType, url); throw new UnknownFormatException(msg); }</code><technical_language>explicit locale? forbidden API complains [ERROR] Forbidden method invocation: java.lang.String#format(java.lang.String,java.lang.Object[]) [Uses default locale] [ERROR] in crawlercommons.sitemaps.SiteMapParser (SiteMapParser.java:232) [ERROR] Forbidden method invocation: java.lang.String#format(java.lang.String,java.lang.Object[]) [Uses default locale] [ERROR] in crawlercommons.sitemaps.SiteMapParser (SiteMapParser.java:237)</technical_language>

Target:
public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { String mimeType = mimeTypeDetector.normalize(contentType, content); if (mimeTypeDetector.isXml(mimeType)) { return processXml(url, content); } else if (mimeTypeDetector.isText(mimeType)) { return processText(url, content); } else if (mimeTypeDetector.isGzip(mimeType)) { try (InputStream decompressed = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(content)))) { String compressedType = mimeTypeDetector.detect(decompressed); if (mimeTypeDetector.isXml(compressedType)) { return processGzippedXML(url, content); } else if (mimeTypeDetector.isText(compressedType)) { return processText(url, decompressed); } } catch (Exception e) { String msg = String.format(Locale.ROOT, "Failed to detect embedded MediaType of gzipped sitemap '%s'", url); throw new UnknownFormatException(msg, e); } } String msg = String.format(Locale.ROOT, "Can't parse a sitemap with MediaType '%s' from '%s'", contentType, url); throw new UnknownFormatException(msg); }
Source:
<code>private void setUpScrollListener() { historyList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); <START> ((MainActivity) requireActivity()).updateToolbarElevation(historyList.canScrollVertically(SCROLL_DIRECTION_UP)); <END> } }); }</code><technical_language>historyList.computeVerticalScrollOffset() != 0, require a custom constant</technical_language>

Target:
private void setUpScrollListener() { historyList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); ((MainActivity) requireActivity()).updateToolbarElevation(historyList.computeVerticalScrollOffset() != 0); } }); }
Source:
<code><START> protected void update(IAction action, ISelection s) { <END> getAction().setEnabled(DebugPlugin.getDefault().getBreakpointManager().hasBreakpoints()); }</code><technical_language>I selection updated in superclass super call is missing: super.update(action, s);</technical_language>

Target:
protected void update(IAction action, ISelection s) { super.update(action, s); getAction().setEnabled(DebugPlugin.getDefault().getBreakpointManager().hasBreakpoints()); }
Source:
<code>public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex == allColumns.size() - 1) { return candidateHeaderColumnIndex; } <START> if (candidateHeaderColumnIndex >= allColumns.size()) { <END> return candidateHeaderColumnIndex - 1; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } if (!Objects.equals(candidateHeaderMetaData.get(headerRowIndex), headerMetaData)) { break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }</code><technical_language>I curious _when_ this occur? is for candidateHeaderColumnIndex exceed number of columns</technical_language>

Target:
public static int getHeaderBlockEndColumnIndex(final List<GridColumn<?>> allColumns, final GridColumn.HeaderMetaData headerMetaData, final int headerRowIndex, final int headerColumnIndex) { int candidateHeaderColumnIndex = headerColumnIndex; if (candidateHeaderColumnIndex >= allColumns.size() - 1) { return allColumns.size() - 1; } while (candidateHeaderColumnIndex < allColumns.size() - 1) { final GridColumn candidateColumn = allColumns.get(candidateHeaderColumnIndex + 1); final List<GridColumn.HeaderMetaData> candidateHeaderMetaData = candidateColumn.getHeaderMetaData(); if (candidateHeaderMetaData.size() - 1 < headerRowIndex) { break; } if (!Objects.equals(candidateHeaderMetaData.get(headerRowIndex), headerMetaData)) { break; } candidateHeaderColumnIndex++; } return candidateHeaderColumnIndex; }
Source:
<code>private void doBushGrowth(Vector3i position, BushDefinitionComponent bushComponent, int stages) { EntityRef newBush = null; Map.Entry<String, GrowthStage> stage = null; if (!isInLastStage(bushComponent) || stages < 0) { bushComponent.currentStage += stages; stage = getGrowthStage(bushComponent, bushComponent.currentStage); worldProvider.setBlock(position, blockManager.getBlock(stage.getKey())); newBush = blockEntityRegistry.getBlockEntityAt(position); newBush.addOrSaveComponent(bushComponent); } <START> if( newBush != null && stage.getValue().maxTime > 0 && stage.getValue().minTime > 0) { <END> resetDelay(newBush, stage.getValue().minTime, stage.getValue().maxTime); } }</code><technical_language>mistaken, time newBush is null is if preceding if is executed. This nested other if, meaning newBush stage need initialised/declared if statement. Additionally, handling for maxTime is done in generateRandom method</technical_language>

Target:
private void doBushGrowth(Vector3i position, BushDefinitionComponent bushComponent, int stages) { if (!isInLastStage(bushComponent) || stages < 0) { bushComponent.currentStage += stages; Map.Entry<String, GrowthStage> stage = getGrowthStage(bushComponent, bushComponent.currentStage); worldProvider.setBlock(position, blockManager.getBlock(stage.getKey())); EntityRef newBush = blockEntityRegistry.getBlockEntityAt(position); newBush.addOrSaveComponent(bushComponent); if (stage.getValue().maxTime > 0 && stage.getValue().minTime > 0) { resetDelay(newBush, stage.getValue().minTime, stage.getValue().maxTime); } } }
Source:
<code>public boolean <START> addNetwork(V1NetworkAttachmentDefinition network, Guid <END> clusterId) { String networkName = network.getMetadata().getName(); if (networkDao.getByNameAndCluster(networkName, clusterId) != null) { return false; } StoragePool dataCenter = storagePoolDao.getForCluster(clusterId); List<Network> dcNetworks = networkDao.getAllForDataCenter(dataCenter.getId()); Network dcNetwork = dcNetworks.stream().filter(n -> n.getName().equals(networkName)).findFirst().orElse(null); Guid dcNetworkId = dcNetwork == null ? null : dcNetwork.getId(); if (dcNetworkId == null) { dcNetwork = new Network(); dcNetwork.setName(networkName); dcNetwork.setDataCenterId(dataCenter.getId()); AddNetworkStoragePoolParameters params = new AddNetworkStoragePoolParameters(dataCenter.getId(), dcNetwork); params.setVnicProfilePublicUse(true); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(clusterId); networkCluster.setRequired(false); params.setNetworkClusterList(List.of(networkCluster)); ActionReturnValue returnValue = backend.get().runInternalAction(ActionType.AddNetwork, params); dcNetworkId = returnValue.getActionReturnValue(); dcNetwork.setId(dcNetworkId); return returnValue.getSucceeded(); } ActionReturnValue returnValue = backend.get() .runInternalAction(ActionType.AttachNetworkToCluster, new AttachNetworkToClusterParameter(clusterId, dcNetwork)); return returnValue.getSucceeded(); }</code><technical_language>pass networkName dependency client code. In this addNetwork removeNetwork signature consistent</technical_language>

Target:
public boolean addNetwork(V1NetworkAttachmentDefinition network, Guid clusterId) { String networkName = getNetworkName(network); if (networkDao.getByNameAndCluster(networkName, clusterId) != null) { return false; } StoragePool dataCenter = storagePoolDao.getForCluster(clusterId); List<Network> dcNetworks = networkDao.getAllForDataCenter(dataCenter.getId()); Network dcNetwork = dcNetworks.stream().filter(n -> n.getName().equals(networkName)).findFirst().orElse(null); Guid dcNetworkId = dcNetwork == null ? null : dcNetwork.getId(); if (dcNetworkId == null) { dcNetwork = new Network(); dcNetwork.setName(networkName); dcNetwork.setDataCenterId(dataCenter.getId()); AddNetworkStoragePoolParameters params = new AddNetworkStoragePoolParameters(dataCenter.getId(), dcNetwork); params.setVnicProfilePublicUse(true); NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setClusterId(clusterId); networkCluster.setRequired(false); params.setNetworkClusterList(List.of(networkCluster)); ActionReturnValue returnValue = backend.get().runInternalAction(ActionType.AddNetwork, params); dcNetworkId = returnValue.getActionReturnValue(); dcNetwork.setId(dcNetworkId); return returnValue.getSucceeded(); } ActionReturnValue returnValue = backend.get() .runInternalAction(ActionType.AttachNetworkToCluster, new AttachNetworkToClusterParameter(clusterId, dcNetwork)); return returnValue.getSucceeded(); }
Source:
<code>public boolean isVideoVisible() { driver.switchTo().frame(commentIFrame); try { wait.forElementVisible(By.cssSelector("img")); return true; <START> } catch(NoSuchElementException e) { <END> PageObjectLogging.logInfo("Video element is not visible", e); return false; } }</code><technical_language>timeoutExcetion, element</technical_language>

Target:
public boolean isVideoVisible() { driver.switchTo().frame(commentIFrame); try { wait.forElementVisible(By.cssSelector("img")); return true; } catch(TimeoutException e) { PageObjectLogging.logInfo("Video element is not visible", e); return false; } }
Source:
<code>protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext() && this.self) { if (source instanceof Player) { return ((Player) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("No IP address was specified!")); } } Object state = args.getState(); String s = args.next(); try { return InetAddress.getByName(s); } catch (UnknownHostException e) { if (this.self) { if (source instanceof RemoteSource) { args.setState(state); return ((RemoteSource) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("Invalid IP address, and source was not a player!")); } } throw args.createError(Text.of("Invalid IP address!")); <START> } <END> }</code><technical_language>specifing a player name obtain ip: /banip badGuy</technical_language>

Target:
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException { if (!args.hasNext() && this.self) { if (source instanceof RemoteSource) { return ((RemoteSource) source).getConnection().getAddress().getAddress(); } else { throw args.createError(Text.of("No IP address was specified!")); } } Object state = args.getState(); String s = args.next(); try { return InetAddress.getByName(s); } catch (UnknownHostException e) { try { return ((Player) this.possiblePlayer.parseValue(source, args)).getConnection().getAddress().getAddress(); } catch (ArgumentParseException ex) { if (this.self && source instanceof RemoteSource) { args.setState(state); return ((RemoteSource) source).getConnection().getAddress().getAddress(); } throw args.createError(Text.of("Invalid IP address!")); } } }
Source:
<code>protected boolean bootProtocolDhcp() { String bootProtocol = (String) this.entry.get("BOOTPROTO"); <START> return bootProtocol != null && "dhcp".equalsIgnoreCase(bootProtocol); <END> }</code><technical_language>simplified by: return "dhcp".equalsIgnoreCase(bootProtocol);</technical_language>

Target:
protected boolean bootProtocolDhcp() { return "dhcp".equalsIgnoreCase((String) entry.get("BOOTPROTO")); }
Source:
<code>public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) { String indexName = hasText(deleteQuery.getIndex()) ? deleteQuery.getIndex() : getPersistentEntityFor(clazz).getIndexName(); String typeName = hasText(deleteQuery.getType()) ? deleteQuery.getType() : getPersistentEntityFor(clazz).getIndexType(); DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName) .setDocTypes(typeName) .setQuery(deleteQuery.getQuery()) .setAbortOnVersionConflict(false) .setRefresh(true); if (deleteQuery.getPageSize() != null) deleteByQueryRequest.setBatchSize(deleteQuery.getPageSize()); if (deleteQuery.getScrollTimeInMillis() != null) deleteByQueryRequest.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis())); try { client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); } catch (IOException e) { <START> throw new ElasticsearchException("Error for search request with scroll: " + deleteByQueryRequest.toString(), e); <END> } }</code><technical_language>please adjust error message fact deleting searching</technical_language>

Target:
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) { String indexName = hasText(deleteQuery.getIndex()) ? deleteQuery.getIndex() : getPersistentEntityFor(clazz).getIndexName(); String typeName = hasText(deleteQuery.getType()) ? deleteQuery.getType() : getPersistentEntityFor(clazz).getIndexType(); DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName) .setDocTypes(typeName) .setQuery(deleteQuery.getQuery()) .setAbortOnVersionConflict(false) .setRefresh(true); if (deleteQuery.getPageSize() != null) deleteByQueryRequest.setBatchSize(deleteQuery.getPageSize()); if (deleteQuery.getScrollTimeInMillis() != null) deleteByQueryRequest.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis())); try { client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); } catch (IOException e) { throw new ElasticsearchException("Error for delete request: " + deleteByQueryRequest.toString(), e); } }
Source:
<code>public boolean handleError(@NotNull List<String> message, @NotNull ExternalSystemException error, @NotNull NotificationData notification, @NotNull Project project) { String firstLine = message.get(0); if (firstLine != null && firstLine.startsWith(ProjectImportErrorHandler.CONNECTION_PERMISSION_DENIED_PREFIX)) { NotificationHyperlink quickFix = <START> new OpenUrlHyperlink("<LINK_1>", <END> "More details (and potential fix)"); updateNotification(notification, project, firstLine, quickFix); return true; } return false; }</code><technical_language>URL: <LINK_0></technical_language>

Target:
public boolean handleError(@NotNull List<String> message, @NotNull ExternalSystemException error, @NotNull NotificationData notification, @NotNull Project project) { String firstLine = message.get(0); if (firstLine != null && firstLine.startsWith(ProjectImportErrorHandler.CONNECTION_PERMISSION_DENIED_PREFIX)) { NotificationHyperlink quickFix = new OpenUrlHyperlink("<LINK_0>", "More details (and potential fix)"); updateNotification(notification, project, firstLine, quickFix); return true; } return false; }
Source:
<code>public void onClusterAdded(String updatedClusterName) { if (_sourceClusterName.equals(updatedClusterName)) { try { <START> DarkClusterConfigMap potentialDarkConfigMap = _facilities.getClusterInfoProvider().getDarkClusterConfigMap(updatedClusterName); <END> for (Map.Entry<String, DarkClusterConfig> entry : potentialDarkConfigMap.entrySet()) { String darkClusterName = entry.getKey(); DarkClusterConfig darkClusterConfig = entry.getValue(); _darkStrategyMap.put(darkClusterName, createStrategy(darkClusterName, darkClusterConfig)); } } catch (ServiceUnavailableException e) { _notifier.notify(() -> new RuntimeException("PEGA_0019 unable to refresh DarkClusterConfigMap for source cluster: " + _sourceClusterName)); } return; } }</code><technical_language>minor I _sourceClusterName is clearer. "updatedDarkConfigMap" "latest..."</technical_language>

Target:
public void onClusterAdded(String updatedClusterName) { if (_sourceClusterName.equals(updatedClusterName)) { try { DarkClusterConfigMap updatedDarkConfigMap = _facilities.getClusterInfoProvider().getDarkClusterConfigMap(_sourceClusterName); Set<String> oldDarkStrategySet = _darkStrategyMap.keySet(); Set<String> updatedDarkClusterConfigKeySet = updatedDarkConfigMap.keySet(); oldDarkStrategySet.removeAll(updatedDarkClusterConfigKeySet); for (String darkClusterToRemove : oldDarkStrategySet) { _darkStrategyMap.remove(darkClusterToRemove); } for (Map.Entry<String, DarkClusterConfig> entry : updatedDarkConfigMap.entrySet()) { _darkStrategyMap.put(entry.getKey(), createStrategy(entry.getKey(), entry.getValue())); } } catch (ServiceUnavailableException e) { _notifier.notify(() -> new RuntimeException("PEGA_0019 unable to refresh DarkClusterConfigMap for source cluster: " + _sourceClusterName)); } } }
Source:
<code>private String getPercentagesLabelPortion(double[] percentages, int i) { <START> StringBuilder sb = new StringBuilder(); <END> if (percentages != null) { sb.append(" (").append(percentages[i]).append(")"); } return sb.toString(); }</code><technical_language>Overly complicated: if (percentages == null) return ""; return " (" + percentages[i] + ")";</technical_language>

Target:
private String getPercentagesLabelPortion(double[] percentages, int i) { if (percentages == null) return ""; else return " (" + percentages[i] + "%)"; }
Source:
<code>public Path resolve(String other) { if (".".equals(other)) { return this; } if (Strings.isFilled(other) && other.startsWith("/")) { <START> return new BridgePath(vfs.resolve(other), fs); <END> } return new BridgePath(virtualFile.resolve(other), fs); }</code><technical_language>suggestion return new BridgePath(vfs.resolve(other), fileSystem);</technical_language>

Target:
public Path resolve(String other) { if (".".equals(other)) { return this; } if (Strings.isFilled(other) && other.startsWith("/")) { return new BridgePath(vfs.resolve(other), fileSystem); } return new BridgePath(virtualFile.resolve(other), fileSystem); }
Source:
<code>public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.setBytes(0); revocableLocalMemoryContext.setBytes(0); <START> systemLocalMemoryContext.setBytes(0); <END> } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }</code><technical_language>Explain local memory in closer, aggregate memory does. In addition, I vaguely remember intended add close method local memory context due address race issues</technical_language>

Target:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.close(); revocableLocalMemoryContext.close(); systemLocalMemoryContext.close(); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }
Source:
<code>public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, <START> Action.JUMP); <END> this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }</code><technical_language>I guess this affect compatibility previous deployments (when reading/writing ZK), nice if confirm</technical_language>

Target:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, null); this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }
Source:
<code>private HostVO getHost(long zoneId, boolean computeClusterMustSupportResign) { List<? extends Cluster> clusters = _mgr.searchForClusters(zoneId, 0L, Long.MAX_VALUE, HypervisorType.XenServer.toString()); if (clusters == null) { clusters = new ArrayList<>(); } Collections.shuffle(clusters, new Random(System.nanoTime())); clusters: for (Cluster cluster : clusters) { if (cluster.getAllocationState() == AllocationState.Enabled) { List<HostVO> hosts = _hostDao.findByClusterId(cluster.getId()); if (hosts != null) { Collections.shuffle(hosts, new Random(System.nanoTime())); for (HostVO host : hosts) { if (host.getResourceState() == ResourceState.Enabled) { if (computeClusterMustSupportResign) { if (computeClusterSupportsResign(cluster.getId())) { return host; } else { continue clusters; } } else { return host; } } } } } <START> } <END> return null; }</code><technical_language>**I realize this issue predates this patch. Therefore, I understand if is address now.** This method appears a duplicate of another implementation. consolidate for consistency maintainability</technical_language>

Target:
private Optional<HostVO> getHost(long zoneId, boolean computeClusterMustSupportResign) { List<? extends Cluster> clusters = mgr.searchForClusters(zoneId, 0L, Long.MAX_VALUE, HypervisorType.XenServer.toString()); if (clusters == null) { clusters = new ArrayList<>(); } Collections.shuffle(clusters, new Random(System.nanoTime())); clusters: for (Cluster cluster : clusters) { if (cluster.getAllocationState() == AllocationState.Enabled) { List<HostVO> hosts = hostDao.findByClusterId(cluster.getId()); if (hosts != null) { Collections.shuffle(hosts, new Random(System.nanoTime())); for (HostVO host : hosts) { if (host.getResourceState() == ResourceState.Enabled) { if (computeClusterMustSupportResign) { if (clusterDao.getSupportsResigning(cluster.getId())) { return Optional.of(host); } else { continue clusters; } } else { return Optional.of(host); } } } } } } return Optional.absent(); }
Source:
<code><START> private void showFilterDialog() { <END> Context context = getContext(); final String[] items = context.getResources().getStringArray(R.array.episode_filter_options); final String[] values = context.getResources().getStringArray(R.array.episode_filter_values); final boolean[] checkedItems = new boolean[items.length]; final Set<String> filter = new HashSet<>(Arrays.asList(feedItemFilter.getValues())); Iterator<String> it = filter.iterator(); while(it.hasNext()) { if(TextUtils.isEmpty(it.next())) { it.remove(); } } for(int i=0; i < values.length; i++) { String value = values[i]; if(filter.contains(value)) { checkedItems[i] = true; } } AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.filter); builder.setMultiChoiceItems(items, checkedItems, (dialog, which, isChecked) -> { if (isChecked) { filter.add(values[which]); } else { filter.remove(values[which]); } }); builder.setPositiveButton(R.string.confirm_label, (dialog, which) -> { feedItemFilter = new FeedItemFilter(filter.toArray(new String[filter.size()])); displayedEpisodes = feedItemFilter.filter(allEpisodes); onFragmentLoaded(displayedEpisodes); }); builder.setNegativeButton(R.string.cancel_label, null); builder.create().show(); }</code><technical_language>this method extracted a new class, shared episodes list feed details list. This class is big</technical_language>

Target:
private void showFilterDialog() { FilterDialog filterDialog = new FilterDialog(getContext(), feedItemFilter) { @Override protected void updateFilter(Set<String> filterValues) { feedItemFilter = new FeedItemFilter(filterValues.toArray(new String[filterValues.size()])); loadItems(); } }; filterDialog.openDialog(); }
Source:
<code><START> long firstAddress() { <END> if (cacheEntries.peek() == null) return Address.NOT_FOUND;; return cacheEntries.peek().txVersion; }</code><technical_language>add access specifier here</technical_language>

Target:
public long firstAddress() { if (cacheEntries.isEmpty()) { return Address.NOT_FOUND; } return cacheEntries.peek().txVersion; }
Source:
<code>public static void createCluster() { UnitTestConnectionService.add(CLUSTER_URI, new PassthroughServerBuilder() .serverEntityService(new ClusterTierManagerServerEntityService()) .clientEntityService(new ClusterTierManagerClientEntityService()) .serverEntityService(OBSERVABLE_CLUSTER_TIER_SERVICE = new ObservableClusterTierServerEntityService()) .clientEntityService(new ClusterTierClientEntityService()) .serverEntityService(new VoltronReadWriteLockServerEntityService()) .clientEntityService(new VoltronReadWriteLockEntityClientService()) <START> <END> .resource("defaultResource", 128, MemoryUnit.MB).build()); }</code><technical_language>Remove space</technical_language>

Target:
public static void createCluster() { UnitTestConnectionService.add(CLUSTER_URI, new PassthroughServerBuilder() .serverEntityService(new ClusterTierManagerServerEntityService()) .clientEntityService(new ClusterTierManagerClientEntityService()) .serverEntityService(observableClusterTierService = new ObservableClusterTierServerEntityService()) .clientEntityService(new ClusterTierClientEntityService()) .serverEntityService(new VoltronReadWriteLockServerEntityService()) .clientEntityService(new VoltronReadWriteLockEntityClientService()) .resource("defaultResource", 128, MemoryUnit.MB).build()); }
Source:
<code>public void customAttributes() { UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .message().customProperty("foo-key", "foo-value") .customProperty("bar-key", "bar-value").build() .build(); <START> assertEquals("foo-value", ((Map) unifiedMessage.getMessage().getAttributes().get("payload")).get("foo-key")); <END> assertEquals("bar-value", ((Map) unifiedMessage.getMessage().getAttributes().get("payload")).get("bar-key")); }</code><technical_language>assertj</technical_language>

Target:
public void customAttributes() { UnifiedMessage unifiedMessage = new UnifiedMessage.Builder() .message().userData("foo-key", "foo-value") .userData("bar-key", "bar-value").build() .build(); assertEquals("foo-value", ((Map) unifiedMessage.getMessage().getAttributes().get("user-data")).get("foo-key")); assertEquals("bar-value", ((Map) unifiedMessage.getMessage().getAttributes().get("user-data")).get("bar-key")); }
Source:
<code>protected void runStreamProcessor(SamzaResourceRequest request, String preferredHost) { CommandBuilder builder = getCommandBuilder(request.getProcessorId()); SamzaResource resource = peekAllocatedResource(preferredHost); if (resource == null) { throw new SamzaException("Expected resource for Processor ID: " + request.getProcessorId() + " was unavailable on host: " + preferredHost); } <START> if(clusterResourceManager.isResourceExpired(resource)) { <END> LOG.info("Lease for the resource has been expired for resource: request: {}", resource, request); resourceRequestState.releaseUnstartableContainer(resource, preferredHost); resourceRequestState.cancelResourceRequest(request); this.requestResource(request.getProcessorId(), request.getPreferredHost()); return; } resourceRequestState.updateStateAfterAssignment(request, preferredHost, resource); String processorId = request.getProcessorId(); LOG.info("Found Container ID: for Processor ID: on host: for request creation time: {}.", resource.getContainerId(), processorId, preferredHost, request.getRequestTimestamp()); state.pendingProcessors.put(processorId, resource); clusterResourceManager.launchStreamProcessor(resource, builder); }</code><technical_language>resource.isExpired()</technical_language>

Target:
protected void runStreamProcessor(SamzaResourceRequest request, String preferredHost) { CommandBuilder builder = getCommandBuilder(request.getProcessorId()); SamzaResource resource = peekAllocatedResource(preferredHost); if (resource == null) { throw new SamzaException("Expected resource for Processor ID: " + request.getProcessorId() + " was unavailable on host: " + preferredHost); } if (clusterResourceManager.isResourceExpired(resource)) { containerManager.handleExpiredResource(request, resource, preferredHost, resourceRequestState, this); return; } resourceRequestState.updateStateAfterAssignment(request, preferredHost, resource); String processorId = request.getProcessorId(); LOG.info("Found Container ID: for Processor ID: on host: for request creation time: {}.", resource.getContainerId(), processorId, preferredHost, request.getRequestTimestamp()); state.pendingProcessors.put(processorId, resource); clusterResourceManager.launchStreamProcessor(resource, builder); }