auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static MapValue convert( ExecutionPlanDescription plan ) { <START> MapValueBuilder out = new MapValueBuilder( ); <END> out.add( "operatorType", stringValue( plan.getName() ) ); out.add( "args", ValueUtils.asMapValue( plan.getArguments() ) ); out.add( "identifiers", ValueUtils.asListValue( plan.getIdentifiers() ) ); out.add( "children", children( plan ) ); if ( plan.hasProfilerStatistics() ) { ExecutionPlanDescription.ProfilerStatistics profile = plan.getProfilerStatistics(); out.add( "dbHits", longValue( profile.getDbHits() ) ); out.add( "pageCacheHits", longValue( profile.getPageCacheHits() ) ); out.add( "pageCacheMisses", longValue( profile.getPageCacheMisses() ) ); out.add( "pageCacheHitRatio", doubleValue( profile.getPageCacheHitRatio() ) ); out.add( "rows", longValue( profile.getRows() ) ); } return out.build(); }</code><technical_language>sense initialize this a size</technical_language>

Target:
public static MapValue convert( ExecutionPlanDescription plan ) { boolean hasProfilerStatistics = plan.hasProfilerStatistics(); int size = hasProfilerStatistics ? 9 : 4; MapValueBuilder out = new MapValueBuilder( size ); out.add( "operatorType", stringValue( plan.getName() ) ); out.add( "args", ValueUtils.asMapValue( plan.getArguments() ) ); out.add( "identifiers", ValueUtils.asListValue( plan.getIdentifiers() ) ); out.add( "children", children( plan ) ); if ( hasProfilerStatistics ) { ExecutionPlanDescription.ProfilerStatistics profile = plan.getProfilerStatistics(); out.add( "dbHits", longValue( profile.getDbHits() ) ); out.add( "pageCacheHits", longValue( profile.getPageCacheHits() ) ); out.add( "pageCacheMisses", longValue( profile.getPageCacheMisses() ) ); out.add( "pageCacheHitRatio", doubleValue( profile.getPageCacheHitRatio() ) ); out.add( "rows", longValue( profile.getRows() ) ); } return out.build(); }
Source:
<code>public static <E> int hashCode(final Collection<? extends E> collection, final Equator<? super E> equator) { <START> Objects.requireNonNull(equator, "Equator"); <END> if (null == collection) { return 0; } int hashCode = 1; for (final E e : collection) { hashCode = 31 * hashCode + equator.hash(e); } return hashCode; }</code><technical_language>"Equator" -> "equator"</technical_language>

Target:
public static <E> int hashCode(final Collection<? extends E> collection, final Equator<? super E> equator) { Objects.requireNonNull(equator, "equator"); if (null == collection) { return 0; } int hashCode = 1; for (final E e : collection) { hashCode = 31 * hashCode + equator.hash(e); } return hashCode; }
Source:
<code>private LineData generateA1cData() { ArrayList<String> xVals = new ArrayList<>(); ArrayList<Entry> yVals = new ArrayList<>(); int k = 0; for (int i = presenter.getA1cReadings().size() - 1; i >= 0; i--) { float val = Float.parseFloat(presenter.getA1cReadings().get(i).toString()); Log.e("glucosio", "ADDING " + val); yVals.add(new Entry(k, val)); k++; } for (int i = presenter.getA1cReadingsDateTime().size() - 1; i >= 0; i--) { String date = presenter.convertDate(presenter.getA1cReadingsDateTime().get(i)); <START> xVals.add(date + ""); <END> } xValues = xVals; return new LineData(generateLineDataSet(yVals, getResources().getColor(R.color.glucosio_fab_HB1AC))); }</code><technical_language>add empty string</technical_language>

Target:
private LineData generateA1cData() { ArrayList<String> xVals = new ArrayList<>(); ArrayList<Entry> yVals = new ArrayList<>(); int k = 0; for (int i = presenter.getA1cReadings().size() - 1; i >= 0; i--) { float val = Float.parseFloat(presenter.getA1cReadings().get(i).toString()); yVals.add(new Entry(k, val)); k++; } for (int i = presenter.getA1cReadingsDateTime().size() - 1; i >= 0; i--) { String date = presenter.convertDate(presenter.getA1cReadingsDateTime().get(i)); xVals.add(date); } xValues = xVals; return new LineData(generateLineDataSet(yVals, getResources().getColor(R.color.glucosio_fab_HB1AC))); }
Source:
<code>public static User parseUserLight(JSONObject jUser) throws JSONException { User user = new User(); user.setUserid(jUser.getInt("userid")); user.setUsername(jUser.getString("username")); if (!jUser.isNull("image")) <START> user.setAvatar(parseImage(jUser.getJSONObject("image"), null)); <END> if (!jUser.isNull("join_date")) user.setJoinDate(jUser.getInt("join_date")); user.setReputation(jUser.getInt("reputation")); return user; }</code><technical_language>This if statement replaced user.setAvatar(parseImage(jUser, "image"))</technical_language>

Target:
public static User parseUserLight(JSONObject jUser) throws JSONException { User user = new User(); user.setUserid(jUser.getInt("userid")); user.setUsername(jUser.getString("username")); user.setAvatar(parseImage(jUser, "image")); if (!jUser.isNull("join_date")) user.setJoinDate(jUser.getInt("join_date")); user.setReputation(jUser.getInt("reputation")); return user; }
Source:
<code>private TransferPartitionKey findTransferBucketKey(List<BlockTransferInfo> transferInfos) { int srcAllocatedCount = 0; int dstAllocatedCount = 0; Set<BlockStoreLocation> srcLocations = new HashSet<>(); Set<BlockStoreLocation> dstLocations = new HashSet<>(); for (BlockTransferInfo transferInfo : transferInfos) { if (transferInfo.getSrcLocation().dir() != BlockStoreLocation.ANY_DIR) { srcAllocatedCount++; } if (transferInfo.getDstLocation().dir() != BlockStoreLocation.ANY_DIR) { dstAllocatedCount++; } <START> srcLocations.add(transferInfo.getSrcLocation()); <END> dstLocations.add(transferInfo.getDstLocation()); } if (srcAllocatedCount == dstAllocatedCount) { if (srcAllocatedCount == 0) { return TransferPartitionKey.NONE; } else { if (srcLocations.size() >= dstLocations.size()) { return TransferPartitionKey.SRC; } else { return TransferPartitionKey.DST; } } } else if (srcAllocatedCount > dstAllocatedCount) { return TransferPartitionKey.SRC; } else { return TransferPartitionKey.DST; } }</code><technical_language>Do want count ANY_DIRs</technical_language>

Target:
private TransferPartitionKey findTransferBucketKey(List<BlockTransferInfo> transferInfos) { int srcAllocatedCount = 0; int dstAllocatedCount = 0; Set<BlockStoreLocation> srcLocations = new HashSet<>(); Set<BlockStoreLocation> dstLocations = new HashSet<>(); for (BlockTransferInfo transferInfo : transferInfos) { if (transferInfo.getSrcLocation().dir() != BlockStoreLocation.ANY_DIR) { srcAllocatedCount++; } if (transferInfo.getDstLocation().dir() != BlockStoreLocation.ANY_DIR) { dstAllocatedCount++; } srcLocations.add(transferInfo.getSrcLocation()); dstLocations.add(transferInfo.getDstLocation()); } if (srcAllocatedCount == 0 && dstAllocatedCount == 0) { return TransferPartitionKey.NONE; } if (srcAllocatedCount > dstAllocatedCount) { return TransferPartitionKey.SRC; } else if (dstAllocatedCount > srcAllocatedCount) { return TransferPartitionKey.DST; } else { if (srcLocations.size() >= dstLocations.size()) { return TransferPartitionKey.SRC; } else { return TransferPartitionKey.DST; } } }
Source:
<code>public ZKDistributedNonblockingLock(LockScope scope, String zkAddress, Long leaseTimeout, String lockMsg, String userId) { this(scope.getPath(), leaseTimeout, lockMsg, userId, 0, Integer.MAX_VALUE, 0, false, <START> new LockListener() { <END> @Override public void onCleanupNotification() { } }, new ZkBaseDataAccessor<ZNRecord>(zkAddress)); }</code><technical_language>If is empty callback, pass null? lock trigger callback all</technical_language>

Target:
public ZKDistributedNonblockingLock(LockScope scope, String zkAddress, Long leaseTimeout, String lockMsg, String userId) { this(scope.getPath(), leaseTimeout, lockMsg, userId, 0, Integer.MAX_VALUE, 0, false, null, new ZkBaseDataAccessor<ZNRecord>(zkAddress)); }
Source:
<code>public ManifestIdentifier identify(Config config) { String buckManifest = System.getProperty(BUCK_ROBOLECTRIC_MANIFEST); FsFile manifestFile = Fs.fileFromPath(buckManifest); String buckResDirs = System.getProperty(BUCK_ROBOLECTRIC_RES_DIRECTORIES); String buckAssetsDirs = System.getProperty(BUCK_ROBOLECTRIC_ASSETS_DIRECTORIES); String packageName = config.packageName(); final List<FsFile> buckResources = getDirectoriesFromProperty(buckResDirs); final List<FsFile> buckAssets = getDirectoriesFromProperty(buckAssetsDirs); final FsFile resDir = buckResources.size() == 0 ? null : buckResources.get(buckResources.size() - 1); final FsFile assetsDir = buckAssets.size() == 0 ? null : buckAssets.get(buckAssets.size() - 1); final List<ManifestIdentifier> libraries; if (resDir == null && assetsDir == null) { libraries = null; } else { libraries = new ArrayList<>(); for (FsFile buckResource: buckResources) { <START> libraries.add(new ManifestIdentifier(null, null, buckResource, null, null)); <END> } for (FsFile buckAsset: buckAssets) { libraries.add(new ManifestIdentifier(null, null, null, buckAsset, null)); } } return new ManifestIdentifier(packageName, manifestFile, resDir, assetsDir, libraries); }</code><technical_language>Yep, needs (String) null. LGTM</technical_language>

Target:
public ManifestIdentifier identify(Config config) { String buckManifest = System.getProperty(BUCK_ROBOLECTRIC_MANIFEST); FsFile manifestFile = Fs.fileFromPath(buckManifest); String buckResDirs = System.getProperty(BUCK_ROBOLECTRIC_RES_DIRECTORIES); String buckAssetsDirs = System.getProperty(BUCK_ROBOLECTRIC_ASSETS_DIRECTORIES); String packageName = config.packageName(); final List<FsFile> buckResources = getDirectoriesFromProperty(buckResDirs); final List<FsFile> buckAssets = getDirectoriesFromProperty(buckAssetsDirs); final FsFile resDir = buckResources.size() == 0 ? null : buckResources.get(buckResources.size() - 1); final FsFile assetsDir = buckAssets.size() == 0 ? null : buckAssets.get(buckAssets.size() - 1); final List<ManifestIdentifier> libraries; if (resDir == null && assetsDir == null) { libraries = null; } else { libraries = new ArrayList<>(); for (int i = 0; i < buckResources.size() - 1; i++) { libraries.add(new ManifestIdentifier((String) null, null, buckResources.get(i), null, null)); } for (int i = 0; i < buckAssets.size() - 1; i++) { libraries.add(new ManifestIdentifier(null, null, null, buckAssets.get(i), null)); } } return new ManifestIdentifier(packageName, manifestFile, resDir, assetsDir, libraries); }
Source:
<code>private void postConstruct() { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(ServerSideRequestProcessor.class.getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor(0, maxPoolSize, 60L, SECONDS, new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( <START> (r, __) -> LOG.warn("Message rejected for execution", r)); <END> requestProcessorConfigurator.put(getEndpointId(), () -> executor); }</code><technical_language>is major websocket endpoint logged error</technical_language>

Target:
private void postConstruct() { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(CheMajorWebSocketEndpoint.class.getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor(0, maxPoolSize, 60L, SECONDS, new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( (r, __) -> LOG.error("Message rejected for execution", r)); requestProcessorConfigurator.put(getEndpointId(), () -> executor); }
Source:
<code>private void warnOnProblemsAndErrors() { for (ModelProblem problem : buildingResult.getProblems()) { <START> ShellMessages.warn(writer, "[ " + problem.getSeverity() + " ] " + problem.getMessage() + " @ " <END> + ModelProblemUtils.formatLocation(problem, problem.getModelId())); } DependencyResolutionResult resolutionResult = buildingResult.getDependencyResolutionResult(); for (Exception collectionError : resolutionResult.getCollectionErrors()) { ShellMessages.warn(writer, collectionError.getMessage()); } for (Dependency unresolvedDep : resolutionResult.getUnresolvedDependencies()) { ShellMessages.warn(writer, "Failed to resolve dependency [ " + unresolvedDep + " ] , due to error(s) : " + resolutionResult.getResolutionErrors(unresolvedDep)); } }</code><technical_language>This of ShellWriter is OK in Forge1, in Forge2 able do this</technical_language>

Target:
private void warnOnProblemsAndErrors() { for (ModelProblem problem : buildingResult.getProblems()) { ShellMessages.warn(writer, "[ " + problem.getSeverity() + " ] " + problem.getMessage() + " @ " + ModelProblemUtils.formatLocation(problem, problem.getModelId())); } DependencyResolutionResult resolutionResult = buildingResult.getDependencyResolutionResult(); for (Exception collectionError : resolutionResult.getCollectionErrors()) { StringBuilder message = new StringBuilder(); message.append(collectionError.getMessage()); message.append('\n'); if(collectionError.getCause() != null) { message.append("Cause : "); message.append(collectionError.getCause().getMessage()); } ShellMessages.warn(writer, message.toString()); } for (Dependency unresolvedDep : resolutionResult.getUnresolvedDependencies()) { ShellMessages.warn(writer, "Failed to resolve dependency [ " + unresolvedDep + " ] , due to error(s) : " + resolutionResult.getResolutionErrors(unresolvedDep)); } }
Source:
<code>static LocalDateDoubleTimeSeries of( LocalDate startDate, LocalDate endDate, Stream<LocalDateDoublePoint> values, DenseTimeSeriesCalculation dateCalculation) { double[] points = new double[dateCalculation.calculatePosition(startDate, endDate) + 1]; Arrays.fill(points, Double.NaN); int size = 0; <START> for (LocalDateDoublePoint pt : Guavate.in(values)) { <END> points[dateCalculation.calculatePosition(startDate, pt.getDate())] = pt.getValue(); size++; } return new DenseLocalDateDoubleTimeSeries(startDate, points, dateCalculation, true, size); }</code><technical_language>Static import</technical_language>

Target:
static LocalDateDoubleTimeSeries of( LocalDate startDate, LocalDate endDate, Stream<LocalDateDoublePoint> values, DenseTimeSeriesCalculation dateCalculation) { double[] points = new double[dateCalculation.calculatePosition(startDate, endDate) + 1]; Arrays.fill(points, Double.NaN); int size = 1; for (LocalDateDoublePoint pt : in(values)) { points[dateCalculation.calculatePosition(startDate, pt.getDate())] = pt.getValue(); size++; } return new DenseLocalDateDoubleTimeSeries(startDate, points, dateCalculation, true, size); }
Source:
<code>public static void assertTextContainsProperty(String text, String propName, Object propValue) { <START> Assert.assertTrue("Property " + propName + " not found in " + text, <END> text.contains(propName + " = " + propValue)); }</code><technical_language>@jmesnil wrap text variable some quotes more easily distinguishable compared text starts? "Property " + propName + " in '" + text + "'"</technical_language>

Target:
public static void assertTextContainsProperty(String text, String propName, Object propValue) { Assert.assertTrue("String '" + propName + " = " + propValue + "' not found in the following output:\n" + text, text.contains(propName + " = " + propValue + "\n")); }
Source:
<code>@Override public boolean start() throws Exception { Map<String,String> overrides = new HashMap<String,String>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<MultiBinding.Unbinder>(); for (MultiBinding<?> binding : step.bindings) { MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); IdCredentials id = CredentialsProvider.findCredentialById(binding.getCredentialsId(), binding.type(), run); <START> CredentialsProvider.track(run, id); <END> } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback(unbinders)). start(); return false; }</code><technical_language>desirable call track(Node, Credentials). (For BindingStep, inject a Node; for SecretBuildWrapper, method AbstractBuild IIRC.) @stephenc guidance</technical_language>

Target:
@Override public boolean start() throws Exception { Map<String,String> overrides = new HashMap<String,String>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<MultiBinding.Unbinder>(); for (MultiBinding<?> binding : step.bindings) { MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback(unbinders)). start(); return false; }
Source:
<code>public static Optional<Map<String, String>> splitParams(HttpServletRequest request) { String pathInfo = request.getPathInfo(); pathInfo = pathInfo.substring(pathInfo.indexOf(TMSDocumentFactory.TILEMAPSERVICE_LEADINGPATH)); String[] params = pathInfo.split("/"); int paramsLength = params.length; Map<String, String> parsed = new HashMap<>(); if (params.length < 4) { return Optional.empty(); } String[] yExt = params[paramsLength - 1].split("\\."); String x = params[paramsLength - 2]; String y = yExt[0]; String z = params[paramsLength - 3]; String flip = yExt[1].toUpperCase(); <START> if (flip.contains("?FLIPY=TRUE")) { <END> String[] yFlip = yExt[1].split("\\?"); int zInt = Integer.parseInt(z); int flippedY = Integer.parseInt(y); flippedY = (int) (Math.pow(2, zInt)) - flippedY - 1; y = Integer.toString(flippedY); yExt[1] = yFlip[0]; } parsed.put("x", x); parsed.put("y", y); parsed.put("z", z); String layerNameAndSRS = params[2]; String[] lsf = ServletUtils.URLDecode(layerNameAndSRS, request.getCharacterEncoding()).split("@"); parsed.put("layerId", lsf[0]); if (lsf.length >= 3) { parsed.put("gridSetId", lsf[1]); parsed.put("format", lsf[2]); } parsed.put("fileExtension", yExt[1]); return Optional.of(parsed); }</code><technical_language>This a fragile handle query parameters. if for example a request "...?cacheBreaker=randomeNumber&flipy=true"? Instead, I throw is ? getParameterNames getParameter grab eventual flipy parameter</technical_language>

Target:
public static Optional<Map<String, String>> splitParams(HttpServletRequest request) { String pathInfo = request.getPathInfo(); pathInfo = pathInfo.substring(pathInfo.indexOf(TMSDocumentFactory.TILEMAPSERVICE_LEADINGPATH)); String[] params = pathInfo.split("/"); int paramsLength = params.length; Map<String, String> parsed = new HashMap<>(); if (params.length < 4) { return Optional.empty(); } String[] yExt = params[paramsLength - 1].split("\\."); parsed.put("x", params[paramsLength - 2]); parsed.put("y", yExt[0]); parsed.put("z", params[paramsLength - 3]); String layerNameAndSRS = params[2]; String[] lsf = ServletUtils.URLDecode(layerNameAndSRS, request.getCharacterEncoding()).split("@"); parsed.put("layerId", lsf[0]); if (lsf.length >= 3) { parsed.put("gridSetId", lsf[1]); parsed.put("format", lsf[2]); } parsed.put("fileExtension", yExt[1]); return Optional.of(parsed); }
Source:
<code>public void doPost(HttpServletRequest req, HttpServletResponse resp) { try { AutomatedAction action = new AutomatedActionFactory().getAction(req, resp); String url = HttpRequestHelper.getRequestedUrl(req); if (!url.startsWith("/worker/")) { Map<String, String[]> params = HttpRequestHelper.getParameterMap(req); LogMessageGenerator logGenerator = new LogMessageGenerator(); log.info(logGenerator.generateBasicActivityLogMessage(url, params, action.getActionMessage(), null)); } action.execute(); } catch (Throwable t) { String requestUrl = req.getRequestURL().toString(); String requestParams = HttpRequestHelper.printRequestParameters(req); log.severe("Exception occured while performing " + requestUrl + "|||" + requestParams + "|||" + TeammatesException.toStringWithStackTrace(t)); <START> throw t; END> } }</code><technical_language>Instead of this, setting response status 200-299 better. ([cron job reference](<LINK_0> / [task queue reference](<LINK_1></technical_language>

Target:
public void doPost(HttpServletRequest req, HttpServletResponse resp) { try { AutomatedAction action = new AutomatedActionFactory().getAction(req, resp); String url = HttpRequestHelper.getRequestedUrl(req); if (!url.startsWith("/worker/")) { Map<String, String[]> params = HttpRequestHelper.getParameterMap(req); LogMessageGenerator logGenerator = new LogMessageGenerator(); log.info(logGenerator.generateBasicActivityLogMessage(url, params, action.getActionMessage(), null)); } action.execute(); } catch (Throwable t) { String requestUrl = req.getRequestURL().toString(); String requestParams = HttpRequestHelper.printRequestParameters(req); log.severe("Exception occured while performing " + requestUrl + "|||" + requestParams + "|||" + TeammatesException.toStringWithStackTrace(t)); resp.setStatus(500); } }
Source:
<code>public static Image getUnscaledPortraitImage(String category, String name) { <START> if (category == null || name == null <END> || category.equals(Crew.PORTRAIT_NONE)) { return getDefaultPortrait(); } initializePortraits(); if (portraitDirectory == null) { return getDefaultPortrait(); } try { if (category.equals(Crew.ROOT_PORTRAIT)) { category = ""; } if (name.equals(Crew.PORTRAIT_NONE)) { name = "default.gif"; } Image image = (Image) portraitDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } LOG.error(PortraitManager.class, "Could not load portrait image! Category: " + category + "; Name: " + name); return getDefaultPortrait(); }</code><technical_language>suggestion if ((category == null) || (name == null)</technical_language>

Target:
public static Image getUnscaledPortraitImage(String category, String name) { if ((category == null) || (name == null) || category.equals(Crew.PORTRAIT_NONE)) { return getDefaultPortrait(); } initializePortraits(); if (portraitDirectory == null) { return getDefaultPortrait(); } try { if (category.equals(Crew.ROOT_PORTRAIT)) { category = ""; } if (name.equals(Crew.PORTRAIT_NONE)) { name = "default.gif"; } Image image = (Image) portraitDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } MegaMek.getLogger().error(PortraitManager.class, "Could not load portrait image! Category: " + category + "; Name: " + name); return getDefaultPortrait(); }
Source:
<code>public synchronized void compact() { for (long address : logCache.keySet()) { <START> if (address < startingAddress) { <END> LogData data = logCache.get(address); if (data != null) logSizeQuota.release (data.getSizeEstimate ()); logCache.remove(address); } } for (long address : trimmed) { LogData data = logCache.get(address); if (data != null) logSizeQuota.release (data.getSizeEstimate ()); logCache.remove(address); } for (long address : trimmed) { if (address < startingAddress) { trimmed.remove(address); } } }</code><technical_language>more consistent release resources close()</technical_language>

Target:
public synchronized void compact() { for (long address : logCache.keySet()) { if (address < startingAddress) { LogData data = logCache.get(address); if (data != null) { logSizeQuota.release(data.getSizeEstimate()); } logCache.remove(address); } } for (long address : trimmed) { LogData data = logCache.get(address); if (data != null) { logSizeQuota.release(data.getSizeEstimate()); } logCache.remove(address); } for (long address : trimmed) { if (address < startingAddress) { trimmed.remove(address); } } }
Source:
<code>private <C extends WriteCommand> Object writeManyRemoteCallback(WriteManyCommandHelper<C , ?, ?> helper,InvocationContext ctx, C command, Object rv) { ConsistentHash ch = checkTopologyId(command).getWriteConsistentHash(); Map<Address, Set<Integer>> backups = backupOwnersOfSegments(ch, ch.getPrimarySegmentsForOwner(rpcManager.getAddress())); if (backups.isEmpty()) { return rv; } boolean isSync = isSynchronous(command); CompletableFuture[] futures = isSync ? new CompletableFuture[backups.size()] : null; int future = 0; for (Entry<Address, Set<Integer>> backup : backups.entrySet()) { C copy = helper.copyForBackup(command, ch, backup.getValue()); copy.setTopologyId(command.getTopologyId()); Address backupOwner = backup.getKey(); if (isSync) { <START> MapResponseCollector collector = new MapResponseCollector(false, 1);futures[future++] = rpcManager.invokeCommand(backupOwner, copy, collector, rpcManager.getSyncRpcOptions()) <END> .toCompletableFuture(); } else { rpcManager.sendTo(backupOwner, copy, DeliverOrder.PER_SENDER); } } return isSync ? asyncValue(CompletableFuture.allOf(futures).thenApply(nil -> rv)) : rv; }</code><technical_language>a new line ; nice</technical_language>

Target:
private <C extends WriteCommand> Object writeManyRemoteCallback(WriteManyCommandHelper<C , ?, ?> helper,InvocationContext ctx, C command, Object rv) { ConsistentHash ch = checkTopologyId(command).getWriteConsistentHash(); Map<Address, Set<Integer>> backups = backupOwnersOfSegments(ch, ch.getPrimarySegmentsForOwner(rpcManager.getAddress())); if (backups.isEmpty()) { return rv; } boolean isSync = isSynchronous(command); CompletableFuture[] futures = isSync ? new CompletableFuture[backups.size()] : null; int future = 0; for (Entry<Address, Set<Integer>> backup : backups.entrySet()) { C copy = helper.copyForBackup(command, ch, backup.getValue()); copy.setTopologyId(command.getTopologyId()); Address backupOwner = backup.getKey(); if (isSync) { futures[future++] = rpcManager .invokeCommand(backupOwner, copy, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()) .toCompletableFuture(); } else { rpcManager.sendTo(backupOwner, copy, DeliverOrder.PER_SENDER); } } return isSync ? asyncValue(CompletableFuture.allOf(futures).thenApply(nil -> rv)) : rv; }
Source:
<code>public List<ArtifactEntry> findByCoordinates(String storageId, String repositoryId, Map<String, String> coordinates, int skip, <START> int limit, <END> String orderBy, boolean strict) { if (coordinates == null || coordinates.keySet().isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } coordinates = coordinates.entrySet() .stream() .filter(e -> e.getValue() != null) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() == null ? null : e.getValue().toLowerCase())); String sQuery = buildCoordinatesQuery(storageId, repositoryId, coordinates, skip, limit, orderBy, strict); OSQLSynchQuery<ArtifactEntry> oQuery = new OSQLSynchQuery<>(sQuery); Map<String, Object> parameterMap = new HashMap<>(coordinates); if (storageId != null && !storageId.trim().isEmpty()){ parameterMap.put("storageId", storageId); } if (repositoryId != null && !repositoryId.trim().isEmpty()){ parameterMap.put("repositoryId", repositoryId); } List<ArtifactEntry> entries = getDelegate().command(oQuery).execute(parameterMap); return entries; }</code><technical_language>Consider adding some new class (PagingCriteria ? ) additional parameter instead of two</technical_language>

Target:
public List<ArtifactEntry> findByCoordinates(String storageId, String repositoryId, Map<String, String> coordinates, int skip, int limit, String orderBy, boolean strict) { if (coordinates == null || coordinates.keySet().isEmpty()) { return findAll().orElse(Collections.EMPTY_LIST); } coordinates = prepareParameterMap(coordinates, true); String sQuery = buildCoordinatesQuery(storageId, repositoryId, coordinates.keySet(), skip, limit, orderBy, strict); OSQLSynchQuery<ArtifactEntry> oQuery = new OSQLSynchQuery<>(sQuery); Map<String, Object> parameterMap = new HashMap<>(coordinates); if (storageId != null && !storageId.trim().isEmpty()){ parameterMap.put("storageId", storageId); } if (repositoryId != null && !repositoryId.trim().isEmpty()){ parameterMap.put("repositoryId", repositoryId); } List<ArtifactEntry> entries = getDelegate().command(oQuery).execute(parameterMap); return entries; }
Source:
<code><START> private char getRandomCharacter() { <END> int randomCharPosition = random.nextInt(TEXT.length()); return TEXT.charAt(randomCharPosition); }</code><technical_language>This next method :)</technical_language>

Target:
private char getRandomCharacter() { int randomPosition = RANDOM.nextInt(CHARACTERS.length()); return CHARACTERS.charAt(randomPosition); }
Source:
<code>@Test public void requestConverterFactoryNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory) .build(); try { retrofit.requestBodyConverter(type, annotations); <START> } catch (IllegalArgumentException e) { <END> assertThat(e).hasMessage("" + "Could not locate RequestBody converter for class java.lang.String.\n" + " Tried:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory.called).isTrue(); }</code><technical_language>fail</technical_language>

Target:
@Test public void requestConverterFactoryNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory) .build(); try { retrofit.requestBodyConverter(type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate RequestBody converter for class java.lang.String.\n" + " Tried:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory.called).isTrue(); }
Source:
<code>public void setUp() { <START> jenkins.CLI.get().setEnabled(true); <END> Set<String> agentProtocols = new HashSet<>(j.jenkins.getAgentProtocols()); agentProtocols.add(ExtensionList.lookupSingleton(CliProtocol2.class).getName()); j.jenkins.setAgentProtocols(agentProtocols); }</code><technical_language>Unnecessary; is enabled default in core, disabled in wizard</technical_language>

Target:
public void setUp() { Set<String> agentProtocols = new HashSet<>(j.jenkins.getAgentProtocols()); agentProtocols.add(ExtensionList.lookupSingleton(CliProtocol2.class).getName()); j.jenkins.setAgentProtocols(agentProtocols); }
Source:
<code>public <T extends TopLevelItem> T create(Class<T> type, String name) { visit("newJob"); fillIn("name", name); findCaption(type, new Finder<WebElement>() { @Override protected WebElement find(String caption) { try { String normalizedCaption = caption.replace('.', '_'); return outer.find(by.css("li." + normalizedCaption)); } catch (NoSuchElementException e) { return outer.find(by.radioButton(caption)); } } }).click(); waitTillEnabledAndClick("OK", 10, TimeUnit.SECONDS); <START> waitFor(by.name("config")); <END> final T j = get(type, name); waitFor().withTimeout(3, TimeUnit.SECONDS) .until(new Callable<Object>() { @Override public Object call() throws Exception { try { j.getJson(); return true; } catch (Exception e) { return false; } } }); return j; }</code><technical_language>Is this waiting for config form interaction ready? In case is, I prefer do in Job.configure() if needed</technical_language>

Target:
public <T extends TopLevelItem> T create(Class<T> type, String name) { visit("newJob"); fillIn("name", name); findCaption(type, new Finder<WebElement>() { @Override protected WebElement find(String caption) { try { String normalizedCaption = caption.replace('.', '_'); return outer.find(by.css("li." + normalizedCaption)); } catch (NoSuchElementException e) { return outer.find(by.radioButton(caption)); } } }).click(); clickButton("OK"); waitFor(by.name("config"), 10); final T j = get(type, name); waitFor().withTimeout(3, TimeUnit.SECONDS) .until(new Callable<Object>() { @Override public Object call() throws Exception { try { j.getJson(); return true; } catch (Exception e) { return false; } } }); return j; }
Source:
<code>long useService(int value) { long result = serviceAmbassador.doRemoteFunction(value); <START> System.out.println(result); <END> return result; }</code><technical_language>logger</technical_language>

Target:
long useService(int value) { long result = serviceAmbassador.doRemoteFunction(value); LOGGER.info("Service result: " + result); return result; }
Source:
<code>public Builder keyValueSeparator(char keyValueSeparator) { if (keyValueSeparator == 0) throw new IllegalArgumentException("keyValueSeparator == 0"); if (keyValueSeparator == entrySeparator) { <START> throw new IllegalArgumentException("keyValueSeparator == entrySeparator"); <END> } this.keyValueSeparator = keyValueSeparator; return this; }</code><technical_language>Validating in setter is nicer I guess means default values 0 replace actual defaults in build. Otherwise, requires hoops do horrible, inconceivable, = entry separator , keyvalue separator</technical_language>

Target:
public Builder keyValueSeparator(char keyValueSeparator) { if (keyValueSeparator == 0) throw new IllegalArgumentException("keyValueSeparator == 0"); this.keyValueSeparator = keyValueSeparator; return this; }
Source:
<code>public void validateWebAnnotation(Annotation webAnnotation) throws ParamValidationException { if (webAnnotation.getCanonical() != null) { try { URI cannonicalUri = URI.create(webAnnotation.getCanonical()); if (!cannonicalUri.isAbsolute()) throw new ParamValidationException("The canonical URI is not absolute:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.CANONICAL, webAnnotation.getCanonical()}); } catch (IllegalArgumentException e) { throw new ParamValidationException("Error when validating canonical URI:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.CANONICAL, webAnnotation.getCanonical()}, e); } } if (webAnnotation.getVia() != null) { if (webAnnotation.getVia() instanceof String[]) { for (String via : webAnnotation.getVia()) { if(!(UriUtils.isUrl(via))) throw new ParamValidationException("This is not a valid URL:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.VIA, via}); } } } switch (webAnnotation.getMotivationType()) { case LINKING: if (webAnnotation.getTarget() != null) { if (webAnnotation.getTarget().getValue() != null) validateResource(webAnnotation.getTarget().getValue()); if (webAnnotation.getTarget().getValues() != null) for (String url : webAnnotation.getTarget().getValues()) { validateResource(url); } } break; case TAGGING: validateTag(webAnnotation); break; case TRANSCRIBING: <START> if (webAnnotation != null && webAnnotation.getBody() != null && webAnnotation.getBody().getRights() != null) <END> validateRights(webAnnotation.getBody().getRights()); break; default: break; } }</code><technical_language>if statement ca nbe included in validate method</technical_language>

Target:
public void validateWebAnnotation(Annotation webAnnotation) throws ParamValidationException { if (webAnnotation.getCanonical() != null) { try { URI cannonicalUri = URI.create(webAnnotation.getCanonical()); if (!cannonicalUri.isAbsolute()) throw new ParamValidationException("The canonical URI is not absolute:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.CANONICAL, webAnnotation.getCanonical()}); } catch (IllegalArgumentException e) { throw new ParamValidationException("Error when validating canonical URI:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.CANONICAL, webAnnotation.getCanonical()}, e); } } if (webAnnotation.getVia() != null) { if (webAnnotation.getVia() instanceof String[]) { for (String via : webAnnotation.getVia()) { if(!(UriUtils.isUrl(via))) throw new ParamValidationException("This is not a valid URL:", I18nConstants.ANNOTATION_VALIDATION, new String[]{WebAnnotationFields.VIA, via}); } } } switch (webAnnotation.getMotivationType()) { case LINKING: if (webAnnotation.getTarget() != null) { if (webAnnotation.getTarget().getValue() != null) validateResource(webAnnotation.getTarget().getValue()); if (webAnnotation.getTarget().getValues() != null) for (String url : webAnnotation.getTarget().getValues()) { validateResource(url); } } break; case TAGGING: validateTag(webAnnotation); break; case TRANSCRIBING: validateEdmRights(webAnnotation); break; default: break; } }
Source:
<code>public void testNetworkClientFactory() throws IOException { Properties props = new Properties(); VerifiableProperties vprops = new VerifiableProperties(props); NetworkConfig networkConfig = new NetworkConfig(vprops); NetworkMetrics networkMetrics = new NetworkMetrics(new MetricRegistry()); NetworkClientFactory networkClientFactory = new NetworkClientFactory(networkMetrics, networkConfig, null, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, new MockTime()); <START> networkClientFactory.getNetworkClient(); <END> }</code><technical_language>Check this is non-null</technical_language>

Target:
public void testNetworkClientFactory() throws IOException { Properties props = new Properties(); VerifiableProperties vprops = new VerifiableProperties(props); NetworkConfig networkConfig = new NetworkConfig(vprops); NetworkMetrics networkMetrics = new NetworkMetrics(new MetricRegistry()); NetworkClientFactory networkClientFactory = new NetworkClientFactory(networkMetrics, networkConfig, null, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, new MockTime()); Assert.assertNotNull("NetworkClient returned should be non-null", networkClientFactory.getNetworkClient()); }
Source:
<code>public GeneratedEntityMergeException(Object entity) { <START> super("Detected attempt to merge generated entity " + entity + ". Merging generated entities is not allowed"); <END> }</code><technical_language>.. merge <b>a</b> generated.... Merging <b>of</b>..</technical_language>

Target:
public GeneratedEntityMergeException(Object entity) { super("Detected attempt to merge a generated entity " + entity + ". Merging of generated entities is not allowed"); }
Source:
<code>List<Pair<OspfLinkTopologyEntity, OspfLinkTopologyEntity>> matchOspfLinks(List<OspfLinkTopologyEntity> allLinks){ List<Pair<OspfLinkTopologyEntity, OspfLinkTopologyEntity>> results = new ArrayList<>(); Set<Integer> parsed = new HashSet<Integer>(); Map<CompositeKey, OspfLinkTopologyEntity> targetLinks = new HashMap<>(); for(OspfLinkTopologyEntity targetLink : allLinks){ targetLinks.put(new CompositeKey(targetLink.getOspfIpAddr(), targetLink.getOspfRemIpAddr()) , targetLink); } for(OspfLinkTopologyEntity sourceLink : allLinks) { if (parsed.contains(sourceLink.getId())) { continue; } parsed.add(sourceLink.getId()); if (LOG.isDebugEnabled()) { LOG.debug("getOspfLinks: source: {}", sourceLink.toString()); } OspfLinkTopologyEntity targetLink = targetLinks.get(new CompositeKey(sourceLink.getOspfRemIpAddr() , sourceLink.getOspfIpAddr())); if(targetLink == null) { LOG.debug("getOspfLinks: cannot find target for source: '{}'", sourceLink.getId()); continue; } if (sourceLink.getId().equals(targetLink.getId()) || parsed.contains(targetLink.getId())) { continue; } <START> LOG.debug("getOspfLinks: target: {}", targetLink.toString()); <END> parsed.add(targetLink.getId()); results.add(Pair.of(sourceLink, targetLink)); } return results; }</code><technical_language>toString() logging. reason for this is, toString()method is implicitly called log level is enabled. If for example log level set WARNING, this execute toString() calculation if is shown afterwards</technical_language>

Target:
List<Pair<OspfLinkTopologyEntity, OspfLinkTopologyEntity>> matchOspfLinks(List<OspfLinkTopologyEntity> allLinks){ List<Pair<OspfLinkTopologyEntity, OspfLinkTopologyEntity>> results = new ArrayList<>(); Set<Integer> parsed = new HashSet<Integer>(); Map<CompositeKey, OspfLinkTopologyEntity> targetLinks = new HashMap<>(); for(OspfLinkTopologyEntity targetLink : allLinks){ targetLinks.put(new CompositeKey(targetLink.getOspfIpAddr(), targetLink.getOspfRemIpAddr()) , targetLink); } for(OspfLinkTopologyEntity sourceLink : allLinks) { if (parsed.contains(sourceLink.getId())) { continue; } parsed.add(sourceLink.getId()); if (LOG.isDebugEnabled()) { LOG.debug("getOspfLinks: source: {}", sourceLink); } OspfLinkTopologyEntity targetLink = targetLinks.get(new CompositeKey(sourceLink.getOspfRemIpAddr() , sourceLink.getOspfIpAddr())); if(targetLink == null) { LOG.debug("getOspfLinks: cannot find target for source: '{}'", sourceLink.getId()); continue; } if (sourceLink.getId().equals(targetLink.getId()) || parsed.contains(targetLink.getId())) { continue; } LOG.debug("getOspfLinks: target: {}", targetLink); parsed.add(targetLink.getId()); results.add(Pair.of(sourceLink, targetLink)); } return results; }
Source:
<code>public void notifyEntryExpired(Cache<K, V> cache, K key, V value) { try { if (!expiredListeners.isEmpty()) { List<CacheEntryEvent<? extends K, ? extends V>> events = createEvent(cache, key, value, EventType.EXPIRED); for (CacheEntryExpiredListener<K, V> listener : expiredListeners) { listener.onExpired(getEntryIterable(events, listenerCfgs.get(listener))); } } } finally { <START> notifySync(cache, key, value); <END> } }</code><technical_language>Is this supposed here? A cache entry expiring a synchronous thing</technical_language>

Target:
public void notifyEntryExpired(Cache<K, V> cache, K key, V value) { if (!expiredListeners.isEmpty()) { List<CacheEntryEvent<? extends K, ? extends V>> events = createEvent(cache, key, value, EventType.EXPIRED); for (CacheEntryExpiredListener<K, V> listener : expiredListeners) { listener.onExpired(getEntryIterable(events, listenerCfgs.get(listener))); } } }
Source:
<code>protected void auditResponseMessage(RetrieveDocumentSetResponseType response, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { <START> gov.hhs.fha.nhinc.common.auditlog.DocRetrieveResponseMessageType message = new gov.hhs.fha.nhinc.common.auditlog.DocRetrieveResponseMessageType(); <END> message.setRetrieveDocumentSetResponse(response); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieveResult(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }</code><technical_language>question above, do need fully-qualified name</technical_language>

Target:
protected void auditResponseMessage(RetrieveDocumentSetResponseType response, String direction, String connectInterface, AssertionType assertion, String requestCommunityID) { DocRetrieveResponseMessageType message = new DocRetrieveResponseMessageType(); message.setRetrieveDocumentSetResponse(response); message.setAssertion(assertion); AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logDocRetrieveResult(message, direction, connectInterface, requestCommunityID); if (auditLogMsg != null) { auditMessage(auditLogMsg, assertion); } }
Source:
<code>private static void changePolicyActivation(Instrumentation instrumentation, String adminName, String change) throws UiObjectNotFoundException { SettingsUtil.openItem(instrumentation, "Security"); UiDevice device = UiDevice.getInstance(instrumentation); UiScrollable itemList = new UiScrollable( new UiSelector().resourceIdMatches(Res.SETTINGS_LIST_CONTAINER_RES) ); itemList.setAsVerticalList(); itemList.getChildByText( new UiSelector().className("android.widget.TextView"), "Device administrators").clickAndWaitForNewWindow(); device.findObject(new UiSelector().text(adminName)).clickAndWaitForNewWindow(); UiObject scrollView = device.findObject( new UiSelector().className("android.widget.ScrollView")); scrollView.waitForExists(TimeUnit.SECONDS.toMillis(3L)); Rect labelRect = scrollView.getBounds(); device.swipe( labelRect.centerX(), labelRect.centerY(), labelRect.centerX(), labelRect.top, 10); UiObject actionButton = device.findObject( new UiSelector().resourceId("com.android.settings:id/action_button")); actionButton.waitForExists(TimeUnit.SECONDS.toMillis(3L)); Assert.assertTrue(actionButton.getText().contains(change)); if(change.equalsIgnoreCase("Activate")){ actionButton.clickAndWaitForNewWindow(); return; } actionButton.click(); <START> device.findObject(new UiSelector().text("OK")).waitForExists( TimeUnit.SECONDS.toMillis(3L)); <END> device.findObject(new UiSelector().text("OK")).click(); }</code><technical_language>Define object UiObject okButton (consistant above). set a boolean boolean hasButton</technical_language>

Target:
private static void changePolicyActivation(Instrumentation instrumentation, String adminName, String change) throws UiObjectNotFoundException { SettingsUtil.openItem(instrumentation, "Security"); UiDevice device = UiDevice.getInstance(instrumentation); UiScrollable itemList = new UiScrollable( new UiSelector().resourceIdMatches(Res.SETTINGS_LIST_CONTAINER_RES) ); itemList.setAsVerticalList(); itemList.getChildByText( new UiSelector().className("android.widget.TextView"), "Device administrators").clickAndWaitForNewWindow(); device.findObject(new UiSelector().text(adminName)).clickAndWaitForNewWindow(); UiObject scrollView = device.findObject( new UiSelector().className("android.widget.ScrollView")); scrollView.waitForExists(TimeUnit.SECONDS.toMillis(3L)); Rect labelRect = scrollView.getBounds(); device.swipe( labelRect.centerX(), labelRect.centerY(), labelRect.centerX(), labelRect.top, 10); UiObject actionButton = device.findObject( new UiSelector().resourceId("com.android.settings:id/action_button")); actionButton.waitForExists(TimeUnit.SECONDS.toMillis(3L)); Assert.assertTrue(actionButton.getText().contains(change)); if (change.equalsIgnoreCase("Activate")) { actionButton.clickAndWaitForNewWindow(); return; } actionButton.click(); UiObject okButton = device.findObject(new UiSelector().text("OK")); okButton.waitForExists(TimeUnit.SECONDS.toMillis(3L)); okButton.click(); }
Source:
<code><START> String getStubItemWithGsiTableName() { <END> return stubItemWithGsiTableName; }</code><technical_language>default/package level visibility</technical_language>

Target:
public String getStubItemWithGsiTableName() { return stubItemWithGsiTableName; }