auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCostBalancerMultithreadStrategy() throws InterruptedException { DataSegment segment = getSegment(1000); <START> BalancerStrategy strategy = new CostBalancerMultithreadStrategy(DateTime.now(DateTimeZone.UTC), 8); <END> ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList); Assert.assertNotNull("Should be able to find a place for new segment!!", holder); Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName()); }</code><technical_language>i testing for concurrency</technical_language>

Target:
public void testCostBalancerMultithreadStrategy() throws InterruptedException { setupDummyCluster(10, 20); DataSegment segment = getSegment(1000); BalancerStrategy strategy = new CostBalancerStrategy(DateTime.now(DateTimeZone.UTC), 1); ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList); Assert.assertNotNull("Should be able to find a place for new segment!!", holder); Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName()); }
Source:
<code>private void restore(final CaseManagementShapeView ghost) { <START> if (state.getOriginalParent().isPresent() && state.getOriginalIndex().isPresent()) { <END> final WiresContainer originalParent = state.getOriginalParent().get(); final int originalIndex = state.getOriginalIndex().get(); restore(ghost, originalParent, originalIndex); } }</code><technical_language>a suggestion this block: suggestion state.getOriginalIndex() .ifPresent(originalIndex -> state.getOriginalParent() .ifPresent(originalParent -> restore(ghost, originalParent, originalIndex)));</technical_language>

Target:
private void restore(final CaseManagementShapeView ghost) { state.getOriginalParent().ifPresent(originalParent -> state.getOriginalIndex().ifPresent(originalIndex -> restore(ghost, originalParent, originalIndex) ) ); }
Source:
<code>public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalList.add( "{}" ); return finalList; } List<String> categories = parse(searchString.trim().toLowerCase()); List<String> catHolder = new ArrayList<String>(); for( String cat : categories ) { if (prefixSplit != null ) { <START> int index = cat.indexOf( prefixSplit ); <END> if ( index != -1 ) { String prefix = cat.substring( 0, index ); String value = cat.substring( index + 1 ); if ( mapPrefix.containsKey( prefix ) ) { addToFinalList( finalList, catHolder ); finalList.add( value ); } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } addToFinalList( finalList, catHolder ); return finalList; }</code><technical_language>Do foresee prefixSplit more character</technical_language>

Target:
public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalList.add( "{}" ); return finalList; } List<String> categories = parse(searchString.trim().toLowerCase()); List<String> catHolder = new ArrayList<String>(); for( String cat : categories ) { if (prefixSplit != null ) { int index = cat.indexOf( prefixSplit ); if ( index != -1 ) { String prefix = cat.substring( 0, index ); String value = cat.substring( index + prefixSplit.length() ); if ( mapPrefix.containsKey( prefix ) ) { addToFinalList( finalList, catHolder ); finalList.add( value ); } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } addToFinalList( finalList, catHolder ); return finalList; }
Source:
<code>public String toStringForLogging() { <START> StringBuilder sb = new StringBuilder(); <END> if(correlationId != null){ sb.append("Corrolation ID: "); sb.append(correlationId); sb.append(", "); } if(jobId != null){ sb.append("Job ID: "); sb.append(jobId.toString()); sb.append(", "); } if(callStack != null){ sb.append("Call Stack: "); sb.append(callStack); sb.append(", "); } if(customEventId != -1){ sb.append("Custom Event ID: "); sb.append(customEventId); sb.append(", "); } if(message != null){ sb.append("Message: "); sb.append(message); } return sb.toString(); }</code><technical_language>I knowing values Null is important. I remove Null checks print (eg. Correlation ID: Null, blah: Null,)</technical_language>

Target:
public String toStringForLogging() { StringBuilder sb = new StringBuilder(); sb.append("Correlation ID: "); sb.append(correlationId); sb.append(", "); if(jobId != null){ sb.append("Job ID: "); sb.append(jobId.toString()); sb.append(", "); } sb.append("Call Stack: "); sb.append(callStack); sb.append(", "); sb.append("Custom Event ID: "); sb.append(customEventId); sb.append(", "); sb.append("Message: "); sb.append(message); return sb.toString(); }
Source:
<code>public Map<String,String> getFlattened(){ Map<String,String> returnVal = new TreeMap<String,String>(); for (Props curr = this; curr != null; curr = curr.getParent()) { for (String key : curr.localKeySet()) { <START> if (!returnVal.containsKey(key)){ <END> returnVal.put(key, curr.get(key)); } } } return returnVal; }</code><technical_language>Is necessary check</technical_language>

Target:
public Map<String,String> getFlattened(){ TreeMap<String,String> returnVal = new TreeMap<String,String>(); returnVal.putAll(getMapByPrefix("")); return returnVal; }
Source:
<code>public void sendBinary(ByteBuffer buf) { if (channel == null) { logger.error("Channel is null. Cannot send text."); <START> throw new NullPointerException("Cannot find the channel to write"); <END> } channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(buf))); }</code><technical_language>throw a NPE</technical_language>

Target:
public void sendBinary(ByteBuffer buf) throws IOException { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(buf))); }
Source:
<code>public String runScript(Script script, Map<String, Object> parameters) { String jsScript = script.getContent(); Object scriptResult; try { scriptResult = jsScriptExecutor.executeScript(jsScript, parameters); } catch (ScriptExecutionException see) { <START> scriptResult = see.getLocalizedMessage(); <END> } return scriptResult != null ? scriptResult.toString() : null; }</code><technical_language>here, bubble I</technical_language>

Target:
public String runScript(Script script, Map<String, Object> parameters) { String jsScript = script.getContent(); Object scriptResult = jsMagmaScriptExecutor.executeScript(jsScript, parameters); return scriptResult != null ? scriptResult.toString() : null; }
Source:
<code>public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); <START> assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, ""); <END> }</code><technical_language>suggestion assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE);</technical_language>

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE); }
Source:
<code>public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { for (SystemTablesProvider delegate : delegates) { Optional<SystemTable> table = delegate.getSystemTable(session, tableName); if (table.isPresent()) { <START> return table; <END> } } return Optional.empty(); }</code><technical_language>nice ensure delegate it... delegates.stream() .map(delegate -> delegate.getSystemTable(session, tableName)) .filter(Optional::isPresent) .map(Optional::get) .collect(toOptional())</technical_language>

Target:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { return delegates.stream() .map(delegate -> delegate.getSystemTable(session, tableName)) .filter(Optional::isPresent) .map(Optional::get) .collect(toOptional()); }
Source:
<code>private RexNode simplifyIsPredicate(SqlKind kind, RexNode a) { if (!RexUtil.isReferenceOrAccess(a, true)) { return null; } for (RexNode p : predicates.pulledUpPredicates) { IsPredicate pred = IsPredicate.of(p); if (pred == null || !a.toString().equals(pred.ref.toString())) { continue; } if (kind == pred.kind) { return rexBuilder.makeLiteral(true); } else if (kind.negate() == pred.kind) { <START> return rexBuilder.makeLiteral(false); <END> } } return null; }</code><technical_language>I if this else branch is taken. @kgyrtkirk , introduce code. please provide a test case for branch? existing tests pass if I remove else return false branch</technical_language>

Target:
private RexNode simplifyIsPredicate(SqlKind kind, RexNode a) { if (!RexUtil.isReferenceOrAccess(a, true)) { return null; } for (RexNode p : predicates.pulledUpPredicates) { IsPredicate pred = IsPredicate.of(p); if (pred == null || !a.toString().equals(pred.ref.toString())) { continue; } if (kind == pred.kind) { return rexBuilder.makeLiteral(true); } } return null; }
Source:
<code>protected void onAfterSave(Object entity) { BlobHardRef ref = getRef(entity); if (ref.changed) { BlobStorageSpace storageSpace = ref.getBlob().getStorageSpace(); String uniqueName = ((BaseEntity<?>) entity).getUniqueName(); if (ref.isFilled()) { storageSpace.markAsUsed(uniqueName, getName(), ref.getKey()); } <START> storageSpace.deleteReferencedBlobs(uniqueName, getName(), ref.getKey()); <END> } ref.changed = false; }</code><technical_language>This changes logic readability?</technical_language>

Target:
protected void onAfterSave(Object entity) { BlobHardRef ref = getRef(entity); if (ref.changed) { BlobStorageSpace storageSpace = ref.getStorageSpace(); String uniqueName = ((BaseEntity<?>) entity).getUniqueName(); if (ref.isFilled()) { storageSpace.markAsUsed(uniqueName, getName(), ref.getKey()); } storageSpace.deleteReferencedBlobs(uniqueName, getName(), ref.getKey()); } ref.changed = false; }
Source:
<code>public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); <START> if (shouldHardWrap()) { <END> text = hardWrap(text); } return text; }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); if (shouldHardWrap()) text = hardWrap(text); return text; }
Source:
<code>public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new ParserInitializationException( <START> "Can only install files with '.jar' and '.js' extension"); <END> } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } File dst = new File(pluginsDir, name); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }</code><technical_language>s/and/or</technical_language>

Target:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new ParserInitializationException( "Can only install files with '.jar' or '.js' extension"); } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } File dst = new File(pluginsDir, name); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }
Source:
<code>private static void checkConfig(Config cfg) { Set<String> keys = new HashSet<>(); for (Table t : Table.values()) { <START> keys.add(t.name().toLowerCase()); <END> } for (String t : cfg.getSubsections(NOTEDB)) { checkArgument(keys.contains(t.toLowerCase()), "invalid notedb table: %s", t); for (String key : cfg.getNames(NOTEDB, t)) { String lk = key.toLowerCase(); checkArgument(lk.equals(WRITE) || lk.equals(READ), "invalid notedb key: %s.%s", t, key); } boolean write = cfg.getBoolean(NOTEDB, t, WRITE, false); boolean read = cfg.getBoolean(NOTEDB, t, READ, false); checkArgument(!(read && !write), "must have write enabled when read enabled: %s", t); } }</code><technical_language>t.key()</technical_language>

Target:
private static void checkConfig(Config cfg) { Set<String> keys = new HashSet<>(); for (Table t : Table.values()) { keys.add(t.key()); } for (String t : cfg.getSubsections(NOTEDB)) { checkArgument(keys.contains(t.toLowerCase()), "invalid notedb table: %s", t); for (String key : cfg.getNames(NOTEDB, t)) { String lk = key.toLowerCase(); checkArgument(lk.equals(WRITE) || lk.equals(READ), "invalid notedb key: %s.%s", t, key); } boolean write = cfg.getBoolean(NOTEDB, t, WRITE, false); boolean read = cfg.getBoolean(NOTEDB, t, READ, false); checkArgument(!(read && !write), "must have write enabled when read enabled: %s", t); } }
Source:
<code>public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); hllsTotalEstimatedInMemorySize = 0; hllsTotalEstimatedSerializedSize = 0; <START> for (HyperLogLog hll : minhash.values()) { <END> increaseTotalHllSize(hll); } }</code><technical_language>nit: minhash.values().stream().forEach(this:: increaseTotalHllSize)</technical_language>

Target:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); minhash.values().forEach(this::increaseTotalHllSize); }
Source:
<code>protected AutoFixableRuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message, int beginLine, int endLine, Class<? extends RuleViolationFix> ruleViolationFixClass) { <START> return null; <END> }</code><technical_language>this implementable for other languages PLSQL</technical_language>

Target:
protected AutoFixableRuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message, int beginLine, int endLine, Class<? extends RuleViolationFix> ruleViolationFixClass) { AutoFixableParametricRuleViolation<EcmascriptNode> rViolation = new AutoFixableParametricRuleViolation<>(rule, ruleContext, (EcmascriptNode) node, message, ruleViolationFixClass); rViolation.setLines(beginLine, endLine); return rViolation; }
Source:
<code>private Profile() { try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) { while (r.readLine() != null) { } maxIndex = r.getLineNumber(); count = new int[maxIndex]; time = new int[maxIndex]; <START> lastTime = System.nanoTime(); <END> Runtime.getRuntime().addShutdownHook(this); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }</code><technical_language>rename lastTime lastTimeNs</technical_language>

Target:
private Profile() { try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) { while (r.readLine() != null) { } maxIndex = r.getLineNumber(); count = new int[maxIndex]; time = new int[maxIndex]; lastTimeNs = System.nanoTime(); Runtime.getRuntime().addShutdownHook(this); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
Source:
<code>public static boolean currentUserHasRole(String... roles) { if (roles == null || roles.length == 0) return false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); <START> if (authorities == null) throw new IllegalStateException("No current user logged in"); <END> for (String role : roles) { for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) return true; } } } return false; }</code><technical_language>Bit of a strange message, like: "No user currently logged in" "No currently logged in user"</technical_language>

Target:
public static boolean currentUserHasRole(String... roles) { if (roles == null || roles.length == 0) return false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); if (authorities == null) throw new IllegalStateException("No user currently logged in"); for (String role : roles) { for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) return true; } } } return false; }
Source:
<code>B firstBatch() throws RetryableException; B nextBatch(B lastBatch) throws RetryableException; } public interface Batch { List<Change> changes(); boolean <START> noChanges(); <END> String advancedUnits(); long advanced(); String leftOffHuman(); Date leftOffDate(); boolean last(); abstract class AbstractDefaultImplementation implements Batch { private final ImmutableList<Change> changes; private final long advanced; private final Object leftOff; public AbstractDefaultImplementation(ImmutableList<Change> changes, long advanced, Object leftOff) { this.changes = checkNotNull(changes); this.advanced = advanced; this.leftOff = leftOff; } @Override public List<Change> changes() { return changes; } @Override public boolean noChanges() { return changes.isEmpty(); } @Override public long advanced() { return advanced; } @Override public String leftOffHuman() { return leftOff.toString(); } @Override public boolean last() { return false; } } }</code><technical_language>usual convention call this method hasChanges() negation (feel free ignore, this is style)</technical_language>

Target:
B firstBatch() throws RetryableException; B nextBatch(B lastBatch) throws RetryableException; } public interface Batch { List<Change> changes(); boolean hasAnyChanges(); String advancedUnits(); long advanced(); String leftOffHuman(); Date leftOffDate(); boolean last(); abstract class AbstractDefaultImplementation implements Batch { private final ImmutableList<Change> changes; private final long advanced; private final Object leftOff; public AbstractDefaultImplementation(ImmutableList<Change> changes, long advanced, Object leftOff) { this.changes = checkNotNull(changes); this.advanced = advanced; this.leftOff = leftOff; } @Override public List<Change> changes() { return changes; } @Override public boolean hasAnyChanges() { return !changes.isEmpty(); } @Override public long advanced() { return advanced; } @Override public String leftOffHuman() { return leftOff.toString(); } @Override public boolean last() { return false; } } }
Source:
<code>public void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.GLUSTER_VOLUME_ID_INVALID.toString()); } } if (clusterId == null) { <START> clusterId = volume.getClusterId(); <END> } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); }</code><technical_language>if volumeId is null NPE i safe send null getById method, no? if null check volumeId removed this prevent NPE</technical_language>

Target:
public void executeQueryCommand() { clusterId = getParameters().getClusterId(); volume = getGlusterVolumeDao().getById(getParameters().getVolumeId()); if (volume == null) { throw new RuntimeException(VdcBllMessages.GLUSTER_VOLUME_ID_INVALID.toString()); } if (clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); }
Source:
<code>private URL getResource(IMetaclass metaclass, String resourcePath) { Object userControlsDisabled = this.options.get(IXWTLoader.DISABLE_USER_CONTROLS); if (!Boolean.TRUE.equals(userControlsDisabled)) { IResourceCache resourceCache = getResourceCache(); if (resourceCache == null) { return doGetResource(metaclass, resourcePath); } else { if (resourceCache.hasCached(metaclass, resourcePath)) { return resourceCache.getCachedResource(metaclass, resourcePath); } <START> System.out.println("Do <END> load resource "+resourcePath); URL url = doGetResource(metaclass, resourcePath); resourceCache.cacheResource(metaclass, resourcePath, url); return url; } } return null; }</code><technical_language>removed</technical_language>

Target:
private URL getResource(IMetaclass metaclass, String resourcePath) { Object userControlsDisabled = this.options.get(IXWTLoader.DISABLE_USER_CONTROLS); if (!Boolean.TRUE.equals(userControlsDisabled)) { IResourceCache resourceCache = getResourceCache(); if (resourceCache == null) { return doGetResource(metaclass, resourcePath); } else { if (resourceCache.hasCached(metaclass, resourcePath)) { return resourceCache.getCachedResource(metaclass, resourcePath); } URL url = doGetResource(metaclass, resourcePath); resourceCache.cacheResource(metaclass, resourcePath, url); return url; } } return null; }
Source:
<code>public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { <START> looting = net.minecraftforge.common.ForgeHooks.getLootingLevel((EntityLivingBase)target, cause, looting); <END> } return looting; }</code><technical_language>java looting = getLootingLevel((EntityLivingBase)target, cause, looting); This code is in ForgeHooks class</technical_language>

Target:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { looting = getLootingLevel((EntityLivingBase)target, cause, looting); } return looting; }
Source:
<code>private static DetailAST findLeftCurly(DetailAST ast) { DetailAST leftCurly; if (ast.findFirstToken(TokenTypes.SLIST) == null) { leftCurly = ast.findFirstToken(TokenTypes.LCURLY); <START> } <END> else { leftCurly = ast.findFirstToken(TokenTypes.SLIST); } if (ast.getType() == TokenTypes.LITERAL_CASE && ast.getNextSibling() != null && "{".equals(ast.getNextSibling().getFirstChild().getText())) { leftCurly = ast.getNextSibling().getFirstChild(); } return leftCurly; }</code><technical_language>code "{".equals ......... is accepted, do Tokens ast.findFirstToken(TokenTypes.LCURLY); if CASE is special IF for in method do previous logic if ast is a CASE.... please prove CASE AST is special</technical_language>

Target:
private static DetailAST findLeftCurly(DetailAST ast) { final DetailAST leftCurly; final DetailAST slistAST = ast.findFirstToken(TokenTypes.SLIST); if (ast.getType() == TokenTypes.LITERAL_CASE && ast.getNextSibling() != null && ast.getNextSibling().getFirstChild().getType() == TokenTypes.SLIST) { leftCurly = ast.getNextSibling().getFirstChild(); } else if (slistAST == null) { leftCurly = ast.findFirstToken(TokenTypes.LCURLY); } else { leftCurly = slistAST; } return leftCurly; }
Source:
<code>private static double chiSquareDistance(List<Long> values) { <START> double mean = values.stream().mapToDouble(Long::doubleValue).reduce(0.0, Double::sum) / values.size(); <END> double distances = values.stream().mapToDouble(Long::doubleValue) .reduce(0.0, (acc, nextVal) -> acc + Math.pow((nextVal - mean), 2)); return distances / mean; }</code><technical_language>more performant sum values longs convert a double end</technical_language>

Target:
private static double chiSquareDistance(List<Long> values) { double mean = values.stream().mapToLong(x -> x).reduce(0L, Long::sum) / (double) values.size(); double distances = values.stream().mapToDouble(Long::doubleValue) .reduce(0.0, (acc, nextVal) -> acc + Math.pow(nextVal - mean, 2)); return distances / mean; }
Source:
<code>private void configureLogCatcher() { logCatcher = new LogCatcher(); final Logger logger = Log.getLogger(); for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); } <START> logger.addHandler(logCatcher); <END> logger.setLevel(Level.ALL); }</code><technical_language>@StefanPenndorf introducing a memory leak test suite here? If removes LogCatcher runs continues accumulate log entries JVM exits</technical_language>

Target:
public void configureLogCatcher() { logCatcher = new LogCatcher(); final Logger logger = Log.getLogger(); logger.addHandler(logCatcher); logger.setLevel(Level.ALL); }
Source:
<code>public boolean isAPIProductAvailable(APIProductIdentifier identifier) throws APIManagementException { String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion(); try { return registry.resourceExists(path); } catch (RegistryException e) { String msg = "Failed to check availability of API Product :" + path; <START> log.error(msg, e); <END> throw new APIManagementException(msg, e); } }</code><technical_language>remove log.error. log throw is antipattern</technical_language>

Target:
public boolean isAPIProductAvailable(APIProductIdentifier identifier) throws APIManagementException { String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion(); try { return registry.resourceExists(path); } catch (RegistryException e) { String msg = "Failed to check availability of API Product :" + path; throw new APIManagementException(msg, e); } }
Source:
<code>private static String[] mergePropertiesToCommandArray(String[] parameters, String[] cmdArray) { <START> if (parameters != null) { <END> cmdArray = ArrayUtils.addAll(cmdArray, parameters); } return cmdArray; }</code><technical_language>is arrays empty. I need handle this properly</technical_language>

Target:
private static String[] mergePropertiesToCommandArray(String[] parameters, String[] cmdArray) { if (parameters != null && cmdArray != null) { Object[] cmdObjectArray = ArrayUtils.addAll(cmdArray, parameters); cmdArray = Arrays.asList(cmdObjectArray).toArray(new String[cmdObjectArray.length]); } return cmdArray; }
Source:
<code>public void processMetadata() throws TranslatorException { DescribeGlobalResult globalResult = connection.getObjects(); DescribeGlobalSObjectResult[] objects = globalResult.getSobjects(); for (DescribeGlobalSObjectResult object : objects) { addTable(object); } List<String> names = new ArrayList<String>(); for (String name : this.tableMap.keySet()) { names.add(name); if (names.size() < 100) { continue; } getColumnsAndRelationships(names); } if (!names.isEmpty()) { getColumnsAndRelationships(names); } addRelationships(); for (Table table:this.metadataFactory.getSchema().getTables().values()) { if (importStatistics) { try { <START> String name = table.getNameInSource(); <END> if (name == null) { name = table.getName(); } Long val = this.connection.getCardinality(name); if (val != null) { table.setCardinality(val); } } catch (Exception e) { LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Could not get cardinality for", table); } } if (table.getPrimaryKey() == null) { continue; } for (Column column:table.getPrimaryKey().getColumns()) { if (!column.isUpdatable()) { column.setAutoIncremented(true); } } } }</code><technical_language>getSourceName() thing</technical_language>

Target:
public void processMetadata() throws TranslatorException { DescribeGlobalResult globalResult = connection.getObjects(); DescribeGlobalSObjectResult[] objects = globalResult.getSobjects(); for (DescribeGlobalSObjectResult object : objects) { addTable(object); } List<String> names = new ArrayList<String>(); for (String name : this.tableMap.keySet()) { names.add(name); if (names.size() < 100) { continue; } getColumnsAndRelationships(names); } if (!names.isEmpty()) { getColumnsAndRelationships(names); } addRelationships(); for (Table table:this.metadataFactory.getSchema().getTables().values()) { if (importStatistics) { try { Long val = this.connection.getCardinality(table.getSourceName()); if (val != null) { table.setCardinality(val); } } catch (Exception e) { LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Could not get cardinality for", table); } } if (table.getPrimaryKey() == null) { continue; } for (Column column:table.getPrimaryKey().getColumns()) { if (!column.isUpdatable()) { column.setAutoIncremented(true); } } } }
Source:
<code>public void parse(String delim, String itemToken) { final FromItem fromItem; final int parenthesisStart = itemToken.indexOf('('); if (parenthesisStart != -1) { if (parenthesisStart != 0) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected parenthesis to start at first character."); } final int parenthesisEnd = itemToken.indexOf(')', parenthesisStart); if (parenthesisEnd == -1) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected end parenthesis."); } final String subQueryString = itemToken.substring(parenthesisStart + 1, parenthesisEnd); logger.debug("Parsing sub-query: {}", subQueryString); final Query subQuery = new QueryParser(_dataContext, subQueryString).parse(); fromItem = new FromItem(subQuery); final String alias = itemToken.substring(parenthesisEnd + 1).trim(); if (!alias.isEmpty()) { fromItem.setAlias(alias); } } else if (itemToken.toUpperCase().indexOf(" JOIN ") != -1) { <START> if(itemToken.split("(?i) JOIN ").length == 2) { <END> fromItem = parseJoinItem(null,itemToken,new HashSet<FromItem>()); } else { fromItem = parseAllJoinItems(itemToken); } } else { fromItem = parseTableItem(itemToken); } _query.from(fromItem); }</code><technical_language>thinking instead of splitting this text (here in parseAllJoinItems) this if-block apply parseAllJoinItems(...)</technical_language>

Target:
public void parse(String delim, String itemToken) { final FromItem fromItem; final int parenthesisStart = itemToken.indexOf('('); if (parenthesisStart != -1) { if (parenthesisStart != 0) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected parenthesis to start at first character."); } final int parenthesisEnd = itemToken.indexOf(')', parenthesisStart); if (parenthesisEnd == -1) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected end parenthesis."); } final String subQueryString = itemToken.substring(parenthesisStart + 1, parenthesisEnd); logger.debug("Parsing sub-query: {}", subQueryString); final Query subQuery = new QueryParser(_dataContext, subQueryString).parse(); fromItem = new FromItem(subQuery); final String alias = itemToken.substring(parenthesisEnd + 1).trim(); if (!alias.isEmpty()) { fromItem.setAlias(alias); } } else if (itemToken.toUpperCase().indexOf(" JOIN ") != -1) { fromItem = parseAllJoinItems(itemToken); } else { fromItem = parseTableItem(itemToken); } _query.from(fromItem); }
Source:
<code>private @NonNull ArrayList<SocketKeepalive> createConcurrentNattSocketKeepalives( @NonNull Network network, int requestCount, @NonNull TestSocketKeepaliveCallback callback) throws Exception { final Executor executor = mContext.getMainExecutor(); final IpSecManager mIpSec = (IpSecManager) mContext.getSystemService(Context.IPSEC_SERVICE); final UdpEncapsulationSocket nattSocket = mIpSec.openUdpEncapsulationSocket(); final InetAddress srcAddr = getFirstV4Address(network); final InetAddress dstAddr = getAddrByName(TEST_HOST, AF_INET); assertNotNull(srcAddr); assertNotNull(dstAddr); ArrayList<SocketKeepalive> result = null; try { result = createConcurrentKeepalivesOfType(requestCount, callback, () -> mCm.createSocketKeepalive(network, nattSocket, srcAddr, dstAddr, executor, callback)); <START> } catch (Exception e) { Log.w(TAG, "Failed to create concurrent keepalives", e); <END> } finally { nattSocket.close(); } return result; }</code><technical_language>+1 lorenzo@</technical_language>

Target:
private @NonNull ArrayList<SocketKeepalive> createConcurrentNattSocketKeepalives( @NonNull Network network, int requestCount, @NonNull TestSocketKeepaliveCallback callback) throws Exception { final Executor executor = mContext.getMainExecutor(); final IpSecManager mIpSec = (IpSecManager) mContext.getSystemService(Context.IPSEC_SERVICE); final UdpEncapsulationSocket nattSocket = mIpSec.openUdpEncapsulationSocket(); final InetAddress srcAddr = getFirstV4Address(network); final InetAddress dstAddr = getAddrByName(TEST_HOST, AF_INET); assertNotNull(srcAddr); assertNotNull(dstAddr); try { return createConcurrentKeepalivesOfType(requestCount, callback, () -> mCm.createSocketKeepalive(network, nattSocket, srcAddr, dstAddr, executor, callback)); } finally { nattSocket.close(); } }
Source:
<code>private static void checkGeneratorExpressionInArgument(List<PyArgumentTree> arguments) { List<PyArgumentTree> nonParenthesizedGeneratorExpressions = arguments.stream() .filter(arg -> arg.expression().is(Tree.Kind.GENERATOR_EXPR) && !arg.expression().firstToken().getValue().equals("(")) .collect(Collectors.toList()); if (!nonParenthesizedGeneratorExpressions.isEmpty() && arguments.size() > 1) { <START> throw new RecognitionException(nonParenthesizedGeneratorExpressions.get(0).firstToken().getLine(), "Generator expression must be parenthesized."); <END> } }</code><technical_language>message line number appears in logs of analysis</technical_language>

Target:
private static void checkGeneratorExpressionInArgument(List<PyArgumentTree> arguments) { List<PyArgumentTree> nonParenthesizedGeneratorExpressions = arguments.stream() .filter(arg -> arg.expression().is(Tree.Kind.GENERATOR_EXPR) && !arg.expression().firstToken().getValue().equals("(")) .collect(Collectors.toList()); if (!nonParenthesizedGeneratorExpressions.isEmpty() && arguments.size() > 1) { int line = nonParenthesizedGeneratorExpressions.get(0).firstToken().getLine(); throw new RecognitionException(line, "Parse error at line " + line + ": Generator expression must be parenthesized if not sole argument."); } }
Source:
<code>public final Optional<BearerToken> getApiToken(String serviceName) { checkArgument(!Strings.isNullOrEmpty(serviceName)); Optional<ServiceConfiguration> maybeServiceConfig = getServiceConfiguration(serviceName); <START> if (!maybeServiceConfig.isPresent()) { <END> return defaultApiToken(); } return maybeServiceConfig.get().apiToken().or(defaultApiToken()); }</code><technical_language>if service is present throw error? question other methods</technical_language>

Target:
public final Optional<BearerToken> getApiToken(String serviceName) { ServiceConfiguration serviceConfig = Preconditions.checkNotNull( getServices().get(serviceName), "Unable to find the configuration for " + serviceName + "."); return serviceConfig.apiToken(); }
Source:
<code>public ValidationResult validateCinderVolumeTypesExist() { return validate(new Callable<ValidationResult>() { @Override public ValidationResult call() { for (final CinderDisk disk : cinderDisks) { if (StringUtils.isEmpty(disk.getCinderVolumeType())) { continue; } OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId()); <START> List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes(); <END> boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() { @Override public boolean evaluate(Object o) { return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType()); } }); if (!volumeTypeExists) { return new ValidationResult(VdcBllMessages.CINDER_VOLUME_TYPE_NOT_EXISTS, String.format("$cinderVolumeType %s", disk.getCinderVolumeType())); } } return ValidationResult.VALID; } }); }</code><technical_language>Sggestion: I suggest CinderStorageRelatedDisksAndProxy private class (by calling getRelatedCinderDisksToStorageDomainMap method). Storage Domain is related proxy avoid calling proxy.getVolumeTypes disk</technical_language>

Target:
public ValidationResult validateCinderVolumeTypesExist() { return validate(new Callable<ValidationResult>() { @Override public ValidationResult call() { final CinderDisk disk = cinderDisks.iterator().next(); if (StringUtils.isEmpty(disk.getCinderVolumeType())) { return ValidationResult.VALID; } OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId()); List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes(); boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() { @Override public boolean evaluate(Object o) { return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType()); } }); if (!volumeTypeExists) { return new ValidationResult(VdcBllMessages.CINDER_VOLUME_TYPE_NOT_EXISTS, String.format("$cinderVolumeType %s", disk.getCinderVolumeType())); } return ValidationResult.VALID; } }); }
Source:
<code>public double getClassNumber(int elem) { <START> return (double) (1 + (3.3 * Math.log10(elem))); <END> }</code><technical_language>This cast is useless, Math.log10 returns a double already</technical_language>

Target:
public double getClassNumber(int elem) { return 1 + (3.3 * Math.log10(elem)); }
Source:
<code>public Void execute(Context context) { KieSession kieSession = ((RegistryContext) context).lookup( KieSession.class ); logger.debug("About to trigger (create) node instance for node in process instance {}", nodeId, processInstanceId); RuleFlowProcessInstance wfp = (RuleFlowProcessInstance) kieSession.getProcessInstance(processInstanceId, false); if (wfp == null) { throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " not found"); } Node node = null; try { node = wfp.getRuleFlowProcess().getNode(nodeId); } catch (Exception e) { } if (node == null) { node = wfp.getRuleFlowProcess().getNodesRecursively().stream().filter(ni -> ni.getId() == nodeId).findFirst().orElse(null); if (node == null) { <START> throw new NodeNotFoundException("Node instance with id " + nodeId + " not found"); <END> } CompositeNodeInstance nodeInstanceContainerNode = ((CompositeNodeInstance) wfp.getNodeInstance(wfp.getRuleFlowProcess().getParentNode(nodeId))); logger.debug("Triggering node on process instance {}", node, wfp); nodeInstanceContainerNode.getNodeInstance(node).trigger(null, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE); logger.debug("Node successfully triggered", node); } else { logger.debug("Triggering node on process instance {}", node, wfp); wfp.getNodeInstance(node).trigger(null, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE); logger.debug("Node successfully triggered", node); } return null; }</code><technical_language>message is bit misleading is node node instance is</technical_language>

Target:
public Void execute(Context context) { KieSession kieSession = ((RegistryContext) context).lookup( KieSession.class ); logger.debug("About to trigger (create) node instance for node in process instance {}", nodeId, processInstanceId); RuleFlowProcessInstance wfp = (RuleFlowProcessInstance) kieSession.getProcessInstance(processInstanceId, false); if (wfp == null) { throw new ProcessInstanceNotFoundException("Process instance with id " + processInstanceId + " not found"); } Node node = null; try { node = wfp.getRuleFlowProcess().getNode(nodeId); } catch (Exception e) { logger.debug("Node with id not found, searching it in workflow containers", nodeId); } if (node == null) { node = wfp.getRuleFlowProcess().getNodesRecursively().stream().filter(ni -> ni.getId() == nodeId).findFirst().orElse(null); if (node == null) { throw new NodeNotFoundException("Node with id " + nodeId + " not found"); } NodeInstanceContainer nodeInstanceContainerNode = ((NodeInstanceContainer) wfp.getNodeInstance(wfp.getRuleFlowProcess().getParentNode(nodeId))); logger.debug("Triggering node on process instance {}", node, wfp); nodeInstanceContainerNode.getNodeInstance(node).trigger(null, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE); logger.debug("Node successfully triggered", node); } else { logger.debug("Triggering node on process instance {}", node, wfp); wfp.getNodeInstance(node).trigger(null, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE); logger.debug("Node successfully triggered", node); } return null; }
Source:
<code>public char[] getTriggerCharacters() { <START> if(serverCapabilities.getCompletionProvider() !=null){ <END> List<String> triggerCharacters = serverCapabilities.getCompletionProvider().getTriggerCharacters(); StringBuilder result = new StringBuilder(); if (triggerCharacters != null) { for (String triggerCharacter : triggerCharacters) { if (triggerCharacter.length() == 1) { result.append(triggerCharacter.charAt(0)); } } } return result.toString().toCharArray(); } return null; }</code><technical_language>code formatting issue (spaces)</technical_language>

Target:
public List<String> getTriggerCharacters() { if (serverCapabilities.getCompletionProvider() != null) { return serverCapabilities.getCompletionProvider().getTriggerCharacters(); } return null; }
Source:
<code><START> private IgniteBiTuple<Long, Long> calculateWalSegmentsCovered() { <END> IgniteBiTuple<Long, Long> tup = new IgniteBiTuple<>(0L, 0L); Map.Entry<Long, CheckpointEntry> lastEntry = histMap.lastEntry(); if (lastEntry == null) return tup; Map.Entry<Long, CheckpointEntry> previousEntry = histMap.lowerEntry(lastEntry.getKey()); WALPointer lastWALPointer = lastEntry.getValue().checkpointMark(); long lastIdx = 0; long prevIdx = 0; if (lastWALPointer instanceof FileWALPointer) { lastIdx = ((FileWALPointer)lastWALPointer).index(); if (previousEntry != null) prevIdx = ((FileWALPointer)previousEntry.getValue().checkpointMark()).index(); } tup.set1(prevIdx); tup.set2(lastIdx > 0 ? lastIdx - 1 : 0); return tup; }</code><technical_language>point, if setting out values of covered segments this method simplified 4 - 5 lines. So, class shorter</technical_language>

Target:
private IgniteBiTuple<Long, Long> calculateWalSegmentsCovered() { IgniteBiTuple<Long, Long> tup = new IgniteBiTuple<>(-1L, -1L); Map.Entry<Long, CheckpointEntry> lastEntry = histMap.lastEntry(); if (lastEntry == null) return tup; Map.Entry<Long, CheckpointEntry> previousEntry = histMap.lowerEntry(lastEntry.getKey()); WALPointer lastWALPointer = lastEntry.getValue().checkpointMark(); long lastIdx = 0; long prevIdx = 0; if (lastWALPointer instanceof FileWALPointer) { lastIdx = ((FileWALPointer)lastWALPointer).index(); if (previousEntry != null) prevIdx = ((FileWALPointer)previousEntry.getValue().checkpointMark()).index(); } tup.set1(prevIdx); tup.set2(lastIdx - 1); return tup; }
Source:
<code>void handleKeyDown(Event event) { <START> if (isDisposed()) return; <END> if (clipboardSelection == null) { clipboardSelection = new Point(selection.x, selection.y); } newOrientation = SWT.NONE; event.stateMask &= SWT.MODIFIER_MASK; Event verifyEvent = new Event(); verifyEvent.character = event.character; verifyEvent.keyCode = event.keyCode; verifyEvent.keyLocation = event.keyLocation; verifyEvent.stateMask = event.stateMask; verifyEvent.doit = true; notifyListeners(ST.VerifyKey, verifyEvent); if (verifyEvent.doit) { if ((event.stateMask & SWT.MODIFIER_MASK) == SWT.CTRL && event.keyCode == SWT.SHIFT && isBidiCaret()) { newOrientation = event.keyLocation == SWT.LEFT ? SWT.LEFT_TO_RIGHT : SWT.RIGHT_TO_LEFT; } handleKey(event); } }</code><technical_language>Instead of returning disposed widget condition, throw SWT error: SWT.error (SWT.ERROR_WIDGET_DISPOSED);</technical_language>

Target:
void handleKeyDown(Event event) { if (isDisposed()) SWT.error (SWT.ERROR_WIDGET_DISPOSED); if (clipboardSelection == null) { clipboardSelection = new Point(selection.x, selection.y); } newOrientation = SWT.NONE; event.stateMask &= SWT.MODIFIER_MASK; Event verifyEvent = new Event(); verifyEvent.character = event.character; verifyEvent.keyCode = event.keyCode; verifyEvent.keyLocation = event.keyLocation; verifyEvent.stateMask = event.stateMask; verifyEvent.doit = true; notifyListeners(ST.VerifyKey, verifyEvent); if (verifyEvent.doit) { if ((event.stateMask & SWT.MODIFIER_MASK) == SWT.CTRL && event.keyCode == SWT.SHIFT && isBidiCaret()) { newOrientation = event.keyLocation == SWT.LEFT ? SWT.LEFT_TO_RIGHT : SWT.RIGHT_TO_LEFT; } handleKey(event); } }