auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void apply(final List<StringBuilder> values, final AdvancingSource source, final String capturedText) { for (StringBuilder value : values) { String newValue = ""; <START> if ((source.getBreedingMethod().getMtype().equals("DER") || source.getBreedingMethod().getMtype().equals("MAN")) <END> && source.getGermplasm().getGpid2() != 0) { final String attributeName = capturedText.substring(1, capturedText.length()-1).split("\\.")[1]; newValue = germplasmDataManager.getAttributeValue(Integer.parseInt(source.getGermplasm().getGid()), attributeName); } this.replaceExpressionWithValue(value, newValue); } }</code><technical_language>change AppConstants.METHOD_TYPE_GEN.getString() generate another for "MAN"</technical_language>

Target:
public void apply(final List<StringBuilder> values, final AdvancingSource source, final String capturedText) { for (StringBuilder value : values) { String newValue = ""; if ((source.getBreedingMethod().getMtype().equals(AppConstants.METHOD_TYPE_DER.getString()) || source.getBreedingMethod().getMtype().equals(AppConstants.METHOD_TYPE_MAN.getString())) && source.getGermplasm().getGpid2() != 0) { final String attributeName = capturedText.substring(1, capturedText.length()-1).split("\\.")[1]; newValue = germplasmDataManager.getAttributeValue(Integer.parseInt(source.getGermplasm().getGid()), attributeName); } this.replaceExpressionWithValue(value, newValue); } }
Source:
<code>public void preClean() { readZKTimestamp = EnvironmentEdgeManager.currentTime(); try { wals = queueStorage.getAllWALs(); } catch (ReplicationException e) { <START> LOG.warn("Failed to read zookeeper, skipping checking deletable files"); <END> if (e.getCause() instanceof KeeperException.ConnectionLossException || e.getCause() instanceof KeeperException.SessionExpiredException || e.getCause() instanceof KeeperException.UnknownSessionException) { try { reconnectAfterKeeperException(); wals = queueStorage.getAllWALs(); return ; } catch (IOException | ReplicationException ex) { LOG.warn("Failed to reconnect zookeeper or load all wal in replication queues.", ex); } } wals = null; } }</code><technical_language>log this warn if root of ReplicationException is covered mentioned if condition. this: catch (ReplicationException e) { Throwable = e.getCause(); if (cause instanceof KeeperException.ConnectionLossException || instanceof KeeperException.SessionExpiredException || instanceof KeeperException.UnknownSessionException) { try { reconnectAfterKeeperException(); wals = queueStorage.getAllWALs(); return; } catch (IOException | ReplicationException ex) { LOG.warn("Failed reconnect zookeeper load wal in replication queues.", ex); } } else { LOG.warn("Failed read zookeeper, skipping checking deletable files", e); } wals = null; }</technical_language>

Target:
public void preClean() { readZKTimestamp = EnvironmentEdgeManager.currentTime(); try { wals = queueStorage.getAllWALs(); } catch (ReplicationException e) { if (e.getCause() instanceof KeeperException.ConnectionLossException || e.getCause() instanceof KeeperException.SessionExpiredException || e.getCause() instanceof KeeperException.UnknownSessionException) { try { reconnectAfterKeeperException(); wals = queueStorage.getAllWALs(); return ; } catch (IOException | ReplicationException ex) { LOG.warn("Failed to reconnect zookeeper or load all wal in replication queues.", ex); } } LOG.warn("Failed to read zookeeper, skipping checking deletable files", e); wals = null; } }
Source:
<code>public boolean isInstructorAllowedToModify() { for (int i = 0; i < getRecoveryCourses().getRows().size(); i++) { RecoveryCoursesTableRow course = getRecoveryCourses().getRows().get(i); <START> if (!instructorsForCourses.get(course.getCourseId()) <END> .isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE)) { return false; } } return true; }</code><technical_language>a stream for this method? anyMatch</technical_language>

Target:
public boolean isInstructorAllowedToModify() { return getRecoveryCourses().getRows().stream() .allMatch(course -> instructorsForCourses.get(course.getCourseId()) .isAllowedForPrivilege(Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE)); }
Source:
<code>public List<Alteration> findMutationsByConsequenceAndPosition(Gene gene, VariantConsequence consequence, int start, int end, List<Alteration> alterations) { Set<Alteration> result = new HashSet<>(); if(gene != null && consequence != null) { for(String cons: consequence.getTerm().split("\\s*,\\s*")) { VariantConsequence tmpConsequence = VariantConsequenceUtils.findVariantConsequenceByTerm(cons); if (alterations != null && alterations.size() > 0) { <START> Set<Alteration> filter = new HashSet<>(); <END> for (Alteration alteration : alterations) { if (alteration.getGene().equals(gene) && alteration.getConsequence() != null && alteration.getConsequence().equals(tmpConsequence) && alteration.getProteinStart() <= start && alteration.getProteinEnd() >= end) { filter.add(alteration); } } result.addAll(filter); } else { List<Alteration> queryResult = getDao().findMutationsByConsequenceAndPosition(gene, tmpConsequence, start, end); if(queryResult != null) { result.addAll(queryResult); } } } } return new ArrayList<>(result); }</code><technical_language>need filter</technical_language>

Target:
public List<Alteration> findMutationsByConsequenceAndPosition(Gene gene, VariantConsequence consequence, int start, int end, List<Alteration> alterations) { Set<Alteration> result = new HashSet<>(); if(gene != null && consequence != null) { for(String cons: consequence.getTerm().split("\\s*,\\s*")) { VariantConsequence tmpConsequence = VariantConsequenceUtils.findVariantConsequenceByTerm(cons); if (alterations != null && alterations.size() > 0) { for (Alteration alteration : alterations) { if (alteration.getGene().equals(gene) && alteration.getConsequence() != null && alteration.getConsequence().equals(tmpConsequence) && alteration.getProteinStart() <= start && alteration.getProteinEnd() >= end) { result.add(alteration); } } } else { List<Alteration> queryResult = getDao().findMutationsByConsequenceAndPosition(gene, tmpConsequence, start, end); if(queryResult != null) { result.addAll(queryResult); } } } } return new ArrayList<>(result); }
Source:
<code>public @ResponseBody List<ExperimentDto> list() throws IOException { Collection<Experiment> experiments = experimentService.list(); <START> return experiments.stream().map(expt -> Dtos.asDto(expt)).collect(Collectors.toList()); <END> }</code><technical_language>changes similar this in a places... If compiler complaining, want update Java version. I previously a version a similar bug</technical_language>

Target:
public @ResponseBody List<ExperimentDto> list() throws IOException { Collection<Experiment> experiments = experimentService.list(); return experiments.stream().map(Dtos::asDto).collect(Collectors.toList()); }
Source:
<code>private Constraint shortenDrivingTimePerMillisecondSquared(ConstraintFactory constraintFactory) { return constraintFactory.from(RockShow.class) .filter(r -> r.getPreviousStandstill() != null) .penalizeConfigurableLong(SHORTEN_DRIVING_TIME_PER_MILLISECOND_SQUARED, <START> r -> (long) Math.pow(r.getDrivingTimeFromPreviousStandstill(), 2)); <END> }</code><technical_language>Math.pow long double conversation, is inaccurate, try (double) 9007199254740993L <LINK_0> convert long (again, inaccurate) Lets simply do r.getDrivingTimeFromPreviousStandstill() * r.getDrivingTimeFromPreviousStandstill()</technical_language>

Target:
private Constraint shortenDrivingTimePerMillisecondSquared(ConstraintFactory constraintFactory) { return constraintFactory.from(RockShow.class) .filter(rockShow -> rockShow.getPreviousStandstill() != null) .penalizeConfigurableLong(SHORTEN_DRIVING_TIME_PER_MILLISECOND_SQUARED, rockShow -> rockShow.getDrivingTimeFromPreviousStandstill() * rockShow.getDrivingTimeFromPreviousStandstill()); }
Source:
<code>private String extractSubject(Map<String, Object> sessionAttributes) { return Stream.of(sessionAttributes.get(SecurityConstants.SECURITY_TOKEN_KEY)) .filter(SecurityTokenHolder.class::isInstance) .map(SecurityTokenHolder.class::cast) .map(SecurityTokenHolder::getPrincipals) .filter(Objects::nonNull) .map(PrincipalCollection.class::cast) <START> .map(principalCollection -> new SessionToken(principalCollection, null, "127.0.0.1")) <END> .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }</code><technical_language>args backwards</technical_language>

Target:
private String extractSubject(Map<String, Object> sessionAttributes) { return Stream.of(sessionAttributes.get(SecurityConstants.SECURITY_TOKEN_KEY)) .filter(SecurityTokenHolder.class::isInstance) .map(SecurityTokenHolder.class::cast) .map(SecurityTokenHolder::getPrincipals) .filter(Objects::nonNull) .map(PrincipalCollection.class::cast) .map(principalCollection -> new SessionToken(null, principalCollection, "127.0.0.1")) .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }
Source:
<code>public void testOffsetFetchRequestBuilderToString() { List<Boolean> stableFlags = Arrays.asList(true, false); for (Boolean requireStable : stableFlags) { String allTopicPartitionsString = new OffsetFetchRequest.Builder("someGroup", requireStable, null).toString(); assertTrue(allTopicPartitionsString.contains("groupId='someGroup', topics=null, requireStable=" + requireStable.toString())); String string = new OffsetFetchRequest.Builder("group1", requireStable, Collections.singletonList(new TopicPartition("test11", 1))).toString(); assertTrue(string.contains("test11")); assertTrue(string.contains("group1")); <START> assertTrue(string.contains(requireStable.toString())); <END> } }</code><technical_language>nit: check for contains requireStable=requireStable.toString()</technical_language>

Target:
public void testOffsetFetchRequestBuilderToString() { List<Boolean> stableFlags = Arrays.asList(true, false); for (Boolean requireStable : stableFlags) { String allTopicPartitionsString = new OffsetFetchRequest.Builder("someGroup", requireStable, null).toString(); assertTrue(allTopicPartitionsString.contains("groupId='someGroup', topics=null, requireStable=" + requireStable.toString())); String string = new OffsetFetchRequest.Builder("group1", requireStable, Collections.singletonList(new TopicPartition("test11", 1))).toString(); assertTrue(string.contains("test11")); assertTrue(string.contains("group1")); assertTrue(string.contains("requireStable=" + requireStable.toString())); } }
Source:
<code>public LinkedHashMap<VariableReferenceExpression, DruidColumnHandle> getAssignments() { LinkedHashMap<VariableReferenceExpression, DruidColumnHandle> result = new LinkedHashMap<>(); <START> selections.entrySet().stream().forEach(entry -> { <END> VariableReferenceExpression variable = entry.getKey(); Selection selection = entry.getValue(); DruidColumnHandle handle = selection.getOrigin() == Origin.TABLE_COLUMN ? new DruidColumnHandle(selection.getDefinition(), variable.getType(), DruidColumnHandle.DruidColumnType.REGULAR) : new DruidColumnHandle(variable, DruidColumnHandle.DruidColumnType.DERIVED); result.put(variable, handle); }); return result; }</code><technical_language>remove stream()</technical_language>

Target:
public Map<VariableReferenceExpression, DruidColumnHandle> getAssignments() { Map<VariableReferenceExpression, DruidColumnHandle> result = new LinkedHashMap<>(); selections.entrySet().forEach(entry -> { VariableReferenceExpression variable = entry.getKey(); Selection selection = entry.getValue(); DruidColumnHandle handle = selection.getOrigin() == Origin.TABLE_COLUMN ? new DruidColumnHandle(selection.getDefinition(), variable.getType(), DruidColumnHandle.DruidColumnType.REGULAR) : new DruidColumnHandle(variable, DruidColumnHandle.DruidColumnType.DERIVED); result.put(variable, handle); }); return result; }
Source:
<code>public void unsubscribe() { State oldState; State newState; do { <START> oldState = state.get(); <END> if (oldState.isUnsubscribed) { return; } newState = oldState.unsubscribe(); } while (!state.compareAndSet(oldState, newState)); unsubscribeActualIfApplicable(newState); }</code><technical_language>field state read a local variable loop</technical_language>

Target:
public void unsubscribe() { State oldState; State newState; final AtomicReference<State> localState = this.state; do { oldState = localState.get(); if (oldState.isUnsubscribed) { return; } newState = oldState.unsubscribe(); } while (!localState.compareAndSet(oldState, newState)); unsubscribeActualIfApplicable(newState); }
Source:
<code>protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } <START> if (getParameters().getOperation() == ImageOperation.Move && getImage().isShareable() && getStorageDomain().getStorageType().equals(StorageType.GLUSTERFS)) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } return true; }</code><technical_language>StorageType is enum - compared ==</technical_language>

Target:
protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } if (getParameters().getOperation() == ImageOperation.Move && getImage().isShareable() && getStorageDomain().getStorageType() == StorageType.GLUSTERFS ) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } return true; }
Source:
<code>public void detonateBomb(Bomb bomb){ bomb.setDetonated(); for (Point p : grid.getAffectedExplosionSquares(bomb)){ for (Entity entity : grid.get(p)){ if (entity.isDestructible()){ if (entity instanceof Player){ killPlayer((Player) entity); <START> } else { <END> grid.remove(entity); } } } } }</code><technical_language>In real game a bomb explosion hits another bomb, detonates of time left...I looked project requirements though, mention this...so simpler leave out anyways</technical_language>

Target:
public synchronized void detonateBomb(Bomb bomb){ bomb.setDetonated(); for (Point p : grid.getAffectedExplosionSquares(bomb)){ for (Entity entity : grid.get(p)){ if (entity instanceof Player){ killPlayer((Player) entity); } else if (entity instanceof Bomb && !((Bomb)entity).isDetonated()){ detonateBomb((Bomb)entity); } else if (entity.isDestructible()){ grid.remove(entity); } } } }
Source:
<code>private static void testListIterator(List<String> test) { ListIterator<String> iterator = test.listIterator(0); assertTrue(iterator.hasNext()); assertFalse(iterator.hasPrevious()); try { iterator.previous(); fail("Should not get here"); } catch (NoSuchElementException e) { } <START> iterator.next(); <END> assertEquals("yo", iterator.next()); assertEquals("yo", iterator.previous()); assertEquals("Hola", iterator.previous()); try { iterator.previous(); fail("Should not get here"); } catch (NoSuchElementException e) { } assertEquals("Hola", iterator.next()); assertEquals("yo", iterator.next()); assertEquals("quiero", iterator.next()); assertEquals("un", iterator.next()); assertEquals("UNSUPPORTEDOPERATIONEXCEPTION!", iterator.next()); try { iterator.next(); fail("Should not get here"); } catch (NoSuchElementException e) { } assertEquals("UNSUPPORTEDOPERATIONEXCEPTION!", iterator.previous()); assertEquals(3, iterator.previousIndex()); assertEquals(4, iterator.nextIndex()); try { iterator.remove(); fail("Should not get here"); } catch (UnsupportedOperationException e) { } try { iterator.set("hej"); fail("Should not get here"); } catch (UnsupportedOperationException e) { } try { iterator.add("hi"); fail("Should not get here"); } catch (UnsupportedOperationException e) { } }</code><technical_language>assert Hola</technical_language>

Target:
private static void testListIterator(List<String> test) { ListIterator<String> iterator = test.listIterator(0); assertTrue(iterator.hasNext()); assertFalse(iterator.hasPrevious()); try { iterator.previous(); fail("Should not get here"); } catch (NoSuchElementException e) { } assertEquals("Hola", iterator.next()); assertEquals("yo", iterator.next()); assertEquals("yo", iterator.previous()); assertEquals("Hola", iterator.previous()); try { iterator.previous(); fail("Should not get here"); } catch (NoSuchElementException e) { } assertEquals("Hola", iterator.next()); assertEquals("yo", iterator.next()); assertEquals("quiero", iterator.next()); assertEquals("un", iterator.next()); assertEquals("UNSUPPORTEDOPERATIONEXCEPTION!", iterator.next()); try { iterator.next(); fail("Should not get here"); } catch (NoSuchElementException e) { } assertEquals("UNSUPPORTEDOPERATIONEXCEPTION!", iterator.previous()); assertEquals(3, iterator.previousIndex()); assertEquals(4, iterator.nextIndex()); try { iterator.remove(); fail("Should not get here"); } catch (UnsupportedOperationException e) { } try { iterator.set("hej"); fail("Should not get here"); } catch (UnsupportedOperationException e) { } try { iterator.add("hi"); fail("Should not get here"); } catch (UnsupportedOperationException e) { } }
Source:
<code>public void write_record_bulk() { RecordStorage<I> storage = getStorage(); int bulkSize = 5; Map<I, EntityRecordWithColumns> initial = new HashMap<>(bulkSize); for (int i = 0; i < bulkSize; i++) { I id = newId(); EntityRecord record = newStorageRecord(id); initial.put(id, EntityRecordWithColumns.of(record)); } storage.write(initial); Collection<EntityRecord> actual = newArrayList( storage.readMultiple(initial.keySet()) ); Collection<EntityRecord> expected = <START> Collections2.transform(initial.values(), EntityRecordWithColumns::getRecord); <END> assertEquals(expected.size(), actual.size()); assertTrue(actual.containsAll(expected)); close(storage); }</code><technical_language>Please replace Stream API</technical_language>

Target:
public void write_record_bulk() { RecordStorage<I> storage = getStorage(); int bulkSize = 5; Map<I, EntityRecordWithColumns> initial = new HashMap<>(bulkSize); for (int i = 0; i < bulkSize; i++) { I id = newId(); EntityRecord record = newStorageRecord(id); initial.put(id, EntityRecordWithColumns.of(record)); } storage.write(initial); Collection<EntityRecord> actual = newArrayList( storage.readMultiple(initial.keySet()) ); Collection<EntityRecord> expected = initial.values() .stream() .map(recordWithColumns -> recordWithColumns != null ? recordWithColumns.getRecord() : null) .collect(Collectors.toList()); assertEquals(expected.size(), actual.size()); assertTrue(actual.containsAll(expected)); close(storage); }
Source:
<code>private void onGetCall(Object message, ActorRef self, ActorRef sender) throws ServletParseException { GetCall getCall = (GetCall)message; String location = getCall.getIdentifier(); if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, location: "+location); } if (location != null) { if (logger.isDebugEnabled()) { <START> logger.debug("onGetCall Before: callLocationMap: "+ callLocationMap.toString()); <END> } ActorRef call = callLocationMap.get(location); if (logger.isDebugEnabled()) { logger.debug("onGetCall After: callLocationMap: "+ callLocationMap.toString()); } if(call == null && location.indexOf("@") != -1 && location.indexOf(":") != -1) { if (logger.isDebugEnabled()) { logger.debug("onGetCall Another try on removing the user part from " + location); } int indexOfAt = location.indexOf("@"); int indexOfColumn = location.indexOf(":"); String newLocation = location.substring(0, indexOfColumn+1).concat(location.substring(indexOfAt+1)); call = callLocationMap.get(newLocation); if (logger.isDebugEnabled()) { logger.debug("onGetCall call " + call + " found for new Location " + newLocation); } } if (call != null) { sender.tell(call, sender()); } else { if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, Call is null"); } } } else { if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, GetCall identifier location is null"); } } }</code><technical_language>removed</technical_language>

Target:
private void onGetCall(Object message, ActorRef self, ActorRef sender) throws ServletParseException { GetCall getCall = (GetCall)message; String location = getCall.getIdentifier(); if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, location: "+location); } if (location != null) { ActorRef call = callLocationMap.get(location); if(call == null && location.indexOf("@") != -1 && location.indexOf(":") != -1) { if (logger.isDebugEnabled()) { logger.debug("onGetCall Another try on removing the user part from " + location); } int indexOfAt = location.indexOf("@"); int indexOfColumn = location.indexOf(":"); String newLocation = location.substring(0, indexOfColumn+1).concat(location.substring(indexOfAt+1)); call = callLocationMap.get(newLocation); if (logger.isDebugEnabled()) { logger.debug("onGetCall call " + call + " found for new Location " + newLocation); } } if (call != null) { sender.tell(call, sender()); } else { if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, Call is null"); } } } else { if (logger.isDebugEnabled()) { logger.debug("MonitoringService onGetCall, GetCall identifier location is null"); } } }
Source:
<code>private UnweightedDoubleReservoirSample(UnweightedDoubleReservoirSample other) { this.count = other.count; this.samples = new double[other.samples.length]; <START> System.arraycopy(other.samples, 0, samples, 0, samples.length); <END> }</code><technical_language>Arrays.copyOf: this.samples = Arrays.copyOf(other.samples, other.samples.length);</technical_language>

Target:
private UnweightedDoubleReservoirSample(UnweightedDoubleReservoirSample other) { this.seenCount = other.seenCount; this.samples = Arrays.copyOf(requireNonNull(other.samples, "samples is null"), other.samples.length); }
Source:
<code>private FileStatus[] listFilesInDir(Path path) throws IOException { boolean done = false; int repeat = 0; FileStatus[] files = null; while (!done) { try { files = dataFileSystem.listStatus(path, p -> { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); }); done = true; } catch (IOException e) { if (++repeat == MAX_IO_ERROR_RETRY) { <START> throw e; <END> } dataFileSystem = path.getFileSystem(hiveConf); } } return files; }</code><technical_language>Add error log failed attempts</technical_language>

Target:
private FileStatus[] listFilesInDir(Path path) throws IOException { return dataFileSystem.listStatus(path, p -> { String name = p.getName(); return !name.startsWith("_") && !name.startsWith("."); }); }
Source:
<code>public void canClickOnStyledText() throws Exception { bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText("This is sample text"); bot.button("Clear").click(); styledText.click(0, 5); <START> verifyNotifyClick(); <END> }</code><technical_language>Verify cursor position click</technical_language>

Target:
public void canClickOnStyledText() throws Exception { final int line = 0, column = 5; bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText("This is sample text"); bot.button("Clear").click(); styledText.click(line, column); verifyNotifyClick(0); assertEquals(new Position(line, column), styledText.cursorPosition(true)); verifyNotifyClick(0); }
Source:
<code>private static Map<IFile, Long> createModificationStampMap(List<IResource> files) { Map<IFile, Long> map= new HashMap<IFile, Long>(); <START> for (Iterator<IResource> iter= files.iterator(); iter.hasNext(); ) { <END> IFile file= (IFile)iter.next(); map.put(file, new Long(file.getModificationStamp())); } return map; }</code><technical_language>modern for loop</technical_language>

Target:
private static Map<IFile, Long> createModificationStampMap(List<IResource> files) { Map<IFile, Long> map= new HashMap<IFile, Long>(); for (IResource file : files) { map.put((IFile) file, file.getModificationStamp()); } return map; }
Source:
<code>private boolean firstCollectionOpen() { if (CollectionHelper.hasStorageAccessPermission(this)) { return CollectionHelper.getInstance().getColSafe(this) != null; } else if (mClosedWelcomeMessage) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); return false; } else { new MaterialDialog.Builder(this) .title(R.string.collection_load_welcome_request_permissions_title) .titleGravity(GravityEnum.CENTER) .content(R.string.collection_load_welcome_request_permissions_details) .positiveText(R.string.dialog_ok) .onPositive((innerDialog, innerWhich) -> { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); <START> this.mClosedWelcomeMessage = true; <END> }) .cancelable(false) .canceledOnTouchOutside(false) .show(); return false; } }</code><technical_language>if practice set member variable prior asking system do something, I be</technical_language>

Target:
private boolean firstCollectionOpen() { if (CollectionHelper.hasStorageAccessPermission(this)) { return CollectionHelper.getInstance().getColSafe(this) != null; } else if (mClosedWelcomeMessage) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); return false; } else { new MaterialDialog.Builder(this) .title(R.string.collection_load_welcome_request_permissions_title) .titleGravity(GravityEnum.CENTER) .content(R.string.collection_load_welcome_request_permissions_details) .positiveText(R.string.dialog_ok) .onPositive((innerDialog, innerWhich) -> { this.mClosedWelcomeMessage = true; ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION); }) .cancelable(false) .canceledOnTouchOutside(false) .show(); return false; } }
Source:
<code>public void ValidationStereotypesListClass4Test() { EList<Stereotype> appliedStereotypes = class4.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype3); expectedStereotypes.add(stereotype1); <START> assertEquals(appliedStereotypes, expectedStereotypes); <END> }</code><technical_language>Please add error message</technical_language>

Target:
public void ValidationStereotypesListClass4Test() { EList<Stereotype> appliedStereotypes = class4.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype3); expectedStereotypes.add(stereotype1); assertEquals("The stereotypes applied on the class must be the same as the expected stereotypes.", appliedStereotypes, expectedStereotypes); }
Source:
<code>public boolean hasSameFaultDomains(String host1, String host2) { if (!hostToRackMap.keySet().contains(host1) || !hostToRackMap.keySet().contains(host2)) { hostToRackMap = computeHostToFaultDomainMap(); state.hostToFaultDomainCacheUpdates.incrementAndGet(); } <START> return hostToRackMap.get(host1).toString().equals(hostToRackMap.get(host2).toString()); <END> }</code><technical_language>equals & hashcode implemented for FaultDomain</technical_language>

Target:
public boolean hasSameFaultDomains(String host1, String host2) { if (!hostToRackMap.keySet().contains(host1) || !hostToRackMap.keySet().contains(host2)) { hostToRackMap = computeHostToFaultDomainMap(); hostToFaultDomainCacheUpdates.inc(); } return hostToRackMap.get(host1).equals(hostToRackMap.get(host2)); }
Source:
<code>public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { T v = future.get(timeout, unit); onceToCircuitbreaker.applyOnce(cb -> nanosecondTimer.elapsed( time -> cb.onSuccess(time, TimeUnit.NANOSECONDS))); return v; } catch (CancellationException | InterruptedException e) { onceToCircuitbreaker.applyOnce(cb -> cb.releasePermission()); throw e; } catch (Exception e) { onceToCircuitbreaker.applyOnce(cb -> nanosecondTimer.elapsed( time -> cb.onError(time, TimeUnit.NANOSECONDS, e))); throw e; } finally { <START> future.cancel(true); <END> } }</code><technical_language>catch TimeoutException. I missing. cancel in case</technical_language>

Target:
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { T v = future.get(timeout, unit); onceToCircuitbreaker.applyOnce(cb -> cb.onSuccess(System.nanoTime() - start, TimeUnit.NANOSECONDS)); return v; } catch (CancellationException | InterruptedException e) { onceToCircuitbreaker.applyOnce(cb -> cb.releasePermission()); throw e; } catch (Exception e) { onceToCircuitbreaker.applyOnce(cb -> cb.onError(System.nanoTime() - start, TimeUnit.NANOSECONDS, e)); throw e; } }
Source:
<code>private void installConfigurationFile(String fileLocation, String finalname, boolean override) throws IOException { finalname = substFinalName(finalname); File file = new File(finalname); <START> if (!file.getCanonicalPath().startsWith(System.getProperty("karaf.base"))) { <END> throw new IOException("Configuration file path must be in the container"); } if (file.exists()) { if (!override) { LOGGER.debug("Configuration file already exists, don't override it", finalname); return; } else { LOGGER.info("Configuration file already exists, overriding it", finalname); } } else { LOGGER.info("Creating configuration file {}", finalname); } try ( InputStream is = new BufferedInputStream(new URL(fileLocation).openStream()) ) { if (!file.exists()) { File parentFile = file.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } file.createNewFile(); } try ( FileOutputStream fop = new FileOutputStream(file) ) { StreamUtils.copy(is, fop); } } catch (RuntimeException | MalformedURLException e) { LOGGER.error(e.getMessage()); throw e; } }</code><technical_language>prevent installing a config "karaf.etc" is "karaf.base"</technical_language>

Target:
private void installConfigurationFile(String fileLocation, String finalname, boolean override) throws IOException { finalname = substFinalName(finalname); File file = new File(finalname); if (!file.getCanonicalPath().startsWith(System.getProperty("karaf.etc"))) { throw new IOException("Configuration file path must be in the 'karaf.etc' directory"); } if (file.exists()) { if (!override) { LOGGER.debug("Configuration file already exists, don't override it", finalname); return; } else { LOGGER.info("Configuration file already exists, overriding it", finalname); } } else { LOGGER.info("Creating configuration file {}", finalname); } try ( InputStream is = new BufferedInputStream(new URL(fileLocation).openStream()) ) { if (!file.exists()) { File parentFile = file.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } file.createNewFile(); } try ( FileOutputStream fop = new FileOutputStream(file) ) { StreamUtils.copy(is, fop); } } catch (RuntimeException | MalformedURLException e) { LOGGER.error(e.getMessage()); throw e; } }
Source:
<code>public AsyncHttpClient get() { HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); NettyAsyncHttpClientConfig asyncConfig = injector.getInstance(Key.get(NettyAsyncHttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); NettyAsyncHttpClientIoPoolProvider poolProvider; if (injector.getExistingBinding(Key.get(NettyAsyncHttpClientIoPoolProvider.class, annotation)) != null) { poolProvider = injector.getInstance(Key.get(NettyAsyncHttpClientIoPoolProvider.class, annotation)); <START> log.info("Http Client %s uses private IO thread pool", name); <END> } else { log.info("Http Client %s uses shared IO thread pool", name); poolProvider = injector.getInstance(NettyAsyncHttpClientIoPoolProvider.class); } NettyAsyncHttpClient client = new NettyAsyncHttpClient(name, poolProvider, config, asyncConfig, filters); clients.add(client); return client; }</code><technical_language>I messages debug messages</technical_language>

Target:
public AsyncHttpClient get() { HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); NettyAsyncHttpClientConfig asyncConfig = injector.getInstance(Key.get(NettyAsyncHttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); NettyIoPool ioPool; if (injector.getExistingBinding(Key.get(NettyIoPool.class, annotation)) != null) { ioPool = injector.getInstance(Key.get(NettyIoPool.class, annotation)); log.debug("HttpClient %s uses private IO thread pool", name); } else { log.debug("HttpClient %s uses shared IO thread pool", name); ioPool = injector.getInstance(NettyIoPool.class); } NettyAsyncHttpClient client = new NettyAsyncHttpClient(name, ioPool, config, asyncConfig, filters); clients.add(client); return client; }
Source:
<code><START> protected IStatus run(IProgressMonitor monitor) { <END> if (stopped) { return Status.OK_STATUS; } currentAlpha += increment; if (currentAlpha <= 0) { currentAlpha = 0; } else if (currentAlpha >= 255) { currentAlpha = 255; } Display.getDefault().syncExec(new Runnable() { public void run() { if (stopped) { return; } if (shell.isDisposed()) { stopped = true; return; } shell.setAlpha(currentAlpha); if (fadeListener != null) { fadeListener.faded(shell, currentAlpha); } } }); if (currentAlpha == 0 || currentAlpha == 255) { stopped = true; } reschedule(); return Status.OK_STATUS; }</code><technical_language>![MAJOR](<LINK_1> Cyclomatic Complexity of this method "run" is 13 is greater 10 authorized. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { if (stopped) { return Status.OK_STATUS; } currentAlpha += increment; if (currentAlpha <= 0) { currentAlpha = 0; } else if (currentAlpha >= 255) { currentAlpha = 255; } Display.getDefault().syncExec(new Runnable() { @Override public void run() { if (stopped) { return; } if (shell.isDisposed()) { stopped = true; return; } shell.setAlpha(currentAlpha); if (fadeListener != null) { fadeListener.faded(shell, currentAlpha); } } }); if (currentAlpha == 0 || currentAlpha == 255) { stopped = true; } reschedule(); return Status.OK_STATUS; }
Source:
<code>public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); List<ConnectorFeature> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(testMethod.get()), classRequires.stream()) <START> .distinct() <END> .collect(toImmutableSet()); Set<ConnectorFeature> supportedFeatures = streamOfSupported(testClass) .distinct() .collect(toImmutableSet()); Set<ConnectorFeature> missingFeatures = Sets.difference(requiredFeatures, supportedFeatures); return missingFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(missingFeatures)); }</code><technical_language>need call distinct if collect set</technical_language>

Target:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); List<ConnectorFeature> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(testMethod.get()), classRequires.stream()) .collect(toImmutableSet()); Set<ConnectorFeature> supportedFeatures = streamOfSupported(testClass) .collect(toImmutableSet()); Set<ConnectorFeature> missingFeatures = Sets.difference(requiredFeatures, supportedFeatures); return missingFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(missingFeatures)); }
Source:
<code>private Appender<ILoggingEvent> createAsyncAppender(final Appender<ILoggingEvent> appender) { final AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setContext(_loggerContext); asyncAppender.setDiscardingThreshold(0); asyncAppender.setName("query-log-async"); <START> asyncAppender.setQueueSize(500); <END> asyncAppender.addAppender(appender); return asyncAppender; }</code><technical_language>move 500 a constant? Also, beneficial allow clients set for queue size builder</technical_language>

Target:
private Appender<ILoggingEvent> createAsyncAppender(final Appender<ILoggingEvent> appender) { final AsyncAppender asyncAppender = new AsyncAppender(); asyncAppender.setContext(_loggerContext); asyncAppender.setDiscardingThreshold(0); asyncAppender.setName("query-log-async"); asyncAppender.setQueueSize(QUEUE_SIZE); asyncAppender.addAppender(appender); return asyncAppender; }
Source:
<code>public SubTabNetworkVmView(SearchableDetailModelProvider<PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel> modelProvider) { super(modelProvider); viewRadioGroup = new ViewRadioGroup<>(Arrays.asList(NetworkVmFilter.values())); viewRadioGroup.setSelectedValue(NetworkVmFilter.running); <START> viewRadioGroup.addChangeHandler(selected -> { <END> onRadioButtonChange(selected); }); initTable(); initWidget(getTableContainer()); }</code><technical_language>viewRadioGroup.addChangeHandler(selected -> onRadioButtonChange(selected));</technical_language>

Target:
public SubTabNetworkVmView(SearchableDetailModelProvider<PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel> modelProvider) { super(modelProvider); viewRadioGroup = new ViewRadioGroup<>(Arrays.asList(NetworkVmFilter.values())); viewRadioGroup.setSelectedValue(NetworkVmFilter.running); viewRadioGroup.addChangeHandler(selected -> onRadioButtonChange(selected)); initTable(); initWidget(getTableContainer()); }
Source:
<code>private boolean createSchema() { try { <START> RequestProcessor.sendPostRequestWithFile(CONTROLLER_URL + "/schemas", new File(_schemaFileName)); <END> return true; } catch (Exception e) { System.out.println(e.getMessage()); return false; } }</code><technical_language>ControllerRequestURLBuilder.baseUrl(CONTROLLER_URL).forSchemaCreate() for table creation/deletion, constructor ControllerRequestURLBuilder (If not, please add there)</technical_language>

Target:
private boolean createSchema() { try { ControllerTest.sendPostRequest( ControllerRequestURLBuilder.baseUrl(ClusterDescriptor.CONTROLLER_URL).forSchemaCreate(), FileUtils.readFileToString(new File(_schemaFileName))); return true; } catch (IOException e) { LOGGER.error("Failed to create schema with file: {}", _schemaFileName, e); return false; } }
Source:
<code>public void enableCertFileReloading() throws IOException { LOG.info("enabling cert file reloading"); ZKConfig config = new ZKConfig(); String keyStoreLocation = config.getProperty(sslKeystoreLocationProperty); if (keyStoreLocation != null && !keyStoreLocation.isEmpty()) { final Path filePath = Paths.get(keyStoreLocation).toAbsolutePath(); Path parentPath = filePath.getParent(); if (parentPath == null) { throw new IOException( "Key store path does not have a parent: " + filePath); } FileChangeWatcher newKeyStoreFileWatcher = new FileChangeWatcher( parentPath, watchEvent -> { handleWatchEvent(filePath, watchEvent); }); if (keyStoreFileWatcher != null) { keyStoreFileWatcher.stop(); } keyStoreFileWatcher = newKeyStoreFileWatcher; keyStoreFileWatcher.start(); } String trustStoreLocation = config.getProperty(sslTruststoreLocationProperty); <START> if (trustStoreLocation != null && !trustStoreLocation.isEmpty()) { <END> final Path filePath = Paths.get(trustStoreLocation).toAbsolutePath(); Path parentPath = filePath.getParent(); if (parentPath == null) { throw new IOException( "Trust store path does not have a parent: " + filePath); } FileChangeWatcher newTrustStoreFileWatcher = new FileChangeWatcher( parentPath, watchEvent -> { handleWatchEvent(filePath, watchEvent); }); if (trustStoreFileWatcher != null) { trustStoreFileWatcher.stop(); } trustStoreFileWatcher = newTrustStoreFileWatcher; trustStoreFileWatcher.start(); } }</code><technical_language>This logic is redundant extracted in a separate method</technical_language>

Target:
public void enableCertFileReloading() throws IOException { LOG.info("enabling cert file reloading"); ZKConfig config = new ZKConfig(); FileChangeWatcher newKeyStoreFileWatcher = newFileChangeWatcher(config.getProperty(sslKeystoreLocationProperty)); if (newKeyStoreFileWatcher != null) { if (keyStoreFileWatcher != null) { keyStoreFileWatcher.stop(); } keyStoreFileWatcher = newKeyStoreFileWatcher; keyStoreFileWatcher.start(); } FileChangeWatcher newTrustStoreFileWatcher = newFileChangeWatcher(config.getProperty(sslTruststoreLocationProperty)); if (newTrustStoreFileWatcher != null) { if (trustStoreFileWatcher != null) { trustStoreFileWatcher.stop(); } trustStoreFileWatcher = newTrustStoreFileWatcher; trustStoreFileWatcher.start(); } }
Source:
<code>Executor getRenamedFilesExecutor(final File file, String sinceRevision) throws IOException { String abs = file.getCanonicalPath(); String filename = ""; if (abs.length() > directoryName.length()) { filename = abs.substring(directoryName.length() + 1); } ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); List<String> cmd = new ArrayList<>(); cmd.add(RepoCommand); cmd.add("log"); <START> cmd.add("-M8"); END> cmd.add("--summary"); cmd.add(ABBREV_LOG); cmd.add("--name-status"); cmd.add("--oneline"); if (file.isFile()) { cmd.add("--follow"); } if (sinceRevision != null) { cmd.add(sinceRevision + ".."); } if (filename.length() > 0) { cmd.add("--"); cmd.add(filename); } return new Executor(cmd, new File(getDirectoryName()), sinceRevision != null); }</code><technical_language>100%</technical_language>

Target:
Executor getRenamedFilesExecutor(final File file, String sinceRevision) throws IOException { ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); List<String> cmd = new ArrayList<>(); cmd.add(RepoCommand); cmd.add("log"); cmd.add("--find-renames=8"); cmd.add("--summary"); cmd.add(ABBREV_LOG); cmd.add("--name-status"); cmd.add("--oneline"); if (file.isFile()) { cmd.add("--follow"); } if (sinceRevision != null) { cmd.add(sinceRevision + ".."); } if (file.getCanonicalPath().length() > directoryName.length() + 1) { cmd.add("--"); cmd.add(file.getCanonicalPath().substring(directoryName.length() + 1)); } return new Executor(cmd, new File(getDirectoryName()), sinceRevision != null); }
Source:
<code>protected void executeCommand() { switch (getDisk().getDiskStorageType()) { case IMAGE: if (getDisk().getContentType() == DiskContentType.MEMORY_DUMP_VOLUME || getDisk().getContentType() == DiskContentType.MEMORY_METADATA_VOLUME) { removeMemoryDiskFromSnapshotIfNeeded(); <START> } <END> ActionReturnValue actionReturnValue = runInternalActionWithTasksContext(ActionType.RemoveImage, buildRemoveImageParameters(getDiskImage())); if (actionReturnValue.getSucceeded()) { incrementVmsGeneration(); getReturnValue().getVdsmTaskIdList().addAll(actionReturnValue.getInternalVdsmTaskIdList()); setSucceeded(true); } break; case LUN: removeLunDisk(); break; case CINDER: RemoveCinderDiskParameters params = new RemoveCinderDiskParameters(getParameters().getDiskId()); params.setEndProcedure(EndProcedure.COMMAND_MANAGED); Future<ActionReturnValue> future = CommandCoordinatorUtil.executeAsyncCommand( ActionType.RemoveCinderDisk, params, cloneContextAndDetachFromParent()); try { setReturnValue(future.get()); setSucceeded(getReturnValue().getSucceeded()); } catch (InterruptedException | ExecutionException e) { log.error("Error removing Cinder disk '{}': {}", getDiskImage().getDiskAlias(), e.getMessage()); log.debug("Exception", e); } break; } }</code><technical_language>well, if user is remove a disk I guess is important for snapshot memory in case removal fails. yet, is a bit awkward update if call in #373 fails, it? moving #377 - end-action phase</technical_language>

Target:
protected void executeCommand() { switch (getDisk().getDiskStorageType()) { case IMAGE: ActionReturnValue actionReturnValue = runInternalActionWithTasksContext(ActionType.RemoveImage, buildRemoveImageParameters(getDiskImage())); if (actionReturnValue.getSucceeded()) { if (getDisk().getContentType() == DiskContentType.MEMORY_DUMP_VOLUME || getDisk().getContentType() == DiskContentType.MEMORY_METADATA_VOLUME) { removeMemoryDiskFromSnapshotIfNeeded(); } incrementVmsGeneration(); getReturnValue().getVdsmTaskIdList().addAll(actionReturnValue.getInternalVdsmTaskIdList()); setSucceeded(true); } break; case LUN: removeLunDisk(); break; case CINDER: RemoveCinderDiskParameters params = new RemoveCinderDiskParameters(getParameters().getDiskId()); params.setEndProcedure(EndProcedure.COMMAND_MANAGED); Future<ActionReturnValue> future = CommandCoordinatorUtil.executeAsyncCommand( ActionType.RemoveCinderDisk, params, cloneContextAndDetachFromParent()); try { setReturnValue(future.get()); setSucceeded(getReturnValue().getSucceeded()); } catch (InterruptedException | ExecutionException e) { log.error("Error removing Cinder disk '{}': {}", getDiskImage().getDiskAlias(), e.getMessage()); log.debug("Exception", e); } break; } }
Source:
<code><START> public HostNetworkQos <END> selectQos(NetworkAttachment networkAttachment, HostNetworkQos daoHostNetworkQos) { return networkAttachment != null && networkAttachment.isQosOverridden() ? HostNetworkQos.fromAnonymousHostNetworkQos(networkAttachment.getHostNetworkQos()) : daoHostNetworkQos; }</code><technical_language>public required, vdsbroker</technical_language>

Target:
HostNetworkQos selectQos(NetworkAttachment networkAttachment, HostNetworkQos daoHostNetworkQos) { return networkAttachment != null && networkAttachment.isQosOverridden() ? HostNetworkQos.fromAnonymousHostNetworkQos(networkAttachment.getHostNetworkQos()) : daoHostNetworkQos; }
Source:
<code>public void add(double value, double weight) { final Map<Double, Long> breakdown = breakdowns.get(getIndexForValue(value)); breakdown.put( weight, <START> breakdown.getOrDefault(weight, Long.valueOf(0)) + Long.valueOf(1)); <END> }</code><technical_language>primitive types? suggestion breakdown.getOrDefault(weight, 0) + 1);</technical_language>

Target:
public void add(double value, double weight) { System.out.println(this + " adding " + value + " -> " + weight + "; " + getIndexForValue(value)); breakdowns[getIndexForValue(value)].add(weight, 1); }