auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected <T> HandlerHolder<T> addRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(registration.getHandler(), "handler"); LocalRegistrationResult result = addLocalRegistration(address, registration, replyHandler, localOnly); addRegistration(result.newAddress, address, replyHandler, localOnly, registration::setResult); START return result.holder; END } Perhaps we should seize the opportunity to rename this method. It is confusing as it is the same name as the current method but its purpose is really to provide a hook for clustered event bus to propagate the registration.

Target:
protected <T> HandlerHolder<T> addRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(registration.getHandler(), "handler"); LocalRegistrationResult<T> result = addLocalRegistration(address, registration, replyHandler, localOnly); addRegistration(result.newAddress, address, replyHandler, localOnly, registration::setResult); return result.holder; }
Source:
public synchronized void close() { START synchronized (this) { END if (timerID >= 0) { client.getVertx().cancelTimer(timerID); timerID = -1; } } endpointMap.clear(); for (HttpClientConnection conn : connectionMap.values()) { conn.close(); } } Why `synchronize(this)` here since the method is `synchronized`?

Target:
public void close() { synchronized (this) { if (timerID >= 0) { client.getVertx().cancelTimer(timerID); timerID = -1; } } endpointMap.clear(); for (HttpClientConnection conn : connectionMap.values()) { conn.close(); } }
Source:
private synchronized void checkExpired() { START if (timerID >= 0) { END long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); } } Why do we need this check?

Target:
private synchronized void checkExpired() { long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); }
Source:
static void checkType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Boolean || obj instanceof Double || obj instanceof Float || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj instanceof byte[] || START obj instanceof JsonObject || END obj instanceof JsonArray || obj instanceof Shareable) { } else { throw new IllegalArgumentException("Invalid type for shareddata data structure: " + obj.getClass().getName()); } } I think that if JsonObject and JsonArray implement it, we need to remove them from this list as well

Target:
static void checkType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Boolean || obj instanceof Double || obj instanceof Float || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj instanceof byte[] || obj instanceof Shareable) { } else { throw new IllegalArgumentException("Invalid type for shareddata data structure: " + obj.getClass().getName()); } }
Source:
void handleData(Buffer data) { synchronized (conn) { START bytesRead += data.getByteBuf().readableBytes(); END if (decoder != null) { try { decoder.offer(new DefaultHttpContent(data.getByteBuf())); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { handleException(e); } } if (dataHandler != null) { dataHandler.handle(data); } } } rather use `data.length()`

Target:
void handleData(Buffer data) { synchronized (conn) { bytesRead += data.length(); if (decoder != null) { try { decoder.offer(new DefaultHttpContent(data.getByteBuf())); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { handleException(e); } } if (dataHandler != null) { dataHandler.handle(data); } } }
Source:
START void add(Closeable hook) { END if (closeHooks == null) { // Has to be concurrent as can be removed from non context thread closeHooks = new ConcurrentHashSet<>(); } closeHooks.add(hook); } synchronization issue here. You may instantiate the set several times.

Target:
synchronized void add(Closeable hook) { if (closeHooks == null) { // Has to be concurrent as can be removed from non context thread closeHooks = new HashSet<>(); } closeHooks.add(hook); }
Source:
boolean isLocal() { START return isFromWire(); END } Shouldn't it be `return !isFromWire();`

Target:
protected boolean isLocal() { return !isFromWire(); }
Source:
private List<String> getArguments() { List<String> args = executionContext.commandLine().allArguments(); // Add system properties passed as parameter if (systemProperties != null) { START args.addAll( END systemProperties.stream().map( entry -> "-D" + entry) .collect(Collectors.toList())); } // Add id - it's important as it's the application mark. args.add("-Dvertx.id=" + getId()); return args; } seems simpler to do `systemProperties.stream().map(entry -> "-D" + entry).forEach(args::add)`

Target:
private List<String> getArguments() { List<String> args = executionContext.commandLine().allArguments(); // Add system properties passed as parameter if (systemProperties != null) { systemProperties.stream().map(entry -> "-D" + entry).forEach(args::add); } // Add id - it's important as it's the application mark. args.add("-Dvertx.id=" + getId()); return args; }
Source:
public List<String> processArgs() { // As we are maintaining the launcher and starter class, choose the right one. START final List<String> processArgument = VertxCommandLauncher.getProcessArguments(); END return processArgument != null ? processArgument : Starter.PROCESS_ARGS; } why final ?

Target:
public List<String> processArgs() { // As we are maintaining the launcher and starter class, choose the right one. List<String> processArgument = VertxCommandLauncher.getProcessArguments(); return processArgument != null ? processArgument : Starter.PROCESS_ARGS; }
Source:
public void testVersion() throws Exception { START String[] args = new String[]{"-version"}; END MyStarter starter = new MyStarter(); starter.run(args); // TODO some way of getting this from the version in pom.xml assertEquals(System.getProperty("vertxVersion"), starter.getVersion()); } no need for new String[], same for others below

Target:
public void testVersion() throws Exception { String[] args = {"-version"}; MyStarter starter = new MyStarter(); starter.run(args); // TODO some way of getting this from the version in pom.xml assertEquals(System.getProperty("vertxVersion"), starter.getVersion()); }
Source:
START protected String rtrim(String s) { END if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); } could be made static

Target:
public static String rtrim(String s) { if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }
Source:
public void requestBegin(HttpClientRequest request) { if (!isEnabled()) return; START timings.put(request, time(null, null)); END } Always called with (null, null) - so method and URI is never taken into account?

Target:
public void requestBegin(HttpClientRequest request) { if (!isEnabled()) return; timings.put(request, time(request.method(), request.uri())); }
Source:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); //Only apply final modifier to val local variables if (parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { START return PsiModifier.FINAL.equals(name) ? Boolean.TRUE : null; END } return null; } It could be better to check for PsiModifier.FINAL.equals(name) first, before checking for instanceof and isVal

Target:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); //Only apply final modifier to val local variables if (PsiModifier.FINAL.equals(name) && parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return Boolean.TRUE; } return null; }
Source:
public ServletOutputStream getOutputStream() throws IOException { START final ServletOutputStream originalStream = this.getResponse().getOutputStream(); END return this.out; } looks the variable originalStream is not used.

Target:
public ServletOutputStream getOutputStream() { return this.out; }
Source:
private void deleteContent( final ArtifactStore store ) throws IndyWorkflowException { START List<Transfer> contents = downloadManager.listRecursively( store.getKey(), DownloadManager.ROOT_PATH ); END Set<String> pending = contents.stream().map( Transfer::getPath ).collect( Collectors.toSet() ); for ( String path : pending ) { contentManager.delete( store, path, new EventMetadata().set( IGNORE_READONLY, Boolean.TRUE ) ); } } You should be able to use `contentManager.delete(store, DownloadManager.ROOT_PATH, ...)` I believe.

Target:
private void deleteContent( final ArtifactStore store ) throws IndyWorkflowException { downloadManager.delete( store, ROOT_PATH, new EventMetadata().set( IGNORE_READONLY, Boolean.TRUE ) ); }
Source:
public String generateStorePath( String physicalPath ) { if ( StringUtils.isBlank( baseDir ) || !physicalPath.contains( baseDir ) ) { return physicalPath; } final int storePathStart = physicalPath.indexOf( baseDir ) + baseDir.length(); final String storePath = physicalPath.substring( storePathStart ); START return storePath.startsWith( "/" ) ? storePath : "/" + storePath; END } I would suggest removing the /. In physical store we use "new File( baseDir, fileInfo.getFileStorage())" so the storage path is always relative to baseDir. Although both works, they mean a bit different, e.g, "9s/3b/jasldjgenha" vs. "/9s/3b/jasldjgenha". In the this case, the leading / might confuse with the root of the whole disk.

Target:
public String generateStorePath( String physicalPath ) { if ( StringUtils.isBlank( baseDir ) || !physicalPath.contains( baseDir ) ) { return physicalPath; } final int storePathStart = physicalPath.indexOf( baseDir ) + baseDir.length(); final String storePath = physicalPath.substring( storePathStart ); return storePath.startsWith( "/" ) ? storePath.substring( 1 ) : storePath; }
Source:
public String toString() { return "ConnectionPoolInfo{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", user='" + user + '\'' START + ", password='" + password + '\'' + ", dataSourceClassname='" + dataSourceClassname + '\'' END + ", driverClassname='" + driverClassname + '\'' + ", useMetrics=" + useMetrics + ", useHealthChecks=" + useHealthChecks + ", properties=" + properties + '}'; } Just some concern for security: should we output user/pass here?

Target:
public String toString() { return "ConnectionPoolInfo{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", dataSourceClassname='" + dataSourceClassname + '\'' + ", driverClassname='" + driverClassname + '\'' + ", useMetrics=" + useMetrics + ", useHealthChecks=" + useHealthChecks + ", properties=" + properties + '}'; }
Source:
private void startRemoteManager() { if ( !remoteConfiguration.isEnabled() ) { logger.info( "Infinispan remote configuration not enabled. Skip." ); return; } ConfigurationBuilder builder = new ConfigurationBuilder(); START builder.addServer().host( remoteConfiguration.getRemoteServer() ).port( remoteConfiguration.getHotrodPort() ); END remoteCacheManager = new RemoteCacheManager( builder.build() ); logger.info( "Infinispan remote cache manager started." ); } Will this need to be a list of remote servers in order to handle clustering? What if the one we have configured goes down but the cluster is still up?

Target:
private void startRemoteManager() { if ( remoteConfiguration == null || !remoteConfiguration.isEnabled() ) { logger.info( "Infinispan remote configuration not enabled. Skip." ); return; } ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host( remoteConfiguration.getRemoteServer() ).port( remoteConfiguration.getHotrodPort() ); remoteCacheManager = new RemoteCacheManager( builder.build() ); logger.info( "Infinispan remote cache manager started." ); }
Source:
public void monthNameFormat(String pattern) { START monthNameFormat = new SimpleDateFormat(pattern, locale); END monthNameFormat.setTimeZone(timeZone); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } validateAndUpdate(); } this looks like it's copied from `init`...can you extract a private method instead?

Target:
private void monthNameFormat(String pattern) { monthNameFormat = new SimpleDateFormat(pattern, locale); monthNameFormat.setTimeZone(timeZone); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } }
Source:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } START monthView.setEvents(this.events); END monthView.init(months.get(position), cells.get(position)); return monthView; } why not pass this in `#init`?

Target:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } monthView.init(months.get(position), cells.get(position)); return monthView; }
Source:
public FluentInitializer withHighlightedDates(Collection<Date> dates) { START if (dates != null) { END highlightDates(dates); } return this; } is the `!= null` check necessary here?

Target:
public FluentInitializer withHighlightedDates(Collection<Date> dates) { highlightDates(dates); return this; }
Source:
public int compareTo(FitnessAndQuality o) { if (fitness == o.fitness) { if (quality == o.quality) { return 0; } START return quality < o.quality ? -1 : 1; END } return fitness < o.fitness ? -1 : 1; } Shouldn't this line be moved one line higher, before the close brace?

Target:
public int compareTo(FitnessAndQuality o) { if (fitness == o.fitness) { if (quality == o.quality) { return 0; } else { return quality < o.quality ? -1 : 1; } } else { return fitness < o.fitness ? -1 : 1; } }
Source:
public boolean accepts(Class<?> aClass) { return aClass.isPrimitive() || aClass.isEnum() || Number.class.isAssignableFrom(aClass) || String.class.equals(aClass) || Character.class.equals(aClass) || Boolean.class.equals(aClass) || java.util.Date.class.isAssignableFrom(aClass) START || java.util.Calendar.class.isAssignableFrom(aClass); END } Can you add _aClass.isEnum()_ at the end so the diff, is just 1 line, instead of 7

Target:
public boolean accepts(Class<?> aClass) { return aClass.isPrimitive() || Number.class.isAssignableFrom(aClass) || String.class.equals(aClass) || Character.class.equals(aClass) || Boolean.class.equals(aClass) || java.util.Date.class.isAssignableFrom(aClass) || java.util.Calendar.class.isAssignableFrom(aClass) || aClass.isEnum(); }
Source:
private boolean hasDateFormat() { return Optional .ofNullable(dateFormatContainer) START .map(DateFormatContainer::getDateFormat) END .isPresent(); } although its nice to use java8 optionals. sometimes its easier to read old fashioned if null checks.

Target:
private boolean hasDateFormat() { return dateFormatContainer != null && dateFormatContainer.getDateFormat() != null; }
Source:
public DozerBeanMapperFactoryBean dozerMapper() throws IOException { DozerBeanMapperFactoryBean factoryBean = new DozerBeanMapperFactoryBean(); factoryBean.setMappingFiles(configurationProperties.getMappingFiles()); factoryBean.setApplicationContext(applicationContext); START return factoryBean; END } Just wondering if the Mapper instance should be returned, instead of the spring factory. Or does spring wire together the Mapper by its "magic" :)

Target:
public DozerBeanMapperFactoryBean dozerMapper() throws IOException { DozerBeanMapperFactoryBean factoryBean = new DozerBeanMapperFactoryBean(); factoryBean.setMappingFiles(configurationProperties.getMappingFiles()); return factoryBean; }
Source:
public int getMetaFromState(IBlockState state) { int i = 0; if (state.getValue(POWERED)) { i = 1; } START return i; END } ```java return state.getValue(POWERED) ? 1 : 0; ```

Target:
public int getMetaFromState(IBlockState state) { return state.getValue(POWERED) ? 1 : 0; }
Source:
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) { double motionY = 1; double motionYGlowstoneMod = 0.1; double motionYFeatherMod = 0.05; entity.fallDistance = 0; TileAlchemyArray tileArray = (TileAlchemyArray) array; START entity.motionY = motionY + motionYGlowstoneMod * (tileArray.getStackInSlot(0).getCount() - 1) + motionYFeatherMod * (tileArray.getStackInSlot(1).getCount() - 1); END } This line is a bit long, do the math on another line like in the movement array.

Target:
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) { double motionY = 1; double motionYGlowstoneMod = 0.1; double motionYFeatherMod = 0.05; entity.fallDistance = 0; TileAlchemyArray tileArray = (TileAlchemyArray) array; motionY += motionYGlowstoneMod * (tileArray.getStackInSlot(0).getCount() - 1); // Glowstone Dust motionY += motionYFeatherMod * (tileArray.getStackInSlot(1).getCount() - 1); // Feathers entity.motionY = motionY; }
Source:
public String getUsage(ICommandSender sender) { START return new TextComponentTranslation("commands.bloodmagic.network." + getName() + ".usage").getFormattedText() + "\n" + help; END } You are returning a localized value. It expects a ***key***.

Target:
public String getUsage(ICommandSender sender) { return "commands.bloodmagic.network." + getName() + ".usage"; }
Source:
public String getHelp() { START return new TextComponentTranslation("commands.bloodmagic.bind.help").getFormattedText(); END } Pretty sure this is also supposed to just be the localization key.

Target:
public String getHelp() { return "commands.bloodmagic.bind.help"; }
Source:
public String getUsage(ICommandSender commandSender) { START return new TextComponentTranslation("commands.bloodmagic.orb.usage").getFormattedText(); END } This is still an issue.

Target:
public String getUsage(ICommandSender commandSender) { return "commands.bloodmagic.orb.usage"; }
Source:
public String getHelp() { START return new TextComponentTranslation("commands.bloodmagic.orb." + getName() + ".help", getInfo()).getFormattedText(); END } This expects a localization key

Target:
public String getHelp() { return "commands.bloodmagic.orb." + getName() + ".help"; }
Source:
public static void onRitualDeath(LivingDropsEvent event){ if(!ConfigHandler.values.wellOfSufferingDrops){ START if(event.getSource().equals(WayofTime.bloodmagic.ritual.RitualManager.RITUAL_DAMAGE)) { END event.getDrops().clear(); } } } Why fully qualified class name?

Target:
public static void onRitualDeath(LivingDropsEvent event){ if(!ConfigHandler.values.wellOfSufferingDrops){ if(event.getSource().equals(RitualManager.RITUAL_DAMAGE)) { event.getDrops().clear(); } } }
Source:
public static ItemStack compressInventory(ItemStack[] inv, World world) { for (CompressionHandler handler : compressionRegistry) { ItemStack stack = handler.compressInventory(inv, world); START if (stack != null && stack != ItemStack.EMPTY) { END return stack; } } return null; } `stack.isEmpty()`

Target:
public static ItemStack compressInventory(ItemStack[] inv, World world) { for (CompressionHandler handler : compressionRegistry) { ItemStack stack = handler.compressInventory(inv, world); if (!stack.isEmpty()) { return stack; } } return null; }
Source:
START public boolean equals(Object o) { END if (o instanceof SoulTicket) return ((SoulTicket) o).getDescription().equals(description); return false; } If you override `equals`, you have to override `hashCode` as well.

Target:
public boolean equals(Object o) { if (this == o) return true; if (o instanceof SoulTicket) return ((SoulTicket) o).getDescription().equals(description); return false; }
Source:
public ItemBlockBloodTank(Block block) { super(block); setHasSubtypes(true); START setMaxDamage(0); END } Unecessary.

Target:
public ItemBlockBloodTank(Block block) { super(block); setHasSubtypes(true); }
Source:
START public ItemStackWrapper(Item item, int stackSize) { END this(item, stackSize, 0, null); } Remove @ReqiredArgsConstructor and make your own ``` public ItemStackWrapper(Item item, int stackSize, int meta) { // Blah } ``` so that NBT isn't set by constructor. Use a Setter. Edit: Or make it not final. Which is perfectly fine here.

Target:
public ItemStackWrapper(Item item, int stackSize) { this(item, stackSize, 0); }
Source:
private boolean canDeclare(AbstractProject owner) { // In Hudson 1.341+ builds will be triggered via DependencyGraph // Inner class added in Hudson 1.341 String ownerClassName = owner.getClass().getName(); START return DependencyGraph.class.getClasses().length > 0 END // See HUDSON-5679 -- dependency graph is also not used when triggered from a promotion && !ownerClassName.equals("hudson.plugins.promoted_builds.PromotionProcess"); } The plugin now requires newer Jenkins core version than in 2016, maybe this check is not required anymore

Target:
private boolean canDeclare(AbstractProject owner) { // See HUDSON-5679 -- dependency graph is also not used when triggered from a promotion return !owner.getClass().getName().equals("hudson.plugins.promoted_builds.PromotionProcess"); }
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); START for (AbstractProject project : projectList) END ParameterizedDependency.add(owner, project, config, graph); } } please use brackets even for single-line cycles

Target:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) { ParameterizedDependency.add(owner, project, config, graph); } } }
Source:
public static void smite(final Player player) { START Command_smite.smite(player, reason); END } please just leave this as `smite(player, reason`

Target:
public static void smite(final Player player) { String reason = null; smite(player, reason); }
Source:
public static void smite(final Player player) { START smite(player, reason); END } Does not compile.

Target:
public static void smite(final Player player) { String reason = null; smite(player, reason); }
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { START if (args.length != 2) END { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } smite(player); return true; } Reason should be optional.

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length != 1) { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } smite(player); return true; }
Source:
START private String shortenPackage(final String pkg) { END final int sep = pkg.indexOf('/'); return sep == -1 ? "" : pkg.substring(sep + 1); } ```suggestion private static String shortenPackage(final String pkg) { ```

Target:
private static String shortenPackage(final String pkg) { final int sep = pkg.indexOf('/'); return sep == -1 ? "" : pkg.substring(sep + 1); }
Source:
private String checkRatioLimit(final String minmax, final BigDecimal v) { if (v != null && (v.compareTo(BigDecimal.ZERO) == -1 START || v.compareTo(BigDecimal.ONE) == 1)) { END return String.format( "given %s ratio is %s, but must be between 0.0 and 1.0", minmax, v); } return null; } While [`BigDecimal.compareTo`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#compareTo-java.math.BigDecimal-) clearly specifies return values as `-1, 0, or 1`, `< 0` (less than zero) and `> 0` (greater than zero) look clearer to my taste, also [`Comparable.compareTo`](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-) specifies return values as `a negative integer, zero, or a positive`.

Target:
private String checkRatioLimit(final String minmax, final BigDecimal v) { if (v != null && (v.compareTo(BigDecimal.ZERO) < 0 || v.compareTo(BigDecimal.ONE) > 0)) { return String.format( "given %s ratio is %s, but must be between 0.0 and 1.0", minmax, v); } return null; }
Source:
public void whenSealed() { START assertLine("whenSealed.when", ICounter.FULLY_COVERED, 0, 0); END assertLine("whenSealed.case1", ICounter.FULLY_COVERED, 0, 2); // without filter next line covered partly and has one uncovered branch: assertLine("whenSealed.case2", ICounter.FULLY_COVERED, 0, 0); assertLine("whenSealed.return", ICounter.FULLY_COVERED, 0, 0); } Probably in conflict with #722.

Target:
public void whenSealed() { assertLine("whenSealed.when", ICounter.FULLY_COVERED); assertLine("whenSealed.case1", ICounter.FULLY_COVERED, 0, 2); // without filter next line covered partly and has one uncovered branch: assertLine("whenSealed.case2", ICounter.FULLY_COVERED); assertLine("whenSealed.return", ICounter.FULLY_COVERED); }
Source:
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { START classAnnotations.clear(); END coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); } AFAIR instances of `ClassAnalyzer` are not reused, so this `clear()` seems useless.

Target:
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); }
Source:
public void analyzeClass(final byte[] buffer, final String location) throws IOException { try { analyzeClass(new ClassReader(buffer)); START } catch (final Exception cause) { END throw analyzerError(location, cause); } } Wondering why? how this is related to ASM 6? I'm asking because we had some improvements and quite some nasty regressions/missed cases of exception handling exactly here.

Target:
public void analyzeClass(final byte[] buffer, final String location) throws IOException { try { analyzeClass(new ClassReader(buffer)); } catch (final RuntimeException cause) { throw analyzerError(location, cause); } }
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { try { output.write(instrument(input, name)); } catch (final RuntimeException e) { START throw instrumentError(name, e); END } } IMO addition of this is an indication of regression in `instrument(InputStream, String)`.

Target:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }
Source:
public byte[] instrument(final byte[] buffer, final String name) throws IOException { try { if (Java9Support.isPatchRequired(buffer)) { final byte[] result = instrument( new ClassReader(Java9Support.downgrade(buffer))); Java9Support.upgrade(result); return result; } else { return instrument(new ClassReader(buffer)); } } catch (final RuntimeException e) { START throw instrumentError("class " + name, e); END } } @Godin Absolutely! In the context of the agent and the class name it should be obvious that classes get instrumented.

Target:
public byte[] instrument(final byte[] buffer, final String name) throws IOException { try { if (Java9Support.isPatchRequired(buffer)) { final byte[] result = instrument( new ClassReader(Java9Support.downgrade(buffer))); Java9Support.upgrade(result); return result; } else { return instrument(new ClassReader(buffer)); } } catch (final RuntimeException e) { throw instrumentError(name, e); } }
Source:
private static boolean isSame(final int size, AbstractInsnNode e, AbstractInsnNode n) { for (int i = 0; i < size; i++) { START if (e.getOpcode() != n.getOpcode()) { END return false; } e = next(e); n = next(n); } return true; } What about also checking operands here? Should be the same except for labels.

Target:
private static boolean isSame(final int size, AbstractInsnNode e, AbstractInsnNode n) { for (int i = 0; i < size; i++) { if (n == null || e.getOpcode() != n.getOpcode()) { return false; } e = next(e); n = next(n); } return true; }
Source:
public void testSetPredecessor() { final Instruction predecessor = new Instruction( new InsnNode(Opcodes.NOP), 122); instruction.setPredecessor(predecessor, 0); assertEquals(1, predecessor.getBranches()); try { instruction.setPredecessor(predecessor, 0); fail("exception expected"); START } catch (IllegalStateException e) { END // expected } } @Godin Why not `@Test(expected=IllegalStateException.class)`?

Target:
public void testSetPredecessor() { final Instruction predecessor = new Instruction( new InsnNode(Opcodes.NOP), 122); instruction.setPredecessor(predecessor, 0); assertEquals(1, predecessor.getBranches()); }
Source:
protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); if (oldValue == null) { getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } else { START getLog().info(name + " set to " + oldValue); END } } Actually we don't set anything here: Either we don't log at all or we log something like: "Keep [property] as [oldValue]".

Target:
protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); if (oldValue == null) { getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } }
Source:
public void testDestFileWithComma() { START AgentOptions options = new AgentOptions(); END AgentOptions options = new AgentOptions("destfile=build/jacoco/foo, bar.exec"); assertEquals("build/jacoco/foo, bar.exec", options.getDestfile()); } This line should be removed

Target:
public void testDestFileWithComma() { AgentOptions options = new AgentOptions("destfile=build/jacoco/foo, bar.exec"); assertEquals("build/jacoco/foo, bar.exec", options.getDestfile()); }
Source:
START public double getRatio(final CounterEntity entity) { END double ratio = DEFAULT_RATIO; if (this.configuration.get(entity) != null) { ratio = this.configuration.get(entity).doubleValue(); } return ratio; } Avoid two lookup, what about this? ``` final Double ratio = this.configuration.get(entity); return ratio == null ? DEFAULT_RATIO : ratio.doubleValue(); ```

Target:
public double getRatio(final CounterEntity entity) { final Double ratio = this.configuration.get(entity); return ratio == null ? DEFAULT_RATIO : ratio.doubleValue(); }
Source:
START public MetadataTermMapping(MetadataSource metadataSource, String metadataTermCode, OpenmrsMetadata referredObject) { END this(); ArgUtil.notNull(metadataSource, "metadataSource"); ArgUtil.notNull(metadataTermCode, "metadataTermCode"); setMetadataSource(metadataSource); setCode(metadataTermCode); if (referredObject != null) { setMappedObject(referredObject); } } Any chance you could add a constructor which takes just metadatsource and metadataTermCode?

Target:
public MetadataTermMapping(MetadataSource metadataSource, String metadataTermCode, OpenmrsMetadata referredObject) { this(); ArgUtil.notNull(metadataSource, "metadataSource"); ArgUtil.notNull(metadataTermCode, "metadataTermCode"); setMetadataSource(metadataSource); setCode(metadataTermCode); setMappedObject(referredObject); }
Source:
public void addEntity(Query query, String alias, Class<?> type) { if (query instanceof NativeQuery) { START query.unwrap(NativeQuery.class).addEntity(alias, type); END } else { throw new IllegalArgumentException(String.format("invalid Query type `%s` in HibernateHandler", query.getClass())); } } When `unwrap` is used, it doesnt have to be cast to a `NativeQuery` in the first place. In fact, unwrap was introduced to prevent the need for casts, which is important in i.e. J2EE environments where the `Query` may be wrapped in a proxy that does not implement `NativeQuery`. `unwrap` will throw a `PersistenceException` if the implementation is not of the requested type. This would be the exception to catch and rethrow in the `IllegalArgumentException`. Or just let it be a `PersistenceException`.

Target:
public void addEntity(Query query, String alias, Class<?> type) { query.unwrap(NativeQuery.class).addEntity(alias, type); }
Source:
private static String escapeName(String name) { if (JavaSyntaxUtils.isReserved(name)) { name = name + "$"; } START if (!Character.isJavaIdentifierStart(name.charAt(0))) { END name = "_" + name; } return name; } They are mutually exclusive? Or is that a micro optimization?

Target:
private static String escapeName(String name) { if (JavaSyntaxUtils.isReserved(name)) { name = name + "$"; } else if (!Character.isJavaIdentifierStart(name.charAt(0))) { name = "_" + name; } return name; }
Source:
START public EntityType(Type type, Set<Supertype> superTypes, Function<EntityType, String> variableNameFunction) { END super(type); this.modifiedSimpleName = variableNameFunction.apply(this); this.superTypes = superTypes; this.variableNameFunction = variableNameFunction; } Maybe getUncapSimpleName could be deprecated and the transformation done outside of EntityType? ``` java String variableName = variableNameFunction(type.getSimpleName()); if (JavaSyntaxUtils.isReserved(name)) { variableName = variableName + "$"; } ```

Target:
private EntityType(Type type, Set<Supertype> superTypes, Function<EntityType, String> variableNameFunction) { super(type); this.superTypes = superTypes; this.modifiedSimpleName = variableNameFunction.apply(this); }
Source:
public EntityType(Type type, Set<Supertype> superTypes) { super(type); this.superTypes = superTypes; START this.modifiedSimpleName = new DefaultVariableNameFunction().apply(this); END } Could you maybe look if this could be removed? I mean the `new DefaultVariableNameFunction().apply(this)`. It's already handled in the other constructor.

Target:
public EntityType(Type type, Set<Supertype> superTypes) { this(type, superTypes, new DefaultVariableNameFunction()); }
Source:
private <A> Cases<A, SimpleExpression<A>> thenSimple(Expression<A> expr) { START return new Cases<A, SimpleExpression<A>>((Class)expr.getType()) { END @Override protected SimpleExpression<A> createResult(Class<A> type, Expression<A> last) { return Expressions.operation(type, Ops.CASE, last); } }.addCase(when, expr); } I think relaxing the type parameter in `Cases`' `type`,`createResult` and constructor to `Class<? extends A>` helps a lot too to eliminate these casts **and** `@SuppressWarnings`.

Target:
private <A> Cases<A, SimpleExpression<A>> thenSimple(Expression<A> expr) { return new Cases<A, SimpleExpression<A>>(expr.getType()) { @Override protected SimpleExpression<A> createResult(Class<? extends A> type, Expression<A> last) { return Expressions.operation(type, Ops.CASE, last); } }.addCase(when, expr); }
Source:
public static String createRootVariable(Path<?> path, int suffix) { START String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES).replace('.', '_'); END return variable + "_" + suffix; } The templates used are already UnderscoreTemplates, so is it necessary to replace '.' with '_'?

Target:
public static String createRootVariable(Path<?> path, int suffix) { String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES); return variable + "_" + suffix; }
Source:
private String serialize(Expression<?> expression) { CollectionAnyVisitor visitor = new CollectionAnyVisitor() { @Override protected Predicate exists(Context c, Predicate condition) { return condition; } }; START Expression<?> transformed = expression.accept(visitor, new Context()); END return transformed.toString(); } Keep in mind, that collectionAnyVisitor is now stateful. The tests should reflect that as well.

Target:
private String serialize(Expression<?> expression) { return serialize(expression, new CollectionAnyVisitor()); }
Source:
public void Case() { START <<<<<<< HEAD END assertEquals(ImmutableList.of(1, 2, 2, 2, 2, 2), query().from(cat).orderBy(cat.id.asc()) .select(cat.name.when("Bob123").then(1).otherwise(2)).fetch()); } You committed merge markers

Target:
public void Case() { assertEquals(ImmutableList.of(1, 2, 2, 2, 2, 2), query().from(cat).orderBy(cat.id.asc()) .select(cat.name.when("Bob123").then(1).otherwise(2)).fetch()); }
Source:
public static boolean isEmpty(Object[] array) { START return array == null ? true : array.length == 0; END } return array == null || array.length == 0

Target:
public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; }
Source:
public void noteOpenConnection(ServerStats serverStats) { if (serverStats == null) { return; } try { serverStats.incrementActiveRequestsCount(); START } catch (Error ex) { END logger.error("Error noting stats for client {}", clientName, ex); } } I noticed a bunch of these transitioned from Throwable to Error. Should that be Exception?

Target:
public void noteOpenConnection(ServerStats serverStats) { if (serverStats == null) { return; } try { serverStats.incrementActiveRequestsCount(); } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } }
Source:
private VipAddressResolver getVipAddressResolver() { if (resolver == null) { synchronized (this) { if (resolver == null) { try { resolver = (VipAddressResolver) Class.forName( (String) getProperty(CommonClientConfigKey.VipAddressResolverClassName)).newInstance(); START } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) { END LOG.error("Cannot instantiate VipAddressResolver", e); } } } } return resolver; } This doesn't look like a recoverable scenario, should you be re-throwing this one? Or is there some default/fallback VipAddressResolver if the instantiation fails here?

Target:
private VipAddressResolver getVipAddressResolver() { if (resolver == null) { synchronized (this) { if (resolver == null) { try { resolver = (VipAddressResolver) Class .forName((String) getProperty(CommonClientConfigKey.VipAddressResolverClassName)) .newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Cannot instantiate VipAddressResolver", e); } } } } return resolver; }
Source:
public void stopServerListRefreshing() { if (eurekaClientProvider != null) { EurekaClient eurekaClient = eurekaClientProvider.get(); if (eurekaClient != null) { eurekaClient.unregisterEventListener(updateListener); } } START serverListUpdateService.shutdown(); END } This will end up doing multiple shutdowns of the shared executor (if used). You may want to track a 'sharedExecutor' variable that is null if the sharedExecutor is not used.

Target:
public void stopServerListRefreshing() { if (eurekaClientProvider != null) { EurekaClient eurekaClient = eurekaClientProvider.get(); if (eurekaClient != null) { eurekaClient.unregisterEventListener(updateListener); } } }
Source:
ExecutionContext<T> getChildContext(Object obj) { if (subContexts == null) { return null; } ChildContext<T> subContext = subContexts.get(obj); if (subContext == null) { subContext = new ChildContext<T>(this); START } END ChildContext<T> old = subContexts.putIfAbsent(obj, subContext); if (old != null) { return old; } else { return subContext; } } Shouldn't this be inside the if above?

Target:
ExecutionContext<T> getChildContext(Object obj) { if (subContexts == null) { return null; } ChildContext<T> subContext = subContexts.get(obj); if (subContext == null) { subContext = new ChildContext<T>(this); ChildContext<T> old = subContexts.putIfAbsent(obj, subContext); if (old != null) { subContext = old; } } return subContext; }
Source:
START public void onExecutionStart() { END if (onStartInvoked.compareAndSet(false, true)) { for (ExecutionListener<I, O> listener : listeners) { try { listener.onExecutionStart(context.getChildContext(listener)); } catch (Throwable e) { if (e instanceof AbortExecutionException) { throw (AbortExecutionException) e; } logger.error("Error invoking listener " + listener, e); } } } } Should calling this more than once throw an exception? Seems like an invalid state.

Target:
public void onExecutionStart() { onExecutionStart(this.context); }
Source:
void restOfInit(IClientConfig clientConfig) { START refeshIntervalMills = Integer.parseInt(clientConfig.getProperty( END CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL).toString()); boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getServerList(true)); } this.setEnablePrimingConnections(primeConnection); } Since we support typed property, this can be simply ``` java clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); ```

Target:
void restOfInit(IClientConfig clientConfig) { refeshIntervalMills =clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getServerList(true)); } this.setEnablePrimingConnections(primeConnection); }
Source:
static List<Date> getDays(long endTs, @Nullable Long lookback) { List<Date> result = new ArrayList<>(); START for (Long epochMillis : DateUtil.epochDays(endTs, lookback)) { END result.add(new Date(epochMillis)); } return result; } Accidental box?

Target:
static List<Date> getDays(long endTs, @Nullable Long lookback) { List<Date> result = new ArrayList<>(); for (long epochMillis : DateUtil.epochDays(endTs, lookback)) { result.add(new Date(epochMillis)); } return result; }
Source:
START Optional<String> getCredentials() { END return Optional.ofNullable(basicCredentials); } Let's just make this `@Nullable` instead of using `Optional`

Target:
String getCredentials() { return basicCredentials; }
Source:
public void setCredentialsRefreshInterval( Integer credentialsRefreshInterval) { // Convert seconds to milliseconds START this.credentialsRefreshInterval = credentialsRefreshInterval * 1000; END } this is a surprising hack. please change the place where it is used instead as it doesn't make sense for a property to be manipulated like this. The scheduled expression might accept seconds expression like `s`.

Target:
public void setCredentialsRefreshInterval( Integer credentialsRefreshInterval) { this.credentialsRefreshInterval = credentialsRefreshInterval; }
Source:
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { String credentials = basicCredentials.getCredentials(); START if (Objects.nonNull(credentials)) { END ctx.addAdditionalRequestHeader(HttpHeaderNames.AUTHORIZATION, credentials); } return delegate().execute(ctx, req); } ```suggestion if (credentials != null) { ```

Target:
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { String credentials = basicCredentials.getCredentials(); if (credentials != null) { ctx.addAdditionalRequestHeader(HttpHeaderNames.AUTHORIZATION, credentials); } return delegate().execute(ctx, req); }
Source:
@Override public Call<Void> accept(List<Span> spans) { Call<Void> call = delegate.accept(spans); START if (isSpanReporterThread()) return call; END return new TracedCall<>(tracer, delegate.accept(spans), "accept-spans"); } I'm probably wrong but I thought since we don't sample client spans, calls from the span reporter thread wouldn't be sampled anyways, they originate from the flush thread not server requests. Why is this check necessary?

Target:
@Override public Call<Void> accept(List<Span> spans) { return new TracedCall<>(tracer, delegate.accept(spans), "accept-spans"); }
Source:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { try { callback.onSuccess(parseResponse(response, bodyConverter)); START } catch (Throwable e) { END callback.onError(e); } } return null; }); } usually I do either ` IOException|RuntimeException` or if doing Throwable, use propagateIfFatal

Target:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { try { callback.onSuccess(parseResponse(response, bodyConverter)); } catch (IOException e) { callback.onError(e); } } return null; }); }
Source:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { // End of input. START throw new IOException("End of input while parsing object."); END } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; } our old code didn't throw I think, rather returned null

Target:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { // End of input so ignore. return null; } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }
Source:
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); START LOGGER.warn("Unexpected error handling request.", cause); END String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } } I'm not sure we want to add this logging in all cases. It seems too verbose to me for bad requests.

Target:
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { LOGGER.warn("Unexpected error handling request.", cause); return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } }
Source:
@Override final String doReadUtf8(int length) { START String result = new String(buf, pos, length, UTF_8); END pos += length; return result; } `require(length)`

Target:
@Override final String doReadUtf8(int length) { String result = new String(buf, offset, length, UTF_8); offset += length; return result; }