auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public RuntimeException translateException(Throwable throwable) { RuntimeException runtimeException = throwable instanceof RuntimeException ? (RuntimeException) throwable : new RuntimeException(throwable.getMessage(), throwable); RuntimeException potentiallyTranslatedException = exceptionTranslator .translateExceptionIfPossible(runtimeException); return potentiallyTranslatedException != null ? potentiallyTranslatedException : runtimeException; }

Target:
Nit: Let's have this method private unless someone asks for it.
Source:
public <T> Optional<T> get(String id, Class<T> clazz, IndexCoordinates index) { GetRequest request = requestFactory.getRequest(id, index); try { GetResponse response = client.get(request, RequestOptions.DEFAULT); return Optional.ofNullable(elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz)); } catch (IOException e) { throw new ElasticsearchException("Error while getting for request: " + request.toString(), e); } }

Target:
Let's stick with `T` instead of `Optional<T>`. A huge number of folks already asked us to roll back the `Optional` change at `findById` and `Optional` isn't being loved that much.
Source:
float getScore() { return score; }

Target:
Nit: `public`
Source:
public static IndexCoordinates of(String... indexNames) { Assert.notNull(indexNames,"indexNames must not be null"); return new IndexCoordinates(indexNames); }

Target:
Let's also ensure that `indexNames` contains at least one element so we can get rid of nullability in `getIndexName()`
Source:
public MappingElasticsearchConverter elasticsearchEntityMapper( SimpleElasticsearchMappingContext elasticsearchMappingContext) { return new MappingElasticsearchConverter(elasticsearchMappingContext, new DefaultConversionService()); }

Target:
Let's use a constructor without a `conversionService` here to align with other modules.
Source:
public void shouldSupportSortOnStandardFieldWithCriteria() { final List<String> sortedIds = repository.findAllByNameOrderByText("Salt").stream() // .map(it -> it.id).collect(Collectors.toList()); assertThat(sortedIds).containsExactly("4", "5"); }

Target:
Nit: No need for `final` keyword in local variables.
Source:
public String getFieldName() { return isAnnotatedFieldName ? annotatedFieldName : getProperty().getName(); }

Target:
```java return annotatedFieldName == null ? getProperty().getName() : annotatedFieldName ```
Source:
protected CompositeJsonFormatter<ILoggingEvent> createFormatter() { LogstashFormatter formatter = new LogstashFormatter(this); formatter.setLineSeparator(getLineSeparator()); return formatter; }

Target:
Hmm. The Encoder's lineSeparator property is the string to output between events. Coupling the separator to output between events with the regex to use to split the message string does not seem ideal. I think the regex to use to split the message string should be separate from the separator string to use between events.
Source:
protected void prepareViewing() { drawRegistration.remove(); clickRegistration.remove(); if(markerRegisration != null) { markerRegisration.remove(); } }

Target:
Don't have the project open ATM, should there be a null check? Can the field go for "view mode" directly if a populated readonly property is set (I don't actually know if this is possible currently with V8)?
Source:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { File reconstructedFileInCache; try { reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); }

Target:
I generally dislike this pattern: ``` X var; try { X = ...; } catch (..) { } ``` Couldn't we just move the `moveFileToFinalLocation` inside the `try`?
Source:
public SortedMap<Long, String> getPurgeFileVersionSettings() { if (purgeFileVersionSettings == null) { purgeFileVersionSettings = new TreeMap<Long, String>(); purgeFileVersionSettings.put(30L * 24L * 3600L, "DD"); purgeFileVersionSettings.put(3L * 24L * 3600L, "HH"); purgeFileVersionSettings.put(3600L, "MI"); } return purgeFileVersionSettings; }

Target:
Shouldn't we use [`TimeUnit`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html) instead of plain strings for interval definitions?
Source:
public void afterPropertiesSet() throws Exception { ThymeleafViewResolver viewResolver = applicationContext.getBean(ThymeleafViewResolver.class); if (viewResolver == null) { LOG.warn( "Cannot adjust ThymeleafViewResolver: " + "bean of this type wasn't found in application context" ); return; } boolean productionEnv = environment.acceptsProfiles("prod"); Boolean useCdn = environment.getProperty("app.use-cdn", Boolean.class, Boolean.TRUE); viewResolver.setStaticVariables(resourcesAsMap(productionEnv, useCdn)); }

Target:
If you want, you can try to use `boolean useCdn = ...` here. It should work.
Source:
public void changeStatus(Integer requestId, String oldStatus, String newStatus) { Validate.isTrue(requestId != null, "Request id must be non null"); Validate.isTrue(StringUtils.isNotBlank(oldStatus), "Old status must be non-blank"); Validate.isTrue(StringUtils.isNotBlank(newStatus), "New status must be non-blank"); Validate.isTrue(!oldStatus.equals(newStatus), "Statuses must be different"); Date now = new Date(); seriesImportDao.changeStatus(new UpdateImportRequestStatusDbDto(requestId, now, oldStatus, newStatus)); }

Target:
Please, extract a local variable: ```java Date now = new Date(); UpdateImportRequestStatusDbDto status = new UpdateImportRequestStatusDbDto( requestId, now, oldStatus, newStatus ); seriesImportDao.changeStatus(status); ```
Source:
public List<SeriesInfoDto> findByMichelNumber(String michelNumberCode, String lang) { Validate.isTrue(michelNumberCode != null, "Michel number code must be non null"); Validate.isTrue(!michelNumberCode.trim().isEmpty(), "Michel number code must be non empty"); List<Integer> seriesIds = seriesDao.findSeriesIdsByMichelNumberCode(michelNumberCode); return seriesIds.isEmpty() ? Collections.emptyList() : seriesDao.findByIdsAsSeriesInfo(seriesIds, lang); }

Target:
Ah, and CheckStyle allows it? Rewrite to the long but more readable form: ``` java if (result.IsEmpty) { return emptyList; } return callDao(); ```
Source:
public boolean isValid(AddSeriesDto dto, ConstraintValidatorContext context) { if (dto == null) { return true; } LocalDate today = LocalDate.now(); if (yearInFuture(today, dto)) { rejectField(context, "year"); return false; } if (yearAndMonthInFuture(today, dto)) { rejectField(context, "month"); return false; } if (dateInFuture(today, dto)) { rejectField(context, "day"); return false; } return true; }

Target:
Ok, let's move this back to the methods, because we don't have any benefits of extracting here. Sorry :)
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context != null && !_context.hasPermission(Computer.CONFIGURE)) { return new ListBoxModel(); } return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context, ACL.SYSTEM, SSHLauncher.SSH_SCHEME)); }

Target:
:bug: this would open a security hole: a direct call to `/descriptorById/hudson.plugins.sshslaves.SSHConnector/fillCredentialsIdItems` from a user with only `Jenkins.READ` permission (perhaps anonymous) could enumerate credentials. I think you meant ``` java if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { ```
Source:
public ExportWiki(String url, String user, String password) throws AuthenticationException { BasicEndpoint basicEndpoint = new BasicEndpoint(); basicEndpoint.setUrl(url); basicEndpoint.setForceTrustSSLCertificate(true); basicEndpoint.setUser(user); basicEndpoint.setPassword(password); basicEndpoint.login(user, password); wikiService = new WikiService(); setEndpoint(basicEndpoint); }

Target:
You don't need setUser and setPassword anymore if you call login(user, password)
Source:
public String getBlogUuid() { return super.getUid(); }

Target:
Could you please remove all the unnecessary super. and this. ? Thanks!
Source:
public void remove() throws BlogServiceException{ if(StringUtil.isNotEmpty(getBlogHandle())){ getService().removeBlogPost(getPostUuid(), getBlogHandle()); } else{ getService().removeBlogPost(getPostUuid(), getAsString(BlogXPath.handle)); } }

Target:
Should this logic be part of getBlogHandle function itself ?
Source:
public void testUnRecommendPost() { JavaScriptPreviewPage previewPage = executeSnippet(SNIPPET_ID); JsonJavaObject json = previewPage.getJson(); System.out.println("aaaaaaaaaaaa "+json.getString("status")); Assert.assertTrue(json.getString("status").equals("204.0")); }

Target:
Should not have any sysout
Source:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "Vimal's testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); //now delete the folder created fileService.deleteFolder(folder.getFileId()); }

Target:
Can we replace description to something else ?
Source:
public static void fireChunkWatch(boolean wasLoaded, boolean load, ServerPlayerEntity entity, ChunkPos chunkpos, ServerWorld world) { if (!wasLoaded && load) MinecraftForge.EVENT_BUS.post(new ChunkWatchEvent.Watch(entity, chunkpos, world)); else if (wasLoaded && !load) MinecraftForge.EVENT_BUS.post(new ChunkWatchEvent.UnWatch(entity, chunkpos, world)); }

Target:
Yes it falls under binary compatibility
Source:
public void setContent(String contents) { this.nameplateContent = Strings.nullToEmpty(contents); }

Target:
Again, why nullToEmpty?
Source:
public static double getLivingVisibility(LivingEntity living, @Nullable Entity lookingEntity, double visibility) { LivingVisibilityEvent event = new LivingVisibilityEvent(living, lookingEntity, visibility); MinecraftForge.EVENT_BUS.post(event); double value = event.getVisibility(); if(living instanceof PlayerEntity) { value = getPlayerVisibilityDistance((PlayerEntity)living, value, visibility); } return value; }

Target:
I think the legacy event should be fired first, so the new event can overwrite the legacy result
Source:
public void setSwingHand(boolean value) { if(isPickBlock()) throw new UnsupportedOperationException("The hand swing can't be disabled if this is a pick block input."); handSwing = value; }

Target:
I would argue there is no point punishing modders for this. Just put in the method doc that changing this value has no affect for pick blocks.
Source:
public static int getItemBurnTime(ItemStack stack) { if (stack.isEmpty()) { return 0; } else { Item item = stack.getItem(); int base = stack.getBurnTime(); //I changed the original logic here. Previously every time ForgeEventFactory#getItemBurnTime was called, now the result is cahced aswell. return getBurnTimes().computeIfAbsent(item, i -> net.minecraftforge.event.ForgeEventFactory.getItemBurnTime(stack, base == -1 ? getVanillaBurnTimes().getOrDefault(i, 0) : base)); } }

Target:
the event should still be fired every time because you could e.g. have mods that dynamically adjust other mods' items' burn times
Source:
public static void invalidate() { burnTimes = null; vanillaBurnTimes = null; }

Target:
not called anywhere?
Source:
public static Map<DataFixer, Pair<Integer, Integer>> getFixVersionsNoVanilla(NBTTagCompound nbttagcompound, boolean useLatestOtherwiseN1) { return getFixVersionsNoVanilla(nbttagcompound, (useLatestOtherwiseN1 ? -2492 : -1)); }

Target:
What is -2492?
Source:
public Class<T> getBaseClass() { return baseClass; }

Target:
Is there a method for modders to share recipe types? An enum system with our extender or some form of get(ResourceLocation) would be good.
Source:
public <T> T get() { if (FMLEnvironment.dist == Dist.CLIENT) { return (T)this.clientSide.apply(client); } else if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) { return (T)this.serverSide.apply(server); } else if (FMLEnvironment.dist == null) { return (T)this.testSide.get(); } else { throw new IllegalArgumentException("THREE SIDES? WUT?"); } }

Target:
This should update and say that custom sides are not supported
Source:
public static <T> Comparator<IForgeRegistryEntry<T>> registryNameComparator() { return Comparator.comparing(IForgeRegistryEntry::getRegistryName, Comparator.naturalOrder()); }

Target:
`Comparator.comparing(IForgeRegistryEntry::getRegistryName)` should be sufficient.
Source:
public void write(PacketBuffer buffer) { this.getBlocks().write(buffer); this.getItems().write(buffer); this.getFluids().write(buffer); //we might wind up sending more data than vanilla needs (and therefore produce excessive Network traffic...) //TODO Check if connected to vanilla client and if so don't write ForgeTag Data writeForgeTags(buffer); }

Target:
Welcome to the world of limited packet sizes. This will explode and explode fast. Do not hijack the vanilla packet.
Source:
public Predicate<IResourceType> get() { if (this.currentPredicate == null) // TODO configs || !ForgeMod.selectiveResourceReloadEnabled) { return ReloadRequirements.all(); } return this.currentPredicate; }

Target:
Default to off until config is back
Source:
private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, String[] validValuesDisplay, String langKey) { Property prop = this.get(category, name, defaultValue); prop.setValidValues(validValues); if (validValuesDisplay != null) prop.setValidValuesDisplay(validValuesDisplay); prop.setLanguageKey(langKey); prop.setComment(comment + " [default: " + defaultValue + "]"); return prop.getStringList(); }

Target:
```suggestion private String[] setPropertyAndGetStringList(String name, String category, String[] defaultValue, String comment, String[] validValues, @Nullable String[] validValuesDisplay, String langKey) ```
Source:
public float getBlockLiquidHeight(World world, BlockPos pos, IBlockState state, Material material) { float filled = getFilledPercentage(world, pos); return filled > 0 ? filled : 0; }

Target:
Use `Math.max`
Source:
public CommandTreeTest() { addSubcommand(new CommandPing()); addSubcommand(new CommandValue()); addSubcommand(new CommandTreeHelp(this)); }

Target:
Use 4 spaces instead of tabs
Source:
public static String remapFieldName(Class<?> clazz, String fieldName) { String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz)); return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null); }

Target:
Maybe make it more clear that this is supposed to be srg name by naming it "fieldSrgName"? (and same for methods)
Source:
public PotionRemoveEvent(EntityLivingBase living, Potion potion) { super(living, living.getActivePotionMap().get(potion)); toRemove = potion; }

Target:
there are two spaces in `Potion potion`
Source:
public @Nullable MobSpawnerBaseLogic getSpawner() { return spawner; }

Target:
`@Nullable` should go on the line before, except in patches where size is being minimized.
Source:
private String getTileEntityName(TileEntity tileEntity) { String className = tileEntity.getClass().getSimpleName(); ResourceLocation registryId = TileEntity.getKey(tileEntity.getClass()); if (registryId == null) return className; else { return registryId.toString(); } }

Target:
Calculate this only if the registry id is null, or it is a waste or time and memory
Source:
public static boolean onLivingKnockBack(EntityLivingBase target, Entity attacker, float strength, double ratioX, double ratioZ) { return !MinecraftForge.EVENT_BUS.post(new LivingKnockBackEvent(target, attacker, strength, ratioX, ratioZ)); }

Target:
As you are negating the result when using this function, it'd be better to avoid the double-negation by just returning the result here directly.
Source:
public static boolean hasElytraFlightAbility(EntityLivingBase player, ItemStack itemstack) { if(!(player instanceof EntityPlayer)) return false; boolean vanillaElytra = itemstack.getItem() == Items.ELYTRA && ItemElytra.isUsable(itemstack); double attributeValue = player.getEntityAttribute(SharedMonsterAttributes.ELYTRA_FLIGHT).getAttributeValue(); return attributeValue>1.0D || (vanillaElytra && attributeValue >=1.0D); }

Target:
Please follow the formatting used elsewhere in the project. Braces go on a new line, spaces after `if` before the parenthesis, spaces around comparison operators, etc.
Source:
public boolean containsAll(Collection<?> tileEntities) { for (Iterator<?> iterator = tileEntities.iterator(); iterator.hasNext();) { if(!contains(iterator.next())) return false; } return true; }

Target:
Missing @ Override
Source:
@Nonnull public Explosion getExplosion() { return explosion; }

Target:
Formatting. Don't sqeeze it in one line, follow forge code style. Use this formatter: https://github.com/ForgeEssentials/ForgeEssentials/blob/develop/misc/eclipseformatter.xml
Source:
public IPropertyWrapper getProperty(String name) { buildPropertyMap(); return null; }

Target:
Ahem.
Source:
public EntityEquipmentInvWrapper(final EntityLivingBase entity, final EntityEquipmentSlot.Type slotType) { this.entity = entity; final List<EntityEquipmentSlot> slots = new ArrayList<EntityEquipmentSlot>(); for (final EntityEquipmentSlot slot : EntityEquipmentSlot.values()) { if (slot.getSlotType() == slotType) { slots.add(slot.getIndex(), slot); } } this.slots = ImmutableList.copyOf(slots); }

Target:
Not a fan of this, it would seem to add non-congruent slots. So the inventory would appear to have 'holes' A better way may be using add instead of a indexed add.
Source:
public int fill(FluidStack resource, boolean doFill) { // NOTE: "Filling" means placement in this context! if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); BlockDynamicLiquid block = BlockLiquid.getFlowingBlock(material); world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }

Target:
You don't need to change the type here.
Source:
public boolean isFluid(@Nonnull IBlockState blockstate) { return blockstate.getMaterial().isLiquid() || blockstate.getBlock() instanceof IFluidBlock; }

Target:
I think this should be private since it shouldn't be overridden.
Source:
public IMerchant getMerchant(){ return merchant; }

Target:
formatting
Source:
public GuiTab(String name, ResourceLocation icon, Class<? extends GuiContainer> clazz) { this.name = name; this.iconResLoc = icon; // Make sure the vanilla tab doesnt get duplicated if (GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB) == false) { GuiTab.VANILLA_INVENTORY_TAB.addTo(clazz); } }

Target:
```java if (!GuiTab.tabRegistry.get(clazz).contains(VANILLA_INVENTORY_TAB)) ```
Source:
public boolean has_finished( int sample_idx ) { if( loop_length <= 1 && sample_idx > loop_start ) { return true; } else { return false; } }

Target:
This shows you don't know about optimization at all.
Source:
public void onItemLoad(AttachCapabilitiesEvent.Item event) { if (!event.getItemStack().func_190926_b() && event.getItemStack().getItem() == Items.STICK) event.addCapability(new ResourceLocation("forge.testcapmod:dummy_cap"), new Provider(event.getItemStack())); }

Target:
Only `event.getItemStack().getItem() == Items.STICK` is enough.
Source:
private static long bytesToMb(long bytes) { return bytes / 1024L / 1024L; }

Target:
```java return bytes >> 20; ```
Source:
public static NonNullList<ItemStack> defaultRecipeGetRemainingItems(InventoryCrafting inv) { NonNullList<ItemStack> ret = NonNullList.func_191197_a(inv.getSizeInventory(), ItemStack.field_190927_a); for (int i = 0; i < ret.size(); i++) { ItemStack container = getContainerItem(inv.getStackInSlot(i)); if (container != null) { ret.set(i, container); } } return ret; }

Target:
The PROPER solution would be to make getContainerItem NOT return null, as Null ItemStacks are not valid anymore in 1.11
Source:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { looting = net.minecraftforge.common.ForgeHooks.getLootingLevel((EntityLivingBase)target, cause, looting); } return looting; }

Target:
``` java looting = getLootingLevel((EntityLivingBase)target, cause, looting); ``` This code is already in `ForgeHooks` class.
Source:
public static MultiPlaceEvent onPlayerMultiBlockPlace(EntityPlayer player, List<BlockSnapshot> blockSnapshots, EnumFacing direction) { BlockSnapshot snap = blockSnapshots.get(0); IBlockState placedAgainst = snap.getWorld().getBlockState(snap.getPos().offset(direction.getOpposite())); MultiPlaceEvent event = new MultiPlaceEvent(blockSnapshots, placedAgainst, player); MinecraftForge.EVENT_BUS.post(event); return event; }

Target:
Dont duplicate code, bounce to the new one with the argument null, this makes it more obvious what to remove when deleting deprecated functions. And illustrates the parameter CAN be null.
Source:
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { if (itemStackIn.hasCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, EnumFacing.UP)) { IGuiProvider provider = itemStackIn.getCapability(CapabilityGuiProvider.GUI_PROVIDER_CAPABILITY, hand == EnumHand.MAIN_HAND ? EnumFacing.UP : EnumFacing.DOWN); playerIn.openGui(provider); return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); } return ActionResult.newResult(EnumActionResult.PASS, itemStackIn); }

Target:
I still think using `UP` or the hand for the `EnumFacing` is fishy here. Nobody else is going to know how to open your gui. I think `null` should be used, unless it's a block and you know which side of the block is being clicked.
Source:
public void writeToNBT(NBTTagCompound nbt) { nbt.setInteger("dimension", this.dimension); nbt.setTag("ForgeCaps", serializable.serializeNBT()); }

Target:
I'm not very versed in WorldSavedData, but is this required? I thought WorldSavedData is already per-world making this redundant
Source:
private void register(VillagerCareer career) { Validate.isTrue(!careers.contains(career), "Attempted to register career that is already registered."); Validate.isTrue(career.profession == this, "Attempted to register career for the wrong profession."); career.id = careers.size(); careers.add(career); TRADES.put(career, new ArrayList<List<ITradeList>>()); }

Target:
Having second lists associated with careers we control is just dumb. That's what the trade list is in the career object.
Source:
public VillagerCareer getCareer(String name) { for (VillagerCareer car : this.careers) { if (car.getName() == name) return car; } return null; }

Target:
Always use `equals` when comparing Strings in Java
Source:
public static boolean canHarvestBlock(Block block, EntityPlayer player, IBlockAccess world, BlockPos pos) { IBlockState state = world.getBlockState(pos); state = state.getBlock().getActualState(state, world, pos); return canHarvestBlock(block, player, state); }

Target:
Shouldn't this be ``` canHarvestBlock(player, state): ``` ?
Source:
public void onPostServerTick() { this.onPreServerTick(this.getMinecraftServerInstance()); }

Target:
``` java this.onPostServerTick(this.getMinecraftServerInstance()); ```
Source:
public void setStackInSlot(int slot, ItemStack stack) { ItemStack[] stacks = this.stacks; validateSlotIndex(slot, stacks); if (ItemStack.areItemStacksEqual(stacks[slot], stack)) return; stacks[slot] = stack; onContentsChanged(slot); }

Target:
Very minor, but a bit redundant?
Source:
public ItemStack getStackInSlot(int slot) { ItemStack[] stacks = this.stacks; validateSlotIndex(slot, stacks); return stacks[slot]; }

Target:
Very minor, but a bit redundant?
Source:
private void registerVillagerSkin(int villagerId, ResourceLocation villagerSkin) { if (newVillagers == null) { newVillagers = Maps.newHashMap(); } newVillagers.put(villagerId, villagerSkin); }

Target:
This is deprecated to be removed in 1.8.8 but still exists because we dont want to fire MissingMethodExceptions.
Source:
public static <P extends IProperty, V>IUnlistedProperty toUnlisted(P property) { return new PropertyAdapter(property); }

Target:
Why is this needed? And all the other places with added/removed casts/generics?
Source:
public Class getType() { return B3DState.class; }

Target:
Raw type here, generic in the base
Source:
public static Set<String> getDimensionTypes(WorldProvider provider) { if (provider instanceof Handler) return ((Handler) provider).getDimensionTypes(); Set<String> types = dimensionTypes.get(provider.dimensionId); return types != null ? SET_UNCATEGORIZED : Collections.<String>emptySet(); }

Target:
If types != null returns SET_UNCATEGORIZED if types == null, returns Collections.<String>emptySet(); Neither case actually returns types. :P
Source:
public FillBucketEvent(EntityPlayer player, ItemStack current, World world, MovingObjectPosition target) { super(player, current, world, target); }

Target:
Moving these fields breaks all current mods that use this event.
Source:
public static boolean checkPerm(EntityPlayer player, String node, Map<String, IContext> contextInfo) { if (player instanceof FakePlayer) throw new IllegalArgumentException("You cannot check permissions with a fake player. Use PermManager.getPerm(username, node)"); return FACTORY.checkPerm(player, node, contextInfo); }

Target:
Obnoxious and buggy. Let FACTORY determine what permissions fake players should have.
Source:
public int size() { return properties.size(); }

Target:
Seriously dude, don't reformat code for no reason.
Source:
private boolean isCountFunction(FunctionCallTree tree) { return FUNCTION_PREDICATE.test(TreeValues.of(tree, context().symbolTable())) && tree.arguments().size() == 1; }

Target:
What about cases where [`count`](https://www.php.net/manual/en/function.count.php) has 2 arguments? I guess that we don't want to exclude such cases.
Source:
public void visitVariableIdentifier(VariableIdentifierTree varIdentifier) { if (inStaticContext && !isWithinNonStaticFunctionExpression(varIdentifier) && "$this".equals(varIdentifier.variableExpression().text())) { context().newIssue(this, varIdentifier.variableExpression(), MESSAGE); } super.visitVariableIdentifier(varIdentifier); }

Target:
Nitpicking: I suppose that this new condition is slightly more costly than the next one. I would have put the new condition last.
Source:
private boolean hasEnoughNumberOfSpecialChars(String value) { int numberOfSpecialChars = 0; for (char c : value.toCharArray()) { if (SPECIAL_CHARS.contains(c)) { numberOfSpecialChars++; } } return numberOfSpecialChars >= 2; }

Target:
we should return from the loop once this var is greater than 2. One way to do also get rid of the set could be to use a switch here : ``` for () { switch(c) { case '+': case '*': case '{': nb++; break; } if(nb == 2) return true; } return false; ```
Source:
private int getPatternArgumentIndex(FunctionCallTree tree) { int index = 0; if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { index = 1; } return index; }

Target:
personal preference (so up to you to take the suggestion into account) but I would go for : ``` if(cond) { return 1; } return 0;
Source:
public static EchoTagStatementTree newEchoTagStatement(SeparatedList<ExpressionTree> expressions, InternalSyntaxToken eosToken) { return new EchoTagStatementTreeImpl(expressions, eosToken); }

Target:
Can we make this method private?
Source:
public void test() { assertThat(PHPLexicalGrammar.FUNCTION_CALL_PARAMETER_LIST) .matches("()") .matches("($p)") .matches("(& $p)") .matches("(...$p)") .matches("(yield $a)") .matches("($p1, & $p2, ...$p3, yield $p4)") .notMatches("('title', 'body','comments',)") .notMatches("(,)") .notMatches("('function','bar',,)") .notMatches("(,'function','bar')"); }

Target:
According to this [rfc](https://wiki.php.net/rfc/trailing-comma-function-calls) this code should "matches" and not the opposite!!!
Source:
PhpCfgBlock(Set<PhpCfgBlock> successors, @Nullable PhpCfgBlock syntacticSuccessor) { this.successors = ImmutableSet.copyOf(successors); this.syntacticSuccessor = syntacticSuccessor; }

Target:
should it be `private`?
Source:
public static Tree findAncestorWithKind(Tree tree, Collection<Tree.Kind> kinds) { Tree parent = tree; while (parent != null && !kinds.contains(parent.getKind())) { parent = parent.getParent(); } if (parent != null) { return parent; } return null; }

Target:
can't we just return `parent`?
Source:
public void test_isDescendant() { Tree tree = PHPParserBuilder.createParser().parse("<?= for(;;) ?>"); StatementTree statementTree = ((CompilationUnitTree) tree).script().statements().get(0); assertThat(isDescendant(statementTree, tree)).isTrue(); assertThat(isDescendant(tree, statementTree)).isFalse(); }

Target:
add `assertThat(isDescendant(tree, tree)).isTrue();` and `assertThat(isDescendant(statementTree, statementTree)).isTrue();`?
Source:
private static boolean hasMoreThanOneStatement(ForEachStatementTree forEach) { if (forEach.statements().size() > 1) { return true; } StatementTree body = forEach.statements().get(0); if (body.is(Tree.Kind.BLOCK)) { return ((BlockTree) body).statements().size() > 1; } return false; }

Target:
what if it's alternative syntax with 0 statements?
Source:
void addPredecessor(PhpCfgBlock predecessor) { this.predecessors.add(predecessor); }

Target:
be consistent on `this` usages (use always or never)
Source:
public void visitSwitchStatement(SwitchStatementTree tree) { tree.cases().stream().forEach(this::checkCaseClause); super.visitSwitchStatement(tree); }

Target:
No need to call stream() here.
Source:
private static boolean isCountCall(ExpressionTree testedValue) { return testedValue.is(Tree.Kind.FUNCTION_CALL) && "count".equals(((FunctionCallTree) testedValue).callee().toString()); }

Target:
No, I don't think there's anything better for the moment. Feel free to create it. Note that function names are case insensitive: ``` <?php echo count([42, 43]) . "\n"; echo coUNt([42, 43]) . "\n"; // ok! function greet($name) { echo "Hello $name\n"; } greet("john"); GrEet("jack"); // ok! $a = 42; echo $A; // fails ```
Source:
public TestSuites parse(File report) { try (InputStream inputStream = new FileInputStream(report)) { final Object parsedObject = xstream().fromXML(inputStream); TestSuites testSuites = (TestSuites) parsedObject; return testSuites; } catch (IOException e) { throw new IllegalStateException("Can't read PhpUnit report : " + report.getAbsolutePath(), e); } }

Target:
@inverno `return (TestSuites) xstream().fromXML(inputStream)` instead?
Source:
public List<ExpressionTree> expressions() { return ImmutableList.copyOf(Iterables.filter(elements, input -> input != null ? !input.is(Kind.HEREDOC_STRING_CHARACTERS) : false)); }

Target:
@vilchik-elena Why do we need to check for null elements?
Source:
public void visitMemberAccess(MemberAccessTree tree) { if (tree.is(Tree.Kind.CLASS_MEMBER_ACCESS) && "self".equals(tree.object().toString()) && !isException(tree) && !isPrivate(tree.member())) { context().newIssue(this, MESSAGE).tree(tree); } super.visitMemberAccess(tree); }

Target:
@ivandalbosco IMHO it's better to move the call to `isPrivate` into `isException`
Source:
public void visitClassPropertyDeclaration(ClassPropertyDeclarationTree tree) { if (tree.hasModifiers("private")) { tree.declarations().forEach(varDec -> privateProperties.add(varDec.identifier().text())); } // don't enter inside class property declarations }

Target:
@ivandalbosco this call we check that `tree` has 1 modifier, which is `private`. Can `private` be combined with smth else?
Source:
private RuleKey getParsingErrorRuleKey() { List<RuleKey> keys = checks.all().stream() .filter(check -> check instanceof ParsingErrorCheck) .map(check -> checks.ruleKeyFor((ParsingErrorCheck) check)) .collect(Collectors.toList()); return keys.isEmpty() ? null : keys.get(0); }

Target:
@ivandalbosco casting to ParsingErrorCheck is useless
Source:
public YieldExpressionTree yieldFromExpression(InternalSyntaxToken yieldToken, InternalSyntaxToken fromToken, ExpressionTree expr) { return "from".equals(fromToken.text()) ? new YieldExpressionTreeImpl(yieldToken, fromToken, expr) : null; }

Target:
@vilchik-elena This method should not return null.
Source:
private boolean isOpenParenthesis(SyntaxToken token) { return TokenUtils.isType(token, PHPPunctuator.LPARENTHESIS); }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isOpenParenthesis" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.internal.sonarsource.com/coding_rules#rule_key=squid%3AS2325)
Source:
public void visitIfStatement(IfStatementTree tree) { ExpressionTree condition = tree.condition().expression(); if (condition.is(Kind.BOOLEAN_LITERAL)) { context().newIssue(this.KEY, MESSAGE).tree(condition); } super.visitIfStatement(tree); }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Change this instance-reference to a static reference. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS2209)
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (!(obj instanceof BaseEntity)) { // This entity has a different type return false; } if (getId() == null) { // This entity has not been persisted return super.equals(obj); } BaseEntity other = (BaseEntity) obj; return getId().equals(other.getId()); }

Target:
@timler I think that we should use do a class comparison using `getClass()` here instead of doing an "instance of" check so that different subclasses can't be considered equal e.g. a Donor and a Donation with the same id.
Source:
public boolean isDuplicateDonorNumber(Donor donor) { String donorNumber = donor.getDonorNumber(); if (StringUtils.isBlank(donorNumber)) return false; Donor existingDonor = donorRepository.findDonorByDonorNumber(donorNumber,false); if (existingDonor != null && !existingDonor.getId().equals(donor.getId())) return true; return false; }

Target:
shouldn't this be: donorRepository.findDonorByDonorNumber(donorNumber,true); since we're including deleted donors
Source:
private static String getSettingValue( String tag, String defaultValue ) { final PluginSettings settings = PluginEnvironment.env().getPluginSettings(); String value = settings.getTagValue( tag ).get( 0 ); if ( value == null ) { value = defaultValue; } return value; }

Target:
I think we get an IndexOutOfBoundException here. You probably want to check something lke this: ``` List<String> values = settings.getTagValue(tag); return values.isEmpty() ? defaultValue : values.get(0); ```
Source:
public void testPostNullMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); boolean badStatus = false; try { builder.post(Control.class, null); } catch (UniformInterfaceException e) { badStatus = true; assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } if (!badStatus){ fail("expected 400 status"); } }

Target:
If you're expecting an exception you could just invoke fail() after the call to builder.post() on line 47.
Source:
private static EventDataConverter createConverter() { if (eventDataLoaded == null) { try { LoaderUtil.loadClass("org.slf4j.ext.EventData"); eventDataLoaded = true; } catch (final ClassNotFoundException cnfe) { eventDataLoaded = false; } } return eventDataLoaded ? new EventDataConverter() : null; }

Target:
Instead of modifying this method, what if we update the `converter` field to be static and call this method on class initialization? That way instead of requiring work (and allocation!) every time a logger is created, it's done once when the application loads.
Source:
public DefaultLogBuilder(Logger logger, Level level) { this.logger = logger; this.level = level; this.inUse = false; this.threadId = Thread.currentThread().getId(); this.inUse = true; }

Target:
`inUse` is set twice in this constructor
Source:
public void testJdkVersionDetection() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { assertEquals(1, Constants.getMajorVersion("1.1.2")); assertEquals(8, Constants.getMajorVersion("1.8.2")); assertEquals(9, Constants.getMajorVersion("9.1.1")); assertEquals(11, Constants.getMajorVersion("11.1.1")); }

Target:
nit: No need to declare these exception types now that we're calling `getMajorVersion` directly.
Source:
JedisPool createPool(String host, int port, SslConfiguration sslConfiguration) { if (sslConfiguration != null) { return new JedisPool( poolConfiguration, URI.create(host + ":" + String.valueOf(port)), sslConfiguration.getSslSocketFactory(), sslConfiguration.getSslContext().getSupportedSSLParameters(), null ); } else { return new JedisPool(poolConfiguration, host, port, false); } }

Target:
What is the purpose of explicitly stringifying `port `?
Source:
private boolean shouldFlushLogQueue(boolean endOfBatch) { return immediateFlush || endOfBatch || logQueue.size() >= queueCapacity; }

Target:
I think we always want to use the result of `BlockingQueue.offer` instead of `logQueue.size() >= queueCapacity`
Source:
void setUserCancel(boolean isUserCancel) { synchronized (this) { this.isUserCancel = isUserCancel; } }

Target:
这里有问题，如果设置需要加锁，那么获取就应该也有锁。然后如果是单个 boolean，完全可以考虑设计成原子变量，加锁毕竟太重了。
Source:
public boolean isFirstData(){ if (index == 0){ return true; } else { return false; } }

Target:
`return index == 0;`
Source:
public boolean shouldReportRequestLog(){ if (requestType.equals(RequestTypeUpLog)){ return false; } else { return true; } }

Target:
`return !requestType.equals(RequestTypeUpLog);`
Source:
private boolean shouldAction(long time){ if (time < actionTime){ return false; } else { return true; } }

Target:
`return time >= actionTime;`
Source:
public static DnsPrefetcher getDnsPrefetcher() { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); synchronized (dnsPrefetcher) { if (dnsPrefetcher == null) { dnsPrefetcher = new DnsPrefetcher(); } } } return dnsPrefetcher; }

Target:
@JemyCheung 为什么这里赋值了两次？一次是 synchronized 一次还不是？
Source:
public List<InetAddress> getInetAddressByHost(String host) { if (mConcurrentHashMap != null) { return mConcurrentHashMap.get(host); } return null; }

Target:
@JemyCheung 这变量不是 init 的时候初始化的吗？为什么会有 null 的可能性？
Source:
private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }

Target:
这个地方该用stringbuilder，性能更好，不需要考虑thread safe
Source:
public void stop() { System.gc(); }

Target:
why is this necessary?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof AbstractTreeNode) { AbstractTreeNode other = (AbstractTreeNode)o; return Objects.equals(parent, other.parent) && Objects.equals(getId(), other.getId()); } return false; }

Target:
I think you should re-work this code. Need to move code from if block.
Source:
public void update(ActionEvent event) { Selection<?> select = selectionAgent.getSelection(); Selection<Resource> selection = (Selection<Resource>)select; if (selection.getFirstElement().getId() != null && select.getFirstElement() instanceof Resource) { event.getPresentation().setEnabled(true); } else event.getPresentation().setEnabled(false); }

Target:
check first (select.getFirstElement() instanceof Resource)
Source:
protected INDArray createGain(long nOut, double gainInit, INDArray gainParamView, boolean initializeParameters) { if (initializeParameters) { INDArray ret = Nd4j.valueArrayOf(new long[] {1, nOut}, gainInit); gainParamView.assign(ret); } return gainParamView; }

Target:
Don't create this temporary ret array. Use ```gainParamView.assign(gainInit)``` instead.
Source:
public void close() throws Exception { // empty arrays have no buffer at all if (released || isEmpty()) return; if (!closeable()) throw new ND4JIllegalStateException("Can't release this INDArray"); data.close(); released = true; }

Target:
Would be great to know why it is not closeable.
Source:
private void initOptionsIfNeeded() { //setup the status object to be used for all tensorflow calls if(status == null) { status = TF_NewStatus(); } if (options == null) { options = TF_NewSessionOptions(); if(protoBufConfigProto != null) { BytePointer bytePointer = new BytePointer(protoBufConfigProto.toByteArray()); TF_SetConfig(options,bytePointer,bytePointer.getStringBytes().length,status); if (TF_GetCode(status) != TF_OK) { throw new RuntimeException("ERROR: Unable to set value configuration:" + TF_Message(status).getString()); } } } }

Target:
Same thing..IllegalStateException.
Source:
protected void init(long[] shape) { if (shape.length == 1) { rows = 1; columns = (int) shape[0]; } else if (this.shape().length == 2) { rows = (int) shape[0]; columns = (int) shape[1]; } rank = shape.length; }

Target:
Let's also change those to `long` instead of casting.
Source:
public Builder() { super(new int[]{1, 1, 1}, new int[]{1, 1, 1}, new int[]{0, 0, 0}, new int[]{0, 0, 0}); }

Target:
Different defaults here to the field defaults...
Source:
public BaseLayer(NeuralNetConfiguration conf, INDArray input) { this.input = input; this.conf = conf; }

Target:
this(conf) seems to have different behaviour: it does ```cacheMode = conf.getCacheMode();``` whereas this constructor (now) doesn't.
Source:
public Tokenizer create(String toTokenize) { if (toTokenize.isEmpty()) { throw new IllegalArgumentException("Unable to proceed; no sentence to tokenize"); } JapaneseTokenizer t = new JapaneseTokenizer(kuromoji, toTokenize, useBaseForm); if (preProcessor != null) { t.setTokenPreProcessor(preProcessor); } return t; }

Target:
JapaneseTokenizer t -> Tokenizer t = new JapaneseTokenizer
Source:
public boolean hasNextFor(int consumer) { if (consumer >= numProducers) throw new ND4JIllegalStateException("Non-existent consumer was requested"); return asyncIterators.get(consumer).hasNext(); }

Target:
Again, being pedantic, but if we're checking, it might as well be ```consumer < 0 || consumer >= numProducers)```
Source:
public boolean hasNext() { if (throwable != null) throw throwable; try { if (nextElement != null && nextElement != terminator) { return true; } else if(nextElement == terminator) return false; nextElement = buffer.take(); if (nextElement == terminator) return false; return true; } catch (Exception e) { log.error("Premature end of loop!"); return false; } }

Target:
Exception should be logged also for debugging purposes?
Source:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { // Shutdown() should be a synchronous operation since the iterator is reset after shutdown() is // called in AsyncLabelAwareIterator.reset(). if (thread != null) thread.join(); } catch (InterruptedException e) { } buffer.clear(); }

Target:
This usually shouldn't happen, but should we be silently swallowing the exception here if it does?
Source:
public Builder() { this.kernelSize = new int[] { 5, 1 }; this.stride = new int[] { 1, 1 }; this.padding = new int[] { 0, 0 }; }

Target:
Where does the 5 come from? I feel like we should just throw an exception here.
Source:
public static void main(String[] args) { GatewayServer gatewayServer = new GatewayServer(new DeepLearning4jEntryPoint()); gatewayServer.start(); logger.info("DeepLearning4j Gateway server running"); }

Target:
Use @Slf4j in lombok.
Source:
public void setPreProcessor(DataSetPreProcessor preProcessor) { throw new UnsupportedOperationException(); }

Target:
This doesn't strike me as reasonable. Just add a field for it and call set :D
Source:
public INDArray params(boolean backwardOnly) { if(backwardOnly) return params(); // if(params != null) // return params; List<INDArray> params = new ArrayList<>(); for (Layer layer: getLayers()){ INDArray layerParams; if(layer instanceof BasePretrainNetwork) layerParams = ((BasePretrainNetwork) layer).paramsBackprop(); else layerParams = layer.params(); if(layerParams != null) params.add(layerParams); //may be null: subsampling etc layers } return Nd4j.toFlattened('f', params); }

Target:
Same reason as noted about training. This is only for backwardOnly
Source:
public void setPlayerState(PlayerState state) throws IllegalArgumentException { if (!this.state.isAllowedTransistionTo(state)) { throw new IllegalArgumentException( "The player is not allowed to switch from the current state (" + this.state.name() + ") to the specified state (" + state.name() + ")"); } this.state = state; }

Target:
player state setter mag niet public --> zie branch #145 (clear DB als player gewonnen is en removeCurrentPlayerFromDB als player verloren is)
Source:
public void addWall(Coordinate coordinate) { if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); // a wall may overwrite a square this.squares.remove(coordinate); }

Target:
This one should be checked after `playerStartingPositions.contains(coordinate)`
Source:
public Grid(Map<Coordinate, ASquare> grid, Map<IPlayer, Coordinate> players) { if (grid == null || players == null) throw new IllegalArgumentException("Grid could not be created!"); this.grid = grid; this.players = players; }

Target:
Package access? Want mag alleen aangeroepen worden door de Builder klasse?
Source:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return Timestamp.valueOf(LocalDateTime.parse(defaultStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } }

Target:
This caused problems in the tests for me. A better approach here (and ultimately more user friendly) would be variable length second fractions. An example of this is here: https://github.com/Bo98/ormlite-core/commit/00fed82b928ef4e2e5b6aad1d8ce54ddeccffc3b, along with adjustments to the tests to make sure they are consistently truncated (H2 supports milliseconds but the tests were comparing it to microseconds on my machine).
Source:
public void toSchemaOrgTest() throws IOException, URISyntaxException { FullBeanImpl bean = MockFullBean.mock(); String output = SchemaOrgUtils.toSchemaOrg(bean); Assert.assertNotNull(output); //Used for testing purposes, use the following call to update the expected output whenever the serialization is updated // writeToFile(output); InputStream stream = getClass().getResourceAsStream(FULL_BEAN_FILE); String expectedOutput = IOUtils.toString(stream, StandardCharsets.UTF_8); //we cannot string compare until the ordering of properties is implemented //still, a fast indication that the output was changed will be indicated through the length of the string System.out.println(output); assertEquals(expectedOutput.length(), output.length()); }

Target:
Please do not use System.out Close the stream on line 49 and 67 Use spaces instead of tabs in the toSchemaOrgEdmOrganizationTest() and writeToFile(). Indentation looks very weird for me in IntelliJ
Source:
public void testMult() { DoubleAD v1 = new DoubleAD(2.0, 4.0); DoubleAD v2 = new DoubleAD(3.0, 2.0); DoubleAD result = ADMath.mult(v1, v2); DoubleAD correctResult = new DoubleAD(6.0, 16.0); testCompareValues(correctResult, result, 0.0); }

Target:
There's nothing about this class that makes it use exact floating point calculations, so I believe 0.0 is not appropriate for the allowed delta.
Source:
public void downloadAllNovelInfo() { touchedForDownload = language + " Light Novels information"; executeDownloadTask(listItems); }

Target:
Ensure language is not null.