auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static int[] stringsToIntegers(String[] strings) { if (strings == null) { return new int[0]; } <START> return Arrays.stream(strings).map(x -> { <END> try { return OptionalInt.of(Integer.parseInt(x)); } catch (NumberFormatException e) { return OptionalInt.empty(); } }).filter(OptionalInt::isPresent).mapToInt(OptionalInt::getAsInt).toArray(); }</code><technical_language>I appreciate a nice stream function I suspect this is efficient method covnert integer strings int. instance is wrapped optional fo filter out non-parsable again</technical_language>

Target:
private static int[] stringsToIntegers(String[] strings) { if (strings == null) { return new int[0]; } return Arrays.stream(strings).map(x -> { try { return Integer.parseInt(x); } catch (NumberFormatException e) { return null; } }).filter(Objects::nonNull).mapToInt(x -> x).toArray(); }
Source:
<code>protected InternalCompletableFuture<Boolean> callRemoveAsync(K key, Data keyData, Data oldValueData, boolean withCompletionEvent, BiConsumer<Boolean, Throwable> statsCallback) { InternalCompletableFuture<Boolean> future = super.callRemoveAsync(key, keyData, oldValueData, withCompletionEvent, null); future.whenCompleteAsync((removed, throwable) -> { try { if (statsCallback != null) { statsCallback.accept(removed, throwable); } } finally { invalidateNearCache(toNearCacheKey(key, keyData)); } }); <START> return future; <END> }</code><technical_language>return future returned whenCompleteAsync. Check other usages in this other proxies return right future, byUpdatingNearCacheAsync</technical_language>

Target:
protected CompletableFuture<Boolean> callRemoveAsync(K key, Data keyData, Data oldValueData, boolean withCompletionEvent, BiConsumer<Boolean, Throwable> statsCallback) { CompletableFuture<Boolean> future = super.callRemoveAsync(key, keyData, oldValueData, withCompletionEvent, null); return future.whenCompleteAsync((removed, throwable) -> { try { if (statsCallback != null) { statsCallback.accept(removed, throwable); } } finally { invalidateNearCache(toNearCacheKey(key, keyData)); } }); }
Source:
<code>public void test() throws Exception { final UriPage uri = new UriPage("uri?offset=god&limit=10"); final UriComponentsBuilder builder = fromUriString("/this/is/{template}").query("other=false"); uri.updateWithPageParams(builder); <START> uri.updateWithPageParams(builder); <END> uri.updateWithPageParams(builder); final UriComponents components = builder.build(); assertThat(components, is(notNullValue())); assertThat(components.getPath(), is("/this/is/{template}")); assertThat(components.getQueryParams(), hasEntry("other", singletonList("false"))); assertThat(components.getQueryParams(), hasEntry("offset", singletonList("god"))); assertThat(components.getQueryParams(), hasEntry("limit", singletonList("10"))); }</code><technical_language>do need this if testUpdateWithPageParamsIdempotency</technical_language>

Target:
public void test() throws Exception { final UriPage uri = new UriPage("uri?offset=god&limit=10"); final UriComponentsBuilder builder = fromUriString("/this/is/{template}").query("other=false"); uri.updateWithPageParams(builder); final UriComponents components = builder.build(); assertThat(components, is(notNullValue())); assertThat(components.getPath(), is("/this/is/{template}")); assertThat(components.getQueryParams(), hasEntry("other", singletonList("false"))); assertThat(components.getQueryParams(), hasEntry("offset", singletonList("god"))); assertThat(components.getQueryParams(), hasEntry("limit", singletonList("10"))); }
Source:
<code>public NonAnnotatedVariantsMongoReader(MongoOperations template, String collectionsVariantsName, String studyId) throws JobParametersInvalidException { if (studyId == null) { <START> throw new JobParametersInvalidException("NonAnnotatedVariantsMongoReader needs a non-null studyId " + <END> "(it can take a studyId or an empty string for reading every study)"); } setTemplate(template); setCollection(collectionsVariantsName); BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start(); if (!studyId.isEmpty()) { queryBuilder.add(STUDY_KEY, studyId); } DBObject query = queryBuilder.add("annot.ct.so", new BasicDBObject("$exists", false)).get(); setQuery(query); String[] fields = { "chr", "start", "end", "ref", "alt" }; setFields(fields); }</code><technical_language>exception type thrown for incorrect arguments is IllegalArgumentException</technical_language>

Target:
public NonAnnotatedVariantsMongoReader(MongoOperations template, String collectionsVariantsName, String studyId) { if (studyId == null) { throw new IllegalArgumentException("NonAnnotatedVariantsMongoReader needs a non-null studyId " + "(it can take a studyId or an empty string for reading every study)"); } setTemplate(template); setCollection(collectionsVariantsName); BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start(); if (!studyId.isEmpty()) { queryBuilder.add(STUDY_KEY, studyId); } DBObject query = queryBuilder.add("annot.ct.so", new BasicDBObject("$exists", false)).get(); setQuery(query); String[] fields = { "chr", "start", "end", "ref", "alt" }; setFields(fields); }
Source:
<code>public SslHandler newSSLHandler(SocketChannel channel) { <START> throw new UnsupportedOperationException("This is a placeholder, please use newSSLHandler(SocketChannel channel, InetSocketAddress address)"); <END> }</code><technical_language>This break existing code. Instead implementation</technical_language>

Target:
public SslHandler newSSLHandler(SocketChannel channel) { SSLEngine engine = newSSLEngine(channel); return new SslHandler(engine); }
Source:
<code><START> protected VmDevice createDiskVmDevice(final DiskImage diskImage) { <END> final VmDevice vmDevice = new VmDevice(); vmDevice.setIsPlugged(true); vmDevice.setId(new VmDeviceId(diskImage.getimage_group_id(), Guid.NewGuid())); return vmDevice; }</code><technical_language>minor: This private method</technical_language>

Target:
private VmDevice createDiskVmDevice(final DiskImage diskImage) { final VmDevice vmDevice = new VmDevice(); vmDevice.setIsPlugged(true); vmDevice.setId(new VmDeviceId(diskImage.getimage_group_id(), Guid.NewGuid())); return vmDevice; }
Source:
<code>public void onMapClick(@NonNull LatLng point) { final SymbolLayer marker = (SymbolLayer) mapboxMap.getLayer("selected-marker-layer"); final PointF pixel = mapboxMap.getProjection().toScreenLocation(point); List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "marker-layer"); List<Feature> selectedFeature = mapboxMap.queryRenderedFeatures(pixel, "selected-marker-layer"); if (selectedFeature.size() > 0 && markerSelected) { return; } <START> if (features.size() <= 0) { <END> if (markerSelected) { deselectMarker(marker); } return; } FeatureCollection featureCollection = FeatureCollection.fromFeatures( new Feature[]{Feature.fromGeometry(features.get(0).getGeometry())}); GeoJsonSource source = mapboxMap.getSourceAs("selected-marker"); if (source != null) { source.setGeoJson(featureCollection); } if (markerSelected) { deselectMarker(marker); } if (features.size() > 0) { selectMarker(marker); } }</code><technical_language>@cammace isEmpty() instead of <=0</technical_language>

Target:
public void onMapClick(@NonNull LatLng point) { final SymbolLayer marker = (SymbolLayer) mapboxMap.getLayer("selected-marker-layer"); final PointF pixel = mapboxMap.getProjection().toScreenLocation(point); List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, "marker-layer"); List<Feature> selectedFeature = mapboxMap.queryRenderedFeatures(pixel, "selected-marker-layer"); if (selectedFeature.size() > 0 && markerSelected) { return; } if (features.isEmpty()) { if (markerSelected) { deselectMarker(marker); } return; } FeatureCollection featureCollection = FeatureCollection.fromFeatures( new Feature[]{Feature.fromGeometry(features.get(0).getGeometry())}); GeoJsonSource source = mapboxMap.getSourceAs("selected-marker"); if (source != null) { source.setGeoJson(featureCollection); } if (markerSelected) { deselectMarker(marker); } if (features.size() > 0) { selectMarker(marker); } }
Source:
<code>private TaskLockPosse createOrFindLockPosse(Task task, TaskLock taskLock) { giant.lock(); <START> Preconditions.checkArgument( <END> task.getGroupId().equals(taskLock.getGroupId()), "lock groupId[%s] is different from task groupId[%s]", taskLock.getGroupId(), task.getGroupId() ); Preconditions.checkArgument( task.getDataSource().equals(taskLock.getDataSource()), "lock dataSource[%s] is different from task dataSource[%s]", taskLock.getDataSource(), task.getDataSource() ); Preconditions.checkArgument( task.getPriority() == taskLock.getPriority(), "lock priority[%s] is different from task priority[%s]", taskLock.getPriority(), task.getPriority() ); try { return createOrFindLockPosse( taskLock.getType(), task.getId(), taskLock.getGroupId(), taskLock.getDataSource(), taskLock.getInterval(), taskLock.getVersion(), taskLock.getPriority(), taskLock.isRevoked() ); } finally { giant.unlock(); } }</code><technical_language>this throw unlock</technical_language>

Target:
private TaskLockPosse createOrFindLockPosse(Task task, TaskLock taskLock) { giant.lock(); try { Preconditions.checkArgument( task.getGroupId().equals(taskLock.getGroupId()), "lock groupId[%s] is different from task groupId[%s]", taskLock.getGroupId(), task.getGroupId() ); Preconditions.checkArgument( task.getDataSource().equals(taskLock.getDataSource()), "lock dataSource[%s] is different from task dataSource[%s]", taskLock.getDataSource(), task.getDataSource() ); Preconditions.checkArgument( task.getPriority() == taskLock.getPriority(), "lock priority[%s] is different from task priority[%s]", taskLock.getPriority(), task.getPriority() ); return createOrFindLockPosse( taskLock.getType(), task.getId(), taskLock.getGroupId(), taskLock.getDataSource(), taskLock.getInterval(), taskLock.getVersion(), taskLock.getPriority(), taskLock.isRevoked() ); } finally { giant.unlock(); } }
Source:
<code>public SshdSession getSession(URIish urIish, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { try { this.uri = urIishToUri(urIish); AuthenticationConfiguration config = CLIENT.getAuthenticationConfiguration(this.uri, context); CredentialCallback locationCallback = new CredentialCallback(SSHCredential.class, null); CredentialCallback keyPairCallback = new CredentialCallback(KeyPairCredential.class, null); Callback[] callbacks = {locationCallback, keyPairCallback}; CLIENT.getCallbackHandler(config).handle(callbacks); if (locationCallback.getCredential() != null) { SSHCredential sshCredential = locationCallback.getCredential().castAs(SSHCredential.class); this.setSshDirectory(sshCredential.getSshDirectory()); this.defaultIdentities = sshCredential.getPrivateKeyIdentities(); this.knownHostsFile = sshCredential.getKnownHostsFile(); <START> } <END> if (keyPairCallback.getCredential() != null) { KeyPairCredential keyPairCredential = keyPairCallback.getCredential().castAs(KeyPairCredential.class); this.keyPair = keyPairCredential.getKeyPair(); } } catch (IOException | UnsupportedCallbackException | URISyntaxException ex) { ServerLogger.ROOT_LOGGER.failedToLoadSSHCredentials(ex, ex.getMessage()); } return super.getSession(urIish, credentialsProvider, fs, tms); }</code><technical_language>I try handle locationCallback if locationCallback.getCredential() returns null, try handle other callback</technical_language>

Target:
public SshdSession getSession(URIish urIish, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { if (context == null) return super.getSession(urIish, credentialsProvider, fs, tms); try { this.uri = urIishToUri(urIish); AuthenticationConfiguration config = CLIENT.getAuthenticationConfiguration(this.uri, context); CredentialCallback locationCallback = new CredentialCallback(SSHCredential.class, null); CredentialCallback keyPairCallback = new CredentialCallback(KeyPairCredential.class, null); Callback[] callbacks = {locationCallback, keyPairCallback}; CLIENT.getCallbackHandler(config).handle(callbacks); if (locationCallback.getCredential() != null) { SSHCredential sshCredential = locationCallback.getCredential().castAs(SSHCredential.class); this.setSshDirectory(sshCredential.getSshDirectory()); this.defaultIdentities = sshCredential.getPrivateKeyIdentities(); this.knownHostsFile = sshCredential.getKnownHostsFile(); } if (keyPairCallback.getCredential() != null) { KeyPairCredential keyPairCredential = keyPairCallback.getCredential().castAs(KeyPairCredential.class); this.keyPair = keyPairCredential.getKeyPair(); } } catch (IOException | UnsupportedCallbackException | URISyntaxException ex) { throw ServerLogger.ROOT_LOGGER.failedToLoadSSHCredentials(ex, ex.getMessage()); } return super.getSession(urIish, credentialsProvider, fs, tms); }
Source:
<code>protected void processChild(BulldozerMovePath child, List<BulldozerMovePath> children, Map<Coords, BulldozerMovePath> shortestPathsToCoords) { <START> int alpha = 1; <END> MoveLegalityIndicator mli = isLegalMove((MovePath) child); boolean canLevel = child.needsLeveling() && !mli.outOfBounds && !mli.destinationImpassable && !mli.goingDownTooLow && !mli.goingUpTooHigh && !mli.wheeledTankRestriction && !mli.destinationHasWeakBridge && !mli.groundTankIntoWater; if((!shortestPathsToCoords.containsKey(child.getFinalCoords()) || (movePathComparator.compare(shortestPathsToCoords.get(child.getFinalCoords()), child) > 0)) && (mli.isLegal() || canLevel) && (child.getMpUsed() + child.getLevelingCost() < maximumCost)) { shortestPathsToCoords.put(child.getFinalCoords(), child); children.add(child); } }</code><technical_language>dead code</technical_language>

Target:
protected void processChild(BulldozerMovePath child, List<BulldozerMovePath> children, Map<Coords, BulldozerMovePath> shortestPathsToCoords) { MoveLegalityIndicator mli = isLegalMove((MovePath) child); boolean canLevel = child.needsLeveling() && !mli.outOfBounds && !mli.destinationImpassable && !mli.goingDownTooLow && !mli.goingUpTooHigh && !mli.wheeledTankRestriction && !mli.destinationHasWeakBridge && !mli.groundTankIntoWater; if((!shortestPathsToCoords.containsKey(child.getFinalCoords()) || (movePathComparator.compare(shortestPathsToCoords.get(child.getFinalCoords()), child) > 0)) && (mli.isLegal() || canLevel) && (child.getMpUsed() + child.getLevelingCost() < maximumCost)) { shortestPathsToCoords.put(child.getFinalCoords(), child); children.add(child); } }
Source:
<code>protected int getDetailsBatchSize() { String batchCfg = _configDao.getValue("detail.batch.query.size"); <START> return batchCfg != null ? Integer.parseInt(batchCfg) : 2000; <END> }</code><technical_language>extracting 2000 a constant in class</technical_language>

Target:
protected int getDetailsBatchSize() { String batchCfg = _configDao.getValue("detail.batch.query.size"); return batchCfg != null ? Integer.parseInt(batchCfg) : DEFAULT_BATCH_QUERY_SIZE; }
Source:
<code>public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); <START> ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ); <END> Files.copy( inStream, archiveDestination ); }</code><technical_language>this stream needs closed</technical_language>

Target:
public void addToArchive( Path archiveDestination, DiagnosticsReporterProgressCallback monitor ) throws IOException { long size = fs.getFileSize( source ); InputStream in = fs.openAsInputStream( source ); try ( ProgressAwareInputStream inStream = new ProgressAwareInputStream( in, size, monitor::percentChanged ) ) { Files.copy( inStream, archiveDestination ); } }
Source:
<code>public void visitElement(PsiElement element) { <START> try { <END> if (!(element instanceof MethodReference)) { return; } MethodReference methodReference = (MethodReference) element; PsiElement[] parameters = methodReference.getParameters(); if (parameters.length == 0) { return; } if (!"directive".equals(methodReference.getName())) { return; } Method method = Symfony2InterfacesUtil.getMultiResolvedMethod(methodReference); if (method == null) { return; } if (method.getContainingClass() == null || !availableClasses.contains(method.getContainingClass().getPresentableFQN())) { return; } if (!(parameters[0] instanceof StringLiteralExpression)) { return; } consumer.accept(Pair.create(element, ((StringLiteralExpression) parameters[0]).getContents())); } finally { super.visitElement(element); } }</code><technical_language>please remove this try catch add additional checks if needed</technical_language>

Target:
public void visitElement(PsiElement element) { if (element instanceof MethodReference) { visitMethodReference((MethodReference) element); } super.visitElement(element); }
Source:
<code>public static String getDirName(Props props) { String dirSuffix = props.get("azkaban.flow.nested.path"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { dirSuffix = props.get("azkaban.job.id"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { throw new RuntimeException("azkaban.flow.nested.path and azkaban.job.id were not set"); } } <START> return "_link_" + dirSuffix; <END> }</code><technical_language>name this directory _resources_...</technical_language>

Target:
public static String getDirName(Props props) { String dirSuffix = props.get("azkaban.flow.nested.path"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { dirSuffix = props.get("azkaban.job.id"); if ((dirSuffix == null) || (dirSuffix.length() == 0)) { throw new RuntimeException("azkaban.flow.nested.path and azkaban.job.id were not set"); } } return "_resources_" + dirSuffix; }
Source:
<code>private List<Match> find(String text, int offset, boolean firstOnly) { int textEnd= text.length(); List<Match> matches= new LinkedList<>(); Node node= root; for (int i= offset; i < textEnd; i++) { Character c= Character.valueOf(text.charAt(i)); Node next; while ((next= node.next(c)) == null) { node= node.fail; } node= next; if (node == root) { if (firstOnly && !matches.isEmpty()) { break; } } else { if (firstOnly && !node.hasChildren()) { <START> matches.clear(); <END> matches.add(new MatchResult(node.match, i - node.match.length() + 1)); break; } if (node.match != null) { matches.add(new MatchResult(node.match, i - node.match.length() + 1)); } if (!firstOnly || matches.isEmpty()) { Node out= node.output; while (out != null) { matches.add(new MatchResult(out.match, i - out.match.length() + 1)); out= out.output; } } } } return matches; }</code><technical_language>This easiest fix for me. I problem in while loop fix waited convinced find some solution</technical_language>

Target:
private List<Match> find(String text, int offset, boolean firstOnly) { int textEnd= text.length(); List<Match> matches= new LinkedList<>(); Node node= root; for (int i= offset; i < textEnd; i++) { Character c= Character.valueOf(text.charAt(i)); Node next; while ((next= node.next(c)) == null) { if (firstOnly && !matches.isEmpty()) { return matches; } node= node.fail; } node= next; if (node != root) { if (firstOnly && !node.hasChildren()) { matches.clear(); matches.add(new MatchResult(node.match, i - node.match.length() + 1)); break; } if (node.match != null) { matches.add(new MatchResult(node.match, i - node.match.length() + 1)); } if (!firstOnly || matches.isEmpty()) { Node out= node.output; while (out != null) { matches.add(new MatchResult(out.match, i - out.match.length() + 1)); out= out.output; } } } } return matches; }
Source:
<code>public static boolean mkdirsIfSaveable(File dir) { <START> if (NO_FILE_CREATION) { <END> return false; } Path path = dir.toPath(); Optional<Path> savesDirOpt = getCurrentSavesDirectory(); if (!savesDirOpt.isPresent()) { return dir.mkdirs(); } Path savesDir = savesDirOpt.get(); if (path.startsWith(savesDir) && !path.equals(savesDir)) { Path worldName = savesDir.relativize(path).getName(0); WorldProperties props; if (worldPropertiesByFolderName.containsKey(worldName.toString())) { props = worldPropertiesByFolderName.get(worldName.toString()); } else if (worldPropertiesByWorldUuid.size() == 1) { props = worldPropertiesByWorldUuid.values().iterator().next(); } else { Optional<WorldProperties> overworld = Sponge.getServer().getDefaultWorld(); if (!overworld.isPresent()) { return dir.mkdirs(); } props = overworld.get(); } if (props.getSerializationBehavior() == SerializationBehaviors.NONE) { return false; } } return dir.mkdirs(); }</code><technical_language>If do end making this a PhaseTracker.getCurrentState().allowsFileCreation() check, is a case this checked for threadedness</technical_language>

Target:
public static boolean mkdirsIfSaveable(File dir) { if (PhaseTracker.getInstance().getSidedThread() == Thread.currentThread()) { IPhaseState state = PhaseTracker.getInstance().getCurrentState(); if (!state.shouldCreateWorldDirectories(PhaseTracker.getInstance().getCurrentContext())) { return false; } } Path path = dir.toPath(); Optional<Path> savesDirOpt = getCurrentSavesDirectory(); if (!savesDirOpt.isPresent()) { return dir.mkdirs(); } Path savesDir = savesDirOpt.get(); if (path.startsWith(savesDir) && !path.equals(savesDir)) { Path worldName = savesDir.relativize(path).getName(0); WorldProperties props; if (worldPropertiesByFolderName.containsKey(worldName.toString())) { props = worldPropertiesByFolderName.get(worldName.toString()); } else if (worldPropertiesByWorldUuid.size() == 1) { props = worldPropertiesByWorldUuid.values().iterator().next(); } else { Optional<WorldProperties> overworld = Sponge.getServer().getDefaultWorld(); if (!overworld.isPresent()) { return dir.mkdirs(); } props = overworld.get(); } if (props.getSerializationBehavior() == SerializationBehaviors.NONE) { return false; } } return dir.mkdirs(); }
Source:
<code>public static String getFileName(String compressedName) { compressedName = compressedName.toLowerCase(); <START> if(isZip(compressedName) || isTar(compressedName) || isRar(compressedName) || compressedName.endsWith(fileExtensionGzipTarShort)) { <END> return compressedName.substring(0, compressedName.lastIndexOf(".")); } else if (isGzippedTar(compressedName)) { return compressedName.substring(0, Utils.nthToLastCharIndex(2, compressedName, '.')); } else { return compressedName; } }</code><technical_language>isGzip</technical_language>

Target:
public static String getFileName(String compressedName) { compressedName = compressedName.toLowerCase(); if(isZip(compressedName) || isTar(compressedName) || isRar(compressedName) || isGzippedTarShort(compressedName)) { return compressedName.substring(0, compressedName.lastIndexOf(".")); } else if (isGzippedTar(compressedName)) { return compressedName.substring(0, Utils.nthToLastCharIndex(2, compressedName, '.')); } else { return compressedName; } }
Source:
<code>protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } if (!isSupportedByManagedBlockStorageDomain(getStorageDomain())) { return false; } boolean moveOrCopy = isMoveOperation() || isCopyOperation(); if (moveOrCopy && getImage().isShareable() && getStorageDomain().getStorageType() == StorageType.GLUSTERFS ) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if ( <START> moveOrCopy && getImage().isShareable() && <END> getStorageDomain().getStorageType().isBlockDomain() && getImage().getVolumeType() == VolumeType.Sparse ) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_OR_COPY_SHAREABLE_THIN_DISK_TO_ISCSI, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if (isMoveOperation()) { if (getImage().getStorageIds().contains(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_ALREADY_CONTAINS_THE_DISK); } } return true; }</code><technical_language>Code duplication: 2 conditions "moveOrCopy && getImage().isShareable()" a separate "if" statement another 2 "if" statements rest of conditions</technical_language>

Target:
protected boolean validateDestStorage() { StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain()); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.domainIsValidDestination())) { return false; } if (!isSupportedByManagedBlockStorageDomain(getStorageDomain())) { return false; } boolean moveOrCopy = isMoveOperation() || isCopyOperation(); if (moveOrCopy && getImage().isShareable()) { if (getStorageDomain().getStorageType() == StorageType.GLUSTERFS) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } if (getStorageDomain().getStorageType().isBlockDomain() && getImage().getVolumeType() == VolumeType.Sparse) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CANT_MOVE_OR_COPY_SHAREABLE_THIN_DISK_TO_ISCSI, String.format("$%1$s %2$s", "diskAlias", getImage().getDiskAlias())); } } if (isMoveOperation()) { if (getImage().getStorageIds().contains(getStorageDomainId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_DESTINATION_STORAGE_DOMAIN_ALREADY_CONTAINS_THE_DISK); } } return true; }
Source:
<code>public List<Location> getLocationsByType(final Integer type, final int start, final int numOfRows) throws MiddlewareQueryException { <START> final List<String> methods = Arrays.asList(COUNT_BY_TYPE, GET_BY_TYPE); <END> return this.getFromCentralAndLocalByMethod(this.getLocationDao(), methods, start, numOfRows, new Object[] { type }, new Class[] { Integer.class }); }</code><technical_language>replace LocationDataManagerImpl.GET_BY_TYPE LocationDataManagerImpl.COUNT_BY_TYPE</technical_language>

Target:
public List<Location> getLocationsByType(final Integer type, final int start, final int numOfRows) throws MiddlewareQueryException { final List<String> methods = Arrays.asList(LocationDataManagerImpl.COUNT_BY_TYPE, LocationDataManagerImpl.GET_BY_TYPE); return this.getFromCentralAndLocalByMethod(this.getLocationDao(), methods, start, numOfRows, new Object[] { type }, new Class[] { Integer.class }); }
Source:
<code>public void pull(PullFilters pullFilters, IPullController.Callback callback) { Log.d(TAG, "Starting PULL process..."); callback.onStep(PullStep.METADATA); try { mPullController.populateMetadataFromCsvs(pullFilters.isDemo()); <START> if (isNetworkAvailable()) { <END> checkCSVVersion(callback); } if(!pullFilters.isDemo()) { mPullController.pullData(pullFilters, new ArrayList<OrganisationUnit>(), callback); }else{ mPullController.onPullDataComplete(callback, true); callback.onComplete(); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); callback.onError(ex); } }</code><technical_language>I checkCSVVersion invoked previously populateMetadataFromCsvs</technical_language>

Target:
public void pull(PullFilters pullFilters, IPullController.Callback callback) { Log.d(TAG, "Starting PULL process..."); callback.onStep(PullStep.METADATA); try { if (isNetworkAvailable()) { checkCSVVersion(callback, pullFilters); } if(!pullFilters.isDemo()) { mPullController.pullData(pullFilters, new ArrayList<OrganisationUnit>(), callback); }else{ mPullController.onPullDataComplete(callback, true); callback.onComplete(); } } catch (Exception ex) { Log.e(TAG, "pull: " + ex.getLocalizedMessage()); callback.onError(ex); } }
Source:
<code>public Object[] getElements(Object element) { <START> if (element instanceof Object[]) { <END> return (Object[]) element; } if (element instanceof Collection) { return ((Collection) element).toArray(); } return new Object[0]; }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public Object[] getElements(Object element) { if (element instanceof Object[]) return (Object[]) element; if (element instanceof Collection) return ((Collection) element).toArray(); return new Object[0]; }
Source:
<code>public void setClientMetaData(Map<String, String> clientMetaData) { <START> this.clientMetaData = clientMetaData; <END> }</code><technical_language>create Immutable copy of clientMetadata assign it. java this.clientMetadata = Collections.unmodifiableMap(mutableClientMetadataMap);</technical_language>

Target:
public void setClientMetaData(Map<String, String> clientMetaData) { this.clientMetaData = Collections.unmodifiableMap(clientMetaData); }
Source:
<code><START> public void testUnknownMessage() throws InterruptedException { <END> AgentMessageProcessor processor = new AgentMessageProcessor( new Agent()); processor.processMessage( new Message() { private static final long serialVersionUID = -3312628850227527510L; }); }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testUnknownMessage() { AgentMessageProcessor processor = new AgentMessageProcessor( new Agent()); processor.processMessage( new Message() { private static final long serialVersionUID = -3312628850227527510L; }); }
Source:
<code>public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { StringBuffer command = createCommand(LTTngControlServiceConstants.COMMAND_LIST_KERNEL); ICommandResult result = executeCommand(command.toString(), monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result) && result.getErrorOutput() != null) { int index = 0; while (index < result.getErrorOutput().length) { String line = result.getErrorOutput()[index]; Matcher matcher = LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN.matcher(line); if (matcher.matches()) { return events; } index++; <START> } <END> throw new ExecutionException(Messages.TraceControl_CommandError + LTTngControlServiceConstants.COMMAND_LIST_KERNEL); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }</code><technical_language>highlight this extract a method return bool</technical_language>

Target:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { StringBuffer command = createCommand(LTTngControlServiceConstants.COMMAND_LIST_KERNEL); ICommandResult result = executeCommand(command.toString(), monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (isError(result) && result.getErrorOutput() != null) { if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } throw new ExecutionException(Messages.TraceControl_CommandError + LTTngControlServiceConstants.COMMAND_LIST_KERNEL); } Document document = getDocumentFromStrings(result.getOutput()); NodeList rawEvents = document.getElementsByTagName(MIStrings.EVENT); getBaseEventInfo(rawEvents, events); return events; }
Source:
<code>private void filterAndUpdateStackingEntitlements( Map<Consumer, List<Entitlement>> consumerSortedEntitlements) { Map<Consumer, List<Entitlement>> stackingEntitlements = new HashMap<Consumer, List<Entitlement>>(); for (Consumer consumer : consumerSortedEntitlements.keySet()) { List<Entitlement> ents = consumerSortedEntitlements.get(consumer); if (CollectionUtils.isNotEmpty(ents)) { for (Entitlement ent : ents) { Pool pool = ent.getPool(); if (!"true".equals(pool.getAttributeValue("pool_derived")) && pool.getProduct().hasAttribute("stacking_id")) { <START> if (!stackingEntitlements.containsKey(consumer)) { <END> stackingEntitlements.put(consumer, new ArrayList<Entitlement>()); } stackingEntitlements.get(consumer).add(ent); } } } } for (Entry<Consumer, List<Entitlement>> entry : stackingEntitlements.entrySet()) { if (log.isDebugEnabled()) { log.debug("Found stacking entitlements to delete for consumer: {}", entry.getValue() .size(), entry.getKey()); } Set<String> stackIds = new HashSet<String>(); for (Entitlement ent : entry.getValue()) { stackIds.add(ent.getPool().getStackId()); } List<Pool> subPools = poolCurator.getSubPoolForStackIds(entry.getKey(), stackIds); if (CollectionUtils.isNotEmpty(subPools)) { poolRules.updatePoolsFromStack(entry.getKey(), subPools, true); } } }</code><technical_language>Another place flip this a bit do lookup</technical_language>

Target:
private void filterAndUpdateStackingEntitlements( Map<Consumer, List<Entitlement>> consumerSortedEntitlements) { Map<Consumer, List<Entitlement>> stackingEntitlements = new HashMap<Consumer, List<Entitlement>>(); for (Consumer consumer : consumerSortedEntitlements.keySet()) { List<Entitlement> ents = consumerSortedEntitlements.get(consumer); if (CollectionUtils.isNotEmpty(ents)) { for (Entitlement ent : ents) { Pool pool = ent.getPool(); if (!"true".equals(pool.getAttributeValue("pool_derived")) && pool.getProduct().hasAttribute("stacking_id")) { List<Entitlement> entList = stackingEntitlements.get(consumer); if (entList == null) { entList = new ArrayList<Entitlement>(); stackingEntitlements.put(consumer, entList); } entList.add(ent); } } } } for (Entry<Consumer, List<Entitlement>> entry : stackingEntitlements.entrySet()) { if (log.isDebugEnabled()) { log.debug("Found stacking entitlements to delete for consumer: {}", entry.getValue() .size(), entry.getKey()); } Set<String> stackIds = new HashSet<String>(); for (Entitlement ent : entry.getValue()) { stackIds.add(ent.getPool().getStackId()); } List<Pool> subPools = poolCurator.getSubPoolForStackIds(entry.getKey(), stackIds); if (CollectionUtils.isNotEmpty(subPools)) { poolRules.updatePoolsFromStack(entry.getKey(), subPools, true); } } }
Source:
<code>static String getCleanedDescription(String description) { if (description != null) { description = CharMatcher.javaIsoControl().removeFrom(description); if (description.length() > MAX_DESCRIPTION) { description = description.substring(0, MAX_DESCRIPTION - Client.PADDING) + "..."; } <START> } else { <END> description = ""; } return description; }</code><technical_language>Nitpick: remove if else (saving lines) starting description = MoreObjects.firstNonNull(description, "") right top</technical_language>

Target:
static String getCleanedDescription(String description) { description = MoreObjects.firstNonNull(description, ""); description = CharMatcher.javaIsoControl().removeFrom(description); if (description.length() > MAX_DESCRIPTION) { description = description.substring(0, MAX_DESCRIPTION - Client.PADDING) + "..."; } return description; }
Source:
<code>public void setWrongJsonAsTemplateFile() throws Exception { IRoute route = Mockito.mock(IRoute.class); when(route.getKind()).thenReturn(ResourceKind.ROUTE); when(factory.create(any(InputStream.class))).thenReturn(route); NotATemplateException ex = null; try { <START> model.setLocalTemplateFileName("resources/jboss_infinispan-server_ImageStreamImport.json"); <END> } catch (NotATemplateException e) { ex = e; assertEquals(ResourceKind.ROUTE, e.getResourceKind()); } assertNotNull(ex); }</code><technical_language>simply assertFalse("No NotATemplateException occurred") here, leaving out more complicated assertion ex variable</technical_language>

Target:
public void setWrongJsonAsTemplateFile() throws Exception { IRoute route = Mockito.mock(IRoute.class); when(route.getKind()).thenReturn(ResourceKind.ROUTE); when(factory.create(any(InputStream.class))).thenReturn(route); try { model.setLocalTemplateFileName("resources/jboss_infinispan-server_ImageStreamImport.json"); fail("No NotATemplateException occurred"); } catch (NotATemplateException e) { assertEquals(ResourceKind.ROUTE, e.getResourceKind()); } }
Source:
<code>public boolean canEditPipeline(String pipelineName, Username username) { <START> return doesPipelineExist(pipelineName) && pipelineConfigNamed(new CaseInsensitiveString(pipelineName)).getOrigin().canEdit() && isUserAdminOfGroup(username.getUsername(), findGroupNameByPipeline(new CaseInsensitiveString(pipelineName))); <END> }</code><technical_language>doesPipelineExist calls pipelineConfigNamed impact performance. Additionally, doesPipelineExist pipelineConfigNamed, pipeline removed, causing a NPE; implementation more resilient a situation</technical_language>

Target:
public boolean canEditPipeline(String pipelineName, Username username) { PipelineConfig pipelineConfig; try { pipelineConfig = pipelineConfigNamed(new CaseInsensitiveString(pipelineName)); } catch (PipelineNotFoundException e) { return false; } return pipelineConfig != null && pipelineConfig.isLocal() && isUserAdminOfGroup(username.getUsername(), findGroupNameByPipeline(pipelineConfig.name())); }
Source:
<code>private void exportMetacard(File dumpLocation, Metacard metacard) throws IOException, CatalogTransformerException { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(getOutputFile(dumpLocation, metacard)))) { oos.writeObject(new MetacardImpl(metacard)); oos.flush(); } } else { List<BinaryContent> binaryContents; if (metacard != null) { for (MultiMetacardTransformer transformer : transformers) { binaryContents = transformer.transform(Collections.singletonList(metacard), new HashMap<>()); if (CollectionUtils.isNotEmpty(binaryContents)) { try (FileOutputStream fos = new FileOutputStream(getOutputFile(dumpLocation, metacard))) { for (BinaryContent binaryContent : binaryContents) { <START> fos.write(binaryContent.getByteArray()); <END> } } break; } } } } }</code><technical_language>This write multiple files file. If is more binary content need zip files together</technical_language>

Target:
private void exportMetacard(File dumpLocation, Metacard metacard) throws IOException, CatalogTransformerException { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(getOutputFile(dumpLocation, metacard)))) { oos.writeObject(new MetacardImpl(metacard)); oos.flush(); } } else { List<BinaryContent> binaryContents = getTransform() .transform( Collections.singletonList(metacard), transformerId, Collections.emptyMap()); if (CollectionUtils.isNotEmpty(binaryContents)) { if (binaryContents.size() == 1) { try (FileOutputStream fos = new FileOutputStream(getOutputFile(dumpLocation, metacard))) { fos.write(binaryContents.get(0).getByteArray()); } } else { createZip(binaryContents, dumpLocation, metacard); } } } }
Source:
<code>public int getNumberOfEntries() { long flags = EnumUtil.bitSetOf(Flag.CACHE_MODE_LOCAL, Flag.SKIP_CACHE_LOAD); SizeCommand command = commandsFactory.buildSizeCommand(flags); <START> return (Integer) invoker.invoke(icf.createInvocationContext(false, UNBOUNDED), command); <END> }</code><technical_language>if want in memory excluding expired, call dataContainer.size this count expired entries</technical_language>

Target:
public int getNumberOfEntries() { return cache.withFlags(Flag.CACHE_MODE_LOCAL).size(); }
Source:
<code>private void waitTillRefCountZero() throws InterruptedException { if (isActive) { long singleWaitMs = Math.min(500, WAIT_TIME_FOR_CLEANUP_MS); long waitSoFar = 0; List<String> segmentsUnderCompaction = compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction(); for (String segmentName : segmentsUnderCompaction) { while (srcLog.getSegment(segmentName).refCount() > 0 && waitSoFar < WAIT_TIME_FOR_CLEANUP_MS) { time.sleep(singleWaitMs); waitSoFar += singleWaitMs; } if (srcLog.getSegment(segmentName).refCount() > 0) { <START> logger.debug("Ref count of in did not go down to 0", segmentName, dataDir); <END> } } } }</code><technical_language>this more a DEBUG statement? a WARN cleanup is happen regardless</technical_language>

Target:
private void waitTillRefCountZero() throws InterruptedException { if (isActive) { long singleWaitMs = Math.min(500, WAIT_TIME_FOR_CLEANUP_MS); long waitSoFar = 0; List<String> segmentsUnderCompaction = compactionLog.getCompactionDetails().getLogSegmentsUnderCompaction(); for (String segmentName : segmentsUnderCompaction) { while (srcLog.getSegment(segmentName).refCount() > 0 && waitSoFar < WAIT_TIME_FOR_CLEANUP_MS) { time.sleep(singleWaitMs); waitSoFar += singleWaitMs; } if (srcLog.getSegment(segmentName).refCount() > 0) { logger.debug("Ref count of in did not go down to 0", segmentName, storeId); } } } }
Source:
<code>public void emit() { String src = group(1); String formatting = group(2); List<String> positional = new ArrayList<>(); positional.add("alt"); positional.add("width"); positional.add("height"); Map<String, String> properties = getFormattingProperties(formatting, positional); if (!properties.containsKey("alt") || properties.get("alt").isEmpty()) { int end = src.lastIndexOf("."); if (end != -1) { String firstSrc = src.substring(0, end); int start = Math.max(firstSrc.lastIndexOf("/") + 1, 0); properties.put("alt", firstSrc.substring(start)); } else { properties.put("alt", src); } } if (group(0).startsWith("image::")) { Attributes imageSpanAttributes = new Attributes(); imageSpanAttributes.setCssClass("imageblock"); builder.beginBlock(BlockType.DIV, imageSpanAttributes); Attributes contentAttr = new Attributes(); contentAttr.setCssClass("content"); builder.beginBlock(BlockType.DIV, contentAttr); emitImage(builder, src, properties); builder.endBlock(); if (properties.containsKey("title")) { Attributes attr = new Attributes(); attr.setCssClass("title"); builder.beginBlock(BlockType.DIV, attr); if (properties.containsKey("caption")) { builder.characters(properties.get("caption")); } builder.characters(properties.get("title")); builder.endBlock(); } builder.endBlock(); } else { <START> Attributes imageblockattr = new Attributes(); <END> imageblockattr.setCssClass("image"); builder.beginSpan(SpanType.SPAN, imageblockattr); emitImage(builder, src, properties); builder.endSpan(); } }</code><technical_language>camel-case? imageblockattr -> imageBlockAttributes</technical_language>

Target:
public void emit() { String src = group(1); String formatting = group(2); List<String> positional = new ArrayList<>(); positional.add("alt"); positional.add("width"); positional.add("height"); Map<String, String> properties = getFormattingProperties(formatting, positional); if (!properties.containsKey("alt") || properties.get("alt").isEmpty()) { int end = src.lastIndexOf("."); if (end != -1) { String firstSrc = src.substring(0, end); int start = Math.max(firstSrc.lastIndexOf("/") + 1, 0); properties.put("alt", firstSrc.substring(start)); } else { properties.put("alt", src); } } if (group(0).startsWith("image::")) { Attributes imageSpanAttributes = new Attributes(); imageSpanAttributes.setCssClass("imageblock"); builder.beginBlock(BlockType.DIV, imageSpanAttributes); Attributes contentAttr = new Attributes(); contentAttr.setCssClass("content"); builder.beginBlock(BlockType.DIV, contentAttr); emitImage(builder, src, properties); builder.endBlock(); if (properties.containsKey("title")) { Attributes attr = new Attributes(); attr.setCssClass("title"); builder.beginBlock(BlockType.DIV, attr); if (properties.containsKey("caption")) { builder.characters(properties.get("caption")); } builder.characters(properties.get("title")); builder.endBlock(); } builder.endBlock(); } else { Attributes imageBlockAttr = new Attributes(); imageBlockAttr.setCssClass("image"); builder.beginSpan(SpanType.SPAN, imageBlockAttr); emitImage(builder, src, properties); builder.endSpan(); } }
Source:
<code>public void testWarningsParser() throws IOException { Collection<FileAnnotation> warnings = new ClangTidyParser().parse(openFile()); <START> assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 5, warnings.size()); <END> }</code><technical_language>Please verify properties</technical_language>

Target:
public void testWarningsParser() throws IOException { Collection<FileAnnotation> warnings = new ClangTidyParser().parse(openFile()); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 6, warnings.size()); Iterator<FileAnnotation> iterator = warnings.iterator(); FileAnnotation annotation = iterator.next(); checkWarning(annotation, 1, 8, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "src/../src/main.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 10, 20, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "/src/main.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 83, 20, "implicit conversion changes signedness: 'int' to 'uint32_t' (aka 'unsigned int')", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-sign-conversion", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 25, 15, "suggest braces around initialization of subobject", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-missing-braces", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 29, 15, "suggest braces around initialization of subobject", "/path/to/project/src/test2.cpp", TYPE, "clang-diagnostic-missing-braces", Priority.NORMAL); annotation = iterator.next(); checkWarning(annotation, 4, 10, "'dbus/dbus.h' file not found", "/path/to/project/src/error_test.cpp", TYPE, "clang-diagnostic-error", Priority.HIGH); }
Source:
<code>protected LockGranularityDeterminResult determineSegmentGranularity( TaskActionClient client, List<Interval> intervals ) throws IOException { if (requireLockExistingSegments()) { if (isPerfectRollup()) { <START> log.info("Using timeChunk lock for perfrect rollup"); <END> return new LockGranularityDeterminResult(LockGranularity.TIME_CHUNK, intervals, null); } else if (!intervals.isEmpty()) { return determineSegmentGranularity(findSegmentsToLock(client, intervals)); } else { log.info("Using segment lock for empty intervals"); return new LockGranularityDeterminResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } } else { log.info("Using segment lock since we don't have to lock existing segments"); return new LockGranularityDeterminResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } }</code><technical_language>perfrect -> perfect</technical_language>

Target:
private LockGranularityDetermineResult determineSegmentGranularity(TaskActionClient client, List<Interval> intervals) throws IOException { if (requireLockExistingSegments()) { if (isPerfectRollup()) { log.info("Using timeChunk lock for perfect rollup"); return new LockGranularityDetermineResult(LockGranularity.TIME_CHUNK, intervals, null); } else if (!intervals.isEmpty()) { return determineSegmentGranularity(findSegmentsToLock(client, intervals)); } else { log.info("Using segment lock for empty intervals"); return new LockGranularityDetermineResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } } else { log.info("Using segment lock since we don't have to lock existing segments"); return new LockGranularityDetermineResult(LockGranularity.SEGMENT, null, Collections.emptyList()); } }