auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Observable<NetworkStatus.State> createObservable(Merlin merlin) { return Observable.create(new MerlinAction(merlin), Emitter.BackpressureMode.LATEST) .distinctUntilChanged(); }

Target:
Did we also have `distinctUntilChanged` before? Although it kinda makes sense, I wonder if we should filter any event at all. Users can always use this themselves right?
Source:
public void unbindWhenUnsubscribed() { Merlin merlin = mock(Merlin.class); Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin, times(1)).unbind(); }

Target:
`times(1)` is not necessary.
Source:
public boolean isConnectedToMobileNetwork() { int simState = telephonyManager.getSimState(); if (simState == TelephonyManager.SIM_STATE_READY) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return networkInfo != null && networkInfo.isConnected(); } return false; }

Target:
Does this mean the following is possible if the sim is not ready? isConnected is true, isConnectedToWifi false and isConnectedToMobileNetwork false
Source:
public String getNameTokenUnitImport() { if (nameTokenPsiClass == null) { return ""; } String importString = "import " + nameTokenPsiClass.getQualifiedName() + ";"; return importString; }

Target:
nl and return directly
Source:
public void addComponentChangeListener(ComponentChangeListener l) { checkState(); if( ! listenerList.contains(l)) { listenerList.add(l); } log.trace("Added ComponentChangeListener " + l + ", current number of listeners is " + listenerList.size()); }

Target:
Hmm, should we switch listenerList to a set?
Source:
private void setDataBindingField() { dataBindingField = holder.generatedClass.field(JMod.PRIVATE, getClasses().VIEW_DATA_BINDING, "viewDataBinding" + ModelConstants.generationSuffix()); }

Target:
not sure but iirc we use static import for `generationSuffix` in other classes
Source:
private InjectMenuActivity.MockMenuInflater createMenuInflater() { final InjectMenuActivity.MockMenuInflater menuInflater = Mockito.mock(InjectMenuActivity.MockMenuInflater.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { menuInflater.menuInflated = true; return null; } }).when(menuInflater).inflate(anyInt(), any(Menu.class)); return menuInflater; }

Target:
OK, i realised you can just you Mockito verification, since you already using mocking. ```java Mockito.verify(menuInflater).inflate(R.menu.my_menu, menu); ``` This way you can get rid of the inner class and the boolean field as well. Another thing: most of the times, we static import methods like `mock` and `verify`.
Source:
public void methodInjectionComesAfterInflation() { Menu menu = mock(Menu.class); assertThat(injectMenuActivity.menuIsInflated).isFalse(); injectMenuActivity.onCreateOptionsMenu(menu); assertThat(injectMenuActivity.menuIsInflated).isTrue(); assertThat(injectMenuActivity.methodInjectedMenu).isSameAs(menu); }

Target:
I think this `assert` is not needed, it is already checked in other tests.
Source:
public EViewHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement) throws Exception { super(environment, annotatedElement); onFinishInflateCallBlock = new ArrayList<>(); addSuppressWarning(); createConstructorAndBuilder(); }

Target:
Let's move the initialisation to the declaration.
Source:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); ShadowActivity a = (ShadowActivity) ShadowExtractor.extract(fragment.getActivity()); a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }

Target:
In other places you static import extract. I think we should be consistent?
Source:
public void testPreferenceChangeCastedParameterPassed() { Preference preference = activity.findPreference(activity.getString(R.string.checkBoxWithCastPrefKey)); Boolean newValue = new Boolean(true); preference.getOnPreferenceChangeListener().onPreferenceChange(preference, newValue); assertThat(activity.preference).isSameAs(preference); assertThat(activity.newValue).isSameAs(newValue); }

Target:
The value checking is not needed here, only the preference. We already check the value in the other test.
Source:
public void activityCompilesWithRegularDrawable() { addManifestProcessorParameter(ContextCompatDrawableTest.class, "AndroidManifestForDrawable.xml"); CompileResult result = compileFiles(ActivityWithDrawable.class); File generatedFile = toGeneratedFile(ActivityWithDrawable.class); assertCompilationSuccessful(result); assertGeneratedClassMatches(generatedFile, DRAWABLE_SIGNATURE); }

Target:
You can move this line to `setUp` from both test methods.
Source:
private void createClass() throws JClassAlreadyExistsException { builderClass = holder.getGeneratedClass()._class(PUBLIC | STATIC, "IntentBuilder" + ModelConstants.generationSuffix()); builderClass._extends(getSuperClass()); holder.setIntentBuilderClass(builderClass); contextField = ref("context"); intentField = ref("intent"); }

Target:
Here, I think we could name the inner class `IntentBuilder`. It's an inner class so there is no risk of conflict. Then, again, a `IntentBuilderImpl` would be weird.
Source:
protected void setScopedObjectsField() { JClass keyWildCard = classes().KEY.narrow(codeModel().wildcard()); JClass scopedHashMap = classes().HASH_MAP.narrow(keyWildCard, classes().OBJECT); getRoboGuiceHolder().scopedObjects = getGeneratedClass().field(JMod.PROTECTED, scopedHashMap, "scopedObjects" + ModelConstants.generationSuffix()); getRoboGuiceHolder().scopedObjects.assign(JExpr._new(scopedHashMap)); }

Target:
Same here. We should keep `scopedObjects_` since `scopeObjectsImpl` would be weird.
Source:
private String extractTag(Element element) { WakeLock annotation = element.getAnnotation(WakeLock.class); String tag = annotation.tag(); if (WakeLock.DEFAULT_TAG.equals(tag)) { tag = element.getEnclosingElement().getSimpleName().toString(); tag += "." + element.getSimpleName().toString(); } return tag; }

Target:
just concat the whole thing, do not +=
Source:
private boolean logContains(String msg) { List<LogItem> logs = ShadowLog.getLogs(); boolean found = false; for (LogItem logItem : logs) { if (logItem.msg.startsWith(msg)) found = true; } return found; }

Target:
Make this static.
Source:
private String getExternalSSOProvider(){ try { return properties.getProperty(USERGRID_EXTERNAL_PROVIDER); } catch(NullPointerException e ){ throw new IllegalArgumentException("External SSO provider is enabled but the provider name is empty"); } }

Target:
I don't think this will throw an NPE as much as it would return `null` to the caller of `getExternalSSOProvider()`
Source:
public void setupStaticKeyspace() throws Exception { migrate(); // Need this legacy stuff for queues if ( USE_VIRTUAL_KEYSPACES ) { logger.info( "Creating static application keyspace " + getApplicationKeyspace() ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), APPLICATIONS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( ApplicationCF.class, getApplicationKeyspace() ) ); cass.createColumnFamilies( getApplicationKeyspace(), getCfDefs( QueuesCF.class, getApplicationKeyspace() ) ); } }

Target:
This if isn't needed anymore, we don't always use virtual. Every row key is app prefixed, and we put all systems into the same keyspace. Eventually, we'll move to an org->keyspace lookup system.
Source:
public static String keyspaceForApplication( UUID applicationId ) { if ( USE_VIRTUAL_KEYSPACES ) { return getApplicationKeyspace(); } else { return "Application_" + applicationId.toString().replace( '-', '_' ); } }

Target:
Just change this code, we always use virtual keyspaces, so the other scheme isn't valid any longer
Source:
public String getString( final Object key ) { //All values are strings , so doing the cast here saves doing the cast elsewhere return String.valueOf(getDynamicProperties().get( key )); }

Target:
you should probably cast to a string or call toString also could be shortened to return (String) get( key );
Source:
public void addIndex(final UUID applicationId,final String indexSuffix,final int shards,final int replicas){ EntityIndex entityIndex = getManagerCache().getEntityIndex(CpNamingUtils.getApplicationScope(applicationId)); if(entityIndex instanceof AliasedEntityIndex) { ((AliasedEntityIndex)entityIndex).addIndex(indexSuffix, shards, replicas); } }

Target:
What if it's not the right instance? Shouldn't we throw an UnsupportedOperationException? Or, is there a way to just create it from the factory, so we know it's always the right instance type? Since this happens very rarely, I don't think we'll need to worry about getting it from the cache for efficiency.
Source:
public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { try { return (running.get()) ? binding.acceptScopingVisitor(new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action)) : false; } catch (Exception e) { LOGGER.warn("failed to register lifecycle actions for {}", destroyableInstance, e); return false; } }

Target:
Shouldn't we be throwing here? Under what conditions would this throw an exception that we are fine with ignoring?
Source:
private LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); }

Target:
Is this method necessary? This code is only called from one place.
Source:
public void call(Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { LOG.info("invoking lifecycle action {}", description); method.invoke(obj); }

Target:
info might be too noisy. Let's make this debug.
Source:
public List<Module> transform(List<Module> modules) { BindingTracingVisitor visitor = new BindingTracingVisitor(); for (Element binding : Elements.getElements(modules)) { LOG.debug("Binding : {}", binding); } return modules; }

Target:
This doesn't seem to be used?
Source:
protected String visitOther(Element element) { Object source = element.getSource(); ElementSource elementSource = null; while (source != null && source instanceof ElementSource) { elementSource = (ElementSource)source; source = elementSource.getOriginalElementSource(); } if (elementSource != null) { return elementSource.getModuleClassNames().toString(); } return null; }

Target:
I think you should be able to call instanceof on a null (which will fail the instanceof)
Source:
private Class<?> classFromInternalName(String name) { try { return Class.forName(name.replace('/', '.'), true, classLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } }

Target:
Shouldn't the 2nd parameter be false so we don't force static initialization?
Source:
public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { Closeables.close(out, false); } }

Target:
why we don't swallow exception here for close?
Source:
protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { this.mapper = mapper; this.logger = LoggerFactory.getLogger(getClass()); }

Target:
Can we make logger a private static final
Source:
public ArchaiusConfigurationProvider(Map<String, String> variableValues) { super(new ObjectMapper()); this.variableValues = Maps.newHashMap(variableValues); this.configurationManager = ConfigurationManager.getConfigInstance(); this.propertyFactory = DynamicPropertyFactory.getInstance(); this.ownershipPolicy = new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return configurationManager.containsKey(key.getKey(variables)); } }; }

Target:
set to 'null' and create a default in AbstractObjectConfigurationProvider
Source:
public PropertiesConfigurationProvider(Properties properties, Map<String, String> variableValues) { this(properties, variableValues, new ObjectMapper()); }

Target:
Pass 'null' for ObjectMapper and create a default in AbstractObjectConfigurationProvider
Source:
public SystemConfigurationProvider(Map<String, String> variableValues) { this(variableValues, new ObjectMapper()); }

Target:
pass 'null' for ObjectMapper and create a default in AbstractObjectConfigurationProvider
Source:
public void addKerberosAuthentication(UserEntity userEntity, String principalName, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.KERBEROS, principalName, new Validator() { @Override public void validate(UserEntity userEntity, String key) throws AmbariException { // Ensure no other authentication entries exist for the same principal... if (!CollectionUtils.isEmpty(userAuthenticationDAO.findByTypeAndKey(UserAuthenticationType.KERBEROS, key))) { throw new AmbariException("The authentication type already exists for this principal"); } } }, persist); }

Target:
let's do it using lambda approach
Source:
public Map<String, String> toMap(Optional<ObjectMapper> mapper) { Map<String, String> map = mapper.orElseGet(() -> new ObjectMapper()).convertValue(this, new TypeReference<Map<String, String>>(){}); if ( !Boolean.parseBoolean(map.get("keyStore")) ) { // keyStore is declared as a primitive value instead of Boolean -> treat false as unset map.remove("keyStore"); } return map; }

Target:
```suggestion mapper.orElseGet(ObjectMapper::new).convertValue(this, new TypeReference<Map<String, String>>(){}); ```
Source:
public static ValueAttributesInfo fromMap(Map<String, String> attributes, Optional<ObjectMapper> mapper) { return mapper.orElseGet(() -> new ObjectMapper()).convertValue(attributes, ValueAttributesInfo.class); }

Target:
```suggestion return mapper.orElseGet(ObjectMapper::new).convertValue(attributes, ValueAttributesInfo.class); ```
Source:
public java.util.Optional<String> getUrlOverride(@Nonnull String service, @Nonnull Link quickLink) { return Optional.ofNullable( urlOverrides.get(Pair.of(service, quickLink.getName())) ); }

Target:
```suggestion public Optional<String> getUrlOverride(@Nonnull String service, @Nonnull Link quickLink) { ```
Source:
public boolean include(String value, String defaultValue) { return value != null && ( defaultValue == null || !Objects.equals(StringUtils.trim(defaultValue), StringUtils.trim(value)) ); }

Target:
This trimming strategy is not always applicable, e.g. it is not for password. See https://github.com/apache/ambari/blob/4839a6f6df8bf741d3acc77ebadbe0300c4e3270/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/BlueprintConfigurationProcessor.java#L783 for more. (Unless passwords are already substituted in this phase)
Source:
private boolean isBuiltInCheckRequired(UpgradeCheck upgradeCheck, UpgradeType upgradeType) { if (upgradeType == null) { return true; } UpgradeCheckInfo annotation = upgradeCheck.getClass().getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return false; } UpgradeType[] upgradeTypes = annotation.required(); if (ArrayUtils.contains(upgradeTypes, upgradeType)) { return true; } return false; }

Target:
simplify: `return ArrayUtils.contains(...)`
Source:
public boolean haveAllRepoUrlsBeenResolved() { if(stackContext == null) { return true; } return stackContext.haveAllRepoTasksCompleted(); }

Target:
Should never be null. How is that happening? Even if there's no directory for a stack (how?) the context should be available.
Source:
public Set<String> getHosts(String serviceName, String componentName) { Set<String> hosts = m_topology.get(serviceName + "/" + componentName); if (null == hosts) { hosts = Sets.newHashSet(); } return hosts; }

Target:
Wouldn't `new HashSet<>()` or even `Collections.emptySet()` be better here since there is not need to have Google collections as a dependency?
Source:
public BlueprintProvisioningState getBlueprintProvisioningState() { BlueprintProvisioningState blueprintProvisioningState = null; ClusterEntity clusterEntity = getClusterEntity(); blueprintProvisioningState = clusterEntity.getBlueprintProvisioningState(); return blueprintProvisioningState; }

Target:
Code: I think the local variable `blueprintProvisioningState` is unnecessary, value can be returned directly. At the least the variable shouldn't be pre-declared with `null` value.
Source:
public boolean isSsoIntegrationEnabled() { try { final Predicate ssoEnabledPredicate = ssoEnabledConfiguration == null ? null : PredicateUtils.fromJSON(ssoEnabledConfiguration); return ssoIntegrationSupported && ssoEnabledPredicate != null && ssoEnabledPredicate.evaluate(configHelper.calculateExistingConfigurations(ambariManagementController, cluster)); } catch (AmbariException e) { throw new AmbariRuntimeException("Error while evaulating if SSO integration is enabled", e); } }

Target:
This does not seem to be backwards compatible with the existing implementation. If it is not, there may be issues with existing mpacks that support this feature. I suggest using a different property for the predicate declaration so that old way can be deprecated and write a message to the log if encountered.
Source:
public JSONObject getSlaveAttributeForLabel(String labelName) { for (MesosSlaveInfo slaveInfo : slaveInfos) { if(labelName != null) { if (labelName.equals(slaveInfo.getLabelString())) { return slaveInfo.getSlaveAttributes(); } } else { if (slaveInfo.getLabelString() == null) { return slaveInfo.getSlaveAttributes(); } } } return null; }

Target:
:ant: I'd use StringUtils.equals for clarity.
Source:
public Boolean getDockerPrivilegedMode() { return dockerPrivilegedMode != null ? dockerPrivilegedMode : false; }

Target:
why not just return dockerPrivilegedMode directly?
Source:
private FormValidation doCheckCpus(@QueryParameter String value) { boolean valid = true; String errorMessage = "Invalid CPUs value, it should be a positive decimal."; if (StringUtils.isBlank(value)) { valid = false; } else { try { if (Double.parseDouble(value.trim()) < 0) { valid = false; } } catch (NumberFormatException e) { valid = false; } } return valid ? FormValidation.ok() : FormValidation.error(errorMessage); }

Target:
So you trim here when you validate but you don't trim when assigning the variables above. Either you should do trim there too or just not trim here.
Source:
public void testFilterBuilderUri() { Warp .execute(clientAction) .filter(request().uri().endsWith(".jsf").build()) .verify(serverAssertion); }

Target:
The `build()` method is not necessary as I can see from `BasicWarpTest`m right?
Source:
public JacksonSerializerHelper() { numberTypes = new HashSet<>(); numberTypes.add(Long.class.getCanonicalName()); numberTypes.add(Float.class.getCanonicalName()); numberTypes.add(Double.class.getCanonicalName()); }

Target:
Could this not be a static list?
Source:
public void should_canUserSeeProcessInstance_call_engine_api() throws Exception { final boolean expected = true; checkCanUserSeeProcessInstanceWhenApiReturn(expected); }

Target:
can be inlined
Source:
public void should_canUserSeeProcessInstance_call_engine_api_false() throws Exception { final boolean expected = false; checkCanUserSeeProcessInstanceWhenApiReturn(expected); }

Target:
can be inlined
Source:
protected File getFolder(final String folderPath) { return getFolder(new File(folderPath)); }

Target:
Is there a reason to be protected ?
Source:
public void should_use_infopath_if_location_param_is_not_defined() throws Exception { when(req.getMethod()).thenReturn("GET"); when(req.getParameter("location")).thenReturn(null); when(req.getPathInfo()).thenReturn("/bonita.css"); final String resourceLocation = resourceLocationReader.getResourceLocationFromRequest(req); verify(req, times(1)).getPathInfo(); assertThat(resourceLocation).isEqualTo("bonita.css"); }

Target:
I don't think you need to stub that
Source:
private Clickable newTaskListLink() { final TreeIndexed<String> tree = new TreeIndexed<String>(); return new Link(_("New List"), _("Check the new task list"), new CheckValidSessionBeforeAction(new ActionShowView(AngularIFrameView.TASK_LISTING_TOKEN, tree))); }

Target:
I think we should remove the _() so that it doesn't show up in crowdin
Source:
public ApplicationPageDataStore create(final APISession session) { ApplicationAPI applicationAPI; PageAPI pageAPI; try { applicationAPI = TenantAPIAccessor.getLivingApplicationAPI(session); pageAPI = TenantAPIAccessor.getCustomPageAPI(session); return new ApplicationPageDataStore(session, applicationAPI, pageAPI, new ApplicationPageItemConverter()); } catch (final Exception e) { throw new APIException(e); } }

Target:
why declaring data out of try block?
Source:
public void onSuccess(final int httpStatusCode, final String response, final Map<String, String> headers) { final PageItem page = JSonItemReader.parseItem(response, PageDefinition.get()); addBody(new DeletePageFormProblemsCallout(formMappings, page.getDisplayName())); pagesLeft--; if (pagesLeft==0) { addBody(new CalloutWarning(_("If you delete a page that is used by a process, the process becomes unresolved.\nBefore deleting a page, you should also check whether it is used in a custom profile navigation."))); addBody(new Paragraph(_("Do you still want to delete the selected pages?"))); } }

Target:
may be inline : if (--pagesLeft==0)
Source:
public ContentHighlighter getHighlighter() { ContentHighlighter t = null; try { t = (ContentHighlighter) Class.forName(getBolderClass()) .getConstructor(new Class[] { GenericConfiguration.class }).newInstance(config); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return t; }

Target:
Use logger here!
Source:
private void testString(final String language, final String str) throws CRException { bean.set("content", str); t.processBean(bean); String s = (String) bean.get("lang"); Assert.assertEquals("The found Language (" + s + ") should be (" + language + "). String: '" + str + "'", language, s); }

Target:
Please use static imports for Assert methods.
Source:
public JSONArray(Collection<?> collection) { this.myArrayList = new ArrayList<Object>(collection == null ? 0 : collection.size()); if (collection != null) { for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } } }

Target:
Better to use an if/else statement here instead of 0 as initial capacity
Source:
public String getString(String key) throws JSONException { Object object = this.get(key); return object.toString(); }

Target:
Just a note for other reviewers, the get(key) will throw an exception if the key or the value is null, so no null check is needed here. I'm not sure if you want to make this more succinct though as ``` java return this.get(key).toString(); ``` I'm personally not a fan of local variables that are only used once.
Source:
public void setEnvironmentFlags(Map<String, String> flags) { try { metadata.update(metadata.new Updater() { @Override public void updateCopy(HostMetadata currentCopy) { currentCopy.set_environment_flags(flags); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (KeeperException e) { throw new RuntimeException(e); } }

Target:
can consolidate this to `catch (InterruptedException | KeeperException e)`
Source:
public void run() { if (IGNORE_PATHS.contains(partition.getPath().getName())) { return; } if (!partition.isDir()) { return; } try { copyPartitionContents(); } catch (IOException e) { this.exception = e; } }

Target:
Instead of those two break off points, I would rather see the core of the method wrapped in an if statement that combines both checks. Much easier to read.
Source:
public final @Nullable TileMultiBlock getMasterBlock() { if (masterBlock != null && !isStructureValid()) { masterBlock.isMaster = false; masterBlock = null; sendUpdateToClient(); } return masterBlock; }

Target:
Don't like this. Its not the slaves job to determine whether a master is a master.
Source:
public boolean needsFuel() { ItemStack fuel = getStackInSlot(SLOT_INPUT); return InvTools.isEmpty(fuel) || sizeOf(fuel) < 8; }

Target:
In the Blast Furnace you removed the isEmpty() check, but here you kept it.
Source:
public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); if (needsFuel()) { fuel = data.getLong("fuel"); } powered = data.getBoolean("powered"); pointPos = NBTPlugin.readBlockPos(data, "point"); prevX = data.getInteger("prevX"); prevY = data.getInteger("prevY"); prevZ = data.getInteger("prevZ"); }

Target:
Don't commit these style changes.
Source:
public float getRailMaxSpeed(World world, EntityMinecart cart, BlockPos pos) { TileEntity tile = WorldPlugin.getBlockTile(world, pos); if (tile instanceof TileTrackOutfitted) return ((TileTrackOutfitted) tile).getTrackKitInstance().getRailMaxSpeed(world, cart, pos, ((TileTrackOutfitted) tile).getTrackType()); return 0.4f; }

Target:
TrackType parameter not needed.
Source:
private ItemStack getOveralls(Entity entity) { if (entity instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) entity); ItemStack pants = player.getItemStackFromSlot(EntityEquipmentSlot.LEGS); if (pants != InvTools.emptyStack() && RailcraftItems.OVERALLS.isInstance(pants) && !((EntityPlayer) entity).capabilities.isCreativeMode) return pants; } return InvTools.emptyStack(); }

Target:
`!InvTools.isEmpty(pants)`
Source:
public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { ItemStack stack = trackKits.get(random.nextInt(trackKits.size())).getTrackKitItem(2); if (stack == null) return; recipeList.add(new MerchantRecipe(stack, null, new ItemStack(Items.EMERALD, MathHelper.getRandomIntegerInRange(random, 1, 3)))); }

Target:
This will crash if trackKits.size() == 0, which might be possible if everything is disabled.
Source:
public ItemIngot() { super(Form.INGOT, true, true, CollectionTools.createIndexedLookupTable(STEEL, COPPER, TIN, BRONZE, LEAD, SILVER)); setSmeltingExperience(1); }

Target:
Add bronze to the end instead of in the middle.
Source:
protected void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); // Command block logic overrode this and the custom name is // somewhat set to the command block's name ("@") compound.setString("CustomName", getCustomNameTag()); }

Target:
hasCustomNameTag()?
Source:
public void setFacing(@Nonnull EnumFacing facing) { TileSteamOven masterOven = (TileSteamOven) getMasterBlock(); if (masterOven != null) { masterOven.facing = facing; } this.facing = facing; WorldPlugin.setBlockState(worldObj, getPos(), getBlockState().withProperty(BlockMachineAlpha.FRONT, facing)); }

Target:
I suspect they just ask the master
Source:
private static boolean isPrimitiveType(Type type) { return (type instanceof Class) && ((Class)type).isPrimitive(); }

Target:
You may be able to avoid compiler warnings about raw types by phrasing as: return type instanceof Class<?> && ((Class<?>) type).isPrimitive(); You can use the straight-wildcard form of a generic type in `instanceof` and casts without issue.
Source:
static AssertionError counterexampleFound( String propertyName, Object[] args, long[] seeds, AssertionError e) { final String message = "Property named '%s' failed%s%n" + "With arguments: %s%n" + "Seeds for reproduction: %s"; return new AssertionError( String.format( message, propertyName, e.getMessage() == null ? ":" : " (" + e.getMessage() + "):", Arrays.deepToString(args), Arrays.toString(seeds)), e); }

Target:
Certainly! I find that `final`-izing local vars and method parameters introduces noise into the code, and provides a benefit that I don't find very helpful (assurance that the values in question won't change). When coming into another code base that opts for marking these vars `final`, I'll gladly oblige. In junit-quickcheck and other personal projects of mine, I lean toward avoiding these declarations. I would likely lean on static analysis tools like FindBugs or Checkstyle to warn me of potentially confusing constructs where a local is getting modified a lot.
Source:
@Test public void shrinkingMoreThanOnePropertyParameter() { assertThat( testResult(ShrinkingMoreThanOnePropertyParameter.class), hasSingleFailureContaining( String.format("Shrunken args: [%s, %s]", new Foo(0), new Foo(1)))); }

Target:
In the pathological case, that could cause some issues. Consider a function that is not defined for 0 (that's why the author put the constraint), and a generator that always returns 0 as a shrink. In every failure case, shrinks will be useless.
Source:
public Properties generate(SourceOfRandomness random, GenerationStatus status) { int size = status.size(); Properties properties = new Properties(); for (int i = 0; i < size; ++i) { properties.setProperty( stringGenerator.generate(random, status), stringGenerator.generate(random, status)); } return properties; }

Target:
@brentvukmer Yeah, I'd prefer keeping both scope indent and long-line indent at four spaces. Thanks!
Source:
public String toString() { return "Capabilities{" + "poolName='" + poolName + '\'' + ", qosSupport='" + qosSupport + '\'' + ", allocatedCapacityGb='" + allocatedCapacityGb + '\'' + ", driverVersion='" + driverVersion + '\'' + ", freeCapacityGb='" + freeCapacityGb + '\'' + ", locationInfo='" + locationInfo + '\'' + ", timestamp='" + timestamp + '\'' + ", volumeBackendName='" + volumeBackendName + '\'' + ", totalCapacityGb='" + totalCapacityGb + '\'' + ", reservedPercentage='" + reservedPercentage + '\'' + ", vendorName='" + vendorName + '\'' + ", storageProtocol='" + storageProtocol + '\'' + ", extraSpecs='" + extraSpecs + '\'' + '}'; }

Target:
The convention is to use ',' instead of '\'.
Source:
LazyIfNumber(List<LazyNumber> lazyParams) { this.lazyParams = lazyParams; }

Target:
Sorry, I missed this completely on my first review. Having a public class but a package-private constructor is slightly problematic from an API point of view. As it allows everyone to see the class, but not to use it. I'd suggest to make it `public` or the whole class `package-private`...but I'd need to do some more thinking about that one, so I'd go with `public`.
Source:
public HashSet<Zoie<BoboIndexReader, ?>> getZoieSystems() { return _core.getZoieSystems(); }

Target:
is there a reason why we're changing from collection to hashset?
Source:
public void testSimpleKafka() throws Exception{ final StreamDataProvider<JSONObject> dataProvider = simpleKafkaGateway.buildDataProvider((DataSourceFilter)null, String.valueOf("0"), null, null); BaseGatewayTestUtil.doTest(dataProvider); }

Target:
What's the point of `String.valueOf("0")` ? Why not just `"0"` ?
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); if (queries != null) { for (Term q : queries) { buffer.append(q); buffer.append(","); } } buffer.append("^"); buffer.append(boost); buffer.append("tieBraker:"); buffer.append(tieBraker); return buffer.toString(); }

Target:
this will be adjacent to the boost
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(super.toString()); // for field buffer.append(":"); buffer.append(value == null ? "" : value); buffer.append("^"); buffer.append(boost); return buffer.toString(); }

Target:
Use StringBuilder
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); if (queries != null) { for (Term q : queries) { buffer.append(q).append(","); } } buffer.append("^").append(boost).append("tieBraker:").append(tieBraker); return buffer.toString(); }

Target:
Use StringBuilder
Source:
public JsonArray getTsnePlotMetaData(String experimentAccession) { JsonObject result = new JsonObject(); result.add("metadata", getMetadata(experimentAccession)); return result.getAsJsonArray("metadata"); }

Target:
What is this method actually doing? Why do you need to a create an JSON object, add something to it, then retrieve it immediately afterwards? What is the purpose of this intermediate step?
Source:
void getTrackFile() throws Exception { this.mockMvc.perform(get(BASELINE_URL_TEMPLATE.format(new Object[] {"E-MTAB-5423", "g391"}))) .andExpect(status().isOk()) .andReturn(); }

Target:
Again, probably out of scope for this PR, but I don't think these `andReturn()` statements are needed.
Source:
private String getCollectionNameForAlias(NamedList<Object> response, String alias) { LinkedHashMap aliases = (LinkedHashMap) response.findRecursive("cluster", "aliases"); Object collectionName = aliases.getOrDefault(alias, null); if(collectionName != null) { return collectionName.toString(); } else { throw new RuntimeException("The alias " + alias + " does not match any collections in Solr"); } }

Target:
`Map::get` will return `null` if the key isn’t found.
Source:
public void loadTSnePlots(String experimentAccession) { DataFileHub.SingleCellExperimentFiles files = dataFileHub.getSingleCellExperimentFiles(experimentAccession); try (TSnePlotStreamer tSnePlotStreamer = new TSnePlotStreamer(files.tSnePlotTsvs)) { tSnePlotStreamer.availablePerplexities() .forEach(p -> tSnePlotDao.loadTSnePlot(experimentAccession, p, tSnePlotStreamer.stream(p))); } }

Target:
All the methods from here on could be private. Or if some other class will call them, shouldn't they also be `@Transactional`?
Source:
private void drawText(Canvas canvas, PointF pos) { if (mText != null && mText != "") { Iterator<Paint> iter = mTextStyle.iterator(); while (iter.hasNext()) { Paint p = iter.next(); p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); } } }

Target:
I think it is slightly easier and cleaner to just use for(Paint p : mTextStyle){ p.setTextSize(DEFAULT_TEXT_SIZE \* mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); }
Source:
public void addLogo(View view) { Intent i = new Intent(this, LogoActivity.class); i.putExtra("photoByteArray", byteArray); i.putExtra("companyTag", companyTag); i.putExtra("filePath", fileUri.getPath()); i.putExtra("accessToken", getIntent().getExtras().getString("accessToken")); startActivity(i); }

Target:
Once we start editing the picture, why do we need to pass around the original? The only reason we would need it is if we offer an option to reset all changes, but right now just passing the byte stream keeps track of the most up to date edited version.
Source:
public void tagPicture(View view) { MapleApplication app = (MapleApplication) getApplication(); // save company tag companyTag = companySuggest.getText().toString(); app.setCurrentCompany(companyTag); // update header ((TextView) this.findViewById(R.id.header)) .setText("Customize Your Ad"); // set company Button ((Button) findViewById(R.id.changeTag)).setText(companyTag); toggleOptions(); }

Target:
nit: This will probably need to be a private instance variable in the future. As functionality grows for MapleApplication we might just want to always get it in the <code>onCreate</code> function
Source:
public void start(Xid xid, int flags) throws XAException { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_START [" + xid + "] Flags=" + flags); }

Target:
Not worth debugging for this QS
Source:
public void end(Xid xid, int flags) throws XAException { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_END [" + xid + "] Flags=" + flags); }

Target:
Not worth debugging for this QS
Source:
public void forget(Xid xid) throws XAException { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_FORGET[" + xid + "]"); }

Target:
Not worth debugging for this QS
Source:
public void commit(Xid xid, boolean onePhase) throws XAException { if (LOG.isTraceEnabled()) { LOG.trace("DummyXAResource.commit(xid=" + xid + ", onePhase=" + onePhase + ")"); } counter.incrementAndGet(); }

Target:
Can be info
Source:
public void rollback(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { LOG.trace("DummyXAResource.rollback(xid=" + xid + ")"); } }

Target:
can be info
Source:
public Xid[] recover(int flag) throws XAException { if (LOG.isTraceEnabled()) { LOG.trace("DummyXAResource.recover(flag=" + flag + ")"); } return null; }

Target:
can be info
Source:
private IWorkbenchPage getActiveWorkbenchPage() { IWorkbenchPage result = null; IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow != null) { result = workbenchWindow.getActivePage(); } if (result != null) { } return result; }

Target:
is something missing here?
Source:
private void showFinalSelection(UIContextImpl context) { UISelection<?> selection = context.getSelection(); if (!selection.isEmpty()) { selectResourceFor(selection.get()); } }

Target:
can the selection be null?
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); deployProcess(parsedModel); }

Target:
This line can be removed. If you check the content method implementation, it's doing nothing.
Source:
public boolean hasEnforcedAppVersion(){ return this.enforcedAppVersion !=0; }

Target:
This doesn't seem right. The `enforcedAppVersion` is Integer, so by default is null, so there's an assumption that it is zero in a default setting
Source:
public ProcessExtensionModel getExtensionsForId(String processDefinitionId) { ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId); System.out.println("processDefinition = " + processDefinition); ProcessExtensionModel processExtensionModel = getExtensionsFor(processDefinition); return processExtensionModel != null ? processExtensionModel : EMPTY_EXTENSIONS; }

Target:
Please, remove `println`.
Source:
public boolean hasEmptyInputsMapping(String elementId) { ProcessVariablesMapping processVariablesMapping = mappings.get(elementId); ProcessConstantsMapping processConstantsMapping = constants.get(elementId); return (processVariablesMapping != null && processVariablesMapping.getInputs().size() == 0) && (processConstantsMapping != null && processConstantsMapping.size() == 0); }

Target:
Constants should not be included there: this method is used to know if we should send none of the process variables to the task. And we still want to do it when the mappings section is empty, but constant is not empty.
Source:
public void execute(DelegateExecution execution) { ThrowMessage throwMessage = getThrowMessage(execution); boolean isSent = send(execution, throwMessage); if(isSent) dispatchEvent(execution, throwMessage); super.execute(execution); }

Target:
Please, use brackets around `if` body, even if it's a single line. BTW, you can install check style plugin in your IDE and configure it to use [this configuration file](https://github.com/Activiti/Activiti/blob/develop/checkstyle-rules.xml).
Source:
public void setTaskVariables(Map<String, Object> taskVariables) { this.taskVariables = taskVariables; }

Target:
This method is only used in the scope of this class, so you don't need a public setter for it. You can use the private field directly.
Source:
public void onEvent(ActivitiEvent event) { if (event.getType().equals(ActivitiEventType.TIMER_FIRED)) { if (event instanceof ActivitiEntityEvent && JobEntity.class.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass())) { converter.from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerFiredEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } }

Target:
Not necessary
Source:
public Optional<BPMNSignalReceivedEvent> from(ActivitiSignalEvent internalEvent) { BPMNSignalReceivedEventImpl event = new BPMNSignalReceivedEventImpl(toSignalConverter.from(internalEvent)); if (event!=null) { event.setProcessInstanceId(internalEvent.getProcessInstanceId()); event.setProcessDefinitionId(internalEvent.getProcessDefinitionId()); } return Optional.of(event); }

Target:
I think you can remove this `if` as `event` cannot be null: you've just instantiate it. Or dit you mean to check something else?
Source:
public void testValidResources() { cleanUp(); final Resource[] resources = new Resource[]{new ClassPathResource(validName1)}; NeverFailAutoDeploymentStrategy deploymentStrategy = new NeverFailAutoDeploymentStrategy(); deploymentStrategy.deployResources(nameHint, resources, repositoryService); assertEquals(1, repositoryService.createDeploymentQuery().count()); cleanUp(); }

Target:
@daisuke-yoshimoto You can use `@Before` and `@After` annotations on `setUp()` and `tearDown()` public method to reduce boilerplate code in tests for cleanup. It should be enough to rename `cleanUp()` with `tearDown()` and annotate it with `@After`.
Source:
public void addCandidateUsers(CandidateUsersPayload candidateUsersPayload) { Task task; try { task = task(candidateUsersPayload.getTaskId()); } catch (IllegalStateException ex) { throw new IllegalStateException("The authenticated user cannot update the task" + candidateUsersPayload.getTaskId() + " due it is not the current assignee"); } if (candidateUsersPayload.getCandidateUsers() != null && !candidateUsersPayload.getCandidateUsers().isEmpty()) { for (String u : candidateUsersPayload.getCandidateUsers()) { taskService.addCandidateUser(task.getId(), u); } } }

Target:
@CTI777 same here.. the check is only on then User endpoints.. if you are admin you can execute the operation no matter what..
Source:
public void shouldConnectorMatchWithConnectorDefinition() throws IOException { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_IMAGE_CONNECTORS_PROCESS) .withVariable("input-variable-name-1", "input-variable-name-1") .withVariable("input-variable-name-2", "input-variable-name-2") .withVariable("expectedKey", true) .build()); }

Target:
May I suggest you to use a process containing a user task after the connector so that you can check the variable updates after the connector execution?
Source:
public void connectorDefinitionEmptyDir() throws IOException { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", true) .build()); }

Target:
Same here, using a process containing a user task would allow to check the variable valued after the connector execution.
Source:
public Link discoverUnique(String rel) throws Exception { List<Link> discover = discover(rel); assertThat(discover, hasSize(1)); return discover.get(0); }

Target:
Please, use AssertJ: `assertThat(discover).hasSize(1)`
Source:
public void activateProcessInstanceCmdExecutorTest() { ActivateProcessInstanceCmd activateProcessInstanceCmd = new ActivateProcessInstanceCmd("x"); assertThat(activateProcessInstanceCmdExecutor).isNotNull(); assertThat(activateProcessInstanceCmdExecutor.getHandledType()).isEqualTo(ActivateProcessInstanceCmd.class); activateProcessInstanceCmdExecutor.execute(activateProcessInstanceCmd); verify(processEngine).activate(activateProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<ActivateProcessInstanceResults>>any()); }

Target:
This assert is not necessary `activateProcessInstanceCmdExecutor` cannot be null because it's being instantiated by Mockito
Source:
public void claimTaskCmdExecutorTest() { ClaimTaskCmd claimTaskCmd = new ClaimTaskCmd("taskId", "assignee"); assertThat(claimTaskCmdExecutor).isNotNull(); assertThat(claimTaskCmdExecutor.getHandledType()).isEqualTo(ClaimTaskCmd.class); claimTaskCmdExecutor.execute(claimTaskCmd); verify(processEngine).claimTask(claimTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<ClaimTaskResults>>any()); }

Target:
Can be removed.
Source:
public ProcessModelResource getProcessModel(@PathVariable String id) { try (final InputStream resourceStream = repositoryService.getProcessModel(id)) { String xml = new String(IoUtil.readInputStream(resourceStream, null), StandardCharsets.UTF_8); return processModelResourceAssembler.toResource(new ProcessModel(id, xml)); } catch (IOException e) { throw new ActivitiException("Error occured while getting process model '" + id + "' : " + e.getMessage(), e); } }

Target:
@daisuke-yoshimoto The endpoint should return the XML string, at least that is what I would expect as a client of this service. We don't need to return a resource. @erdemedeiros what do you think about that?
Source:
public synchronized void receive(ProcessEngineEventEntity event) { System.out.println(">>>> Recieved Event" + event); System.out.println(">>>> \t Event Meta Data: " + event.getTimestamp() + " > " + event.getEventType()); System.out.println(">>>> \t Event Class: " + event.getClass().getCanonicalName()); eventsRepository.save(event); }

Target:
@erdemedeiros let's remove all the system outs
Source:
public void send(ProcessEngineEvent newEvent) { System.out.println("Sending Event: " + newEvent); producer.send(MessageBuilder.withPayload(newEvent).build()); }

Target:
@erdemedeiros let's remove all the system outs
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); deployProcess(parsedModel); }

Target:
We should also assert the parsedModel
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull("BPMN Model XML not found", bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); deployProcess(parsedModel); }

Target:
Is the deployProcess() method doing something? if not we should start getting rid of dead code.
Source:
public void doubleConversionValidation() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); validateModel(bpmnModel); bpmnModel = exportAndReadXMLFile(bpmnModel); validateModel(bpmnModel); }

Target:
This should be validated with an assertion as well
Source:
public void testJobCanceledEventOnBoundaryEvent() throws Exception { Clock testClock = new DefaultClockImpl(); assertNotNull(testClock); processEngineConfiguration.setClock(testClock); testClock.setCurrentTime(new Date()); runtimeService.startProcessInstanceByKey("testTimerCancelledEvent"); listener.clearEventsReceived(); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); checkEventCount(1, ActivitiEventType.JOB_CANCELED); }

Target:
This one doesn't make much sense.. we just created the instance.
Source:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { throw new IllegalStateException("parameterDefinitionName is null"); } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }

Target:
I would still throw an `IllegalArgumentException` here
Source:
public String getLocation() { return bundle != null ? bundle.getLocation() : ""; }

Target:
Not sure that the `""` is the correct alternative? `null`?
Source:
public String getVersion() { return bundle != null ? bundle.getVersion().toString() : ""; }

Target:
Not sure that the `""` is the correct alternative? `null`?
Source:
private boolean shouldNotCache(@NotNull String path) { Intrinsics.checkParameterIsNotNull(bundleContext, "path"); return path.endsWith(".map"); }

Target:
`path` ?
Source:
public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); return headers; }

Target:
TODO: write headers