auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void writeIndexToFile(long fileEndPointer) throws IOException, StoreException { if (prevNumOfEntriesWritten != index.size()) { File temp = new File(getFile().getAbsolutePath() + ".tmp"); FileOutputStream fileStream = new FileOutputStream(temp); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { rwLock.readLock().lock(); writer.writeShort(PersistentIndex.version); writer.writeInt(this.keySize); writer.writeInt(this.valueSize); writer.writeLong(fileEndPointer); int numOfEntries = 0; for (Map.Entry<StoreKey, IndexValue> entry : index.entrySet()) { if (entry.getValue().getOffset() + entry.getValue().getSize() <= fileEndPointer) { writer.write(entry.getKey().toBytes()); writer.write(entry.getValue().getBytes().array()); logger.trace("IndexSegment : writing key offset size fileEndOffset {}", getFile().getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), <START> entry.getValue().getOffset(), fileEndPointer); <END> numOfEntries++; } } prevNumOfEntriesWritten = numOfEntries; long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); temp.renameTo(getFile()); } catch (IOException e) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " IO error while persisting index to disk", e, StoreErrorCodes.IOError); } finally { writer.close(); rwLock.readLock().unlock(); } logger.trace("IndexSegment : completed writing index to file", indexFile.getAbsolutePath()); } }</code><technical_language>size offset. (you passing in offset twice)</technical_language>

Target:
public void writeIndexToFile(long fileEndPointer) throws IOException, StoreException { if (prevNumOfEntriesWritten != index.size()) { File temp = new File(getFile().getAbsolutePath() + ".tmp"); FileOutputStream fileStream = new FileOutputStream(temp); CrcOutputStream crc = new CrcOutputStream(fileStream); DataOutputStream writer = new DataOutputStream(crc); try { rwLock.readLock().lock(); writer.writeShort(PersistentIndex.version); writer.writeInt(this.keySize); writer.writeInt(this.valueSize); writer.writeLong(fileEndPointer); int numOfEntries = 0; for (Map.Entry<StoreKey, IndexValue> entry : index.entrySet()) { if (entry.getValue().getOffset() + entry.getValue().getSize() <= fileEndPointer) { writer.write(entry.getKey().toBytes()); writer.write(entry.getValue().getBytes().array()); logger.trace("IndexSegment : writing key - value - offset size fileEndOffset {}", getFile().getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), entry.getValue().getSize(), fileEndPointer); numOfEntries++; } } prevNumOfEntriesWritten = numOfEntries; long crcValue = crc.getValue(); writer.writeLong(crcValue); fileStream.getChannel().force(true); temp.renameTo(getFile()); } catch (IOException e) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " IO error while persisting index to disk", e, StoreErrorCodes.IOError); } finally { writer.close(); rwLock.readLock().unlock(); } logger.trace("IndexSegment : completed writing index to file", indexFile.getAbsolutePath()); } }
Source:
<code>public String run(Transition trans, Attributes a) { StringBuilder sb = new StringBuilder(); boolean verbose = a.typeSafeGet(Boolean.class, PRINT_VERBOSE_GRAPH); KRunGraph graph = a.typeSafeGet(KRunGraph.class); if (definition == null) { definition = a.typeSafeGet(Attribute.Key.get(Definition.class)); populateRuleStore(); } if (unparser == null) { Context context = a.typeSafeGet(Context.class); unparser = new Unparser(context); } Location location = trans.getLocation(); Source source = trans.getSource(); <START> Pair keyPair = new MutablePair<>(source, location); <END> ModuleItem ruleItem = ruleStore.get(keyPair); if (trans.getType() == TransitionType.RULE) { if (verbose) { sb.append("\n"); sb.append(statePrinter.run(graph.getSource(trans), a)); sb.append("\n=>\n"); sb.append(statePrinter.run(graph.getDest(trans), a)); sb.append("\n"); sb.append("Rule at Source " + source.toString() + " " + location.toString() + "\n"); if (ruleItem != null) { sb.append(unparser.print(ruleItem)); } } else { sb.append(" [Node "); sb.append(graph.getSource(trans).getStateId()); sb.append(" Rule at " + source.toString() + " " + location.toString()); sb.append(", Node "); sb.append(graph.getDest(trans).getStateId()); sb.append("]\n"); } return sb.toString(); } else if (trans.getType() == TransitionType.REDUCE) { sb.append("\nFunction evaluation"); } else if (trans.getType() == TransitionType.UNLABELLED) { sb.append("\nUnlabelled rule"); } else { sb.append("\nRead " + StringBuiltin.of(trans.getReadString()).value()); } return sb.toString(); }</code><technical_language>same: Pair.of</technical_language>

Target:
public String run(Transition trans, Attributes a) { StringBuilder sb = new StringBuilder(); boolean verbose = a.typeSafeGet(Boolean.class, PRINT_VERBOSE_GRAPH); KRunGraph graph = a.typeSafeGet(KRunGraph.class); if (definition == null) { definition = a.typeSafeGet(Attribute.Key.get(Definition.class)); populateRuleStore(); } if (unparser == null) { Context context = a.typeSafeGet(Context.class); unparser = new Unparser(context); } Location location = trans.getLocation(); Source source = trans.getSource(); Pair keyPair = Pair.of(source, location); ModuleItem ruleItem = ruleStore.get(keyPair); if (trans.getType() == TransitionType.RULE) { if (verbose) { sb.append("\n"); sb.append(statePrinter.run(graph.getSource(trans), a)); sb.append("\n=>\n"); sb.append(statePrinter.run(graph.getDest(trans), a)); sb.append("\n"); sb.append("Rule at Source " + source.toString() + " " + location.toString() + "\n"); if (ruleItem != null) { sb.append(unparser.print(ruleItem)); } } else { sb.append(" [Node "); sb.append(graph.getSource(trans).getStateId()); sb.append(" Rule at " + source.toString() + " " + location.toString()); sb.append(", Node "); sb.append(graph.getDest(trans).getStateId()); sb.append("]\n"); } return sb.toString(); } else if (trans.getType() == TransitionType.REDUCE) { sb.append("\nFunction evaluation"); } else if (trans.getType() == TransitionType.UNLABELLED) { sb.append("\nUnlabelled rule"); } else { sb.append("\nRead " + StringBuiltin.of(trans.getReadString()).value()); } return sb.toString(); }
Source:
<code><START> public boolean awaitTerminalEvent(long timeout, TimeUnit unit) { <END> try { return latch.await(timeout, unit); } catch (InterruptedException e) { throw new RuntimeException("Interrupted", e); } }</code><technical_language>This is a breaking change</technical_language>

Target:
public void awaitTerminalEvent(long timeout, TimeUnit unit) { try { if (!latch.await(timeout, unit)) { throw new RuntimeException(new TimeoutException()); } } catch (InterruptedException e) { throw new RuntimeException("Interrupted", e); } }
Source:
<code>protected Collection<String> getInAppFrames(Dsn dsn) { if (dsn.getOptions().containsKey(IN_APP_FRAMES_OPTION)) { ArrayList<String> inAppPackages = new ArrayList<>(); for (String inAppPackage : dsn.getOptions().get(IN_APP_FRAMES_OPTION).split(",")) { if (!inAppPackage.trim().equals("")) { inAppPackages.add(inAppPackage); } } return inAppPackages; } <START> return Collections.emptyList(); <END> }</code><technical_language>Stylistic nitpick: usually, in this case, invert conditional top return empty immediately top of function, wrapping bulk of "real" code in conditional block. (Is this idomatic Java style?)</technical_language>

Target:
protected Collection<String> getInAppFrames(Dsn dsn) { if (!dsn.getOptions().containsKey(IN_APP_FRAMES_OPTION)) { return Collections.emptyList(); } ArrayList<String> inAppPackages = new ArrayList<>(); for (String inAppPackage : dsn.getOptions().get(IN_APP_FRAMES_OPTION).split(",")) { if (!inAppPackage.trim().equals("")) { inAppPackages.add(inAppPackage); } } return inAppPackages; }
Source:
<code>@Override public void log(int priority, @Nullable String tag, @NonNull String message) { checkNotNull(message); <START> <END> Log.println(priority, tag, message); }</code><technical_language>In here, check empty/null case of tag provide a default tag. "NO_TAG" ok</technical_language>

Target:
@Override public void log(int priority, @Nullable String tag, @NonNull String message) { checkNotNull(message); if (tag == null) { tag = DEFAULT_TAG; } Log.println(priority, tag, message); }
Source:
<code>private boolean isMatchPath(String[] linkPathSegments, List<PathSegment> uriPathSegments) { for (int i = 0; i < linkPathSegments.length; i++) { String uriPathSegment = uriPathSegments.get(i).getPath(); <START> if (isUUID(uriPathSegment) || uriPathSegment.equals(linkPathSegments[i])) { <END> continue; } else { return false; } } return true; }</code><technical_language>invert condition return false: if (!isUUID(uriPathSegment) && !uriPathSegment.equals(linkPathSegments[i])) { return false; } need else branch</technical_language>

Target:
private boolean isMatchPath(String[] linkPathSegments, List<PathSegment> uriPathSegments) { for (int i = 0; i < linkPathSegments.length; i++) { String uriPathSegment = uriPathSegments.get(i).getPath(); if (!isUUID(uriPathSegment) && !uriPathSegment.equals(linkPathSegments[i])) { return false; } } return true; }
Source:
<code>public String toString() { try { return asString(); } catch (Exception e) { <START> Log.e("RestResponse: toString()", "Exception caught while calling asString()"); <END> return ((response == null) ? "" : response.toString()); } }</code><technical_language>log exception too: Log.e("RestResponse: toString()", "Exception caught while calling asString()", e);</technical_language>

Target:
public String toString() { try { return asString(); } catch (Exception e) { Log.e("RestResponse: toString()", "Exception caught while calling asString()", e); return ((response == null) ? "" : response.toString()); } }
Source:
<code>protected <T extends HazelcastEntity> Collection<T> find(Collection<String> devices, Collection<String> names, Date timestamp, String status, Integer take, Boolean hasResponse, HivePrincipal principal, Class<T> entityClass) { <START> final Predicate filters = hazelcastHelper.prepareFilters(getAvailableDevices(devices, principal), names, timestamp, status, hasResponse); <END> return retrieve(filters, take, entityClass); }</code><technical_language>@YermakovSergiy a matter of coding style, introduce new variable</technical_language>

Target:
protected <T extends HazelcastEntity> Collection<T> find(Collection<String> devices, Collection<String> names, Date timestamp, String status, Integer take, Boolean hasResponse, HivePrincipal principal, Class<T> entityClass) { List<String> availableDevicesGUIDs = getAvailableDevices(devices, principal); final Predicate filters = hazelcastHelper.prepareFilters(availableDevicesGUIDs, names, timestamp, status, hasResponse); return retrieve(filters, take, entityClass); }
Source:
<code>void checkPreferredLocation(Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { String preferredLocation = configuration.getConfigurationValue(PREFERRED_LOCATION, localizationContext); if (preferredLocation != null && !preferredLocation.isEmpty()) { LOG.info(">> Querying zone '{}'", preferredLocation); GoogleCredentials credentials = provider.getCredentials(); Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String regionName = provider.getConfigurationValue(REGION_SQL, localizationContext); String computeRegionName = regionName; <START> if (computeRegionName.equals("us-central")) { <END> computeRegionName = "us-central1"; } try { Zone zone = compute.zones().get(projectId, preferredLocation).execute(); if (!Urls.getLocalName(zone.getRegion()).equals(computeRegionName)) { addError(accumulator, PREFERRED_LOCATION, localizationContext, null, PREFERRED_LOCATION_NOT_FOUND_IN_REGION_MSG, preferredLocation, regionName, projectId); } } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { addError(accumulator, PREFERRED_LOCATION, localizationContext, null, PREFERRED_LOCATION_NOT_FOUND_MSG, preferredLocation, projectId); } else { throw new TransientProviderException(e); } } catch (IOException e) { throw new TransientProviderException(e); } } }</code><technical_language>This brittle</technical_language>

Target:
void checkPreferredLocation(Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { String preferredLocation = configuration.getConfigurationValue(PREFERRED_LOCATION, localizationContext); if (preferredLocation != null && !preferredLocation.isEmpty()) { LOG.info(">> Querying zone '{}'", preferredLocation); GoogleCredentials credentials = provider.getCredentials(); Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String cloudSQLRegionName = provider.getConfigurationValue(REGION, localizationContext); String computeRegionName = Names.convertCloudSQLRegionToComputeRegion(cloudSQLRegionName, provider.getGoogleConfig()); try { Zone zone = compute.zones().get(projectId, preferredLocation).execute(); if (!Urls.getLocalName(zone.getRegion()).equals(computeRegionName)) { addError(accumulator, PREFERRED_LOCATION, localizationContext, null, PREFERRED_LOCATION_NOT_FOUND_IN_REGION_MSG, preferredLocation, cloudSQLRegionName, projectId); } } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { addError(accumulator, PREFERRED_LOCATION, localizationContext, null, PREFERRED_LOCATION_NOT_FOUND_MSG, preferredLocation, projectId); } else { throw new TransientProviderException(e); } } catch (IOException e) { throw new TransientProviderException(e); } } }
Source:
<code>public static <T> TranslatedExpression<T> untranslated(RowExpression originalExpression) { <START> return new TranslatedExpression<>(Optional.empty(), originalExpression, emptyList()); <END> }</code><technical_language>ImmutableList.of()</technical_language>

Target:
public static <T> TranslatedExpression<T> untranslated(RowExpression originalExpression) { return new TranslatedExpression<>(Optional.empty(), originalExpression, ImmutableList.of()); }
Source:
<code>public void initializeVanityUrlCache(String hostId, long languageId) { List<VanityUrl> activeVanityUrls = APILocator.getVanityUrlAPI() .getActiveVanityUrlsByHostAndLanguage(hostId, languageId, APILocator.systemUser()); <START> activeVanityUrls.stream().forEach((VanityUrl vanity) -> updateCache(vanity)); <END> }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Replace this lambda a method reference. (sonar.java.source set. Assuming 8 greater.) [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public void initializeVanityUrlCache(String hostId, long languageId) { List<VanityUrl> activeVanityUrls = APILocator.getVanityUrlAPI() .getActiveVanityUrlsByHostAndLanguage(hostId, languageId, APILocator.systemUser()); activeVanityUrls.forEach(this::updateCache); }
Source:
<code>public void modifyPool(org.ovirt.engine.core.common.businessentities.MacPool macPool) { try (AutoCloseableLock lock = writeLockResource()) { if (!macPools.containsKey(macPool.getId())) { throw new IllegalStateException(INEXISTENT_POOL_EXCEPTION_MESSAGE); } log.debug("Updating pool {}. (old will be deleted and <START> new initialized from db entity)", <END> macPool); removeWithoutLocking(macPool.getId()); initializeMacPool(macPool); } }</code><technical_language>new created DB entitity initialized cluster vNics consider breaking reporting steps (moving relevant caode locations): creating, initializing vnics</technical_language>

Target:
public void modifyPool(org.ovirt.engine.core.common.businessentities.MacPool macPool) { try (AutoCloseableLock lock = writeLockResource()) { Guid macPoolId = macPool.getId(); if (!macPools.containsKey(macPoolId)) { throw new IllegalStateException(createExceptionMessageMacPoolHavingIdDoesNotExist(macPoolId)); } log.debug("Updating pool {}. (old will be deleted and new initialized from db entity)", macPool); removeWithoutLocking(macPoolId); initializeMacPool(macPool); } }
Source:
<code>public boolean isApplicable(Class<? extends AbstractProject<?,?>> jobType) { <START> return true; <END> }</code><technical_language>isPresent() is expected here</technical_language>

Target:
public boolean isApplicable(Class<? extends AbstractProject<?,?>> jobType) { return AbortAndRestartOperation.isPresent(); }
Source:
<code>public Response addMetadata(@PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname, @PathParam("namespace") @ApiParam(value = "namespace", required = true) String namespace, @ApiParam(value = "metadata", required = true) MetadataDTO metadata) { Item item = getItem(itemname); if (item == null) { logger.info("Received HTTP PUT request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname); return Response.status(Status.NOT_FOUND).build(); } <START> if (namespace.startsWith(MetadataRegistry.INTERNAL_NAMESPACE_PREFIX)) { <END> logger.info("Received HTTP PUT request at '{}' for internal namespace '{}'.", uriInfo.getPath(), namespace); return Response.status(Status.FORBIDDEN).build(); } MetadataKey key = new MetadataKey(namespace, itemname); Metadata md = new Metadata(key, metadata.value, metadata.config); if (metadataRegistry.get(key) == null) { metadataRegistry.add(md); return Response.status(Status.CREATED).type(MediaType.TEXT_PLAIN).build(); } else { metadataRegistry.update(md); return Response.ok(null, MediaType.TEXT_PLAIN).build(); } }</code><technical_language>isInternalNamespace(namespace))</technical_language>

Target:
public Response addMetadata(@PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname, @PathParam("namespace") @ApiParam(value = "namespace", required = true) String namespace, @ApiParam(value = "metadata", required = true) MetadataDTO metadata) { Item item = getItem(itemname); if (item == null) { logger.info("Received HTTP PUT request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname); return Response.status(Status.NOT_FOUND).build(); } if (metadataRegistry.isInternalNamespace(namespace)) { logger.info("Received HTTP PUT request at '{}' for internal namespace '{}'.", uriInfo.getPath(), namespace); return Response.status(Status.FORBIDDEN).build(); } MetadataKey key = new MetadataKey(namespace, itemname); Metadata md = new Metadata(key, metadata.value, metadata.config); if (metadataRegistry.get(key) == null) { metadataRegistry.add(md); return Response.status(Status.CREATED).type(MediaType.TEXT_PLAIN).build(); } else { metadataRegistry.update(md); return Response.ok(null, MediaType.TEXT_PLAIN).build(); } }
Source:
<code><START> public TimestampSpec getTimestampSpec() <END> { return timestampSpec; }</code><technical_language>Suggestion: this private, clients of this class other Jackson getNonNullTimestampSpec(). Also, rename this method API nicer short name getTimestampSpec()</technical_language>

Target:
public TimestampSpec getTimestampSpec() { if (timestampSpec == null) { timestampSpec = Preconditions.checkNotNull(getParser(), "inputRowParser").getParseSpec().getTimestampSpec(); } return timestampSpec; }
Source:
<code>public static MessageNumberSet[] createMessageNumberSets(@Nonnull final int[] msgs) { final List<MessageNumberSet> v = new ArrayList<MessageNumberSet>(); int i = 0; while (i < msgs.length) { int start = msgs[i]; int j = i + 1; while (j < msgs.length && msgs[j] == msgs[j - 1] + 1) { j++; } int end = msgs[j - 1]; v.add(new MessageNumberSet(start, end)); i = j; } <START> return v.toArray(new MessageNumberSet[0]); <END> }</code><technical_language>I original code is better, allocate memory size for MessageNumberSet array based v.size(). If changed 0, needs allocate default size in toArray(), is memory efficient before</technical_language>

Target:
public static MessageNumberSet[] createMessageNumberSets(@Nonnull final int[] msgs) { final List<MessageNumberSet> v = new ArrayList<MessageNumberSet>(); int i = 0; while (i < msgs.length) { int start = msgs[i]; int j = i + 1; while (j < msgs.length && msgs[j] == msgs[j - 1] + 1) { j++; } int end = msgs[j - 1]; v.add(new MessageNumberSet(start, end)); i = j; } return v.toArray(new MessageNumberSet[v.size()]); }
Source:
<code>private static Map<String, Integer> createCountryCodeByIsoMap() { Map<String, Integer> map = new HashMap<>(MAX_COUNTRIES); for (int i = 0; i < COUNTRY_TO_REGION_CODES.size(); i++) { int code = COUNTRY_TO_REGION_CODES.keyAt(i); List<String> regions = COUNTRY_TO_REGION_CODES.get(code); for (String region : regions) { map.put(region, code); } } <START> map.remove("001"); <END> map.remove("TA"); map.put("HM", 672); map.put("GS", 500); map.put("XK", 381); return map; }</code><technical_language>Ok in COUNTRY_TO_REGION_CODES have: java map.put(800, singletonList("001")); map.put(808, singletonList("001")); // ... map.put(870, singletonList("001")); map.put(878, singletonList("001")); // ... map.put(881, singletonList("001")); map.put(882, singletonList("001")); map.put(883, singletonList("001")); // ... map.put(888, singletonList("001")); // ... map.put(979, singletonList("001")); looping map overwrite 001 key with, 800 808 870 etc. while end result is OK do map.remove("001") I worried map inversion technique. other codes multiple times overwriting? If a problem</technical_language>

Target:
private static Map<String, Integer> createCountryCodeByIsoMap() { Map<String, Integer> map = new HashMap<>(MAX_COUNTRIES); for (int i = 0; i < COUNTRY_TO_REGION_CODES.size(); i++) { int code = COUNTRY_TO_REGION_CODES.keyAt(i); List<String> regions = COUNTRY_TO_REGION_CODES.get(code); for (String region : regions) { if (region.equals("001")) { continue; } if (map.containsKey(region)) { throw new IllegalStateException("Duplicate regions for country code: " + code); } map.put(region, code); } } map.remove("TA"); map.put("HM", 672); map.put("GS", 500); map.put("XK", 381); return map; }
Source:
<code>public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException { includeValue= includeValue && fValue != Value.UNKNOWN; short firstBytes = ITypeMarshalBuffer.EVAL_FIXED; if (includeValue) firstBytes |= ITypeMarshalBuffer.FLAG1; switch (fValueCategory) { case LVALUE: firstBytes |= ITypeMarshalBuffer.FLAG2; break; case PRVALUE: <START> firstBytes |= ITypeMarshalBuffer.FLAG3; <END> break; default: break; } buffer.putShort(firstBytes); buffer.marshalType(fType); if (includeValue) { buffer.marshalValue(fValue); } }</code><technical_language>sense swap FLAG2 FLAG3 LVALUE is common PRVALUE</technical_language>

Target:
public void marshal(ITypeMarshalBuffer buffer, boolean includeValue) throws CoreException { includeValue= includeValue && fValue != Value.UNKNOWN; short firstBytes = ITypeMarshalBuffer.EVAL_FIXED; if (includeValue) firstBytes |= ITypeMarshalBuffer.FLAG1; switch (fValueCategory) { case PRVALUE: firstBytes |= ITypeMarshalBuffer.FLAG2; break; case LVALUE: firstBytes |= ITypeMarshalBuffer.FLAG3; break; default: break; } buffer.putShort(firstBytes); buffer.marshalType(fType); if (includeValue) { buffer.marshalValue(fValue); } }
Source:
<code>public abstract H launchApp(StreamingApplication application, Configuration configuration, Attribute.AttributeMap launchParameters) throws LauncherException; public void shutdownApp(H app) { shutdownApp(app, ShutdownMode.ORDERLY); }</code><technical_language>formatting</technical_language>

Target:
public abstract H launchApp(StreamingApplication application, Configuration configuration, Attribute.AttributeMap launchParameters) throws LauncherException; public void shutdownApp(H app) throws LauncherException { shutdownApp(app, ShutdownMode.AWAIT_TERMINATION); }
Source:
<code>private void drop( final DruidCoordinatorRuntimeParams params, final DataSegment segment, final CoordinatorStats stats ) { final DruidCluster druidCluster = params.getDruidCluster(); <START> for (final Object2IntMap.Entry<String> entry : targetReplicants.object2IntEntrySet()) { <END> final String tier = entry.getKey(); if (druidCluster.hasTier(tier) && entry.getIntValue() > currentReplicants.getOrDefault(tier, 0)) { return; } } for (final Object2IntMap.Entry<String> entry : currentReplicants.object2IntEntrySet()) { final String tier = entry.getKey(); final NavigableSet<ServerHolder> holders = druidCluster.getHistoricalsByTier(tier); final int numDropped; if (holders == null) { log.makeAlert("No holders found for tier[%s]", tier).emit(); numDropped = 0; } else { final int currentReplicantsInTier = entry.getIntValue(); final int numToDrop = currentReplicantsInTier - targetReplicants.getOrDefault(tier, 0); numDropped = dropForTier(numToDrop, holders, segment); } stats.addToTieredStat(DROPPED_COUNT, tier, numDropped); } }</code><technical_language>Please extract this block a method boolean result</technical_language>

Target:
private void drop( final DruidCoordinatorRuntimeParams params, final DataSegment segment, final CoordinatorStats stats ) { final DruidCluster druidCluster = params.getDruidCluster(); if (loadingInProgress(druidCluster)) { return; } for (final Object2IntMap.Entry<String> entry : currentReplicants.object2IntEntrySet()) { final String tier = entry.getKey(); final NavigableSet<ServerHolder> holders = druidCluster.getHistoricalsByTier(tier); final int numDropped; if (holders == null) { log.makeAlert("No holders found for tier[%s]", tier).emit(); numDropped = 0; } else { final int currentReplicantsInTier = entry.getIntValue(); final int numToDrop = currentReplicantsInTier - targetReplicants.getOrDefault(tier, 0); numDropped = dropForTier(numToDrop, holders, segment); } stats.addToTieredStat(DROPPED_COUNT, tier, numDropped); } }
Source:
<code>public static Pair<SizeUnit, Double> autoConvert(long size, SizeUnit inUnit) { for (Pair<Long, SizeUnit> currentUnitPair : SizeUnit.weightToUnit) { if (size / Math.pow(CONVERT_FACTOR, currentUnitPair.getFirst() - inUnit.getUnitWeight()) >= 1) { return new Pair<SizeConverter.SizeUnit, Double>(currentUnitPair.getSecond(), Double.valueOf(SizeConverter.convert(size, inUnit, currentUnitPair.getSecond()).doubleValue())); } } return new Pair<SizeConverter.SizeUnit, Double>(SizeUnit.BYTES, Double.valueOf(size)); <START> } <END></code><technical_language>casting double</technical_language>

Target:
public static Pair<SizeUnit, Double> autoConvert(long size, SizeUnit inUnit) { for (Pair<Long, SizeUnit> currentUnitPair : SizeUnit.weightToUnit) { if (size / Math.pow(CONVERT_FACTOR, currentUnitPair.getFirst() - inUnit.getUnitWeight()) >= 1) { return new Pair<SizeConverter.SizeUnit, Double>(currentUnitPair.getSecond(), SizeConverter.convert(size, inUnit, currentUnitPair.getSecond()).doubleValue()); } } return new Pair<SizeConverter.SizeUnit, Double>(SizeUnit.BYTES, (double)size); }
Source:
<code>public PatternDSL.PatternDef<A> getAPattern() { <START> return leftParentStream.getLeftPattern(); <END> }</code><technical_language>DroolsAbstractBiConstraintStream getAPattern()? If Tri's getAPattern(), getBPattern() getCPattern() Bi's getAPattern(), getBPattern() - getLeftPattern() getRightPattern() Uni's getAPattern() day Quads getAPattern(), getBPattern() getCPattern() getDPattern()</technical_language>

Target:
public PatternDSL.PatternDef<A> getAPattern() { return leftParentStream.getAPattern(); }
Source:
<code>protected void ensureValuesCapacity(int capacity, boolean includeNulls) { if (values.length < capacity) { values = Arrays.copyOf(values, Math.max(capacity + 10, values.length * 2)); if (valueIsNull != null) { valueIsNull = Arrays.copyOf(valueIsNull, values.length); } } <START> if (includeNulls && valueIsNull == null) { <END> valueIsNull = new boolean[values.length]; } }</code><technical_language>want resize valueIsNull match size of values.length if array is null? Edit: I do above</technical_language>

Target:
protected void ensureValuesCapacity(int capacity, boolean includeNulls) { if (values == null) { values = new long[capacity]; } else if (values.length < capacity) { values = Arrays.copyOf(values, Math.max(capacity + 10, values.length * 2)); if (valueIsNull != null) { valueIsNull = Arrays.copyOf(valueIsNull, values.length); } } if (includeNulls && valueIsNull == null) { valueIsNull = new boolean[values.length]; } }
Source:
<code>public boolean lookupMD5Quick(Content content) throws TskCoreException { assert content instanceof AbstractFile; if (content instanceof AbstractFile) { AbstractFile file = (AbstractFile) content; if (null != file.getMd5Hash()) { try{ return EamDb.getInstance().isFileHashInReferenceSet(file.getMd5Hash(), this.referenceSetID); } catch (EamDbException ex){ <START> Logger.getLogger(SleuthkitHashSet.class.getName()).log(Level.SEVERE, "Error performing central reposiotry hash lookup", ex); END> throw new TskCoreException("Error performing central reposiotry hash lookup", ex); } } } return false; }</code><technical_language>I in debugging if identify database experienced error</technical_language>

Target:
public boolean lookupMD5Quick(Content content) throws TskCoreException { assert content instanceof AbstractFile; if (content instanceof AbstractFile) { AbstractFile file = (AbstractFile) content; if (null != file.getMd5Hash()) { try{ return EamDb.getInstance().isFileHashInReferenceSet(file.getMd5Hash(), this.referenceSetID); } catch (EamDbException ex){ Logger.getLogger(SleuthkitHashSet.class.getName()).log(Level.SEVERE, "Error performing central reposiotry hash lookup for hash " + file.getMd5Hash() + " in reference set " + referenceSetID, ex); throw new TskCoreException("Error performing central reposiotry hash lookup", ex); } } } return false; }
Source:
<code>public boolean chkAuthorization(String userName, List<String> projectIds, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { boolean haveAccess = false; for (String projectId : projectIds) { haveAccess = chkAuthorization(userName, projectId, userRoles); if (!haveAccess) { break; } } <START> return haveAccess; <END> }</code><technical_language>this condensed if (!chkAuthorization(...)) { return false; } ... return true get rid of haveAccess</technical_language>

Target:
public boolean chkAuthorization(String userName, List<String> projectIds, String[] userRoles) throws QuadrigaStorageException, QuadrigaAccessException { for (String projectId : projectIds) { if (!chkAuthorization(userName, projectId, userRoles)) { return false; } } return true; }
Source:
<code>static <T> Future<T> of(ExecutorService executorService, CheckedSupplier<? extends T> computation, long delay) { Objects.requireNonNull(executorService, "executorService is null"); Objects.requireNonNull(computation, "computation is null"); final FutureImpl<T> future = new FutureImpl<>(executorService); final CheckedSupplier<? extends T> task = (delay <= 0) ? computation : () -> { <START> Thread.sleep(delay); <END> return computation.get(); }; future.run(task); return future; }</code><technical_language>sleep</technical_language>

Target:
static <T> Future<T> of(ExecutorService executorService, CheckedSupplier<? extends T> computation, long delay) { Objects.requireNonNull(executorService, "executorService is null"); Objects.requireNonNull(computation, "computation is null"); final FutureImpl<T> future = new FutureImpl<>(executorService); future.run(computation, delay); return future; }
Source:
<code>private void refreshProject() { <START> projectService.getProject(appContext.getWorkspace().getId(), "Spring", new AsyncRequestCallback<ProjectConfigDto>( <END> dtoUnmarshallerFactory.newUnmarshaller(ProjectConfigDto.class)) { @Override protected void onSuccess(ProjectConfigDto result) { eventBus.fireEvent(new ProjectUpdatedEvent(project.getPath(), result)); } @Override protected void onFailure(Throwable exception) { notificationManager.notify(exception.getLocalizedMessage(), FAIL, true, project); } }); }</code><technical_language>I refresh current project instead of "Spring"</technical_language>

Target:
private void refreshProject() { projectService.getProject(workspaceId, project.getName(), new AsyncRequestCallback<ProjectConfigDto>( dtoUnmarshallerFactory.newUnmarshaller(ProjectConfigDto.class)) { @Override protected void onSuccess(ProjectConfigDto result) { eventBus.fireEvent(new ProjectUpdatedEvent(project.getPath(), result)); } @Override protected void onFailure(Throwable exception) { notificationManager.notify(exception.getLocalizedMessage(), FAIL, true, project); } }); }
Source:
<code>public void createKafkaTopic(String topic_name) throws Exception { try{ commonspec.getLogger().debug("Creating a kafka topic"); commonspec.getKafkaUtils().createTopic(topic_name); <START> }catch (Exception e) { <END> commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } }</code><technical_language>exception caught, trown runtime</technical_language>

Target:
public void createKafkaTopic(String topic_name) throws Exception { commonspec.getLogger().debug("Creating a kafka topic"); commonspec.getKafkaUtils().createTopic(topic_name); }
Source:
<code>protected void activateDefaultView(String deepLinkPath) { <START> boolean isStartup = m_attachedCount <= 1; <END> if (safeHandleDeepLink(deepLinkPath)) { } else if (isStartup) { interceptDefaultView(); } }</code><technical_language>rearranging this method more readable? if (safeHandleDeepLink(deepLinkPath)) { return; } if (m_attachedCount <= 1) { // startup interceptDefaultView(); }</technical_language>

Target:
protected void activateDefaultView(String deepLinkPath) { if (safeHandleDeepLink(deepLinkPath)) { return; } if (m_attachedCount <= 1) { interceptDefaultView(); } }
Source:
<code>public String update(Request request, Response response) { String environmentName = request.params("name"); BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) buildEntityFromRequestBody(request); EnvironmentConfig oldEnvironmentConfig = fetchEntityFromConfig(environmentName); HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult(); if (!environmentConfig.getAllErrors().isEmpty()) { operationResult.unprocessableEntity("Error parsing environment config from the request"); return handleCreateOrUpdateResponse(request, response, environmentConfig, operationResult); } if (isPutRequestStale(request, oldEnvironmentConfig)) { <START> throw haltBecauseEtagDoesNotMatch("environment", environmentName); <END> } if (!StringUtils.equals(environmentName, environmentConfig.name().toString())) { throw haltBecauseRenameOfEntityIsNotSupported("environment"); } environmentConfigService.updateEnvironment(environmentConfig.name().toString(), environmentConfig, currentUsername(), etagFor(oldEnvironmentConfig), operationResult); setEtagHeader(environmentConfig, response); return handleCreateOrUpdateResponse(request, response, environmentConfig, operationResult); }</code><technical_language><LINK_0></technical_language>

Target:
public String update(Request request, Response response) { String environmentName = request.params("name"); BasicEnvironmentConfig environmentConfig = (BasicEnvironmentConfig) buildEntityFromRequestBody(request); EnvironmentConfig oldEnvironmentConfig = fetchEntityFromConfig(environmentName); HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult(); if (!StringUtils.equalsIgnoreCase(environmentName, environmentConfig.name().toString())) { throw haltBecauseRenameOfEntityIsNotSupported("environment"); } if (!environmentConfig.getAllErrors().isEmpty()) { operationResult.unprocessableEntity("Error parsing environment config from the request"); return handleCreateOrUpdateResponse(request, response, environmentConfig, operationResult); } if (isPutRequestStale(request, oldEnvironmentConfig)) { throw haltBecauseEtagDoesNotMatch("environment", environmentName); } environmentConfigService.updateEnvironment(environmentConfig.name().toString(), environmentConfig, currentUsername(), etagFor(oldEnvironmentConfig), operationResult); setEtagHeader(environmentConfig, response); return handleCreateOrUpdateResponse(request, response, environmentConfig, operationResult); }
Source:
<code>public void shutdownAndSuspend() throws InterruptedException { try { deactivateQueueMetrics(queueId); queuing.setActive(queueId, false); boolean hasWorkRunning = false; for (Work work : running) { work.setWorkInstanceSuspending(); log.trace("suspending and rescheduling " + work.getId()); work.setWorkInstanceState(State.SCHEDULED); queuing.workReschedule(queueId, work); hasWorkRunning = true; } if (hasWorkRunning) { long shutdownDelay = Long.parseLong(Framework.getService(ConfigurationService.class) .getProperty(SHUTDOWN_DELAY_MS_KEY, "0")); if (shutdownDelay > 0) { <START> Thread.sleep(shutdownDelay); <END> } } shutdownNow(); } finally { executors.remove(queueId); } }</code><technical_language>I review code originally added this, a bit nicer: in a loop sleep 100ms re-check if running works, more complete timeout expired. This allows for fast-stop works finished</technical_language>

Target:
public void shutdownAndSuspend() throws InterruptedException { try { deactivateQueueMetrics(queueId); queuing.setActive(queueId, false); boolean hasRunningWork = false; for (Work work : running) { work.setWorkInstanceSuspending(); log.trace("suspending and rescheduling " + work.getId()); work.setWorkInstanceState(State.SCHEDULED); queuing.workReschedule(queueId, work); hasRunningWork = true; } if (hasRunningWork) { long shutdownDelay = Long.parseLong( Framework.getService(ConfigurationService.class).getProperty(SHUTDOWN_DELAY_MS_KEY, "0")); Thread.sleep(shutdownDelay); } shutdownNow(); } finally { executors.remove(queueId); } }
Source:
<code>private boolean processAllResponses(final Connection connection) throws IOException { boolean isEmpty = false; connection.responseWriteLock.lock(); try { for (int i = 0; i < 20; i++) { Call call = connection.responseQueue.pollFirst(); if (call == null) { return true; } <START> metrics.removeCallFromResponseQueue(call.response.getRemaining()); <END> if (!processResponse(call)) { connection.responseQueue.addFirst(call); metrics.addCallToResponseQueue(call.response.getRemaining()); return false; } } isEmpty = connection.responseQueue.isEmpty(); } finally { connection.responseWriteLock.unlock(); } return isEmpty; }</code><technical_language>add in multiple places, processResponse(call) is place actual change is happening, move updates method? if (!call.response.hasRemaining()) { call.done(); // Remove <==== return true; } else { // update <===== return false; // Socket more, back. }</technical_language>

Target:
private boolean processAllResponses(final Connection connection) throws IOException { boolean isEmpty = false; connection.responseWriteLock.lock(); try { for (int i = 0; i < 20; i++) { Call call = connection.responseQueue.pollFirst(); if (call == null) { return true; } long beforeProcess = call.response.getRemaining(); if (!processResponse(call)) { connection.responseQueue.addFirst(call); long afterProcess = call.response.getRemaining(); metrics.updateResponseQueueSize(afterProcess - beforeProcess); return false; } else { metrics.removeCallFromResponseQueue(); metrics.updateResponseQueueSize(-beforeProcess); } } isEmpty = connection.responseQueue.isEmpty(); } finally { connection.responseWriteLock.unlock(); } return isEmpty; }
Source:
<code>private boolean checkForAssembler() { synchronized(this.executionControl) { if (this.executionControl.incrementAndGet() <= 1) { this.executionControl.set(1); if (logger.isDebugEnabled()) { logger.debug(this.getConnectionId() + " Running an assembler"); } try { this.taskExecutor.execute2(this); } <START> catch (RejectedExecutionException e) { <END> this.executionControl.decrementAndGet(); if (logger.isInfoEnabled()) { logger.info("Insufficient threads in the assembler fixed thread pool; consider increasing " + "this task executor pool size"); } return false; } } else { this.executionControl.decrementAndGet(); } } return true; }</code><technical_language>this is good, too</technical_language>

Target:
private boolean checkForAssembler() { synchronized(this.executionControl) { if (this.executionControl.incrementAndGet() <= 1) { this.executionControl.set(1); if (logger.isDebugEnabled()) { logger.debug(this.getConnectionId() + " Running an assembler"); } try { this.taskExecutor.execute2(this); } catch (RejectedExecutionException e) { this.executionControl.decrementAndGet(); if (logger.isInfoEnabled()) { logger.info("Insufficient threads in the assembler fixed thread pool; consider increasing " + "this task executor pool size"); } throw e; } } else { this.executionControl.decrementAndGet(); } } return true; }
Source:
<code><START> protected String rtrim(String s) { <END> if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }</code><technical_language>static</technical_language>

Target:
public static String rtrim(String s) { if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SomethingWithOption that = (SomethingWithOption) o; if (id != that.id) return false; <START> return name != null ? name.equals(that.name) : that.name == null; <END> }</code><technical_language>Aside: assuming this generated. IDE using? of able generated Java 7-style equals java.util.Objects.equals(Object, Object) avoid null checks</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SomethingWithOption that = (SomethingWithOption) o; return id == that.id && Objects.equals(name, that.name); }
Source:
<code>public void cmnClearRegion(RegionEventImpl regionEvent, boolean cacheWrite, boolean useRVV) { if (!getBucketAdvisor().isPrimary()) { if (logger.isDebugEnabled()) { logger.debug("Not primary bucket when doing clear, do nothing"); } return; } boolean enableRVV = useRVV && getConcurrencyChecksEnabled(); RegionVersionVector rvv = null; if (enableRVV) { rvv = getVersionVector().getCloneForTransmission(); } Set<InternalDistributedMember> participants = getCacheDistributionAdvisor().adviseInvalidateRegion(); <START> boolean isLockedAlready = this.partitionedRegion.getClearPartitionedRegion() .isLockedForListenerAndClientNotification(); try { if (!isLockedAlready) { obtainWriteLocksForClear(regionEvent, participants); } <END> clearRegionLocal(regionEvent, cacheWrite, null); distributeClearOperation(regionEvent, rvv, participants); } finally { if (!isLockedAlready) { releaseWriteLocksForClear(regionEvent, participants); } } }</code><technical_language>exist a small race condition of isLockedAlready changes call isLockedForListenerAndClientNotification() call obtainWriteLocksForClear(). Is this happen? happen if isLockedAlready is initially false, call obtainWriteLocksForClear(), actual true</technical_language>

Target:
public void cmnClearRegion(RegionEventImpl regionEvent, boolean cacheWrite, boolean useRVV) { if (!getBucketAdvisor().isPrimary()) { if (logger.isDebugEnabled()) { logger.debug("Not primary bucket when doing clear, do nothing"); } return; } boolean enableRVV = useRVV && getConcurrencyChecksEnabled(); RegionVersionVector rvv = null; if (enableRVV) { rvv = getVersionVector().getCloneForTransmission(); } Set<InternalDistributedMember> participants = getCacheDistributionAdvisor().adviseInvalidateRegion(); boolean isLockedAlready = this.partitionedRegion.getPartitionedRegionClear() .isLockedForListenerAndClientNotification(); try { if (!isLockedAlready) { obtainWriteLocksForClear(regionEvent, participants); } clearRegionLocally(regionEvent, cacheWrite, null); distributeClearOperation(regionEvent, rvv, participants); } finally { if (!isLockedAlready) { releaseWriteLocksForClear(regionEvent, participants); } } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HostDeviceView)) { return false; } if (!super.equals(o)) return false; HostDeviceView other = (HostDeviceView) o; <START> return super.equals(other) <END> && Objects.equals(configuredVmId, other.configuredVmId) && Objects.equals(attachedVmNames, other.attachedVmNames) && Objects.equals(runningVmName, other.runningVmName) && Objects.equals(iommuPlaceholder, other.iommuPlaceholder); }</code><technical_language>#62 is redundant, right</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HostDeviceView)) { return false; } HostDeviceView other = (HostDeviceView) o; return super.equals(other) && Objects.equals(configuredVmId, other.configuredVmId) && Objects.equals(attachedVmNames, other.attachedVmNames) && Objects.equals(runningVmName, other.runningVmName) && Objects.equals(iommuPlaceholder, other.iommuPlaceholder); }
Source:
<code><START> private static Map<String, ModuleService> loadModules(Class cls) { <END> Map<String, ModuleService> modules = new HashMap<>(); if(cls != null) { Map<String, ExtensionProxy> proxies = new HashMap<>(); ExtMap context = new ExtMap() .mput(ModuleService.EXTENSIONS_MAP, proxies) .mput(ModuleService.PROGRAM_NAME, PROGRAM_NAME); ServiceLoader<ModuleService> loader = ServiceLoader.load(cls); for (ModuleService module : loader) { modules.put(module.getName(), module); module.setContext(context); } } return modules; }</code><technical_language>please debug modules available</technical_language>

Target:
private Map<String, ModuleService> loadModules(Class cls) { Map<String, ModuleService> modules = new HashMap<>(); if(cls != null) { Map<String, ExtensionProxy> proxies = new HashMap<>(); ExtMap context = new ExtMap() .mput(ModuleService.EXTENSIONS_MAP, proxies) .mput(ModuleService.PROGRAM_NAME, PROGRAM_NAME); ServiceLoader<ModuleService> loader = ServiceLoader.load(cls); for (ModuleService module : loader) { modules.put(module.getName(), module); module.setContext(context); } } logger.debug("Loaded modules: {}", StringUtils.join(modules.keySet(), ",")); return modules; }
Source:
<code>protected Optional<TestToolsView> getTestToolsView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); <START> if (activity != null) { <END> final AbstractWorkbenchActivity testToolsActivity = (AbstractWorkbenchActivity) activity; return Optional.of((TestToolsView) testToolsActivity.getWidget()); } else { return Optional.empty(); } }</code><technical_language>Indirect condition. replaced if (activity == null) { return Optional.empty();} else{ final AbstractWorkbenchActivity testToolsActivity = (AbstractWorkbenchActivity) activity; return Optional.of((TestToolsView) testToolsActivity.getWidget()); }</technical_language>

Target:
protected Optional<TestToolsView> getTestToolsView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity testToolsActivity = (AbstractWorkbenchActivity) activity; return Optional.of((TestToolsView) testToolsActivity.getWidget()); } }
Source:
<code><START> public Object getPrincipal() { <END> return this.principal; }</code><technical_language>This need changed</technical_language>

Target:
public OAuth2User getPrincipal() { return this.principal; }