auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TermCons(String psort, List<Term> contents, Production production) { super(psort); START cons = ""; END this.contents = contents; this.production = production; } don't forget this

Target:
public TermCons(String psort, List<Term> contents, Production production) { super(psort); cons = null; this.contents = contents; this.production = production; }
Source:
START public String toString() { return "" + key; } END Integer.toString?

Target:
public String toString() { return Integer.toString(key); }
Source:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { ASTNode vis; if (!tc.getProduction().containsAttribute("klabel")) START vis = super.visitNode(tc.getContents().get(0), _); END else vis = super.visit(tc, _); return vis; } this.visitNode?

Target:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { ASTNode vis; if (!tc.getProduction().containsAttribute("klabel")) vis = this.visitNode(tc.getContents().get(0), _); else vis = super.visit(tc, _); return vis; }
Source:
START public int hashCode() { END if (upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; } Well, there's actually a bug here which causes the hashCode returned by this function to always be zero. I suspect if you fix this bug (line 160 should contain the ! operator), you will find that the code no longer works. So yes, technically it's safe, but only because you are currently hashing everything into the same bucket.

Target:
public int hashCode() { if (!upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }
Source:
public boolean add(NonTerminal newNT) { START if (startNonTerminals.containsKey(newNT.nonTerminalId)) { END return false; } else { startNonTerminals.put(newNT.nonTerminalId, newNT); return true; } } I don't like that NonTerminal contains a NonTerminalId field, and you also have a Map<NonTerminalId, NonTerminal>. What stops the Map from connecting one NonTerminalId to a NonTerminal with a different NonTerminalId? If you want to maintain a bijection between NonTerminals and their Ids, then you should maintain that bijection in one place, as a BiMap, and then use that as the authoritative source for all ID information. You could even make this class implement BiMap...

Target:
public boolean add(NonTerminal newNT) { if (startNonTerminals.containsKey(newNT.name)) { return false; } else { startNonTerminals.put(newNT.name, newNT); return true; } }
Source:
public ASTNode transform(KApp node) throws TransformerException { ASTNode rez = node.getChild().accept(this); if (rez == null) node.setChild(KList.EMPTY); else if (rez instanceof KList) node.setChild((KList) rez); START else { END KList contents = new KList(); contents.getContents().add((Term) rez); node.setChild(contents); } return node; } This seems really weird to me. Better for a transformation of a KList to return a KList than to return an element that gets turned back into a KList by the caller.

Target:
public ASTNode transform(KApp node) throws TransformerException { ASTNode rez = node.getChild().accept(this); assert rez != null; if (rez instanceof KList) node.setChild((KList) rez); else { KList contents = new KList(); contents.getContents().add((Term) rez); node.setChild(contents); } return node; }
Source:
public String toString() { String content = ""; for (Term term : contents) if (term != null) content += term + ","; if (content.length() > 1) START content = content.substring(0, content.length() - 2); END return "'amb(" + content + ")"; } this should not be here anymore if you reverted the change with only 1 comma

Target:
public String toString() { String content = ""; for (Term term : contents) if (term != null) content += term + ","; if (content.length() > 1) content = content.substring(0, content.length() - 1); return "'amb(" + content + ")"; }
Source:
public static BoolToken matchable(Term subject, Term pattern, TermContext context) { PatternMatcher matcher = new PatternMatcher(context); try { matcher.match(subject, pattern); START } catch (PatternMatchingFailure e) { END return BoolToken.FALSE; } return BoolToken.TRUE; } Same question, why a third Exception class?

Target:
public static BoolToken matchable(Term subject, Term pattern, TermContext context) { return PatternMatcher.matchable(subject, pattern, context) ? BoolToken.TRUE : BoolToken.FALSE; }
Source:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index) || (index instanceof KLabelIndex && START ((KLabelIndex) index).kLabel().sorts().contains(sort)); END } same question

Target:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index); }
Source:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index) || (index instanceof TokenIndex && START kLabel.sorts().contains(((TokenIndex) index).sort())); END } I think `syntax Name ::= "$h"`` should actually be `syntax Name ::= Token{$h}`` We should probably have a check in compile for this.

Target:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index); }
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return field != null START ? beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 END || field.getAnnotationsByType(Optional.class).length > 0 : beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0; } I meant, `beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0` could be evaluated at the beginning of method: ``` if (beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0) return true; Field field = getField(...); return field != null && ...

Target:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { if (beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0) { return true; } Field field = getField(beanClass, beanProp.getName()); return field != null && field.getAnnotationsByType(Optional.class).length > 0; }
Source:
public static Config defaultOverrides() { START if (!getOverrideWithEnv()) { END return systemProperties(); } else { return systemEnvironmentOverrides().withFallback(systemProperties()); } } Think it's easier to read if you reverse the if/else to avoid the `!`

Target:
public static Config defaultOverrides() { if (getOverrideWithEnv()) { return systemEnvironmentOverrides().withFallback(systemProperties()); } else { return systemProperties(); } }
Source:
public static ConfigSyntax syntaxFromExtension(String filename) { if (filename == null) return null; START if (filename.endsWith(".json")) END return ConfigSyntax.JSON; else if (filename.endsWith(".conf")) return ConfigSyntax.CONF; else if (filename.endsWith(".properties")) return ConfigSyntax.PROPERTIES; else return null; } this could be an "else if" I think?

Target:
public static ConfigSyntax syntaxFromExtension(String filename) { if (filename == null) return null; else if (filename.endsWith(".json")) return ConfigSyntax.JSON; else if (filename.endsWith(".conf")) return ConfigSyntax.CONF; else if (filename.endsWith(".properties")) return ConfigSyntax.PROPERTIES; else return null; }
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); if (field == null) { START throw new ConfigException.BadBean("Bean property '" + beanProp + "' of class " + beanClass.getName() + " does not exist"); END } return (field.getAnnotationsByType(Optional.class).length > 0); } this this exception possible? How did we get beanProp if there's no associated field?

Target:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return (field.getAnnotationsByType(Optional.class).length > 0); }
Source:
START public Iterable<AbstractConfigNode> children() { END return children; } this can be final I guess

Target:
final public Collection<AbstractConfigNode> children() { return children; }
Source:
static String render(Iterator<Token> tokens) { START String renderedText = ""; END while (tokens.hasNext()) { renderedText += tokens.next().tokenText(); } return renderedText; } StringBuilder would seem more natural for this maybe? Passing in an iterable rather than an iterator might also avoid some bugs (since iterator is mutable and caller may forget to make a copy)

Target:
static String render(Iterator<Token> tokens) { StringBuilder renderedText = new StringBuilder(); while (tokens.hasNext()) { renderedText.append(tokens.next().tokenText()); } return renderedText.toString(); }
Source:
Substitution(ConfigOrigin origin, boolean optional, List<Token> expression) { super(TokenType.SUBSTITUTION, origin, START "${" + (optional? "?" : "") + Tokenizer.render(expression.iterator()) + "}"); END this.optional = optional; this.value = expression; } this makes me wonder if tokenText() should be virtual instead of final, so we don't need to precompute and keep around a field here that's completely derivable from the other fields we already have.

Target:
Substitution(ConfigOrigin origin, boolean optional, List<Token> expression) { super(TokenType.SUBSTITUTION, origin); this.optional = optional; this.value = expression; }
Source:
public HoeUpgrade() { START super(UPGRADE_NAME, "enderio.darksteel.upgrade.hoe", new ItemStack(Items.DIAMOND_HOE), DarkSteelConfig.darkSteelHoeCost.get()); END } use the `super(String, String, ItemStack, IValue<Integer>)` here, not the `super(String, String, ItemStack, int)` one

Target:
public HoeUpgrade() { super(UPGRADE_NAME, "enderio.darksteel.upgrade.hoe", new ItemStack(Items.DIAMOND_HOE), DarkSteelConfig.darkSteelHoeCost); }
Source:
public @Nonnull ItemStack getStackInSlot(int index) { final ItemStack itemStack = items.get(index); START return itemStack.isEmpty() ? master.getStackInSlot(index) : itemStack; END } This actually is a logic error. It must be possible to have an empty itemstack in the shadow inventory override an existing one in the shadowed one...

Target:
public @Nonnull ItemStack getStackInSlot(int index) { final ItemStack itemStack = items[index]; return itemStack.isEmpty() ? master.getStackInSlot(index) : itemStack; }
Source:
public void removeTarget(TelepadTarget target) { if (target == null) { return; } for (TelepadTarget t : targets) { if (target.equals(t)) { START targets.remove(t); END } } markDirty(); } * CME? * Isn't that exactly what remove() does? Removing on equals()...

Target:
public void removeTarget(TelepadTarget target) { if (target == null) { return; } targets.remove(target); markDirty(); }
Source:
public IItemFilter read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable IItemFilter object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (object == null) { // Note: This will be called with no nbt when a fresh itemstack is placed---output should be null! if (nbt.hasKey(name)) { object = FilterRegistry.loadFilterFromNbt(nbt.getCompoundTag(name)); START } else { END return object; } } object.readFromNBT(nbt.getCompoundTag(name)); return object; } fallthrough to `readFromNBT` in line 47. Intended?

Target:
public IItemFilter read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable IItemFilter object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (object == null && !nbt.hasKey(name)) { // Note: This will be called with no nbt when a fresh itemstack is placed---output should be null! return object; } object = FilterRegistry.loadFilterFromNbt(nbt.getCompoundTag(name)); return object; }
Source:
public final void updateEntity() { START if (Config.allowExternalTickSpeedup || worldObj == null || worldObj.getTotalWorldTime() != lastUpdate) { END lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } } OR if `worldObj == null`? This means this is getting called if the world object is null..... I guess you want ANDs here.

Target:
public final void updateEntity() { if (Config.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }
Source:
public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { if(itemstack.getItem() == null) { return; } String unloc = null; START if (itemstack.getItem() instanceof IResourceTooltipProvider) { END unloc = ((IResourceTooltipProvider)itemstack.getItem()).getUnlocalizedNameForTooltip(itemstack); } if(unloc == null) { unloc = itemstack.getItem().getUnlocalizedName(itemstack); } addCommonTooltipFromResources(list, unloc); } This is now duplicated code from below. Should extract this into a private helper method that is called from multiple places.

Target:
public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { if(itemstack.getItem() == null) { return; } addCommonTooltipFromResources(list, getUnlocalizedNameForTooltip(itemstack)); }
Source:
public void stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); super.stopQueue(); START reaper.stop(); END dao.close(); dispatcher.stop(); } } Not sure if it matters but shouldn't the reaper be stopped first (so it doesn't move entries after the queue is stopped)? Also, shouldn't the `dao` be the last one to stop?

Target:
public void stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); reaper.stop(); super.stopQueue(); dispatcher.stop(); dao.close(); } }
Source:
START private static boolean copyDescription( END RtpDescriptionPacketExtension description, ColibriConferenceIQ.Channel channel) { boolean added = false; for (PayloadTypePacketExtension payloadType : description.getPayloadTypes()) { channel.addPayloadType(payloadType); added = true; } for (RTPHdrExtPacketExtension rtpHdrExt : description.getExtmapList()) { channel.addRtpHeaderExtension(rtpHdrExt); added = true; } return added; } my only hesitation with 'copy' was that we don't actually do a deep copy of the header extensions (just add the references), but if you don't think that's a big deal then i'm fine with `copyDescriptionToChannel`

Target:
private static boolean copyDescription( RtpDescriptionPacketExtension description, ColibriConferenceIQ.Channel channel) { boolean added = false; for (PayloadTypePacketExtension payloadType : description.getPayloadTypes()) { channel.addPayloadType(new PayloadTypePacketExtension(payloadType)); added = true; } for (RTPHdrExtPacketExtension rtpHdrExt : description.getExtmapList()) { channel .addRtpHeaderExtension(new RTPHdrExtPacketExtension(rtpHdrExt)); added = true; } return added; }
Source:
public void setUp() { try { xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParserFactory.setNamespaceAware(true); xmlPullParser = xmlPullParserFactory.newPullParser(); } catch (XmlPullParserException e) START AbstractSmackInteroperabilityLayer.setImplementationClass( END SmackV3InteroperabilityLayer.class); colibriIQProvider = new ColibriIQProvider(); } While we're at it, please move the braces to new lines (and the identation is wrong too).

Target:
public void setUp() throws Exception { xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParserFactory.setNamespaceAware(true); xmlPullParser = xmlPullParserFactory.newPullParser(); AbstractSmackInteroperabilityLayer.setImplementationClass( SmackV3InteroperabilityLayer.class); colibriIQProvider = new ColibriIQProvider(); }
Source:
START public Object[] getExpectedResultsForHive() { END return new Object[]{ new Integer(1), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), new BigDecimal("1000000.05000") }; } Source of code duplication again! I would move these expected values into a helper class or a super class (choice is up to you).

Target:
public Object[] getExpectedResultsForHive() { return new Object[]{ new Integer(1), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), null }; }
Source:
public void testImportWithPadding() throws IOException { if(failWithPadding){ thrown.expect(IOException.class); thrown.expectMessage("Failure during job; return status 1"); START NumericTypesTestUtils.configureJunitToExpectFailure(thrown); END } ArgumentArrayBuilder builder = getArgsBuilder(); NumericTypesTestUtils.addPadding(builder); runImport(builder.build()); if (!failWithPadding) { verify(); } } This method seems to be doing the same thing as the previous line.

Target:
public void testImportWithPadding() throws IOException { if(failWithPadding){ NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); NumericTypesTestUtils.addPadding(builder); runImport(builder.build()); if (!failWithPadding) { verify(); } }
Source:
public PDataType getDataType() { // WE need to implement getDataType for which need to check the datatype START if (baseType == null) { END PDataType elementType = null; for (int i = 0; i < children.size(); i++) { Expression child = children.get(i); // Should we check for mismatch here? I think not needed here if (child.getDataType() != elementType) { elementType = child.getDataType(); } } baseType = elementType; } return PDataType.fromTypeId(baseType.getSqlType() + Types.ARRAY); } Do this check in the constructor instead (or a static factory method). You'll want to be careful in how you calculate the baseType and you'll definitely want to throw if you can't find a baseType for which all elements are coercibleTo. You basically want to find the common base PDataType. Something like the first loop in CaseExpression: ``` private static List<Expression> coerceIfNecessary(List<Expression> children) throws SQLException { ```

Target:
public PDataType getDataType() { return PDataType.fromTypeId(baseType.getSqlType() + Types.ARRAY); }
Source:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { START return false; END } Though not strictly necessary, I think this would read better as return index == 0, as this indicates that other parameters are ok to be null.

Target:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return index == 0; }
Source:
public ExpressionProjector(String name, String tableName, Expression expression, boolean isCaseSensitive) { this.name = name; this.expression = expression; this.tableName = tableName; this.isCaseSensitive = isCaseSensitive; START this.arrayIndex = -1; END } Remove this change please, as it should not be necessary.

Target:
public ExpressionProjector(String name, String tableName, Expression expression, boolean isCaseSensitive) { this.name = name; this.expression = expression; this.tableName = tableName; this.isCaseSensitive = isCaseSensitive; }
Source:
public static Expression create(Expression expression, PDataType toType) throws SQLException { final PDataType dataType = expression.getDataType(); START if (toType != null && !dataType.isCoercibleTo(toType)) { END throw new TypeMismatchException(dataType, toType, expression.toString()); } return toType == dataType ? expression : expression instanceof LiteralExpression ? LiteralExpression.newConstant(((LiteralExpression)expression).getValue(), toType) : new CoerceExpression(expression, toType); } Let's move the isCoercibleTo check from the CoerceExpression.create() to the visit method for your CastParseNode in ExpressionCompiler. There are cases where we know we'll be able to coerce, even though it's not always allowed.

Target:
public static Expression create(Expression expression, PDataType toType) throws SQLException { return toType == expression.getDataType() ? expression : expression instanceof LiteralExpression ? LiteralExpression.newConstant(((LiteralExpression)expression).getValue(), toType) : new CoerceExpression(expression, toType); }
Source:
public Object toObject(String value) { // TODO: How can this be done? START throw new IllegalDataException("This operation is not suppported"); END } This is basically like a load of a String in CSV format. Take a look at CSVLoader for how we use au.com.bytecode.opencsv.CSVReader (an open source CSV reader). This isn't crucial, though, so how about if we just TODO it for now?

Target:
public Object toObject(String value) { // TODO: Do this as done in CSVLoader throw new IllegalArgumentException("This operation is not suppported"); }
Source:
public KeyValueColumnExpression(PColumn column) { super(column); this.cf = column.getFamilyName().getBytes(); this.cq = column.getName().getBytes(); START this.maxLength = column.getMaxLength(); END this.scale = column.getScale(); } I think this logic should be in the super class b/c it'll apply for RowKeyColumnExpression too

Target:
public KeyValueColumnExpression(PColumn column) { super(column); this.cf = column.getFamilyName().getBytes(); this.cq = column.getName().getBytes(); }
Source:
public PTableStatsImpl() { START regionGuidePosts = new HashMap<String, byte[][]>(); END } Don't need this - regionGuidePosts is either set in the other constructor or set in the readFields method.

Target:
public PTableStatsImpl() { }
Source:
public ReadOnlyTableException(String message) { START super(SQLExceptionInfo.getNewInfoObject(code).setMessage(message).toString(), code.getSQLState()); END } Here too for message - remove if we can get away with it.

Target:
public ReadOnlyTableException(String message) { super(new SQLExceptionInfo.Builder(code).setMessage(message).toString(), code.getSQLState()); }
Source:
public static boolean delete(File file) START { END Assert.notNull(file, "File to delete must not be null."); return delete(file, false); } This could be replaced by this code: http://www.adam-bien.com/roller/abien/entry/java_7_deleting_recursively_a

Target:
public static boolean delete(File file) throws IOException { Assert.notNull(file, "File to delete must not be null."); return delete(file, false); }
Source:
protected boolean matchesSafely(T item) { if (condition.matches(itemToMatchCondition)) { return matcher.matches(item); START } else { END Description conditionDescription = new StringDescription() .appendValue(itemToMatchCondition) .appendDescriptionOf(condition); throw new AssumptionViolatedException( String.format("Condition is not satisfied: %s", conditionDescription)); } } no need to define `else` explicitly

Target:
protected boolean matchesSafely(T item) { if (condition.matches(itemToMatchCondition)) { return matcher.matches(item); } Description conditionDescription = new StringDescription() .appendValue(itemToMatchCondition) .appendDescriptionOf(condition); throw new AssumptionViolatedException( String.format("Condition is not satisfied: %s", conditionDescription)); }
Source:
protected void damageTool(GlowPlayer player, ItemStack holding, int damage) { START if (player.getGameMode() == GameMode.CREATIVE || damage == 0) { END return; } holding.setDurability((short) (holding.getDurability() + damage)); if (holding.getDurability() == maxDurability + damage) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); player.getInventory().remove(holding); } } Why `damage == 0`?

Target:
protected void damageTool(GlowPlayer player, ItemStack holding, int damage) { if (holding == null || player.getGameMode() == GameMode.CREATIVE || damage == 0) { return; } holding.setDurability((short) (holding.getDurability() + damage)); if (holding.getDurability() > maxDurability) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); player.getInventory().remove(holding); } }
Source:
protected boolean canTakeDamage(EntityDamageEvent.DamageCause damageCause) { START return gameMode == GameMode.SURVIVAL || gameMode == GameMode.ADVENTURE && super.canTakeDamage(damageCause); END } This will evaluate incorrectly

Target:
protected boolean canTakeDamage(EntityDamageEvent.DamageCause damageCause) { return (gameMode == GameMode.SURVIVAL || gameMode == GameMode.ADVENTURE) && super.canTakeDamage(damageCause); }
Source:
public Rotation getRotation() { switch (rot) { case 0: return Rotation.NONE; START case 1: END return Rotation.NONE; case 2: return Rotation.CLOCKWISE; case 3: return Rotation.CLOCKWISE; case 4: return Rotation.FLIPPED; case 5: return Rotation.FLIPPED; case 6: return Rotation.COUNTER_CLOCKWISE; case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; } This switch can be reduced as follows: ``` java case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; // ... ```

Target:
public Rotation getRotation() { switch (rot) { case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; case 4: case 5: return Rotation.FLIPPED; case 6: case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }
Source:
public void playSound(Location location, Sound sound, float volume, float pitch) { if (location == null || sound == null) return; START final double radiusSquared = Math.pow(volume > 1 ? volume * 16 : 16, 2); END for (Player player : getRawPlayers()) { if (player.getLocation().distanceSquared(location) <= radiusSquared) { player.playSound(location, sound, volume, pitch); } } } What was the issue?

Target:
public void playSound(Location location, Sound sound, float volume, float pitch) { if (location == null || sound == null) return; final double radiusSquared = Math.pow(volume * 16, 2); for (Player player : getRawPlayers()) { if (player.getLocation().distanceSquared(location) <= radiusSquared) { player.playSound(location, sound, volume, pitch); } } }
Source:
START ToolType(Material bukkitMaterial, ToolType better) { END this.bukkitMaterial = bukkitMaterial; this.better = better; } Should be `private`

Target:
private ToolType(Material bukkitMaterial, ToolType better) { this.bukkitMaterial = bukkitMaterial; this.better = better; }
Source:
private void traceBlockPowerStartSolid(GlowBlock srcBlock, RSManager rsManager, BlockFace toDir, boolean isDirect) { // Get the destination block and ensure that it is suitable. GlowBlock destBlock = srcBlock.getRelative(toDir); if (destBlock == null) { return; } Material destMat = destBlock.getType(); START if (destMat == Material.REDSTONE_WIRE) { END // Will trace } else { return; } // Trace to target. rsManager.traceFromBlock(srcBlock, toDir, 15, isDirect); } Reduces to `if (destMat != Material.REDSTONE_WIRE) return;`

Target:
private void traceBlockPowerStartSolid(GlowBlock srcBlock, RSManager rsManager, BlockFace toDir, boolean isDirect) { // Get the destination block and ensure that it is suitable. GlowBlock destBlock = srcBlock.getRelative(toDir); if (destBlock == null) { return; } Material destMat = destBlock.getType(); if (destMat != Material.REDSTONE_WIRE) { return; } // Trace to target. rsManager.traceFromBlock(srcBlock, toDir, 15, isDirect); }
Source:
START public void sendBlockEntityChange(Location location, CompoundTag nbt, GlowBlockEntity type) throws NullPointerException { END Validate.notNull(location, "Location cannot be null"); Validate.notNull(nbt, "NBT cannot be null"); Validate.notNull(type, "Type cannot be null"); afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt)); } throws is not required

Target:
public void sendBlockEntityChange(Location location, CompoundTag nbt, GlowBlockEntity type) { Validate.notNull(location, "Location cannot be null"); Validate.notNull(nbt, "NBT cannot be null"); Validate.notNull(type, "Type cannot be null"); afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt)); }
Source:
public boolean add(E object) { switch (additionMode) { START case ALL: { END int modified = 0; for (Collection<E> parent : parents) { if (parent.add(object)) { modified++; } } return resultBoolean(modified); } case LAST: { return parents.get(parents.size() - 1).add(object); } } throw new IllegalStateException("This SuperCollection has an invalid addition mode!"); } We don't use braces on case statements. Please don't use them and use break/return where needed.

Target:
public boolean add(E object) { switch (additionMode) { case ALL: int modified = 0; for (Collection<E> parent : parents) { if (parent.add(object)) { modified++; } } return resultBoolean(modified); case LAST: return parents.get(parents.size() - 1).add(object); } throw new IllegalStateException("This SuperCollection has an invalid addition mode!"); }
Source:
START public GlowHorse(Location location) { END super(location, EntityType.HORSE); Random rand = new Random(); // Todo make this cleaner and safer to use for spawning random horses this.variant = Variant.HORSE; this.horseStyle = Style.values()[rand.nextInt(4)]; this.horseColor = Color.values()[rand.nextInt(6)]; } Why not call the other constructor?

Target:
public GlowHorse(Location location) { this(location, null); }
Source:
public void updatePhysics(GlowBlock me) { Block below = me.getRelative(BlockFace.DOWN); switch (below.getType()) { case AIR: START FIRE: END WATER: LAVA: transformToFallingEntity(me); } } Missing `case` x3 as these are labels, not cases.

Target:
public void updatePhysics(GlowBlock me) { Block below = me.getRelative(BlockFace.DOWN); switch (below.getType()) { case AIR: case FIRE: case WATER: case LAVA: transformToFallingEntity(me); } }
Source:
public Material getType() { Material mat = Material.getMaterial(getTypeId()); START return (mat == null ? Material.AIR : mat); END } Something that is an unknown type is not air.

Target:
public Material getType() { return Material.getMaterial(getTypeId()); }
Source:
public int getBlockPower(BlockFace face) { BlockType type = ItemTable.instance().getBlock(getType()); if(type == null) { return 0; } START return (type.canBlockEmitPower(this, face, false) END ? getWorld().getRSManager().getBlockPower(this) : 0); } It doesn't fit the style guidelines. Also the parenthesis need to be removed.

Target:
public int getBlockPower(BlockFace face) { BlockType type = ItemTable.instance().getBlock(getType()); if(type == null) { return 0; } return type.canBlockEmitPower(this, face, false) ? getWorld().getRSManager().getBlockPower(this) : 0; }
Source:
public void onlyApprovedCode() { START onlyApprovedCode(true); END } should this be false here?

Target:
public void onlyApprovedCode() { onlyApprovedCode(false); }
Source:
private boolean containsComment(GHPullRequest ghPullRequest, String expectedBody) { List<GHIssueComment> prComments = null; try { prComments = ghPullRequest.getComments(); } catch (IOException e) { logger.log(Level.WARNING, "Failed to get comments for PR " + ghPullRequest, e); return false; } for (GHIssueComment comment : prComments) { START if (comment.getBody() != null && comment.getBody().contains(expectedBody)) { END return true; } } return false; } i think contains is not the thing we are looking for. the body should exactly match the expected content, no?

Target:
private boolean containsComment(GHPullRequest ghPullRequest, String expectedBody) { List<GHIssueComment> prComments; try { prComments = ghPullRequest.getComments(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to get comments for PR " + ghPullRequest, e); // return false in case of an error - probably safer to have multiple comments than possibly none return false; } for (GHIssueComment comment : prComments) { if (comment.getBody() != null && comment.getBody().equals(expectedBody)) { return true; } } return false; }
Source:
public GhprbGitHubAuth getGitHubApiAuth() { if (gitHubAuthId == null) { START GhprbGitHubAuth auth = getDescriptor().getGithubAuth().get(0); END gitHubAuthId = auth.getId(); getDescriptor().save(); return auth; } return getDescriptor().getGitHubAuth(gitHubAuthId); } This assumes that there will always be at least one entry, which it is possible there may not be.

Target:
public GhprbGitHubAuth getGitHubApiAuth() { GhprbGitHubAuth auth = getDescriptor().getGitHubAuth(gitHubAuthId); if (gitHubAuthId == null && auth != null) { gitHubAuthId = auth.getId(); getDescriptor().save(); } return auth; }
Source:
public String postBuildComment(AbstractBuild<?, ?> build, TaskListener listener) { START return "\nRefer to this link for build results (access rights to CI server needed): \n" + END generateCustomizedMessage(build) + "\n"; } The StringBuilder is cleaner and more readable. It also allows for easier expansion or editing.

Target:
public String postBuildComment(AbstractBuild<?, ?> build, TaskListener listener) { StringBuilder msg = new StringBuilder(); msg.append("\nRefer to this link for build results (access rights to CI server needed): \n"); msg.append(generateCustomizedMessage(build)); msg.append("\n"); return msg.toString(); }
Source:
public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); START checkSkipBuild(pr); END tryBuild(); } I think this (and tryBuild) needs to be under a synch too, because shouldRun will be updated.

Target:
public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Source:
public boolean matches(ScriptPath path) { String mob = path.eventArgLowerAt(1); if (!mob.equals("mob") START && runGenericCheck(mob, mythicmob.getMobType().getInternalName())) { END return false; } if (!runInCheck(path, location)) { return false; } return super.matches(path); } weird newline

Target:
public boolean matches(ScriptPath path) { String mob = path.eventArgLowerAt(1); if (!mob.equals("mob") && !runGenericCheck(mob, mythicmob.getMobType().getInternalName())) { return false; } if (!runInCheck(path, location)) { return false; } return super.matches(path); }
Source:
private void reloadData(Quester quester) { START if (quester == null) return; END quester.saveData(); quester.loadData(); } use `{}` for all if statements, even single-line ones.

Target:
private void reloadData(Quester quester) { if (quester == null) { return; } quester.saveData(); quester.loadData(); }
Source:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } //Getting the ViaVersion API object START ViaAPI api = Via.getAPI(); END // <--[tag] // @attribute <PlayerTag.viaversion> // @returns ElementTag(Number) // @description // Returns the protocol version number of the player's client. // See https://wiki.vg/Protocol_version_numbers as a reference list. // @Plugin Depenizen, ViaVersion. // --> if (attribute.startsWith("viaversion")) { return new ElementTag(api.getPlayerVersion(player.getOfflinePlayer().getUniqueId())) .getAttribute(attribute.fulfill(1)); } return null; } This should be INSIDE the attribute `if` block, not outside.

Target:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } // <--[tag] // @attribute <PlayerTag.viaversion> // @returns ElementTag(Number) // @description // Returns the protocol version number of the player's client. // See <@link url https://wiki.vg/Protocol_version_numbers> as a reference list. // @Plugin Depenizen, ViaVersion // --> if (attribute.startsWith("viaversion")) { ViaAPI api = Via.getAPI(); return new ElementTag(api.getPlayerVersion(player.getOfflinePlayer().getUniqueId())) .getAttribute(attribute.fulfill(1)); } return null; }
Source:
START protected TreeSet<CClassType> getTypes() { END TreeSet<CClassType> t = new TreeSet<>(Comparator.comparing(CClassType::getFQCN)); for(FullyQualifiedClassName type : types) { try { t.add(CClassType.get(type)); } catch (ClassNotFoundException ex) { // This can't happen, because throw new Error(ex); } } return t; } [Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle) is the preferred approach here, so still want to return Set, as well as use Set on the lhs of the assignment.

Target:
protected Set<CClassType> getTypes() { Set<CClassType> t = new TreeSet<>(Comparator.comparing(CClassType::getFQCN)); for(FullyQualifiedClassName type : types) { try { t.add(CClassType.get(type)); } catch (ClassNotFoundException ex) { // This can't happen, because throw new Error(ex); } } return t; }
Source:
public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCPlayerVelocityEvent) { if(key.equalsIgnoreCase("velocity")) { Vector3D v3d = ObjectGenerator.GetGenerator().vector(value, Target.UNKNOWN); Vector vector = new Vector(v3d.X(), v3d.Y(), v3d.Z()); START ((MCPlayerVelocityEvent) event).setVelocity(vector); END return true; } } return false; } Part 4: This particular usage can be avoided... (see part 5)

Target:
public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCPlayerVelocityEvent) { if(key.equalsIgnoreCase("velocity")) { Vector3D vector = ObjectGenerator.GetGenerator().vector(value, Target.UNKNOWN); ((MCPlayerVelocityEvent) event).setVelocity(vector); return true; } } return false; }
Source:
public void setGlowing(Boolean glow) { START if(ReflectionUtils.hasMethod(e.getClass(), "setGlowing", null)) { // Added around 1.9 END e.setGlowing(glow); } } These (glowing methods) were added on day 1 of 1.9 builds, so no check is required here.

Target:
public void setGlowing(Boolean glow) { e.setGlowing(glow); }
Source:
public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "char_is_uppercase('a')"), START new ExampleScript("", "char_is_uppercase('D')"),}; END } Also need "Basic usage" here too

Target:
public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "char_is_uppercase('a')"), new ExampleScript("Basic usage", "char_is_uppercase('D')"),}; }
Source:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(args[0], t); boolean glide = Static.getBoolean(args[1]); if (e.isOnGround()) { START throw new CREException("The specified entity cannot glide right now", t); END } e.setGliding(glide); return CVoid.VOID; } If we're going to do this, it should probably be mentioned in the docs. Do we need to check if grounded? As far as I can tell, it would just revert to not gliding immediately.

Target:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(args[0], t); boolean glide = Static.getBoolean(args[1]); e.setGliding(glide); return CVoid.VOID; }
Source:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); double temp; temp = loc.getBlock().getTemperature(); START return new CDouble(temp, target); END } In this case, you can combine that last 3 lines into "return new CDouble(loc.getBlock().getTemperature(), target);

Target:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); return new CDouble(loc.getBlock().getTemperature(), target); }
Source:
public Boolean runAsync() { START return true; END } Does this NEED to be async?

Target:
public Boolean runAsync() { return false; }
Source:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { START if (args.length < 1) { END throw new ConfigRuntimeException("bit_xor requires at least one argument", ExceptionType.InsufficientArgumentsException, t); } long val = Static.getInt(args[0], t); for (int i = 1; i < args.length; i++) { val = val ^ Static.getInt(args[i], t); } return new CInt(val, t); } Does this make sense with just one value? Also, here's a neat trick, you can turn insufficient arguments into a compiler error. implement optimizeDynamic, throw a ConfigCompileException if children.size() < minSize, then return null.

Target:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { long val = Static.getInt(args[0], t); for (int i = 1; i < args.length; i++) { val = val ^ Static.getInt(args[i], t); } return new CInt(val, t); }
Source:
START MCCriteria(String crit) { END this.criteria = crit; } Should be private, not package protected.

Target:
private MCCriteria(String crit) { criteria = crit; }
Source:
public void onTrimMemory(int level) { if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { //Log.d(TAG, "app went to background"); START isInBackground = true; END } if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) { MemoryCacheHelper.trimMemory(); } } > I'm sure There are better ways of doing this but this is what came to me at that moment. You shouldn't code like that, it makes the code worse than the best you can achieve.

Target:
public void onTrimMemory(int level) { if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) { MemoryCacheHelper.trimMemory(); } }
Source:
static Spanned enrichText(String text, List<Pair<Integer, Integer>> positions, Context context) { SpannableString enriched = new SpannableString(text); int primaryColor = UIColors.getPrimaryColor(context); for (Pair<Integer, Integer> position : positions) { enriched.setSpan( START new ForegroundColorSpan(primaryColor), END position.first, position.second, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); } return enriched; } do you need to create a new one everytime?

Target:
Spanned enrichText(String text, List<Pair<Integer, Integer>> positions, Context context) { SpannableString enriched = new SpannableString(text); int primaryColor = UIColors.getPrimaryColor(context); for (Pair<Integer, Integer> position : positions) { enriched.setSpan( new ForegroundColorSpan(primaryColor), position.first, position.second, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); } return enriched; }
Source:
public static int getPrimaryColor(Context context) { if (primaryColor == -1) { String primaryColorStr = PreferenceManager.getDefaultSharedPreferences(context).getString("primary-color", COLOR_DEFAULT_STR); // Transparent can't be displayed for text color, replace with light gray. if (primaryColorStr.equals("#00000000") || primaryColorStr.equals(("#AAFFFFFF"))) { START return 0xFFBDBDBD; END } primaryColor = Color.parseColor(primaryColorStr); } return primaryColor; } You probably shouldn't return anymore

Target:
public static int getPrimaryColor(Context context) { if (primaryColor == -1) { String primaryColorStr = PreferenceManager.getDefaultSharedPreferences(context).getString("primary-color", COLOR_DEFAULT_STR); // Transparent can't be displayed for text color, replace with light gray. if (primaryColorStr.equals("#00000000") || primaryColorStr.equals(("#AAFFFFFF"))) { primaryColor = 0xFFBDBDBD; } else { primaryColor = Color.parseColor(primaryColorStr); } } return primaryColor; }
Source:
public void setTags(String tags) { // Set the actual user-friendly name this.tags = tags; START if (tags != null) { END this.tags = this.tags.replaceAll("<", "&lt;"); // Normalize name for faster searching Pair<String, int[]> normalized = StringNormalizer.normalizeWithMap(this.tags); this.tagsNormalized = normalized.first; this.tagsPositionMap = normalized.second; } } Check with `this.tags`?

Target:
public void setTags(String tags) { // Set the actual user-friendly name this.tags = tags; if (this.tags != null) { this.tags = this.tags.replaceAll("<", "&lt;"); // Normalize name for faster searching Pair<String, int[]> normalized = StringNormalizer.normalizeWithMap(this.tags); this.tagsNormalized = normalized.first; this.tagsPositionMap = normalized.second; } }
Source:
public int mapTagsPosition(int position) { if (this.tagsPositionMap != null) { if (position < this.tagsPositionMap.length) { return this.tagsPositionMap[position]; START } else { END return this.tags.length(); } } else { // No mapping defined if (position < this.tags.length()) { return position; } else { return this.tags.length(); } } } No need for else if you return in the previous if

Target:
public int mapTagsPosition(int position) { if (this.tagsPositionMap != null) { if (position < this.tagsPositionMap.length) { return this.tagsPositionMap[position]; } return this.tags.length(); } else { // No mapping defined if (position < this.tags.length()) { return position; } return this.tags.length(); } }
Source:
private void updatePrimaryButtonEnabledStatus() { START View view = getView(); if (view != null) { END String currentPassword = mPasswordInput.getEditText().getText().toString(); getPrimaryButton().setEnabled(!currentPassword.trim().isEmpty()); } } Why exactly do we need to check this here?

Target:
private void updatePrimaryButtonEnabledStatus() { String currentPassword = mPasswordInput.getEditText().getText().toString(); getPrimaryButton().setEnabled(!currentPassword.trim().isEmpty()); }
Source:
private void performPrimaryAction() { switch (getPrimaryAction()) { case PUBLISH_NOW: case UPDATE: case SCHEDULE: START case SUBMIT_FOR_REVIEW: END mAnalyticsTrackerWrapper.track(Stat.EDITOR_POST_PUBLISH_TAPPED); showPrepublishingNudgeBottomSheet(); return; case SAVE: uploadPost(false); break; } } I might have asked this already, but I forgot the explanation, sorry. Is it okay that we track `EDITOR_POST_PUBLISH_TAPPED` for all the actions (not just "publish")?

Target:
private void performPrimaryAction() { switch (getPrimaryAction()) { case PUBLISH_NOW: mAnalyticsTrackerWrapper.track(Stat.EDITOR_POST_PUBLISH_TAPPED); showPrepublishingNudgeBottomSheet(); return; case UPDATE: case SCHEDULE: case SUBMIT_FOR_REVIEW: showPrepublishingNudgeBottomSheet(); return; case SAVE: uploadPost(false); break; } }