auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String param(String key) { WebService.Param definition = action.param(key); String value = defaultString(readParam(key, definition), definition.defaultValue()); Integer maximumLength = definition.maximumLength(); if (value != null && maximumLength != null) { int valueLength = value.length(); checkArgument(valueLength <= maximumLength, "'%s' length (%s) is longer than the maximum authorized (%s)", key, valueLength, maximumLength); } <START> String trimmedValue = value == null ? null : CharMatcher.WHITESPACE.trimFrom(value); <END> if (trimmedValue != null) { validateValue(trimmedValue, definition); } return trimmedValue; }</code><technical_language>Suggestion: is trimmed, check length trim operation</technical_language>

Target:
public String param(String key) { WebService.Param definition = action.param(key); String valueOrDefault = defaultString(readParam(key, definition), definition.defaultValue()); String value = valueOrDefault == null ? null : CharMatcher.WHITESPACE.trimFrom(valueOrDefault); if (value == null) { return null; } validatePossibleValues(key, value, definition); validateMaximumLength(key, definition, valueOrDefault); validateMaximumValue(key, definition, value); return value; }
Source:
<code>private void moveControl(MElementContainer<MUIElement> elementContainer, MUIElement element) { if (element == null || elementContainer == null) return; PositionInfo positionInfo = findMovePositionInfo(element); if (positionInfo != null) { List<MUIElement> elements = elementContainer.getChildren(); if (elements.remove(element)) { switch (positionInfo.getPosition()) { case LAST: elements.add(element); break; case FIRST: elements.add(0, element); break; case INDEX: int index = positionInfo.getPositionReferenceAsInteger(); if (index >= 0 && index < elements.size()) { elements.add(index, element); } else { elements.add(element); } break; case BEFORE: case AFTER: int idx = indexOfElementWithID(elements, positionInfo.getPositionReference()); if (idx < 0) { elements.add(element); } else { if (positionInfo.getPosition() == Position.AFTER) { idx++; } if (idx < elements.size()) { elements.add(idx, element); } else { elements.add(element); } } break; default: <START> throw new IllegalArgumentException( <END> "Unknown position: " + positionInfo.getPosition()); } } } }</code><technical_language>If fails out do it, please log error information. WorkbenchPlugin.log(*). Throwing exception kill workbench startup completely</technical_language>

Target:
private void moveControl(MElementContainer<MUIElement> elementContainer, MUIElement element) { if (element == null || elementContainer == null) return; PositionInfo positionInfo = findMovePositionInfo(element); if (positionInfo != null) { List<MUIElement> elements = elementContainer.getChildren(); if (elements.remove(element)) { switch (positionInfo.getPosition()) { case LAST: elements.add(element); break; case FIRST: elements.add(0, element); break; case INDEX: int index = positionInfo.getPositionReferenceAsInteger(); if (index >= 0 && index < elements.size()) { elements.add(index, element); } else { elements.add(element); } break; case BEFORE: case AFTER: int idx = indexOfElementWithID(elements, positionInfo.getPositionReference()); if (idx < 0) { elements.add(element); } else { if (positionInfo.getPosition() == Position.AFTER) { idx++; } if (idx < elements.size()) { elements.add(idx, element); } else { elements.add(element); } } break; default: WorkbenchPlugin.log("Can't position control '" + element.getElementId() + "' because of the unknown position type '" + positionInfo.getPosition() + "'!"); } } } }
Source:
<code>toWorkspaceVolumes(CheContainer container) throws InfrastructureException { Map<String, VolumeImpl> result = new HashMap<>(); if (container.isMountSources()) { result.put(PROJECTS_VOLUME_NAME, new VolumeImpl().withPath(PROJECTS_MOUNT_PATH)); } for (Volume volume : container.getVolumes()) { <START> if (volume.getName().equals(PROJECTS_VOLUME_NAME)) { <END> throw new InfrastructureException( format( "Plugin '%s' tried to manually mount the projects volume into its container '%s'." + " This is illegal. Set the mountSources attribute to true instead. The mount" + " path of the sources will then be available automatically in the " + PROJECTS_MOUNT_PATH_ENV_VAR_NAME + " environment variable.", pluginName, container.getName())); } result.put(volume.getName(), new VolumeImpl().withPath(volume.getMountPath())); } return result; }</code><technical_language>this current plugins allow starting a workspace. elaborate handle that</technical_language>

Target:
toWorkspaceVolumes(CheContainer container) throws InfrastructureException { Map<String, VolumeImpl> result = new HashMap<>(); if (container.isMountSources()) { result.put(PROJECTS_VOLUME_NAME, new VolumeImpl().withPath(projectsRootPathEnvVar.second)); } for (Volume volume : container.getVolumes()) { if (volume.getName().equals(PROJECTS_VOLUME_NAME) && !projectsRootPathEnvVar.second.equals(volume.getMountPath())) { throw new InfrastructureException( format( "Plugin '%s' tried to manually mount the '%s' volume into its container '%s' on" + " path '%s'. This is illegal because sources need to be mounted to '%s'. Set" + " the mountSources attribute to true instead and remove the manual volume" + " mount in the plugin. After that the mount path of the sources will be" + " available automatically in the '%s' environment variable.", pluginId, PROJECTS_VOLUME_NAME, container.getName(), volume.getMountPath(), projectsRootPathEnvVar.second, projectsRootPathEnvVar.first)); } result.put(volume.getName(), new VolumeImpl().withPath(volume.getMountPath())); } return result; }
Source:
<code><START> protected void updateConfigFile(String content, Path configFile) throws IOException { <END> Files.write(configFile, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); }</code><technical_language>reuse this method</technical_language>

Target:
private void updateConfigFile(String content, Path configFile) throws IOException { Files.write(configFile, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); }
Source:
<code>VisibilityCache(FluoConfiguration conf) { visCache = CacheBuilder.newBuilder() <START> .expireAfterAccess(FluoConfigurationImpl.getTxIfoCacheTimeout(conf, TimeUnit.MILLISECONDS), <END> TimeUnit.MILLISECONDS) .maximumWeight(FluoConfigurationImpl.getVisibilityCacheSize(conf)).weigher(new VisWeigher()) .concurrencyLevel(10).build(); }</code><technical_language>This call getVisibilityCacheTimeout()</technical_language>

Target:
VisibilityCache(FluoConfiguration conf) { visCache = CacheBuilder.newBuilder() .expireAfterAccess(FluoConfigurationImpl.getVisibilityCacheTimeout(conf, TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) .maximumWeight(FluoConfigurationImpl.getVisibilityCacheSize(conf)).weigher(new VisWeigher()) .concurrencyLevel(10).build(); }
Source:
<code>public static boolean handlePistonEvent(IMixinWorldServer world, WorldServer.ServerBlockEventList list, Object obj, BlockPos pos, Block blockIn, int eventId, int eventParam) { boolean extending = (eventId == 0); final IBlockState blockstate = ((net.minecraft.world.World)world).getBlockState(pos); EnumFacing direction = (EnumFacing) blockstate.getValue(BlockDirectional.FACING); List<BlockPos> blocks = new ArrayList<BlockPos>(); blocks.add(pos); BlockPistonStructureHelper movedBlocks = new BlockPistonStructureHelper((WorldServer) (Object) world, pos, direction, extending); movedBlocks.canMove(); List<BlockPos> blocksToAdd = new ArrayList<BlockPos>(); blocksToAdd.addAll(movedBlocks.getBlocksToDestroy()); blocksToAdd.addAll(movedBlocks.getBlocksToMove()); <START> for (BlockPos add : blocksToAdd) { END> boolean duplicate = false; for (BlockPos equals : blocks) { if (equals.getX() == add.getX() && equals.getY() == add.getY() && equals.getZ() == add.getZ()) { duplicate = true; } } if (!duplicate) blocks.add(add); } List<Location<org.spongepowered.api.world.World>> locations = new ArrayList<Location<org.spongepowered.api.world.World>>(); for (BlockPos block : blocks) { locations.add(new Location<>((World)world, block.getX(), block.getY(), block.getZ())); } String namedCause = extending ? NamedCause.PISTON_EXTEND : NamedCause.PISTON_RETRACT; return SpongeCommonEventFactory.callChangeBlockEventPre(world, ImmutableList.copyOf(locations), NamedCause.of(namedCause, world), ((World) world).createSnapshot(pos.getX(), pos.getY(), pos.getZ())).isCancelled(); }</code><technical_language>this unnecessarily complicated filter... simplify this a simple for loop of movedBlocks.getBlocksToMove while creating new Location objects</technical_language>

Target:
public static boolean handlePistonEvent(IMixinWorldServer world, WorldServer.ServerBlockEventList list, Object obj, BlockPos pos, Block blockIn, int eventId, int eventParam) { boolean extending = (eventId == 0); final IBlockState blockstate = ((net.minecraft.world.World) world).getBlockState(pos); EnumFacing direction = (EnumFacing) blockstate.getValue(BlockDirectional.FACING); HashSet<Location<org.spongepowered.api.world.World>> locations = new HashSet<Location<org.spongepowered.api.world.World>>(); locations.add(new Location<>((World) world, pos.getX(), pos.getY(), pos.getZ())); BlockPistonStructureHelper movedBlocks = new BlockPistonStructureHelper((WorldServer) (Object) world, pos, direction, extending); movedBlocks.canMove(); Stream.concat(movedBlocks.getBlocksToMove().stream(), movedBlocks.getBlocksToDestroy().stream()) .map(block -> new Location<>((World) world, block.getX(), block.getY(), block.getZ())) .collect(Collectors.toCollection(() -> locations)); String namedCause = extending ? NamedCause.PISTON_EXTEND : NamedCause.PISTON_RETRACT; return SpongeCommonEventFactory.callChangeBlockEventPre(world, ImmutableList.copyOf(locations), NamedCause.of(namedCause, world), ((World) world).createSnapshot(pos.getX(), pos.getY(), pos.getZ())).isCancelled(); }
Source:
<code>@Override public void onDeleteFeatureClicked(String featureId) { QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause(String.format("OBJECTID = %s", featureId)); ListenableFuture<FeatureQueryResult> featureQueryResult = mFeatureLayer.getFeatureTable() .queryFeaturesAsync(queryParameters); featureQueryResult.addDoneListener(() -> { try { if (featureQueryResult.get().iterator().hasNext()) { Feature foundFeature = featureQueryResult.get().iterator().next(); <START> deleteFeature(foundFeature, mFeatureTable, () -> { <END> applyEdits(mFeatureTable); }); } } catch (InterruptedException | ExecutionException e) { logToUser(true, getString(R.string.error_feature_deletion, e.getCause().getMessage())); } }); }</code><technical_language>I this lambda moved line {}s</technical_language>

Target:
@Override public void onDeleteFeatureClicked(String featureId) { QueryParameters queryParameters = new QueryParameters(); queryParameters.setWhereClause(String.format("OBJECTID = %s", featureId)); ListenableFuture<FeatureQueryResult> featureQueryResult = mFeatureLayer.getFeatureTable() .queryFeaturesAsync(queryParameters); featureQueryResult.addDoneListener(() -> { try { if (featureQueryResult.get().iterator().hasNext()) { Feature foundFeature = featureQueryResult.get().iterator().next(); deleteFeature(foundFeature, mFeatureTable, () -> applyEdits(mFeatureTable)); } } catch (InterruptedException | ExecutionException e) { logToUser(true, getString(R.string.error_feature_deletion, e.getCause().getMessage())); } }); }
Source:
<code>public void dispatchEvent(final DistributedObjectEventPacket eventPacket, Object ignore) { String serviceName = eventPacket.getServiceName(); if (eventPacket.getEventType() == CREATED) { try { final ProxyRegistry registry = getOrCreateRegistry(serviceName); if (!registry.contains(eventPacket.getName())) { registry.createProxy(eventPacket.getName(), false, true, true); } } catch (HazelcastInstanceNotActiveException ignored) { ignore(ignored); } } else { final ProxyRegistry registry = registries.get(serviceName); if (registry != null) { <START> registry.destroyProxy(eventPacket.getName(), true); <END> } } }</code><technical_language>true means publish events destroying proxy. Is this intentional</technical_language>

Target:
public void dispatchEvent(final DistributedObjectEventPacket eventPacket, Object ignore) { String serviceName = eventPacket.getServiceName(); if (eventPacket.getEventType() == CREATED) { try { final ProxyRegistry registry = getOrCreateRegistry(serviceName); if (!registry.contains(eventPacket.getName())) { registry.createProxy(eventPacket.getName(), true, true); } } catch (HazelcastInstanceNotActiveException ignored) { ignore(ignored); } } else { final ProxyRegistry registry = registries.get(serviceName); if (registry != null) { registry.destroyProxy(eventPacket.getName(), false); } } }
Source:
<code>public FileMockContext(Context context) { mContext = context; <START> requestedPermissionName = "android.permission.INTERNET"; <END> responsePermissionFlag = PackageManager.PERMISSION_GRANTED; permissionMap.put(requestedPermissionName,responsePermissionFlag); }</code><technical_language>do need requestePermissionName responsePermissionFlag</technical_language>

Target:
public FileMockContext(Context context) { mContext = context; String requestedPermissionName = "android.permission.INTERNET"; int responsePermissionFlag = PackageManager.PERMISSION_GRANTED; permissionMap.put(requestedPermissionName,responsePermissionFlag); }
Source:
<code>public boolean filterOut(final SAMRecord first, final SAMRecord second) { return (readNameFilterSet.contains(first.getReadName()) && <START> readNameFilterSet.contains(second.getReadName())) != includeReads; <END> }</code><technical_language>negation of expression readNameFilterSet.contains(first.getReadName()) && readNameFilterSet.contains(second.getReadName()) is !readNameFilterSet.contains(first.getReadName()) || !readNameFilterSet.contains(second.getReadName()), match version else clause, (!readNameFilterSet.contains(first.getReadName()) && !readNameFilterSet.contains(second.getReadName()))</technical_language>

Target:
public boolean filterOut(final SAMRecord first, final SAMRecord second) { if (includeReads) { if (readNameFilterSet.contains(first.getReadName()) && readNameFilterSet.contains(second.getReadName())) { return false; } } else { if (!readNameFilterSet.contains(first.getReadName()) && !readNameFilterSet.contains(second.getReadName())) { return false; } } return true; }
Source:
<code>private void stopTestingServer() { if (!synapseServer.getLocalServer().isEmpty()) { try { getLog().info("Stopping unit testing agent runs on port " + synapseServer.getUnitTestPort()); if (System.getProperty("os.name").toLowerCase().contains("win")) { Runtime runTime = Runtime.getRuntime(); Process proc = runTime.exec("cmd /c netstat -ano | findstr " + synapseServer.getUnitTestPort()); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); String stream = stdInput.readLine(); if (stream != null) { int index = stream.lastIndexOf(' '); String pid = stream.substring(index); getLog().info("Unit testing agent runs with PID of " + pid); runTime.exec("cmd /c Taskkill /PID" + pid + " /T /F"); } } else { Process pr = Runtime.getRuntime().exec("lsof -t -i:" + synapseServer.getUnitTestPort()); <START> BufferedReader read = new BufferedReader(new InputStreamReader(pr.getInputStream())); <END> String pid = read.readLine(); getLog().info("Unit testing agent runs with PID of " + pid); Runtime.getRuntime().exec("kill -9 " + pid); } getLog().info("Unit testing agent stopped"); } catch (Exception e) { getLog().error("Error in closing the server"); } } }</code><technical_language>BufferedReader closed</technical_language>

Target:
private void stopTestingServer() { String unitTestPort = synapseServer.getUnitTestPort(); if (!synapseServer.getLocalServer().isEmpty()) { try { getLog().info("Stopping unit testing agent runs on port " + unitTestPort); BufferedReader bufferReader; if (System.getProperty("os.name").toLowerCase().contains("win")) { Runtime runTime = Runtime.getRuntime(); Process proc = runTime.exec("cmd /c netstat -ano | findstr " + unitTestPort); bufferReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String stream = bufferReader.readLine(); if (stream != null) { int index = stream.lastIndexOf(' '); String pid = stream.substring(index); getLog().info("Unit testing agent runs with PID of " + pid); runTime.exec("cmd /c Taskkill /PID" + pid + " /T /F"); } } else { Process pr = Runtime.getRuntime().exec("lsof -t -i:" + unitTestPort); bufferReader = new BufferedReader(new InputStreamReader(pr.getInputStream())); String pid = bufferReader.readLine(); getLog().info("Unit testing agent runs with PID of " + pid); Runtime.getRuntime().exec("kill -9 " + pid); } bufferReader.close(); getLog().info("Unit testing agent stopped"); } catch (Exception e) { getLog().error("Error in closing the server", e); } } }
Source:
<code>public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); <START> int serializedSize = walletProto.getSerializedSize(); <END> int bufferSize = serializedSize > this.walletWriteBufferSize ? this.walletWriteBufferSize : serializedSize; final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }</code><technical_language>this forced call slow saving considerably? Do need minimum calculation? hurt pick a larger buffer, no</technical_language>

Target:
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }
Source:
<code>public double getDistanceToPoint(XYPair otherPoint) { <START> return Math.sqrt(Math.pow((otherPoint.x - this.x), 2) + Math.pow((otherPoint.y - this.y), 2)); <END> }</code><technical_language>This more concise subtracting vectors magnitude Math.hypot</technical_language>

Target:
public double getDistanceToPoint(XYPair otherPoint) { XYPair normalizedPoint = this.clone().add(otherPoint.clone().scale(-1)); return normalizedPoint.getMagnitude(); }
Source:
<code>private static void sendBlobStoreControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId, PartitionId partitionId, short numReplicasCaughtUpPerPartition, boolean enable) throws IOException, TimeoutException { ServerErrorCode errorCode = serverAdminTool.controlBlobStore(dataNodeId, partitionId, numReplicasCaughtUpPerPartition, enable); if (errorCode == ServerErrorCode.No_Error) { <START> LOGGER.info("Enable state of replication from "); <END> } else { LOGGER.error("From {}, received server error code for request to set enable state for replication for {}", dataNodeId, errorCode, enable, partitionId); } }</code><technical_language>incorrect/incomplete statement</technical_language>

Target:
private static void sendBlobStoreControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId, PartitionId partitionId, short numReplicasCaughtUpPerPartition, boolean enable) throws IOException, TimeoutException { ServerErrorCode errorCode = serverAdminTool.controlBlobStore(dataNodeId, partitionId, numReplicasCaughtUpPerPartition, enable); if (errorCode == ServerErrorCode.No_Error) { LOGGER.info("Enable state of controlling BlobStore from has been set to for on {}", enable, partitionId, dataNodeId); } else { LOGGER.error( "From {}, received server error code for request to set enable state for controlling BlobStore for {}", dataNodeId, errorCode, enable, partitionId); } }
Source:
<code>protected InputStream loadFile(String keycloakConfigFile) { if (keycloakConfigFile.startsWith("classpath:")) { String classPathLocation = keycloakConfigFile.substring(10); return getClass().getClassLoader().getResourceAsStream(classPathLocation); } else { try { if (!keycloakConfigFile.contains(":")) { keycloakConfigFile = "file://" + keycloakConfigFile; } return new URL(keycloakConfigFile).openStream(); } catch (Exception e) { LOG.warn("Couldn't find keycloak config file on location: " + keycloakConfigFile); <START> LOG.debug("ouldn't find keycloak config file", e); <END> return null; } } }</code><technical_language>fix typo? :-)</technical_language>

Target:
protected InputStream loadFile(String keycloakConfigFile) { if (keycloakConfigFile.startsWith("classpath:")) { String classPathLocation = keycloakConfigFile.substring(10); return getClass().getClassLoader().getResourceAsStream(classPathLocation); } else { try { if (!keycloakConfigFile.contains(":")) { keycloakConfigFile = "file://" + keycloakConfigFile; } return new URL(keycloakConfigFile).openStream(); } catch (Exception e) { LOG.warn("Couldn't find keycloak config file on location: " + keycloakConfigFile); LOG.debug("Couldn't find keycloak config file", e); return null; } } }
Source:
<code>public void testAvatar() { UrlValidator urlValidator = new UrlValidator(); <START> assertTrue(urlValidator.isValid(faker.avatar().image())); <END> }</code><technical_language>hamcrest matchers please? Thx</technical_language>

Target:
public void testAvatar() { String avatar = faker.avatar().image(); assertThat(avatar, matchesRegularExpression("^https:\\/\\/s3.amazonaws\\.com\\/uifaces\\/faces\\/twitter\\/[a-zA-Z0-9_]+\\/128\\.jpg$")); }
Source:
<code>void notifyCallbackWithSuccess(RealmResults<PermissionOffer> permissions) { <START> activeTasks.remove(this); <END> callback.onSuccess(permissions); }</code><technical_language>try-finally in other cases fixed problem if order matters for some reason</technical_language>

Target:
void notifyCallbackWithSuccess(RealmResults<PermissionOffer> permissions) { try { callback.onSuccess(permissions); } finally { activeTasks.remove(this); } }
Source:
<code>public void checkConfigFile(File configFile, File serverDir) { try { ServerFeature servUtil = new ServerFeature(); Set<String> features = servUtil.getServerFeatures(serverDir); features.removeAll(existingFeatures); if (!features.isEmpty()) { List<String> configFeatures = new ArrayList<String>(features); log.info("Configuration features have been added"); runMojo("net.wasdev.wlp.maven.plugins:liberty-maven-plugin", "install-feature", serverName, configFeatures); this.existingFeatures.addAll(features); } } catch (Exception e) { <START> log.debug("Failed to read configuration file", e); <END> } }</code><technical_language>throw a MojoExecutionException instead of logging it? If wrong installing features expect dev mode continue working properly</technical_language>

Target:
public void checkConfigFile(File configFile, File serverDir) { try { ServerFeature servUtil = getServerFeatureUtil(); Set<String> features = servUtil.getServerFeatures(serverDir); features.removeAll(existingFeatures); if (!features.isEmpty()) { List<String> configFeatures = new ArrayList<String>(features); log.info("Configuration features have been added"); runMojo("net.wasdev.wlp.maven.plugins:liberty-maven-plugin", "install-feature", serverName, configFeatures); this.existingFeatures.addAll(features); } } catch (MojoExecutionException e) { log.error("Failed to install features from configuration file", e); } }
Source:
<code>private HBox createMilestoneDetailsBox() { HBox milestoneDetailsBox = new HBox(); milestoneDetailsBox.setSpacing(3); milestoneDetailsBox.setPrefWidth(250); milestoneDetailsBox.setAlignment(Pos.CENTER_RIGHT); if (getDueDate().isPresent()) { Label dueDate = new Label("Due on: " + getDueDate().get().toString()); dueDate.setPrefWidth(150); milestoneDetailsBox.getChildren().add(dueDate); } int totalIssues = getOpenIssues() + getClosedIssues(); double progressValue = totalIssues > 0 <START> ? (double) getClosedIssues() / (getOpenIssues() + getClosedIssues()) : 0; <END> MilestoneProgressBar progressBar = new MilestoneProgressBar(progressValue); Label progressLabel = new Label(String.format("%3.0f%%", progressValue * 100)); progressLabel.setPrefWidth(50); milestoneDetailsBox.getChildren().addAll(progressBar, progressLabel); return milestoneDetailsBox; }</code><technical_language>this is done in PickerMilestone, I extract progressValue a separate method compute in constructor instead. store result in a class variable. This is need re-compute progressValue time this is called. Also, do change (getOpenIssues() + getClosedIssues()) totalIssues I missed out time. :stuck_out_tongue:</technical_language>

Target:
private HBox createMilestoneDetailsBox() { HBox milestoneDetailsBox = new HBox(); milestoneDetailsBox.setSpacing(3); milestoneDetailsBox.setPrefWidth(250); milestoneDetailsBox.setAlignment(Pos.CENTER_RIGHT); if (getDueDate().isPresent()) { Label dueDate = new Label("Due on: " + getDueDate().get().toString()); dueDate.setPrefWidth(150); milestoneDetailsBox.getChildren().add(dueDate); } MilestoneProgressBar progressBar = new MilestoneProgressBar(getProgress()); Label progressLabel = new Label(String.format("%3.0f%%", getProgress() * 100)); progressLabel.setPrefWidth(50); milestoneDetailsBox.getChildren().addAll(progressBar, progressLabel); return milestoneDetailsBox; }
Source:
<code>private String getFormattedAmountByLocaleAndInvoiceCurrency(BigDecimal amount) { <START> final DecimalFormat number = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); <END> java.util.Currency currency = java.util.Currency.getInstance(invoice.getCurrency().toString()); DecimalFormatSymbols dfs = number.getDecimalFormatSymbols(); dfs.setInternationalCurrencySymbol(currency.getCurrencyCode()); dfs.setCurrencySymbol(currency.getSymbol(currencyLocaleMap.get(currency))); number.setDecimalFormatSymbols(dfs); return number.format(amount.doubleValue()); }</code><technical_language>rename numberFormatter</technical_language>

Target:
private String getFormattedAmountByLocaleAndInvoiceCurrency(BigDecimal amount) { String invoiceCurrencyCode = invoice.getCurrency().toString(); CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode); final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode()); try { final java.util.Currency currency = java.util.Currency.getInstance(invoiceCurrencyCode); dfs.setCurrencySymbol(currency.getSymbol(currencyLocaleMap.get(currency))); } catch (Exception e) { dfs.setCurrencySymbol(currencyUnit.getSymbol(locale)); } numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits()); numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits()); return numberFormatter.format(amount.doubleValue()); }
Source:
<code>private synchronized boolean updateWeatherData() { try { weatherData = getWeatherData( <START> "<LINK_0>*%20FROM%20weather.forecast%20WHERE%20u=%27c%27%20AND%20woeid%20=%20%27" <END> + location + "%27"); if (weatherData != null) { updateStatus(ThingStatus.ONLINE); return true; } } catch (IOException e) { logger.warn("Error accessing Yahoo weather: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage()); } return false; }</code><technical_language>is difference http urls put method argument instead of treating internal information of method, url needs called</technical_language>

Target:
private synchronized boolean updateWeatherData() { try { weatherData = getWeatherData("SELECT * FROM weather.forecast WHERE u = 'c' AND woeid = " + location); if (weatherData != null) { updateStatus(ThingStatus.ONLINE); return true; } } catch (IOException e) { logger.warn("Error accessing Yahoo weather: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage()); } return false; }
Source:
<code>public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) { final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); RecyclerView.ViewHolder holder; View view; if (viewType == HEADER_TYPE) { view = inflater.inflate(R.layout.header_list_item_layout, null); holder = new HeaderViewHolder(view); } else { view = inflater.inflate(R.layout.contact_list_item_layout, null); holder = new ContactListViewHolder(view, new ContactListViewHolder.OnSelectionChanged() { @Override public void clickedItem(GenericContact contact) { itemClicked(contact); } @Override <START> public void follow(final GenericContact item, final int position) { <END> TwitterService.follow(item.getScreenName(), new Callback<TwitterUser>() { @Override public void success(Result<TwitterUser> result) { CustomContactListAdapter.this.follow(item); showSnackBar(parent, item, true); } @Override public void failure(TwitterException e) { Toast.makeText(mContext, R.string.cant_follow, Toast.LENGTH_LONG).show(); } }); } @Override public void unfollow(final GenericContact item, final int position) { if (mContactType == BaseContactFragment.FOLLOWING) { removeItem(position); } TwitterService.unfollow(item.getScreenName(), new Callback<TwitterUser>() { @Override public void success(Result<TwitterUser> result) { CustomContactListAdapter.this.unfollow(item); showSnackBar(parent, item, false); } @Override public void failure(TwitterException e) { Toast.makeText(mContext, R.string.cant_unfollow, Toast.LENGTH_LONG).show(); } }); } }); } return holder; }</code><technical_language>MVP pattern in ContactsActivity, ContactsFragmentand DeviceContactsFragmentand server calls there</technical_language>

Target:
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) { final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); RecyclerView.ViewHolder holder; View view; if (viewType == HEADER_TYPE) { view = inflater.inflate(R.layout.header_list_item_layout, null); holder = new HeaderViewHolder(view); } else { view = inflater.inflate(R.layout.contact_list_item_layout, null); holder = new ContactListViewHolder(view, new ContactListViewHolder.OnSelectionChanged() { @Override public void clickedItem(GenericContact contact) { itemClicked(contact); if (mOnContactSelectionChanged != null){ mOnContactSelectionChanged.clickedItem(contact); } } @Override public void follow(final GenericContact item, final int position) { if (mOnContactSelectionChanged != null){ mOnContactSelectionChanged.follow(item, position); } } @Override public void unfollow(final GenericContact item, final int position) { if (mContactType == BaseContactFragment.FOLLOWING) { removeItem(position); } if (mOnContactSelectionChanged != null){ mOnContactSelectionChanged.unfollow(item, position); } } }); } return holder; }
Source:
<code>public Product getProduct() { Product product = new Product(); String productTitle = informationClient.getProductTitle(); Integer productInventory = inventoryClient.getProductInventories(); if (productTitle != null) { product.setTitle(productTitle); } else { product.setTitle("Error: Fetching Product Title Failed"); } <START> if (productInventory != null) { <END> product.setProductInventories(productInventory); } else { product.setProductInventories(-1); } return product; }</code><technical_language>ProductInventoryClientImpl return null 0 exception occurs. returning null correct way, change implemented in client.</technical_language>

Target:
public Product getProduct() { var product = new Product(); String productTitle = informationClient.getProductTitle(); Integer productInventory = inventoryClient.getProductInventories(); if (productTitle != null) { product.setTitle(productTitle); } else { product.setTitle("Error: Fetching Product Title Failed"); } if (productInventory != null) { product.setProductInventories(productInventory); } else { product.setProductInventories(-1); } return product; }
Source:
<code>public Collection<Cookie> getRequestCookies() { final Collection<Cookie> pac4jCookies = new LinkedHashSet<>(); <START> for (javax.servlet.http.Cookie c : this.request.getCookies()) { <END> final Cookie cookie = new Cookie(c.getName(), c.getValue()); cookie.setComment(c.getComment()); cookie.setDomain(c.getDomain()); cookie.setHttpOnly(c.isHttpOnly()); cookie.setMaxAge(c.getMaxAge()); cookie.setPath(c.getPath()); cookie.setSecure(c.getSecure()); pac4jCookies.add(cookie); } return pac4jCookies; }</code><technical_language>If request.getCookies() null, is this line is working correctly?! Shouldnt fix this too</technical_language>

Target:
public Collection<Cookie> getRequestCookies() { final Collection<Cookie> pac4jCookies = new LinkedHashSet<>(); final javax.servlet.http.Cookie[] cookies = this.request.getCookies(); if (cookies != null) { for (javax.servlet.http.Cookie c : cookies) { final Cookie cookie = new Cookie(c.getName(), c.getValue()); cookie.setComment(c.getComment()); cookie.setDomain(c.getDomain()); cookie.setHttpOnly(c.isHttpOnly()); cookie.setMaxAge(c.getMaxAge()); cookie.setPath(c.getPath()); cookie.setSecure(c.getSecure()); pac4jCookies.add(cookie); } } return pac4jCookies; }
Source:
<code>Pair<StoreKey, PersistentIndex.IndexEntryType> getResetKey() { <START> if (version == (short) 1 && resetKey != null) { <END> return new Pair<>(resetKey.getFirst(), PersistentIndex.IndexEntryType.values()[resetKey.getSecond()]); } else { return null; } }</code><technical_language>check suffice? is requirement for check (and check updated if versions upgraded)</technical_language>

Target:
Pair<StoreKey, PersistentIndex.IndexEntryType> getResetKey() { return resetKey; }
Source:
<code>public List<ICompletionProposal> getExpressionTextPrefixes() { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); result.add(new TextCompletionProposal(AstBuilderListener.NOT_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal(AstBuilderListener.UNARY_MIN_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal("()", 1)); result.add(new TextCompletionProposal("true", 0)); result.add(new TextCompletionProposal("false", 0)); result.add(new TextCompletionProposal("null", 0)); result.add(new TextCompletionProposal("{}", 1)); result.add(new <START> TextCompletionProposal("Sequence()", <END> 1)); result.add(new TextCompletionProposal("OrderedSet()", 1)); result.add(new TextCompletionProposal(AstBuilderListener.LET_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal(AstBuilderListener.CONDITIONAL_OPERATOR + SPACE, 0)); return result; }</code><technical_language>In OCL, a sequence literal is "Sequence{}". for OrderedSet below</technical_language>

Target:
public List<ICompletionProposal> getExpressionTextPrefixes() { final List<ICompletionProposal> result = new ArrayList<ICompletionProposal>(); result.add(new TextCompletionProposal(AstBuilderListener.NOT_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal(AstBuilderListener.UNARY_MIN_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal("()", 1)); result.add(new TextCompletionProposal("true", 0)); result.add(new TextCompletionProposal("false", 0)); result.add(new TextCompletionProposal("null", 0)); result.add(new TextCompletionProposal("{}", 1)); result.add(new TextCompletionProposal("Sequence{}", 1)); result.add(new TextCompletionProposal("OrderedSet{}", 1)); result.add(new TextCompletionProposal(AstBuilderListener.LET_OPERATOR + SPACE, 0)); result.add(new TextCompletionProposal(AstBuilderListener.CONDITIONAL_OPERATOR + SPACE, 0)); return result; }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodes.CRED_SAVE_FLOW) { finish(resultCode, data); } <START> if (resultCode == ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) { <END> finish(resultCode, data); } }</code><technical_language>Nit: merge this if above</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodes.CRED_SAVE_FLOW || resultCode == ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) { finish(resultCode, data); } }
Source:
<code>public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { BigDecimal ssd = sumSquaredDeviation(); <START> ssd = ssd.divide(new BigDecimal(getDataPointsCount()), MathContext.DECIMAL128); <END> cachedResult = new BigDecimal(Math.sqrt(ssd.doubleValue())); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(cachedResult); ptr.set(buffer); return true; }</code><technical_language>precision scale based child expressions precision scale. a DecimalDivideExpression call NumberUtil.setDecimalWidthAndScale(). @tonyhuang - give some advice here, please</technical_language>

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { BigDecimal ssd = sumSquaredDeviation(); ssd = ssd.divide(new BigDecimal(getDataPointsCount()), PDataType.DEFAULT_MATH_CONTEXT); int resultPrecision = colPrecision; for (int i = 1; i < this.totalCount; i++) { if (resultPrecision >= PDataType.MAX_PRECISION) break; Pair<Integer, Integer> precisionScale = BigDecimalUtil.getResultPrecisionScale(this.colPrecision, this.colScale, this.colPrecision, this.colScale, Operation.OTHERS); resultPrecision = precisionScale.getFirst(); } cachedResult = new BigDecimal(Math.sqrt(ssd.doubleValue()), new MathContext(resultPrecision, RoundingMode.HALF_UP)); cachedResult.setScale(this.colScale, RoundingMode.HALF_UP); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(cachedResult); ptr.set(buffer); return true; }
Source:
<code>public RepoObjectMetadata getArticleItemFile(ArticleFileIdentifier fileId) { ArticleItem work = articleCrudService.getArticleItem(fileId.getItemIdentifier()); String fileType = fileId.getFileType(); ArticleFile articleFile = work.getFile(fileType) .orElseThrow(() -> new RestClientException("Unrecognized type: " + fileType, HttpStatus.NOT_FOUND)); try { return contentRepoService.getRepoObjectMetadata(articleFile.getCrepoVersion()); } catch (NotFoundException e) { <START> throw new RestClientException("Object not found: " + fileId, HttpStatus.NOT_FOUND); <END> } }</code><technical_language>Do report bucket-key-UUID tuple articleFile object, in addition fileId</technical_language>

Target:
public RepoObjectMetadata getArticleItemFile(ArticleFileIdentifier fileId) { ArticleItem work = articleCrudService.getArticleItem(fileId.getItemIdentifier()); String fileType = fileId.getFileType(); ArticleFile articleFile = work.getFile(fileType) .orElseThrow(() -> new RestClientException("Unrecognized type: " + fileType, HttpStatus.NOT_FOUND)); try { return contentRepoService.getRepoObjectMetadata(articleFile.getCrepoVersion()); } catch (NotFoundException e) { throw new RestClientException("Object not found: " + fileId + ". File info: " + articleFile, HttpStatus.NOT_FOUND); } }
Source:
<code>public File saveData(String filename) { IPath newDataLoc = getNewDataLocation(filename, DATA_EXT); IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData(); File newDataFile = new File(newDataLoc.toOSString()); File defaultDataFile = defaultDataLoc.toFile(); if (canSave(newDataFile)) { try { newDataFile.createNewFile(); if (copyFile(defaultDataFile, newDataFile)) { PerfPlugin.getDefault().setPerfProfileData(newDataLoc); PerfPlugin.getDefault().getProfileView() .setContentDescription(newDataLoc.toOSString()); return newDataFile; <START> } else { <END> openErroDialog(Messages.PerfSaveSession_failure_title, Messages.PerfSaveSession_failure_msg, newDataLoc.lastSegment()); } } catch (IOException e) { openErroDialog(Messages.PerfSaveSession_failure_title, Messages.PerfSaveSession_failure_msg, newDataLoc.lastSegment()); } } return null; }</code><technical_language>This 'else' exception caught do thing.. handling a failed copy</technical_language>

Target:
public File saveData(String filename) { IPath newDataLoc = getNewDataLocation(filename, DATA_EXT); IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData(); File newDataFile = new File(newDataLoc.toOSString()); File defaultDataFile = defaultDataLoc.toFile(); if (canSave(newDataFile)) { try { newDataFile.createNewFile(); copyFile(defaultDataFile, newDataFile); PerfPlugin.getDefault().setPerfProfileData(newDataLoc); PerfPlugin.getDefault().getProfileView() .setContentDescription(newDataLoc.toOSString()); return newDataFile; } catch (IOException e) { openErroDialog(Messages.PerfSaveSession_failure_title, Messages.PerfSaveSession_failure_msg, newDataLoc.lastSegment()); } } return null; }
Source:
<code>public Map<Errors, Integer> errorCounts() { return errorCounts(data.topics().stream() <START> .flatMap(topic -> topic.partitions().stream()) <END> .map(partition -> Errors.forCode(partition.errorCode()))); }</code><technical_language>reason do map flatMap</technical_language>

Target:
public Map<Errors, Integer> errorCounts() { return errorCounts(data.topics().stream().flatMap(topic -> topic.partitions().stream().map(partition -> Errors.forCode(partition.errorCode())))); }
Source:
<code>public List<RelationKey> getMatchingRelationKeys(final String searchTerm) throws CatalogException { if (isClosed) { throw new CatalogException("Catalog is closed."); } final String expandedSearchTerm = '%' + Joiner.on("%").join(Splitter.fixedLength(1).split(searchTerm.toLowerCase())) + '%'; try { return queue.execute(new SQLiteJob<List<RelationKey>>() { @Override protected List<RelationKey> job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection.prepare("SELECT user_name, program_name, relation_name FROM relations " + "WHERE lower(user_name || ':' || program_name || ':' || relation_name) LIKE ? AND tombstone=0"); statement.bind(1, expandedSearchTerm); ImmutableList.Builder<RelationKey> result = ImmutableList.builder(); while (statement.step()) { String userName = statement.columnString(0); String programName = statement.columnString(1); String relationName = statement.columnString(2); result.add(new RelationKey(userName, programName, relationName)); } statement.dispose(); return result.build(); } catch (final SQLiteException e) { throw new CatalogException(e); } } }).get(); } catch (InterruptedException | ExecutionException e) { <START> if (e instanceof InterruptedException) { <END> Thread.currentThread().interrupt(); } throw new CatalogException(e); } }</code><technical_language>Sorry, I completely wrong suggested handling of InterruptedException (@jingjingwang straightened out). sense set interrupted status of current thread, InterruptedException caught a completely thread (the thread pool worker Future executed). correct do is original code doing</technical_language>

Target:
public List<RelationKey> getMatchingRelationKeys(final String searchTerm) throws CatalogException { if (isClosed) { throw new CatalogException("Catalog is closed."); } final String expandedSearchTerm = '%' + Joiner.on("%").join(Splitter.fixedLength(1).split(searchTerm.toLowerCase())) + '%'; try { return queue.execute(new SQLiteJob<List<RelationKey>>() { @Override protected List<RelationKey> job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { try { SQLiteStatement statement = sqliteConnection.prepare("SELECT user_name, program_name, relation_name FROM relations " + "WHERE lower(user_name || ':' || program_name || ':' || relation_name) LIKE ? AND is_deleted=0"); statement.bind(1, expandedSearchTerm); ImmutableList.Builder<RelationKey> result = ImmutableList.builder(); while (statement.step()) { String userName = statement.columnString(0); String programName = statement.columnString(1); String relationName = statement.columnString(2); result.add(new RelationKey(userName, programName, relationName)); } statement.dispose(); return result.build(); } catch (final SQLiteException e) { throw new CatalogException(e); } } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }
Source:
<code>public static String getDeleteTabletOnAllVolumesUri(TableId tableId, String dirName) { <START> if (dirName.contains(Path.SEPARATOR)) { <END> throw new IllegalArgumentException("invalid dir name " + dirName); } return ALL_VOLUMES_PREFIX + ServerConstants.TABLE_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + dirName; }</code><technical_language>inconsistently path separator literal "/". Also, this path separator Hadoop... if stable, if guaranteed platform-independent, dangerously close Java's platform-dependent path separator, this do a double-take. if want depend Hadoop code for formatting serialized data in metadata tables of Accumulo. constant literal slashes. Is a more restrictive pattern for is a valid dirName, excludes invalid (instead of excluding invalid slashes)</technical_language>

Target:
public static String getDeleteTabletOnAllVolumesUri(TableId tableId, String dirName) { ServerColumnFamily.validateDirCol(dirName); return ALL_VOLUMES_PREFIX + ServerConstants.TABLE_DIR + Path.SEPARATOR + tableId + Path.SEPARATOR + dirName; }
Source:
<code>public void internalReceiveCommand(String itemName, Command command) { logger.trace("internalReceiveCommand({},{}) called.", itemName, command.toString()); if (this.eventPublisher == null) { <START> logger.error("internalReceiveCommand(): eventPublisher is NULL. Should NEVER occur."); <END> return; } VeluxBindingConfig itemConfig = this.bindingProvider.getConfigForItemName(itemName); VeluxItemType itemType = itemConfig.getBindingItemType(); if (itemType.isWritable() || itemType.isExecutable()) { logger.trace("internalReceiveCommand() is about to send update to item {}.", itemName); for (VeluxBindingProvider provider : providers) { logger.trace("internalReceiveCommand() working with VeluxBindingProvider {}.", provider); bridgeHandler.handleCommandOnChannel(itemName, command, itemConfig, provider, this.eventPublisher); } } else { logger.warn("internalReceiveCommand() ignoring command to item as neither writable nor executable.", itemName); } logger.trace("internalReceiveCommand() done."); }</code><technical_language>Revert WARN</technical_language>

Target:
public void internalReceiveCommand(String itemName, Command command) { logger.trace("internalReceiveCommand({},{}) called.", itemName, command.toString()); if (this.eventPublisher == null) { logger.warn("internalReceiveCommand(): eventPublisher is NULL. Should NEVER occur."); return; } VeluxBindingConfig itemConfig = this.bindingProvider.getConfigForItemName(itemName); VeluxItemType itemType = itemConfig.getBindingItemType(); if (itemType.isWritable() || itemType.isExecutable()) { logger.trace("internalReceiveCommand() is about to send update to item {}.", itemName); for (VeluxBindingProvider provider : providers) { logger.trace("internalReceiveCommand() working with VeluxBindingProvider {}.", provider); bridgeHandler.handleCommandOnChannel(itemName, command, itemConfig, provider, this.eventPublisher); } } else { logger.warn("internalReceiveCommand() ignoring command to item as neither writable nor executable.", itemName); } logger.trace("internalReceiveCommand() done."); }
Source:
<code>public CustomSpinnerAdapter(Context context, ArrayList<Long> speedList) { super(context, R.layout.spinner_item_layout, speedList); <START> mContext = context; <END> mSpeedList = speedList; mInflater = LayoutInflater.from(mContext); }</code><technical_language>context is automatically stored in ArrayAdapter, call getContext()</technical_language>

Target:
public CustomSpinnerAdapter(Context context, ArrayList<Long> speedList) { super(context, R.layout.spinner_item_layout, speedList); mInflater = LayoutInflater.from(getContext()); }