auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void buildErrataDetailPanel() { errataDetailPanel.clear(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.setStyleName("testtest"); //$NON-NLS-1$ errataDetailPanel.add(errataDetailFormPanel); }

Target:
style name wrong? should use the style.something()?
Source:
public List<String> getMoreStable(String branch) { int i = order.indexOf(fullName(branch)); if (0 <= i) { return order.subList(i + 1, order.size()); } else { return Collections.emptyList(); } }

Target:
This subList should not be mutable to the caller.
Source:
public void notifyListeners(int eventType, Event event) { if (this.dropdownTableViewer != null && !this.dropdownTable.isDisposed()) this.dropdownTable.notifyListeners(eventType, event); }

Target:
why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.
Source:
public static void setup() throws Exception { assumeTrue("Skipping tests since Hive supports only JDK 8.", HiveTestUtilities.supportedJavaVersion()); startMiniDfsCluster(TestSqlStdBasedAuthorization.class.getSimpleName()); prepHiveConfAndData(); setSqlStdBasedAuthorizationInHiveConf(); startHiveMetaStore(); startDrillCluster(true); addHiveStoragePlugin(getHivePluginConfig()); addMiniDfsBasedStorage(new HashMap<>()); generateTestData(); }

Target:
Can't we move check to `BaseTestHiveImpersonation` and extend from some common Hive test class?
Source:
public OrderType retireOrderType(OrderType orderType, String reason) { orderType.setRetired(true); orderType.setRetireReason(reason); return dao.saveOrderType(orderType); }

Target:
these fields are already set by AOP in RetireSaveHandler and this needs to delegate to saveOrderType instead of calling the DAO just in case there is extra logic in the save method we don't want to by pass
Source:
private void updateFiltersCheckState() { Object[] children = filterContentProvider .getElements(getContentService()); ICommonFilterDescriptor filterDescriptor; INavigatorFilterService filterService = getContentService() .getFilterService(); for (Object element : children) { filterDescriptor = (ICommonFilterDescriptor) element; if(filterService.isActive(filterDescriptor.getId())) { getTableViewer().setChecked(element, true); getCheckedItems().add(element); } else { getTableViewer().setChecked(element, false); } } }

Target:
rename 'child'?
Source:
public FeatureTypeStyle transform(MBStyle styleContext, Double minScaleDenominator, Double maxScaleDenominator) { // Would prefer to accept zoom levels here (less concepts in our API) // If we accept zoom levels we may be able to reduce, and return a list of FeatureTypeStyles // (with the understanding that the list may be empty if the MBLayer does not contribute any content // at a specific zoom level range) FeatureTypeStyle style = transform(styleContext); for (Rule rule : style.rules()) { if (minScaleDenominator != null) { rule.setMinScaleDenominator(minScaleDenominator); } if (maxScaleDenominator != null) { rule.setMaxScaleDenominator(maxScaleDenominator); } } return style; }

Target:
This may return null if layer visibility = false
Source:
public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets, Collection<RevCommit> starters) throws MissingObjectException, IncorrectObjectTypeException, IOException { walk.reset(); walk.setRetainBody(false); if (topoSort) { walk.sort(RevSort.TOPO); } for (RevCommit target: targets) { walk.markStart(target); } for (RevCommit starter : starters) { walk.markUninteresting(starter); } return Optional.ofNullable(walk.next()); }

Target:
The reason why ReachabilityChecker supports reusing an existing RevWalk (instead of maintaining our own), presumably, is so that we can save on object parsing. So I think it's less flexible if we set this here - the caller should be setting it if they know that they want it.
Source:
public Optional<SessionStore<J2EContext>> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { return trackableSession == null ? Optional.empty() : Optional.of(new J2EProvidedSessionStore((HttpSession) trackableSession)); }

Target:
shouldn't trackableSession be an Optional? Either they are both or none are for me… actually, I don't think we really need to introduce Optional here, it is the caller that should be careful of not calling this with a null value!
Source:
public Response awaitResponse() throws Exception { return Objects.requireNonNull(remoteFuture).get(); }

Target:
I don't see any advantage of using `requireNonNull()`
Source:
static boolean isDefaultArgumentsConstructor(final MethodNode methodNode) { if (!methodNode.name.equals("<init>")) { return false; } final Type[] argumentTypes = Type.getMethodType(methodNode.desc) .getArgumentTypes(); if (argumentTypes.length < 2) { return false; } return "kotlin.jvm.internal.DefaultConstructorMarker" .equals(argumentTypes[argumentTypes.length - 1].getClassName()); }

Target:
"<init>".equals() is null safe and consistent to the last check in this method.
Source:
public void increment(long amount) { long now = clock.now() / 1000L; if (now != currentSecond.get()) { currentCount.set(0); } long count = currentCount.addAndGet(amount); updatePeak(count); }

Target:
Where is currentSecond being updated?
Source:
public static void assertValidSubmodulePath(String path) throws SubmoduleValidationException { if (path.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submodulePathInvalid, path), ObjectChecker.ErrorType.GITMODULES_PATH); } }

Target:
Ack
Source:
public String getMessage() { String ret = super.getMessage(); if (pql.isPresent()) { ret += " with pql \"" + pql.get() + "\""; } return ret; }

Target:
`ret` -> `message`
Source:
protected AbstractGraphDecorator(Graph g) { if (g == null) { throw new NullPointerException("g may not be null."); } this.inner = g; }

Target:
Minor suggestion to change this exception to: ``` throw new IllegalArgumentException("g may not be null."); ```
Source:
public boolean isDTS() { return getCodecA() != null && (getCodecA().startsWith("dts") || "dca".equals(getCodecA()) || "dca (dts)".equals(getCodecA())); }

Target:
`return getCodecA() != null && ("dts".contains(getCodecA()) || "dca".contains(getCodecA()));`
Source:
public CacheCollection<V> values(EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) { return new ValueCacheCollection<>(this, cacheEntrySet(explicitFlags, explicitClassLoader)); }

Target:
This one shouldn't be public.
Source:
public synchronized void setBrightnessInUserInterfaceDimensionUnit(float percent) { if (percent < 0f) { percent = 0f; } else if (percent > 200f) { percent = 200f; } brightness = percent / 100f; changeShader = true; refreshTextures(); }

Target:
Please, change as discussed.
Source:
public Handles setForceEndTransactions(boolean forceEndTransactions) { this.forceEndTransactions = forceEndTransactions; return this; }

Target:
This is a backwards incompatible change and cannot be merged.
Source:
protected Cause createUpstreamCause(Run<?, ?> build) { if(Jenkins.getInstance().getPlugin("promoted-builds") != null) { // Test only when promoted-builds is installed. if(build instanceof Promotion) { Promotion promotion = (Promotion)build; // This cannot be done for PromotionCause#PromotionCause is in a package scope. // return new PromotionCause(build, promotion.getTarget()); return new UpstreamCause((Run<?,?>)promotion.getTarget()); } } return new UpstreamCause((Run) build); }

Target:
You should remove obsolete class casts
Source:
public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) { return d2 == null; } else if (d2 == null) { return false; } return (d1 instanceof Timestamp || d2 instanceof Timestamp) ? compare((Date) d1, (Date) d2) == 0 : d1.equals(d2); }

Target:
Wouldn't it actually be better to check if instance of Date and then delegate to compare(Date, Date)?
Source:
public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final HeapObject other = (HeapObject) obj; if ( node == null ) { return other.node == null; } else return node.equals(other.node); }

Target:
You don't need the `else` clause because the `if` clause does a `return`.
Source:
public void testSignalIntermediateThrow() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-IntermediateThrowEventSignal.bpmn2"); ksession = createKnowledgeSession(kbase); Map<String, Object> params = new HashMap<String, Object>(); params.put("x", "MyValue"); ProcessInstance processInstance = ksession.startProcess( "SignalIntermediateEvent", params); Assertions.assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED); }

Target:
I think in this class it is possible.
Source:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); hllsTotalEstimatedInMemorySize = 0; hllsTotalEstimatedSerializedSize = 0; for (HyperLogLog hll : minhash.values()) { increaseTotalHllSize(hll); } }

Target:
nit: how about `minhash.values().stream().forEach(this:: increaseTotalHllSize)`?
Source:
public ChangeControl controlFor(Change change, CurrentUser user) throws NoSuchChangeException { final Project.NameKey projectKey = projectCache.get(change.getProject()).getProject().getNameKey(); try { return projectControl.controlFor(projectKey, user).controlFor(change); } catch (NoSuchProjectException e) { throw new NoSuchChangeException(change.getId(), e); } }

Target:
This is dumb. Add a Project.Id form to ProjectControl.GenericFactory and ProjectControl.Factory. That way we only have to perform 1 cache lookup, not 2.
Source:
public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (ShareFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnShareFragmentInteractionListener"); } }

Target:
Should throw ```IllegalStateException``` , or similar.
Source:
public void afterTaskInputVariableChangedEvent(TaskEvent event, Map<String, Object> variables) { if (variables == null || variables.isEmpty()) { return; } Task task = event.getTask(); List<TaskVariableImpl> taskVariables = indexVariables(task, variables, VariableType.INPUT); AuditTaskImpl auditTaskImpl = createAuditTask(task, event.getEventDate()); sendMessage(new AuditTaskData(auditTaskImpl, null, taskVariables, null), 2); }

Target:
I wonder why we don't emit an event in this case. Another thing is that I think in this case (using JMS) we will update autitTaskImpl in the database, but we currently don't update it in case we use normal JPA LifeCycleListener for tasks. Isn't this a little bit inconsistent? https://github.com/kiegroup/jbpm/blob/25fabbca948df52f69475ca54a8cf85fe09e4074/jbpm-human-task/jbpm-human-task-audit/src/main/java/org/jbpm/services/task/audit/JPATaskLifeCycleEventListener.java#L743-L753 Here we just index and persist variables.
Source:
public RubyGemParser(IFile file) throws IOException, CoreException { mSetupDefinitions = new HashMap<String, ArrayList<Object>>(); mSetupDependencies = new HashMap<String, ArrayList<Object>>(); if (file.getContents().available() <= 0) return; this.file = file; gemVariable = ""; parse(); }

Target:
Remember to put around if/else/while/for etc.
Source:
public boolean canHandle(Message<?> message) { return super.canHandle(message) && deadlineNameMatch((DeadlineMessage) message); }

Target:
I would turn this `&&` around. A simple deadlineName check is a lot cheaper than the full parameter assignment verification.
Source:
private void checkImportedSymbol(Symbol symbol) { for (IdentifierTree usageIdentifier : symbol.usages()) { Tree parent = usageIdentifier.parent(); if (parent.is(Kind.MEMBER_SELECT) && ((MemberSelectExpressionTree) parent).expression().is(Kind.MEMBER_SELECT)) { reportIssue(parent, String.format(MESSAGE, symbol.name())); hasIssue.add(parent); } } }

Target:
This approach won't work if all the classes of a project are in a single root package: ``` package org; import org.B; class A { org.B b; // should be noncompliant } ``` ``` package org; class B { ... } ``` You probably should rather rely on the type of the symbol associated to the identifier of the parent member select, if the parent is a member select. ``` if (parent.is(Kind.MEMBER_SELECT)) { ExpressionTree expression = ((MemberSelectExpressionTree) parent).expression(); if (expression.is(Kind.MEMBER_SELECT) && !((MemberSelectExpressionTree) expression).identifier().symbol().isTypeSymbol()) { return; } reportIssue(parent, String.format(MESSAGE, symbol.name())); hasIssue.add(parent); } ```
Source:
public void jmsPort_shouldBeExportedWithCorrectId() throws Exception { if (!featuresService.isInstalled(featuresService.getFeature("openengsb-ports-ws"))) { featuresService.installFeature("openengsb-ports-jms"); } OutgoingPort serviceWithId = OpenEngSBCoreServices.getServiceUtilsService().getServiceWithId(OutgoingPort.class, "jms-json", 60000); assertNotNull(serviceWithId); }

Target:
maybe, if @ Before doesn't work, create a method setUp for this? since the same code lines are in the beginning of each test of this class
Source:
private EventHandler createContextEventHandler() { if (contextEventHandler == null) { contextEventHandler = new EventHandler() { @Override public void handleEvent(Event event) { handleContextSet(event); } }; } return contextEventHandler; }

Target:
we have lambdas for this now.
Source:
public AnnotationValueReader(@Nonnull DexBuffer dex, @Nonnull ByteInput in) { super(dex, in); this.dex = dex; }

Target:
Make the "super" dex field protected and remove this one? Or a protected getDexBuffer() method?
Source:
protected Blob convertBlobToMimeType(Blob blob, String destinationMimeType) { BlobHolder bh = new SimpleBlobHolder(blob); bh = convertToMimeType(destinationMimeType, bh, new HashMap<String, Serializable>()); if (bh == null) { return null; } Blob result = bh.getBlob(); return result; }

Target:
You can pass `null` instead of `new HashMap<String, Serializable>()`.
Source:
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() { // Lets not modify the existing collection. Hence creating a new hashset. Set<SupportedAdditionalClusterFeature> featuresSupported = new HashSet<SupportedAdditionalClusterFeature>(getVdsGroup().getAddtionalFeaturesSupported()); featuresSupported.removeAll(clusterFeatureDao.getSupportedFeaturesByClusterId(getVdsGroup().getId())); return featuresSupported; }

Target:
i don't think redeclaring the type on the right side is needed.
Source:
static void runScript(String filename, Connection cx) throws SQLException { try { SqlUtil.runScript(new GeoPackage().getClass().getResourceAsStream(filename), cx); } catch (IOException e) { } }

Target:
Eeek, eatin away exceptions?
Source:
public void recycleAttributes(long ts) { fPoolAttributes.entrySet().stream().forEach(e -> { NonNullUtils.checkNotNull(e.getKey()).recycle(e.getValue(), ts); }); }

Target:
why stream? entrySet is iterable.
Source:
public boolean hasNext() { // If we do not have the next element pipelined, go ahead and fetch it. if (next == null) { // If the iterator is valid, this means that the next entry exists. checkInvariants(); if (iterator.isValid()) { // Go ahead and cache that entry. next = new AbstractMap.SimpleEntry( serializer.deserialize(Unpooled.wrappedBuffer(iterator.key()), corfuRuntime), serializer.deserialize(Unpooled.wrappedBuffer(iterator.value()), corfuRuntime)); // Advance the underlying iterator. iterator.next(); } else { // If there is no more elements to consume, we should release the resources. iterator.close(); } } return next != null; }

Target:
please invert `if` condition
Source:
public int run() throws IOException { int b; if (in != null) { while ((b = in.read()) != -1) out.write(b); in.close(); } out.close(); return -1; }

Target:
Missing braces
Source:
public List<Cohort> getCohortsContainingPatientId(Integer patientId) throws DAOException { return (List<Cohort>) sessionFactory.getCurrentSession().createCriteria(Cohort.class) .add(Restrictions.eq("voided", false)) .createAlias("members", "m") .createAlias("m.patientId", "p") .add(Restrictions.eq("p.patientId", patientId)) .list(); }

Target:
Do you have a voided field in this cohort_member table? In theory members don't get removed from the set. You might need to update Cohort.removeMember() to set stop date instead of removing. Which means that getCohortsContainingPatientId() should return cohorts that contain the patient as of the current date i.e members that have no stop date or those where the startDate is before current date and end date is after current date
Source:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { if (dataSink != null) { tupleWriter.open(dataSink.getOutputStream()); } tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); } catch (IOException e) { throw new DbException(e); } }

Target:
How can this succeed if `tupleWriter.open()` isn't called (when `dataSink` is `null`)?
Source:
public long getSizeInBytes() { long sizeInBytes = 0; int partitionCount = partitionFunction.getPartitionCount(); for (int i = 0; i < partitionCount; i++) { sizeInBytes += partitionData[i].getSizeInBytes(); } return sizeInBytes; }

Target:
use partitionData.length for consistency with getRetainedSizeInBytes ``` public long getSizeInBytes() { long sizeInBytes = 0; for (int i = 0; i < partitionData.length; i++) { sizeInBytes += partitionData[i].getSizeInBytes(); } return sizeInBytes; } ```
Source:
public FixedRealVarImpl(String name, double value, Model model) { super(name, model); this.lb = value; this.ub = value; }

Target:
Replace by `this(name, value, value, model);`
Source:
public void isGreaterThan() { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); assertTrue(V3_0.isGreaterThan(NEGATIVE_VERSION_1)); assertTrue(NEGATIVE_VERSION_1.isGreaterThan(NEGATIVE_VERSION_2)); }

Target:
I'd expect this to be the other way around, when version is a WAN version. I'm thinking about subclassing `Version`. That way we can create `ClusterVersion` and `WanVersion` that can - compare/sort the versions properly, - validate that once we set a cluster version, it can't be replaced by a WAN version (checking the sign bit) and vice-versa. WDYT?
Source:
private String extractDefinitionLine(String typeDeclaration) { String typeLine = ""; String[] lines = typeDeclaration.split("\n"); for (String line : lines) { typeLine = typeLine + "\n" + line; if (line.contains("{")) { break; } } return typeLine; }

Target:
I think that it is ok, although I am not sure how I feel about including the "\n".
Source:
public ItemAshenMask(ArmorMaterial material, int renderIndex, EntityEquipmentSlot slot, AshenMasks maskType) { super(material, renderIndex, slot); setHasSubtypes(true); this.maxStackSize = 64; this.maskType = maskType; ItemRegistry.maskMap.put(maskType, this); }

Target:
stackable armo(u)r?
Source:
private void onSuccess() { if (errorCount.getAndSet(0) >= config.storeIOErrorCountToTriggerShutdown) { logger.info("Resetting the error count of BlobStore because restart or one operation succeeded", storeId); } }

Target:
I don't understand the `if` here. If the errorCount() was higher or equal to `config.storeIOErrorCountToTriggerShutdown`, won't the store be shutting/shut down?
Source:
private ApplicationReportModel createAppDependencyGraphReport(GraphContext context) { ApplicationReportService applicationReportService = new ApplicationReportService(context); ApplicationReportModel report = applicationReportService.create(); report.setReportPriority(104); report.setReportIconClass("glyphicon glyphicon-tree-deciduous"); report.setTemplatePath(TEMPLATE); report.setTemplateType(TemplateType.FREEMARKER); report.setDisplayInApplicationReportIndex(Boolean.TRUE); report.setDescription(REPORT_DESCRIPTION); return report; }

Target:
Perhaps the '104' could be a constant?
Source:
private void startClient() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, UnknownHostException { if (client == null) { LOG.info("Connecting to the ElasticSearch cluster: " + configuration.getClusterName()); if (configuration.getHostAddressesList() != null && !configuration.getHostAddressesList().isEmpty()) { client = createClient(); } else { LOG.info("Incorrect ip address and port parameters settings for ElasticSearch cluster"); } } }

Target:
Should this not be WARN or some exception thrown? Instead of logging that the ip is incorrect. And maybe this validation should be done in the doStart method so its validated earlier
Source:
protected String getRemoveQosMessage(int size) { return ConstantsManager.getInstance().getMessages().removeStorageQoSMessage(); }

Target:
shouldn't the message get the 'size'?
Source:
public static Map<Guid, List<DiskImage>> getImagesLeaf(List<DiskImage> images) { Map<Guid, List<DiskImage>> retVal = new HashMap<>(); images.stream().forEach(image -> MultiValueMapUtils.addToMap(image.getId(), image, retVal)); retVal.values().forEach(ImagesHandler::sortImageList); return retVal; }

Target:
Just use images.forEach
Source:
protected boolean moveToState(STATE to) { if (state.get() == to) { return false; } return moveToState(state.get(), to); }

Target:
What is the contract for the return of this method? If we are already at the state that we are trying to move to, it could be said that the moveToState is successful (i.e. true).
Source:
public void writeTo(Resource file) throws JDOMException, IOException { OutputStream out = path.out(); try { IOUtils.write(body, out); } finally { out.close(); } }

Target:
@NielsCharlier try-with-resources?
Source:
public ApplicationFetchException(String apiKey, ErrorCode errorCode) { super(); this.apiKey = apiKey; this.errorCode = errorCode; }

Target:
The class is abstract. Constructor should be `protected`
Source:
private void addResource(final BackendResource resource) { resource.setMessageBundle(messageBundle); resource.setBackend(backend); resource.setSessionHelper(sessionHelper); if (resource instanceof AbstractBackendResource) { ((AbstractBackendResource) resource).setMappingLocator(mappingLocator); } else if (resource instanceof CapabilitiesResource) { ((BackendCapabilitiesResource) resource).setMappingLocator(mappingLocator); } resource.setValidatorLocator(validatorLocator); singletons.add(resource); }

Target:
using this approach only root collections will have validatorLocator, all sub-collections/resources will get NPE, when you'll try to use it, you need to inject it in runtime to every resource.
Source:
public boolean isEmpty() { synchronized (listeners) { return listeners.size() == 0; } }

Target:
listeners is atomic
Source:
void setEnd(int end) { this.end = end; if (this.end > this.maxSeen) { this.maxSeen = this.end; } }

Target:
Here we need to take sequence number wrap around into account. Alternatively, what we could do is unconditionally set the `maxSeen`, and prevent the `maxSeen` from being set if the `end` has been set. However, I don't like adding this kind of logic in the setters. Maybe it'd be better to have a getMaxOrEnd() method.
Source:
public void dispose() { //Remove all messages from the queue this.mHandler.removeCallbacksAndMessages(null); this.mHandler = null; this.mPhone = null; }

Target:
> Use this.mHandler.removeCallbacksAndMessages(null) instead. Done in Patch set 2
Source:
public boolean indexShareable() { TypedProperties properties = properties(); boolean hasRamDirectoryProvider = false; boolean hasOtherDirectoryProvider = false; for (Object objKey : properties.keySet()) { String key = (String) objKey; if (key.endsWith(DIRECTORY_PROVIDER_KEY)) { if (properties.get(key).equals(RAM_DIRECTORY_PROVIDER)) { hasRamDirectoryProvider = true; } else { hasOtherDirectoryProvider = true; } } } boolean ramOnly = hasRamDirectoryProvider && !hasOtherDirectoryProvider; return !ramOnly; }

Target:
a couple of questions: - can't you return true here? - is it possible to configure multiple directory providers?
Source:
public boolean delete( final ConcreteResource resource, final EventMetadata eventMetadata ) throws TransferException { final Transfer item = getCacheReference( resource ); if ( !resource.allowsDeletion() ) { throw new TransferException( "Deletion not allowed for: {}", resource ); } return doDelete( item, eventMetadata ); }

Target:
move this to the first line of this method for optimization.
Source:
public String getActualCpuTopology() { if (actualCpuTopology < 0) { return ConstantsManager.getInstance().getConstants().notAvailableLabel(); } else { return String.valueOf(actualCpuTopology); } }

Target:
when will it be < 0? isnt it better to use Integer that can be null? (like other fields in vm dynamic)
Source:
public void onPageScrolled(int i, float v, int i2) { if (pager.getCurrentItem() != 0) { speakerbox.stop(); } if (pager.getCurrentItem() == pagerPositionWhenPaused) { resume.setVisibility(View.GONE); getView().findViewById(R.id.routes).setBackgroundColor(act.getBaseContext() .getResources().getColor(R.color.transparent_white)); } }

Target:
Oh I see now it does get slightly darker when you manually page. It was so subtle I didn't see it at first.
Source:
public void benchWavTrack() throws Exception { WavTrack wavTrack = new WavTrack(url); boolean isEOMReached = false; while (!isEOMReached) { Frame process = wavTrack.process(0); isEOMReached = process.isEOM(); } wavTrack.close(); }

Target:
If an exception can be thrown, then wrap wavTrack.close() in a try-finally block, to guarantee resources are properly closed.
Source:
private static void setupLogger(Map<String, Object> args) throws IOException{ String logfile = (String)args.get("log-file"); Logger logger = Logger.getLogger(""); logger.setLevel((Level)args.get("log-level")); logger.addHandler(new ConsoleHandler()); if(logfile != null) { FileHandler fh = new FileHandler(logfile); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); } }

Target:
aren't these already set by logging.properties?
Source:
public XWikiAttachment set(XWikiAttachment attachment) { XWikiAttachment put = map.put(attachment.getFilename(), attachment); if (put == null || !put.equals(attachment)) { added(attachment); updatedMap(); } return put; }

Target:
I would use == instead of equals. XWikiAttachment don't implement equals and even if they were is might be super slow (they would have to compare sometime big files contents). Then no need for `put == null` anymore since the input cannot be null.
Source:
public boolean equals(Object obj) { if (obj instanceof MethodKey) { MethodKey toCompare = (MethodKey) obj; return toCompare.name.equals(name) && toCompare.parameterTypes.equals(parameterTypes); } return false; }

Target:
final, here and elsewhere
Source:
MongoDBTracing(Builder builder) { tracing = builder.tracing; maxAbbreviatedCommandLength = builder.maxAbbreviatedCommandLength; commandsWithCollectionName = Collections.unmodifiableSet(builder.commandsWithCollectionName); }

Target:
Copy into a new set too, the user will still be able to modify the set through the builder.
Source:
public void disconnect() { Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { document = null; partitions = null; try { inputStream.close(); } catch (IOException e) { } } }

Target:
this makes no sense. synchronizing on a new object is meaningless. I do not know why partitions must be null, if we want synchronize on this object, we should make it final and never null, instead simply clear() them on dispose
Source:
private void printInfo(String sizeMessage, String inAlluxioMessage, String inMemMessage, String path) { System.out.println(inMemMessage.equals("") ? String.format(SHORT_INFO_FORMAT, sizeMessage, inAlluxioMessage, path) : String.format(LONG_INFO_FORMAT, sizeMessage, inAlluxioMessage, inMemMessage, path)); }

Target:
can use `inMemMessage.isEmpty()`
Source:
public void tearDown() { // Destroy JMX beans created during testing. MetricsService metricsService = new MetricsService(nodeEngineMock, () -> metricsRegistry); metricsService.init(nodeEngineMock, new Properties()); metricsService.shutdown(true); JmxLeakHelper.checkJmxBeans(); // Stop executor service. if (executionService != null) { executionService.shutdown(); } }

Target:
I think alternatively we can move out the construction of the service from the test cases into a factory method that sets a shutdown function object field that we can call in the tearDown. This may prevent some other unwanted potential side-effects. With this approach we construct two services, but shutdown only one. For example, the service submits a scheduled task. I think it is fine for now, but it would be safer with the function proposed.
Source:
public AdsBaseObject verifyAdImage(String slotName, String src, String imageUrl) { WebElement element = getWebElement(slotName); boolean isMobile = src.toUpperCase().equals("MOBILE"); Assertion.assertTrue(new AdsComparison().compareImageWithScreenshot(imageUrl, element, driver, isMobile)); PageObjectLogging.log("verifyAdImage", "Ad looks good", true, driver); return this; }

Target:
swap the left and right for the equals to avoid NullPointerException also, use equalsIgnoreCase instead ``` "MOBILE".equalsIgnoreCase(src); ```
Source:
public Set<String> getUnmatchedLabels() { return Collections.unmodifiableSet(unmatchedLabels); }

Target:
Missing synchronization?
Source:
public void scanForRepoChanges() throws IOException { refs.refresh(); getAllRefs(); // This will look for changes to refs if (!isBare()) getIndex(); // This will detect changes in the index }

Target:
This shouldn't be necessary anymore. RefDirectory.refresh() should trigger an event listener if one or more refs was detected to be modified, which means we can drop the getAllRefs() call here.
Source:
public List<Server> getReachableServers() { return getServerList(true); }

Target:
In the LB impls (both this and the Base version), if we are deprecating getServerList(boolean), it would be preferable to move the code logic into getReachableServer() and getAllServers(), and defer getServerList(boolean) to call either getReachableServers or getAllServers based on the boolean.
Source:
protected Guid getStoragePoolId() { return getDbFacade().getStoragePoolDao().getAllForStorageDomain(getStorageDomainId()).get(0).getId(); }

Target:
Might throw an IndexOutOfBound if no the storage domain is not attached to any storage pool
Source:
private Integer prerequirementImgResource(String group) { if (group.equalsIgnoreCase(AssignmentPrerequirement.RANK.toString())) { return R.drawable.rank_prerequirement; } else if (group.equalsIgnoreCase(AssignmentPrerequirement.MISSION.toString())) { return R.drawable.group_prerequirement; } else { return R.drawable.empty; } }

Target:
Why returning Integer instead of plain int?
Source:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); // TODO: Better implementation, include INT_RGB types for 3BYTE_BGR and 4BYTE_ABGR for INT_ARGB return Collections.singletonList(getRawImageType(pImageIndex)).iterator(); }

Target:
The TODO above the changed line indicates the reason for using a multi value list here... But of course, we could change this until we actually return multiple values.
Source:
public void resetPositions(int positionCount) { positions = ensureCapacity(positions, positionCount); this.positionCount = 0; }

Target:
For better readability i would sort the methods in the way they are used `resetPositions` -> `addPosition` -> `appendData` -> `flush`. Please also order the private methods accordingly: Method that uses a private method - > private method
Source:
public static SelectorHandler getHandler(final String selectorStr) { if (!selectorStr.isEmpty()) for (final Entry<String, SelectorHandler> handler : selectorHandlers.subMap(selectorStr, true, selectorStr.substring(0, 1), true).entrySet()) if (selectorStr.startsWith(handler.getKey())) return handler.getValue(); return vanillaHandler; }

Target:
Why `selectorStr.substring(0, 1)`
Source:
public synchronized void close() { if (closed) { return; } closed = true; if (parentMemoryContext != null) { parentMemoryContext.updateBytes(-usedBytes); } usedBytes = 0; }

Target:
This `if` is redundant. Question for you, @nezihyigitbasi: Do you see IntelliJ "warning"s for this? If not, you should turn those on.
Source:
public Map<K, V> getEntries() { return (Map<K, V>) entries; }

Target:
Change seems unneeded. And actually the unchecked can be removed as well.
Source:
public void testDefaultConfig() throws Exception { Files.write(springTestFile.toPath(), "modification".getBytes(), StandardOpenOption.SYNC); // Adding few millis to avoid fleaky tests // The file hasher could sometimes evaluate these two changes as duplicate, as the second modification of file could be done before hashing is done Thread.sleep(50); Files.write(springTestFile.toPath(), "modification 2".getBytes(), StandardOpenOption.SYNC); MockEndpoint mock = getMockEndpoint("mock:springTest"); mock.setExpectedCount(1); // The same with testCustomHasher, that second MODIFY event is discarded mock.setResultWaitTime(1000); mock.assertIsSatisfied(); }

Target:
Why are you changing expectation, when no related production code changed? There should be really two events (`modification` and `modification 2`) Please note that this test is platform dependent. We are targetting to Linux and CI reports no issues or flakes with this test. Which OS are you running tests? Last CI build is here: https://builds.apache.org/view/C/view/Apache%20Camel/job/Camel/job/master/1533/consoleFull
Source:
private boolean startsOrEndsWithWhitespace(String value) { boolean startsOrEndsWithWhitespace = false; if (value != null && StringUtils.isNotBlank(value)) { int lastIndex = value.length() - 1; if (Character.isSpaceChar(value.charAt(0))) { startsOrEndsWithWhitespace = true; } else if (Character.isSpaceChar(value.charAt(lastIndex))) { startsOrEndsWithWhitespace = true; } } else { startsOrEndsWithWhitespace = false; } return startsOrEndsWithWhitespace; }

Target:
Isn't isNotBlank already checking for null?
Source:
private void updateData(OCShare share) { // Update DB with the response share.setPath(mPath); if (mPath.endsWith(FileUtils.PATH_SEPARATOR)) { share.setIsFolder(true); } else { share.setIsFolder(false); } share.setPermissions(READ_ONLY); getStorageManager().saveShare(share); // Update OCFile with data from share: ShareByLink and publicLink OCFile file = getStorageManager().getFileByPath(mPath); if (file!=null) { file.setShareWithSharee(true); // TODO - this should be done by the FileContentProvider, as part of getStorageManager().saveShare(share) getStorageManager().saveFile(file); } }

Target:
This Block can be shortened to `share.setIsFolder(mPath.endsWith(FileUtils.PATH_SEPARATOR))`
Source:
protected void startMasters(boolean isLeader) { try { connectToUFS(); mRegistry.start(isLeader); } catch (IOException e) { LOG.error("Failed to start master.", e); throw Throwables.propagate(e); } }

Target:
does the propagated exception not get logged? This looks like it would result in logging the same thing twice
Source:
public BugzillaRestRepositoryConnectorUi() { connector = BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault(); }

Target:
The default constructor should assign "null" to connector.
Source:
public static ListStatusPOptions getListStatusOptions() { FileSystemMasterCommonPOptions commonOptions = getCommonOptions().toBuilder().setTtl(Configuration.getMs(PropertyKey.USER_FILE_LOAD_TTL)) .setTtlAction(GrpcUtils.toProto( Configuration.getEnum(PropertyKey.USER_FILE_LOAD_TTL_ACTION, TtlAction.class))) .build(); return ListStatusPOptions.newBuilder().setCommonOptions(commonOptions) .setLoadMetadataType(GrpcUtils.toProto(Configuration .getEnum(PropertyKey.USER_FILE_METADATA_LOAD_TYPE, LoadMetadataType.class))) .build(); }

Target:
helper for setting common options?
Source:
Node(final String name, final NodeProcessor nodeProcessor, final Dag dag) { requireNonNull(nodeProcessor, "The nodeProcessor parameter can't be null."); this.nodeProcessor = nodeProcessor; requireNonNull(name, "The name of the node can't be null"); this.name = name; requireNonNull(name, "The dag of the node can't be null"); this.dag = dag; }

Target:
small typo - I think `name` is supposed to be `dag`, right?
Source:
public String getTooltip(MergeMode mode) { String tooltip; switch (mode) { case LEFT_TO_RIGHT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.right.tooltip"); //$NON-NLS-1$ break; case RIGHT_TO_LEFT: tooltip = EMFCompareDiagramEditMessages.getString("merged.to.left.tooltip"); //$NON-NLS-1$ break; case ACCEPT: tooltip = EMFCompareDiagramEditMessages.getString("accept.change.tooltip"); //$NON-NLS-1$ break; case REJECT: tooltip = EMFCompareDiagramEditMessages.getString("reject.change.tooltip"); //$NON-NLS-1$ break; default: throw new IllegalStateException(); } return tooltip; }

Target:
Here it's not the state of this class that's invalid, it's the given parameter. The relevant exception in such a case is IllegalArgumentException
Source:
public TriggeredBuildSelector(boolean fallbackToLastSuccessful, UpstreamFilterStrategy upstreamFilterStrategy, boolean allowUpstreamDependencies) { this.fallbackToLastSuccessful = fallbackToLastSuccessful ? Boolean.TRUE : null; this.upstreamFilterStrategy = upstreamFilterStrategy; this.allowUpstreamDependencies = allowUpstreamDependencies ? Boolean.TRUE : null; }

Target:
Please add an overloaded constructor to keep comparibility (like `TriggerredBuildSelector(boolean)`).
Source:
public static Result deleteUser(Long userId) { if (User.findByLoginId(session().get("loginId")).isSiteManager()){ if (!Project.isOnlyManager(userId)) { User.find.byId(userId).delete(); } else { flash(Constants.WARNING, "site.userList.deleteAlert"); } } else { flash(Constants.WARNING, "auth.unauthorized.waringMessage"); } return redirect(routes.SiteApp.userList(0, null)); }

Target:
사소한 거긴 하지만 if (not a) { ... } not not a { ... } 가 되지 않도록 if 순서를 변경해 주세요.
Source:
public Attachment(@NonNull Uri uri, @NonNull String contentType, long date, @Nullable String fileName) { if (date < 0) { throw new AssertionError("uri, content type, and date must all be specified"); } this.uri = uri; this.fileName = fileName; this.contentType = contentType; this.date = date; }

Target:
I know these are annotated nonnull, but since this is an assertion let's leave it in
Source:
private List<VoldemortService> createServices() { List<VoldemortService> services = new ArrayList<VoldemortService>(); CoordinatorProxyService coordinator = new CoordinatorProxyService(config, storeClientConfigs); services.add(coordinator); if(config.isAdminServiceEnabled()) { services.add(new CoordinatorAdminService(config, storeClientConfigs)); } return ImmutableList.copyOf(services); }

Target:
Just this will work too : services.add(new CoordinatorProxyService(config, storeClientConfigs)); You can save a line by not declaring a coordinator object.
Source:
public void afterBegin() throws EJBException, RemoteException { log.info("afterBegin called"); checker.setSynchronizedBegin(); }

Target:
log.trace
Source:
private boolean checkPagingSpec(PagingSpec pagingSpec, boolean descending) { for (Integer value : pagingSpec.getPagingIdentifiers().values()) { if (descending ^ value < 0) { return false; } } return pagingSpec.getThreshold() >= 0; }

Target:
This is a part of the java spec I'm not as familiar with. Is this doing `((descending ? 1 : 0) ^ value) < 0` or `descending ^ (value < 0)`?
Source:
private void init(Jdbi db) { db.registerArrayType(SqlArrayTypeFactory.of(UserId.class, "int", UserId::getId)); db.registerColumnMapper(new UserIdColumnMapper()); }

Target:
Can we unroll this to use the new `Configurable` method instead?
Source:
protected boolean updateBrickServerName(GlusterBrickEntity brick, boolean addCanDoActionMessage) { VdsStatic server = getVdsStaticDao().get(brick.getServerId()); if ((server == null || !server.getvds_group_id().equals(getVdsGroupId())) && addCanDoActionMessage) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_BRICK_SERVER_ID); return false; } brick.setServerName(server.gethost_name()); return true; }

Target:
shouldn't it return false even if addCanDoActionMessage=false? from the name of the parameter it sounds like only the message is not needed but still give the correct return value
Source:
public static @NonNull String getSpanName(String attributeName) { return attributeName.substring(0, attributeName.lastIndexOf('/')); }

Target:
private
Source:
private static boolean containsAll(String text, final Collection<String> items) { final String _text = text.toLowerCase(); return items.stream() .allMatch((String it) -> { return _text.contains(it); }); }

Target:
Why do you need to type parameter ?
Source:
private void recursiveDelete(Path file) throws IOException { Files.walkFileTree(file, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw e; } } }); }

Target:
This doesn't really need to be in an else clause. It might be more readable to invert the logic of this block, i.e.: if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE;
Source:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); if (pageNumber < (totalCount / pageSize)) { return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }

Target:
Does the `pageNumber` start at 1 or 0? If it starts at one, this conditional could be wrong: pageNumber=1, totalCount=7,pageSize=5 would return false, but there is still a next page.
Source:
public void testInvalidUser(AuthenticationFlowContext context, UserModel user) { if (user == null || user.getServiceAccountClientLink() != null) { dummyHash(context); context.getEvent().error(Errors.USER_NOT_FOUND); Response challengeResponse = challenge(context, getDefaultChallengeMessage(context)); context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse); } }

Target:
Is it really necessary to add this check here? Doesn't the AuthenticationProcessor prevent the login request from reaching this point?
Source:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { try { return DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); } catch (IOException e) { throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } return true; }

Target:
missing second argument to view the actual exception message/stack trace: `file: " + downloadedFilePath, e)`
Source:
public RegistrationUpdateEvent(String address, List<RegistrationInfo> registrations) { this.address = address; if (registrations == null || registrations.isEmpty()) { this.registrations = Collections.emptyList(); } else { this.registrations = Collections.unmodifiableList(registrations); } }

Target:
can we avoid using `unmodifiableList` and have the cluster manager trust the list will be not modified ?
Source:
public InvocationContext createInvocationContext(boolean isWrite, int keyCount) { if (keyCount == 1) { SingleKeyNonTxInvocationContext result = new SingleKeyNonTxInvocationContext(true, keyEq); return result; } else if (keyCount > 0) { NonTxInvocationContext ctx = new NonTxInvocationContext(keyCount, true, keyEq); return ctx; } return createInvocationContext(null); }

Target:
I would remove the variables and do `return new SingleKeyNonTxInvocationContext(true, keyEq);` the same thing can be applied to other methods
Source:
private boolean isRealWorklog(final EveritWorklog worklog) { boolean isRealWorklog = true; if (issuesRegex != null) { for (final Pattern issuePattern : issuesRegex) { final boolean issueMatches = issuePattern.matcher(worklog.getIssue()).matches(); // if match not count in summary if (issueMatches) { isRealWorklog = false; break; } } } return isRealWorklog; }

Target:
Remove all of the unnecessary final modifier from the local variables from all of the modified classes.
Source:
public void removed(IExtension[] extensions) { for (IExtension extension : extensions) { CustomLayoutAlgorithmProvider layoutAlgorithmProvider = extensionToLayoutAlgorithmProvider.get(extension); if (layoutAlgorithmProvider != null) { List<CustomLayoutAlgorithm> customLayoutAlgorithms = layoutAlgorithmProvider.getCustomLayoutAlgorithms(); for (CustomLayoutAlgorithm customLayoutAlgorithm : customLayoutAlgorithms) { layoutProviderRegistry.remove(customLayoutAlgorithm.getId()); } } extensionToLayoutAlgorithmProvider.put(extension, null); } }

Target:
remove instead?
Source:
public void increment( int typeId ) { if ( typeId >= counts.length ) { counts = Arrays.copyOf( counts, max( counts.length * 2, typeId ) ); } counts[typeId]++; if ( typeId > highestTypeId ) { highestTypeId = typeId; } }

Target:
This needs to be `typeId + 1`, since the parameter here is the _length_, while `typeId` is elsewhere used as an _index_.
Source:
private static void delete(List<ReceiveCommand> cmds, List<ReceiveCommand> createCmds) { for (ReceiveCommand c : createCmds) { ObjectId id = c.getNewId(); String n = c.getRefName(); cmds.add(new ReceiveCommand(id, ObjectId.zeroId(), n)); } }

Target:
s/n/name/ n is always an index
Source:
public RefreshLocalVisitor(IProgressMonitor monitor) { this.monitor = SubMonitor.convert(monitor, TOTAL_WORK); workspace = (Workspace) ResourcesPlugin.getWorkspace(); resourceChanged = false; String msg = Messages.resources_errorMultiRefresh; errors = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_LOCAL, msg, null); }

Target:
Use the one-argument version of convert, since the second argument passed in here is never used.
Source:
private ConfigurationImpl() { this.validationBootstrapParameters = new ValidationBootstrapParameters(); this.defaultResourceBundleLocator = new PlatformResourceBundleLocator( ResourceBundleMessageInterpolator.USER_VALIDATION_MESSAGES ); this.defaultTraversableResolver = new DefaultTraversableResolver(); this.defaultConstraintValidatorFactory = new ConstraintValidatorFactoryImpl(); if ( Version.getJavaRelease() >= 8 ) { this.defaultParameterNameProvider = new Java8DefaultParameterNameProvider(); } else { this.defaultParameterNameProvider = new DefaultParameterNameProvider(); } this.defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); }

Target:
Should we really use it by default? I agree this would be nice (and we surely will do it as of BV 1.2) but for now the spec [describes](http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-methodlevelconstraints-definingparameterconstraints-namingparameters) "arg0", "arg1" etc. as the default names. I feel we should stick to this for now.
Source:
public void testNull_Event() { XDRResponseEventType eventA = new XDRResponseEventType(); XDREventType eventB = new XDREventType(); eventA = null; eventB = null; assertNull(xdrTransformHelper.transformXDRResponseToCheckPolicy(eventA)); assertNull(xdrTransformHelper.transformXDRToCheckPolicy(eventB)); }

Target:
Do we need to declare object and then assign to null? Just remove them
Source:
public void testJNDIBindingsNoAppName() throws Exception { boolean passed = false; Context ctx = getInitialContext(HOST, PORT); Hello ejb = (Hello) ctx.lookup("ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello"); Assert.assertNotNull("Null object returned for local business interface lookup in the ejb namespace", ejb); Assert.assertTrue("Expected JNDI binding message not found", LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, "ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello")); }

Target:
Cruft, It doesn't matter, but this is an unused variable.