auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onFailure(Throwable t) { log.error("Unable to RefreshCapabilities: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); postProcessRefresh(false, releaseLock.getAndSet(false)); }

Target:
This change may cause the lock not to be released in some cases. With this change, in case of a failure VdsManager is responsible for releasing the lock. The VdsManager releases the lock only in case it catches an immediate exception. In case of a time-out or other SetupNetworks vdsm failure, the lock will never be unlocked.
Source:
public CountsComputer( long lastCommittedTransactionId, NodeStore nodes, RelationshipStore relationships, int highLabelId, int highRelationshipTypeId ) { this( lastCommittedTransactionId, nodes, relationships, highLabelId, highRelationshipTypeId, new SilentMigrationProgressMonitor().NO_OP_SECTION ); }

Target:
There is no reason to create new instance if SilentMigrationProgressMonitor here since NO_OP_SECTION is static
Source:
public ArrayLiteralTreeImpl newArrayLiteralWithElidedElements(List<InternalSyntaxToken> commaTokens) { List<Tree> commas = Lists.newArrayList(); for (InternalSyntaxToken comma : commaTokens) { commas.add(comma); } return new ArrayLiteralTreeImpl(commas); }

Target:
@vilchik-elena can't we directly use commaTokens?
Source:
public void onSuccess() { log.debug("Command succeeded, releasing macs {}.", Arrays.toString(super.macs.toArray())); releaseMacs(); }

Target:
why not to rely on AbstractCollection..toString?
Source:
SubresourceParameter(String value) { super("t", value); }

Target:
Make the constructor public
Source:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { return expirationTimeInMs < referenceTimeInMs && expirationTimeInMs != Utils.Infinite_Time; }

Target:
flip the order of the checks - more intuitive IMO. Something like saying "time is valid and is less than" rather than "time is less than and valid"
Source:
public void testEncodeSpatial() throws Exception { Document doc = encode(FilterMockData.intersects(), FES.Filter); assertEquals("fes:Filter", doc.getDocumentElement().getNodeName()); Element e = getElementByQName(doc, FES.Intersects); assertNotNull(e); print(e); assertNotNull(getElementByQName(e, FES.ValueReference)); assertNotNull(getElementByQName(e, GML.Point)); }

Target:
Please do not print to stdout/stderr. Please log instead so output can be silenced by the build infrastructure.
Source:
public View getTopContainer(final View view) { View topView = null; EObject container; if (view != null) { container = view.eContainer(); if (isStereotypeCompartment(container) || isStereotypeBrace(container) || isStereotypeLabel(container)) { container = container.eContainer(); } if (container instanceof View) { topView = (View) container; } } return topView; }

Target:
The local variable is declared in bad scope.
Source:
public StreamDeployer(ZooKeeperConnection zkConnection, StreamDefinitionRepository repository, StreamRepository streamRepository, XDParser parser) { super(zkConnection, repository, streamRepository, parser, stream); this.zkConnection = zkConnection; this.parser = parser; updateModuleDefinitions(); }

Target:
I don't think this method should be called in a constructor.
Source:
public String toString() { Object oScope = scope; Object oKey = key; if (oScope instanceof MarshalledValue) { oScope = ((MarshalledValue) oScope).get(); } if (oKey instanceof MarshalledValue) { oKey = ((MarshalledValue) oKey).get(); } return "ScopedKey{scope = " + oScope + ", key = " + oKey + "}"; }

Target:
Is this really necessary? AFAIK the scope and key should never be MarshalledValues.
Source:
static String left(String str, int len) { if (str == null || str.isEmpty() || len == 0) { return ""; } if (len > 0) { return str.substring(0, Math.min(len, str.length())); } final int finalLen = str.length() + len; return finalLen > 0 ? str.substring(0, finalLen) : ""; }

Target:
`str == null` cannot be true here as this was already checked upfront by https://github.com/crate/crate/pull/8879/files#diff-7a2324ee3f0c0f2c921e7ffeb1740058R70 (it also correctly results in `null` there). We could also move this empty string or 0 length up under that check as it would be same for both functions.
Source:
public ResponseEntity addRole(@RequestBody @Validated RoleForm roleForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (roleForm == null) { throw new RequestBodyValidationException("Empty request body", bindingResult); } if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ADD_ROLE, bindingResult); } // Convert RoleForm to Role Role role = conversionService.convert(roleForm, Role.class); return processConfig(config -> addRole(config, role), () -> SUCCESSFUL_ADD_ROLE, acceptHeader); }

Target:
It should never happen, since `org.springframework.web.bind.annotation.RequestBody#required` is `default true`
Source:
public AbstractJsonGetter(Getter parent) { super(parent); }

Target:
Minor: you can decrease the visibility modifier for some methods here and change some methods to be static.
Source:
NumaValidator(VdsNumaNodeDao vdsNumaNodeDao) { Objects.requireNonNull(vdsNumaNodeDao); this.vdsNumaNodeDao = vdsNumaNodeDao; }

Target:
how about this.vdsNumaNodeDao = Objects.requireNonNull(vdsNumaNodeDao) ?
Source:
public List<ClientModel> getClients() { return session.realms().getClients(this, 0, session.realms().getClientsCount(this).intValue()); }

Target:
getClients(this, null, null)
Source:
public List<String> getTokens() { ArrayList<String> ret = new ArrayList<>(this.tokenCount); for (int i = 0; i < this.tokenCount; i++) { ret.add(getToken(i)); } return ret; }

Target:
Coding best practices: Interface i = new Implementation();
Source:
public EndpointAffinity(final DrillbitEndpoint endpoint, final double affinity, final boolean mandatory, final int maxWidth) { Preconditions.checkArgument(maxWidth >= 1, "MaxWidth for given endpoint should be at least one."); this.endpoint = endpoint; this.affinity = affinity; this.mandatory = mandatory; this.maxWidth = maxWidth; this.numLocalWorkUnits = 0; }

Target:
Not needed. By default it will always be initialized to 0
Source:
public void run() { LOG.trace("BacklogMetricEmitter running for entities"); executor = new ScheduledThreadPoolExecutor(10); List<Future> futures = new ArrayList<>(); try { for (Entity entity : entityBacklogs.keySet()) { futures.add(executor.submit(new BacklogCalcService(entity, entityBacklogs.get(entity)))); } waitForFuturesToComplete(futures); } finally { executor.shutdown(); } }

Target:
Intentional change. Keep the originial.
Source:
public void onBackPressed() { if (projectListFragment != null) { projectListFragment.cancelLoadProjectTask(); Log.d(TAG, "Back press detected!"); } super.onBackPressed(); }

Target:
projectListFragment is always set, no null check needed Please remove log output
Source:
private void changeStatus(DestroyVmVDSCommandParameters parameters, VM curVm) { // do the state transition only if that VM is really running on SRC if (getParameters().getVdsId().equals(curVm.getRunOnVds())) { ResourceManager.getInstance().InternalSetVmStatus(curVm, parameters.getGracefully() ? VMStatus.PoweringDown : VMStatus.Down, curVm.getStatusUpdatedTime()); } }

Target:
not needed (the value is null and won't be used anyway)
Source:
public TransactionQuery(Selection selection, Publisher publisher, Optional<String> contentUri, Optional<String> transactionId, Optional<TransactionStateType> transactionStatus) { this.selection = checkNotNull(selection); this.publisher = checkNotNull(publisher); this.contentUri = checkNotNull(contentUri); this.transactionId = checkNotNull(transactionId); this.transactionStatus = checkNotNull(transactionStatus); }

Target:
Should this be private?
Source:
private static boolean appendPort(final String scheme, final int port) { return port > -1 && ((HTTP.equals(scheme) && port != 80) || (HTTPS.equals(scheme) && port != 443)); }

Target:
maybe not necessary, but protocol is case-insensitive - maybe should be equalsIgnoreCase used?
Source:
public void addPage(BenchmarkData data) { int pageCount = data.getPageCount(); Page page = data.getDataPage(); PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < pageCount; i++) { operator.addInput(page); } operator.finish(); }

Target:
We can inline these two vars
Source:
private Element timeZone() { return textElement(BlogConstants.TIMEZONE, entity.getTimeZone()); }

Target:
Use import static
Source:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, true, true); if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); }

Target:
so do not resolve groups and no recursive as you going to search it anyway.
Source:
public PatternScatterGraphView() { super(ID); this.addPartPropertyListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(TmfXmlStrings.XML_LATENCY_OUTPUT_DATA)) { Object newValue = event.getNewValue(); if (newValue instanceof String) { String data = (String) newValue; fViewInfo.setViewData(data); setPartName(fViewInfo.getLabel()); loadLatencyView(); } } } }); }

Target:
lambda?
Source:
public void setMaxSpeed(double maxSpeed) { if (this.maxSpeed == null || maxSpeed > this.maxSpeed) { this.maxSpeed = maxSpeed; } }

Target:
I believe `&&` should be here also
Source:
Object getValue(Object obj) throws Exception { throw new HazelcastException("Path agnostic value extraction is not supported"); }

Target:
Minor: can remove `throws`
Source:
public boolean apply(Resource resource) { Predicate<EObject> hasOuterRef = new EObjectHasReferencesTo(modifiedResources); boolean result = Iterators.any(EcoreUtil.<EObject> getAllProperContents(resource, false), hasOuterRef); return result; }

Target:
Except for debugging purpose, the "result" local does not seem necessary.
Source:
private URI endSessionEndpoint(OAuth2AuthenticationToken token) { String registrationId = token.getAuthorizedClientRegistrationId(); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint"); URI result = null; if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } return result; }

Target:
`clientRegistration` may be `null`. Please add a null check here.
Source:
public AddUnseenToBitmapFilter(BitmapBuilder seen, BitmapBuilder bitmap) { this.seen = seen; this.bitmap = bitmapResult; }

Target:
bitmap.
Source:
public void testQuantileAtValueBigint() { QuantileDigest qdigest = new QuantileDigest(1); addAll(qdigest, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 20)", toHexString(qdigest)), DOUBLE, 1.0); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), 6)", toHexString(qdigest)), DOUBLE, 0.6); functionAssertions.assertFunction(format("quantile_at_value(CAST(X'%s' AS qdigest(bigint)), -1)", toHexString(qdigest)), DOUBLE, 0.0); }

Target:
I see some surprising results here when adding additional test cases for doubles: * `Double.NaN` as the input value returns 1.0 (Edit: Double.MIN_VALUE is fine, I forgot this was just slightly greater than 0)
Source:
public boolean isOverutilized() { return memoryManager.isOverUtilized(); }

Target:
I'm ok with either capitalization. But it needs to be consistent. The `overutilized` 2 lines above is capitalized differently.
Source:
public String explain() throws CouchbaseLiteException { if (c4query == null) check(); synchronized (getDatabase().getLock()) { return c4query.explain(); } }

Target:
c4query should also be synchronized. Move c4query checks to the check method itself. The same thing for the execute() method. See https://github.com/couchbase/couchbase-lite-ios/blob/feature/2.0/Objective-C/CBLQuery.mm#L605-L606
Source:
public boolean isObjectFactory() { return getTargetTypeParameter() != null || getParameters().isEmpty(); }

Target:
just return `false` here.
Source:
StandardRotationPolicy(DelegatingSessionFactory<?> factory, List<KeyDirectory> keyDirectories, boolean fair) { Assert.notNull(factory, "factory cannot be null"); Assert.notNull(keyDirectories, "keyDirectories cannot be null"); Assert.isTrue(keyDirectories.size() > 0, "At least one KeyDirectory is required"); this.factory = factory; this.keyDirectories.addAll(keyDirectories); this.fair = fair; this.iterator = this.keyDirectories.iterator(); }

Target:
Shound't this ctor be `public` or at least `protected`? Otherwise I don't see reason in all those `protected` methods below.
Source:
public void add(EntityType entity) { validateAddAllowed(entity); createAcl(entity); super.add(entity); }

Target:
Tricky! `validateAddAllowed` currently checks if you have the WRITE_META permission on the entity. Acl gets created after the check. This breaks OneClickImporter
Source:
private ArtifactCoordinates getArtifactCoordinates(Path p) { return ThrowingFunction.unchecked(RepositoryFiles::readCoordinates).apply((RepositoryPath) p); }

Target:
@adavid9 can you please add `throws IOException` here and use `TrowingFunction` at `GroupRepositoryProvider.search` ?
Source:
public IPinUpdater<? extends ActivityNode> instantiate(ActivityNode node){ IPinUpdater<? extends ActivityNode> updater = null; if(node instanceof CallBehaviorAction){ updater = new CallBehaviorActionPinUpdater(); }else if(node instanceof CallOperationAction){ updater = new CallOperationActionPinUpdater(); }else if(node instanceof SendSignalAction){ updater = new SendSignalActionPinUpdater(); } return updater; }

Target:
To avoid accidental class casts, you can use the following signature: public <T extends ActivityNode> IPinUpdater<T> instantiate(T node) Then unchecked casts can be regrouped into this method (Rather than in each Clients)
Source:
public boolean supportsScroll() { StorageConfiguration conf = coreFeature.getStorageConfiguration(); // DBS mem and marklogic are not yet supported return conf.isDBSMongoDB() || conf.isVCS(); }

Target:
Please don't do cleanups in the same commit as bugfixes/features/improvements
Source:
public void onResume() { super.onResume(); addCachedDevices(); if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) removeAllDevices(); if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }

Target:
Style issue: please use braces in a multiline conditional.
Source:
protected void upgradeNexusVersion() throws IOException { final String currentVersion = checkNotNull( applicationStatusSource.getSystemStatus().getVersion() ); final String previousVersion = getConfiguration().getNexusVersion(); if ( currentVersion.equals( previousVersion ) ) { setInstanceUpgraded( false ); } else { setInstanceUpgraded( true ); getConfiguration().setNexusVersion( currentVersion ); storeConfiguration(); eventMulticaster.notifyEventListeners( new NexusVersionChangedEvent( this, previousVersion, currentVersion ) ); } }

Target:
Not sure i'd go with events (yet). Model upgrade was not emitting events either, and Status flags with this change would be properly set. Let's go with baby steps, and not introduce events for these yet (unless some other good reason mentioned for it's need)
Source:
public DefDeclaration(String name, Type returnType, List<NameBinding> argNames, TypedAST body, boolean isClassDef, FileLocation location) { if (argNames == null) { argNames = new LinkedList<NameBinding>(); } this.type = getMethodType(argNames, returnType); this.name = name; this.body = (ExpressionAST) body; this.argNames = argNames; this.isClass = isClassDef; this.location = location; }

Target:
Can you make the old constructor call the new one (with a default value for the additional parameter)?
Source:
public Waiter<HeadBucketRequest> bucketNotExists() { return new WaiterBuilder<HeadBucketRequest, HeadBucketResult>() .withSdkFunction(new HeadBucketFunction(client)) .withAcceptors( new HttpFailureStatusAcceptor(404, WaiterState.SUCCESS)) .withDefaultPollingStrategy( new PollingStrategy(new MaxAttemptsRetryStrategy(20), new FixedDelayStrategy(5))) .withExecutorService(executorService).build(); }

Target:
Can we all add the generic parameters for the acceptors? (Like `HttpFailureStatusAcceptor<HeadBucketResult>`?)
Source:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addKeyDownHandler(keyDownEvent -> { final int keyCode = keyDownEvent.getNativeKeyCode(); if (keyCode == KeyCodes.KEY_TAB) { destroyResources(); gridPanel.setFocus(true); keyDownEvent.preventDefault(); } keyDownEvent.stopPropagation(); }); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }

Target:
@jomarko A couple of question: 1) from the ticket description it seems that somehow both TAB and ESC should be managed (in different way) but I do not see that here: is the ESC managed elsewhere or in different way? 2) is this kind of interaction specific ot ScenarioSImulation? Is it not the same for other grid editor? If the behavior should be the same on different component, then it should be better to create a builder/getter somewhere else (some abstract/parent class) to avoid duplicate this snippet
Source:
public void testHierarchyView() { DockerImagesTab imageTab = openDockerImagesTab(); buildImage(IMAGE_TEST_BUILD, DOCKERFILE_FOLDER, imageTab); if (mockitoIsUsed()) { setupDataForMockito(); } DockerImageHierarchyTab hierarchyTab = openDockerImageHierarchyTab(); List<TreeItem> treeItems = hierarchyTab.getTreeItems(); compareTextInFirstNode(treeItems, "alpine:3.3"); List<TreeItem> treeItems2 = treeItems.get(0).getItems(); compareTextInFirstNode(treeItems2, IMAGE_TEST_BUILD + NAME_TAG_SEPARATOR + IMAGE_TAG_LATEST); }

Target:
Why is setupDataForMockito() called here when it is designated with the @Before keyword below? I have seen this in a few other tests as well.
Source:
void doBadOffsetInputTest(String name, long offset) { try { new Offset(name, offset); fail("Should have thrown because one of the inputs is invalid"); } catch (IllegalArgumentException e) { // expected. } }

Target:
private
Source:
private void enablePhiro() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPreferences.getBoolean(Constants.PHIRO_INITIALIZED, false)) { BaseSettingsActivity.setPhiroSharedPreferenceEnabled(this, true); sharedPreferences.edit().putBoolean(Constants.PHIRO_INITIALIZED, true).apply(); } }

Target:
why is the same code still present in the SettingsActivity?
Source:
private void checkReturnedValue(ReturnStatementTree tree, String nonNullAnnotation) { SymbolicValue returnedValue = programState.peekValue(); Constraint constraint = programState.getConstraint(returnedValue); if (constraint == null) { reportIssue(tree, "This method''s return value is marked \"{0}\" but null may be returned.", nonNullAnnotation); } else if (constraint.isNull()) { reportIssue(tree, "This method''s return value is marked \"{0}\" but null is returned.", nonNullAnnotation); } }

Target:
We should not raise issues in this case, as we are not certain. As we are not (yet) doing cross-procedural analysis, doing the assumption that we may end up with a null value with necessarily raise à lot of FPs.
Source:
private void verifyEditResultCode(EditingResult result) { assertThat(result.getResult(), equalTo(SUCCESS)); }

Target:
Minor: consider replacing equalTo with is from Hamcrest here and below.
Source:
public EnginesPreferencePage() { }

Target:
should call super(); explicitly
Source:
public List<AmbryReplica> getReplicaIds() { return clusterManagerCallback.getReplicaIdsForPartition(this) .stream() .map(r -> (AmbryReplica) r) .collect(Collectors.toList()); }

Target:
Instead of copying the list and requiring a (potentially) unsafe cast. I think we could make more use of generics in `ClusterManagerCallback`.
Source:
private String blockingSSLConnect(int socketBufSize) throws IOException { String connectionId = selector.connect(new InetSocketAddress("localhost", server.port), socketBufSize, socketBufSize, PortType.SSL); while (!selector.connected().contains(connectionId)) { System.out.println("here"); selector.poll(10000L); } return connectionId; }

Target:
remove?
Source:
public EDDifferentialPrivacy(double epsilon, double delta, DataGeneralizationScheme generalization) { super(delta); this.epsilon = epsilon; this.generalization = generalization; this.beta = calculateBeta(epsilon); this.k = calculateK(getDelta(), epsilon, this.beta); }

Target:
Why does this constructor not simply call the other one?
Source:
private final String getSessionIndex(Assertion subjectAssertion) { List<AuthnStatement> authnStatements = subjectAssertion.getAuthnStatements(); if(authnStatements != null && authnStatements.size() > 0) { AuthnStatement statement = authnStatements.get(0); return statement.getSessionIndex(); } return null; }

Target:
Can `statement` be null?
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree method = (MethodTree) tree; if (!INPUT_STREAM_READ.matches(method) || method.block() == null) { return; } method.accept(new ReturnStatementVisitor()); }

Target:
I would switch those two conditions.
Source:
protected void onFinishInflate() { super.onFinishInflate(); View.inflate(getContext(), R.layout.merge_login_view, this); loginButton = Views.findById(this, R.id.sign_in_button); loginButton.setSize(SignInButton.SIZE_WIDE); }

Target:
Can't be set in xml ?
Source:
private int encode(int bucketIndex, int value) { return (bucketIndex << VALUE_BITS) | value; }

Target:
static
Source:
public void onUberfireDocksInteractionEvent(@Observes final UberfireDocksInteractionEvent uberfireDocksInteractionEvent) { if (isUberfireDocksInteractionEventToManage(uberfireDocksInteractionEvent) && !uberfireDocksInteractionEvent.getTargetDock().getIdentifier().equals(TestToolsPresenter.IDENTIFIER)) { populateRightDocks(uberfireDocksInteractionEvent.getTargetDock().getIdentifier()); } }

Target:
Are you sure that `getTargetDock().getIdentifier()` is always not `null`? I suggest to rewrite the condition as `!TestToolsPresenter.IDENTIFIER.equals(uberfireDocksInteractionEvent.getTargetDock().getIdentifier())`
Source:
public String getDocType() { if (Objects.isNull(docType)) { List<SelectItem> allDocTypes = getAllDoctypes(); for (SelectItem item : allDocTypes) { if ("Monograph".equals(item.getValue())) { setDocType((String) item.getValue()); return docType; } } setDocType((String) allDocTypes.get(0).getValue()); } return docType; }

Target:
No, such a feature has not been requested so far. The current state is that each division can be the type of root element. It was discussed that we might later add a possibility that these types can be restricted. In the context, one could also implement the selection of a standard type.
Source:
public boolean shouldUseCommitTemplate() { return Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.COMMIT_DIALOG_MESSAGE_TEMPLATE) && getCommitMessage() == null && getCommitTemplate().isPresent(); }

Target:
why is this needed ?
Source:
public void waitUntilAllBlocked() { try { _blockersDoneLatch.await(); } catch (Exception ex) { } }

Target:
missing exception. either log, rethrow runtime or rename exception ignored. Expand Exception
Source:
private static boolean hasMatrixParam(List<PathSegment> pathSegments, String param) { if (pathSegments != null) for (PathSegment segement : pathSegments) { MultivaluedMap<String, String> matrixParams = segement.getMatrixParameters(); if (matrixParams != null && !matrixParams.isEmpty()) for (String key : matrixParams.keySet()) { if (key.equals(param)) return true; } } return false; }

Target:
Why not if (matrixParams.containsKey(param) { ... } ?
Source:
public void setAttached(boolean attached) { attached = attached; }

Target:
this is self assignment - please modify to: this.attached = attached
Source:
public void visited(RevObject o) { lowestDepthVisited.put(o, Long.valueOf(walk.getTreeDepth())); }

Target:
Stupid question: why long/Long? walk.getTreeDepth() returns int, so why not use Integer (also in the Map, and intValue() above)?
Source:
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) { for (Object[] item : list) { item[index] = new Long((long) item[index]); } return list; }

Target:
Is this superfluous casting?
Source:
private void flushAll() throws AuthException { for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) { CacheResource cacheResource = new CacheResource(e.getPluginName(), e.getExportName(), e.getProvider()); if (FlushCache.WEB_SESSIONS.equals(cacheResource.getName())) { continue; } flushCache.get().apply(cacheResource, new FlushCache.Input()); } }

Target:
No new for constant object in loop. Either pass null, or construct the instance outside of the looop.
Source:
public static Map<String, IAnalysisModule> getAnalysisModules() { if (fAnalysisModules.isEmpty()) { TmfAnalysisType analysis = TmfAnalysisType.getInstance(); List<IAnalysisModule> modules = analysis.getAnalysisModules(); for (IAnalysisModule module : modules) { fAnalysisModules.add(module); } } return getExecutableModules(); }

Target:
I'm not sure I like the fact we're creating 2-3 Lists and Maps everytime the "get" is called. Wouldn't there be a way to keep the fAnalsysiModules map always up-to-date as analyzes register, so that the get can simply return the map directly (wrapped into a Collections.unmodifiableMap of course) ?
Source:
void validateValueParameter(String name, Object value) { Class<? extends IValueValidator> validators[] = wrappedParameter.validateValueWith(); if (validators != null && validators.length>0) { for(final Class<? extends IValueValidator> validator: validators) { validateValueParameter(validator, name, value); } } }

Target:
Spaces.
Source:
public <C> Stream<Match> match(Object object, Captures captures, C context) { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }

Target:
final?
Source:
public ArticlePageObject savePage() { waitForElementInViewPort(editSummary); waitForElementInViewPort(reviewChangesButton); waitForElementVisibleByElement(savePanel); publishButton.click(); PageObjectLogging.log("savePage", "The 2nd Publish Button is clicked", true); return new ArticlePageObject(driver); }

Target:
Global listener catch each click. You don't need to log it.
Source:
public void executeCommand(CommandSender sender, List<String> arguments) { // Get the list of banned players Set<OfflinePlayer> bannedPlayers = bukkitService.getBannedPlayers(); Set<String> namedBanned = new HashSet<>(bannedPlayers.size()); for (OfflinePlayer offlinePlayer : bannedPlayers) { namedBanned.add(offlinePlayer.getName()); } purgeService.purgePlayers(sender, namedBanned, bannedPlayers.toArray(new OfflinePlayer[0])); }

Target:
Please revert. I know it's an IntelliJ warning but why should we tell Java to create an array generically by reflection when we literally know the size beforehand?
Source:
public static Keyspace getKeyspace() { return keyspace; }

Target:
Why do we need to make this public? It should be package scoped, protected would work as well. All Astyanax classes in com.rackspace.blueflood.io.astyanax.\* should be able to call this method without it being public.
Source:
void setNewElementYPosition(final Element elementReference, final Element newElement) { int referencePosition = getDndListComponent().getPositionY(elementReference); getDndListComponent().setPositionY(newElement, referencePosition); }

Target:
just for consistency, can we use `final int`?
Source:
public void layoutTopRight(CTabFolder ctf) { Composite trComp = getTRComposite(ctf); if (trComp.getChildren().length > 0) { trComp.setVisible(true); ctf.setTopRight(trComp, SWT.RIGHT | SWT.WRAP); } else { ctf.setTopRight(null); trComp.setVisible(false); } trComp.pack(); ctf.layout(true, true); }

Target:
I'm not sure if we should fix it in this way. Removing the CTabFolder.layout invocation is a part of the optimization process that is needed to fix the issue exposed by the "JRockit Mission Control " application. It blocks the similar applications to be migrated to the E4 (poor GUI rendering performance) Daniel
Source:
ByteBuf buffer() throws IOException { if (buf == null) { buf = Netty4Utils.toByteBuf(context.get()); context = null; } return buf; }

Target:
Can we `assert context == null` here?
Source:
public String getName() { String name = super.getName(); if (name == null || name.isEmpty()) { return ""; } else { return name; } }

Target:
Now we have `isEmpty` method for Strings in Utils. Is it good idea to use it here as well? https://github.com/kiegroup/kie-wb-common/blob/master/kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-api/kie-wb-common-stunner-core-api/src/main/java/org/kie/workbench/common/stunner/core/util/StringUtils.java
Source:
private void verifyInvalidValueSize(IndexValue value, String logSegmentName) { try { int capacity = TestUtils.RANDOM.nextInt(value.getBytes().capacity()); ByteBuffer invalidValue = ByteBuffer.allocate(capacity); invalidValue.put(value.getBytes().array(), 0, capacity); new IndexValue(logSegmentName, invalidValue, version); fail( "Contruction of IndexValue expected to fail with invalid byte buffer capacity of " + invalidValue.capacity()); } catch (IllegalArgumentException e) { } }

Target:
minor: put _only_ the statement you expect to fail in `try`.
Source:
void dispose() { if (semanticResourcesUpdater != null) { semanticResourcesUpdater.dispose(); semanticResourcesUpdater = null; } }

Target:
session could be set to null on dispose().
Source:
public void deleteByContentType(final ContentTypeIf type) throws DotDataException{ final DotConnect dc = new DotConnect(); dc.setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE); dc.addParam(type.id()); dc.addParam(type.id()); dc.loadResults(); }

Target:
you can do this things in one line such as ``` new DotConnect().setSQL(sql.DELETE_RELATIONSHIP_BY_PARENT_OR_CHILD_INODE).addParam(type.id()).addParam(type.id()).loadResults(); ```
Source:
public int getUniqueNotificationId() { if (uniqueNotificationIdCounter == null) { uniqueNotificationIdCounter = new AtomicInteger(0); } return uniqueNotificationIdCounter.incrementAndGet(); }

Target:
Is the if block still needed?
Source:
public void run() { // Loops till QueueProcessorThread is shutdown while (!shutdown) { synchronized (this) { try { // start processing queue if active, other wait for sometime if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { logger.info( "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }

Target:
How come not logger.error()?
Source:
public HllSketchMergeBufferAggregator( final ColumnValueSelector<HllSketch> selector, final int lgK, final TgtHllType tgtHllType, final int size ) { this.selector = selector; this.lgK = lgK; this.tgtHllType = tgtHllType; this.size = size; this.emptyUnion = new byte[size]; //noinspection ResultOfObjectAllocationIgnored (Union writes to "emptySketch" as a side effect of construction) new Union(lgK, WritableMemory.wrap(emptyUnion, ByteOrder.LITTLE_ENDIAN)); }

Target:
No need to force byte order when wrapping byte[]
Source:
public void checkIPAdress() { Set<ConstraintViolation<IPAdress>> validate = validator.validate(new IPAdress(address)); assertEquals(validate.isEmpty(), expectedResult); }

Target:
The expected value should be 1st, it affects error messages by junit
Source:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { try { // Ignore first call, which comes from onCreate() if (currentFormat != null) calc(); } catch (GeopointException e) { context.showToast(e.getMessage()); spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }

Target:
No good idea. ;)
Source:
public boolean visitTableWithType(String schemaName, String tableName, TableType type) { Preconditions .checkNotNull(type, "Error. Type information for table %s.%s provided is null.", schemaName, tableName); records.add(new Records.Table(IS_CATALOG_NAME, schemaName, tableName, type.toString())); return false; }

Target:
why return `false`?
Source:
public boolean add(XWikiAttachment attachment) { return set(attachment) != null; }

Target:
Comparing with null is not enough. You might replace an existing attachment with a different instance in which case you should return true. In short if the return is different from the input then something changed.
Source:
public String toString() { return Objects.toStringHelper(this).add("liveWorkerNum", mLiveWorkerNum) .add("lostWorkerNum", mLostWorkerNum).add("capacityBytes", mCapacityBytes) .add("usedBytes", mUsedBytes).add("freeBytes", mFreeBytes) .add("capacityBytesOnTiers", mCapacityBytesOnTiers) .add("usedBytesOnTiers", mUsedBytesOnTiers).toString(); }

Target:
ditto: sort by name please
Source:
public static final void assertJenkinsNotInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .until(() -> !j.jenkins.get().getQueue().isBlockedByShutdown(task)); }

Target:
```suggestion .until(() -> !j.jenkins.getQueue().isBlockedByShutdown(task)); ```
Source:
private TreeLayer getTreeLayer() { NatTable natTable = (NatTable) getTableManager().getAdapter(NatTable.class); ILayer layer = natTable.getLayer(); if (layer instanceof PapyrusGridLayer) { PapyrusGridLayer gridLayer = (PapyrusGridLayer) layer; ILayer rowLayer = gridLayer.getRowHeaderLayer(); if (rowLayer instanceof RowHeaderHierarchicalLayerStack) { return ((RowHeaderHierarchicalLayerStack) rowLayer).getTreeLayer(); } } throw new UnknownError("TreeLayer has not been found"); //$NON-NLS-1$ }

Target:
The method signature doesn't specify the Exception which could be thrown.
Source:
public boolean equals(@Nullable Object obj) { if (!(obj instanceof DataDrivenValueSelf)) { return false; } return true; }

Target:
return directly
Source:
public void differentUrlForPostsAndVideo() { SearchInput searchInput = new SearchInput().searchInputValue(); SearchInput searchInputSubmit = new SearchInput().searchInputSubmit(); String URL = driver.getCurrentUrl(); Assert.assertEquals(URL, "http://qa.fandom.wikia.com/?s=TEST"); SearchInput postsResult = new SearchInput().searchResultsPosts(); String postUrl = driver.getCurrentUrl(); SearchInput videosResult = new SearchInput().searchResultsVideos(); String videoUrl = driver.getCurrentUrl(); Assert.assertNotEquals(postUrl, videoUrl); }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Remove this unused "searchInput" local variable. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://sonar-s1/coding_rules#rule_key=squid%3AS1481)
Source:
String convert(Blob blob) { if (blob.getLength() == 0L) { return ""; } try (InputStream stream = blob.getStream()) { Xml2TextHandler xml2text = new Xml2TextHandler(); return xml2text.parse(stream); } catch (IOException | SAXException | ParserConfigurationException e) { throw new ConversionException("Error during XML2Text conversion", e); } }

Target:
I would deprecate it and add a new one.
Source:
public static void validateHeaderConfigAction(String action) { if (!HEADER_ACTIONS.stream().anyMatch(action::equalsIgnoreCase)) { throw new ConfigException(String.format("Invalid header config action: '%s'. " + "Expected one of %s", action, HEADER_ACTIONS)); } }

Target:
This should be package-level protected: ```suggestion // Visible for testing static void validateHeaderConfigAction(String action) { ```
Source:
private String getVariableLabel(VariableMetadata variableMetadata) { if (variableMetadata.getName().startsWith(CASE_VARIABLE_PREFIX)) { return translationService.getValue(CASE_VARIABLE_LABEL_PREFIX) + " " + variableMetadata.getName().substring(CASE_VARIABLE_PREFIX.length(), variableMetadata.getName().length()); } else { return variableMetadata.getName(); } }

Target:
`variableMetadata.getName().length()` invocation is redundant.
Source:
private Long findFreeId(){ while(personRepository.findOne(lastId) != null){ // New person lastId++; } return lastId; }

Target:
[existsById(long id)](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#existsById-ID-) 💯
Source:
public void cameraDeviceCallsAreForwardedToCallback() throws InterruptedException { Assume.assumeTrue(mCameraId != null); mUseCase.addStateChangeListener( mCameraRepository.getCamera( getCameraIdForLensFacingUnchecked(mConfig.getLensFacing()))); mUseCase.doNotifyActive(); mCameraRepository.onGroupActive(mUseCaseGroup); // Wait for the CameraDevice.onOpened callback. mUseCase.mDeviceStateCallback.waitForOnOpened(1); mCameraRepository.onGroupInactive(mUseCaseGroup); // Wait for the CameraDevice.onClosed callback. mUseCase.mDeviceStateCallback.waitForOnClosed(1); }

Target:
Move to setUp(). You can make mCameraId a local variable again.
Source:
public String getDescription() { return getStatuteType().getName().getContent(I18N.getLocale()) + (studentStatute instanceof SeniorStatute ? (" (" + ((SeniorStatute) studentStatute).getRegistration().getDegree().getPresentationName() + ") ") : ""); }

Target:
Beware that invoking [`getContent(I18N.getLocale())`](https://github.com/FenixEdu/fenixedu-commons/blob/v1.1.0/src/main/java/org/fenixedu/commons/i18n/LocalizedString.java#L461-L475) is different than just invoking [`getContent()`](https://github.com/FenixEdu/fenixedu-commons/blob/v1.1.0/src/main/java/org/fenixedu/commons/i18n/LocalizedString.java#L480-L496).
Source:
public boolean teleportToSpawn() { Location target = server.getWorlds().get(0).getSpawnLocation(); EntityPortalEvent event = EventFactory.callEvent(new EntityPortalEvent(this, location.clone(), target, null)); if (event.isCancelled()) { return false; } target = event.getTo(); teleport(target); return true; }

Target:
Do this and the other method need to be public? Would `protected` suffice?
Source:
public String[] getGroupFilters() { String[] result = null; IAnnotation before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before != null) { result = ((ConfigurationAnnotation) before).getGroupFilters(); } return result; }

Target:
Can we please have this variable initialized to an empty array so that we can avoid a null check to be done ?
Source:
protected PageCacheNumberArray( PagedFile pagedFile, int entrySize, long length, long defaultValue, long base ) throws IOException { this.pagedFile = pagedFile; this.entrySize = entrySize; this.entriesPerPage = pagedFile.pageSize() / entrySize; this.length = length; this.defaultValue = defaultValue; this.base = base; try ( PageCursor cursorToSetLength = pagedFile.io( 0, PF_SHARED_WRITE_LOCK ) ) { setLength( cursorToSetLength, length ); } if ( defaultValue != 0 ) { setDefaultValue( defaultValue ); } }

Target:
some of the protected items here can be package private
Source:
public InterpretedPageProjectionOutput(DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions) { this.yieldSignal = requireNonNull(yieldSignal, "yieldSignal is null"); this.blocks = requireNonNull(page, "page is null").getBlocks(); this.selectedPositions = requireNonNull(selectedPositions, "selectedPositions is null"); this.nextIndexOrPosition = selectedPositions.getOffset(); if (selectedPositions.isList()) { this.positions = selectedPositions.getPositions(); } else { this.positions = null; } }

Target:
Don't precompute `selectedPositions.getPositions`. It is unnecessary. And it makes the code harder to follow.
Source:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); return study.isCompleted() ? this.radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid() : null; }

Target:
this ternary will not behave as stated in the 1. should annotation
Source:
private Declaration getDeclarationCorrespondingToXpath( Pattern pattern, boolean isXPath, Constraint constraint ) { Declaration declFromXpath = null; if (!isXPath && pattern.hasXPath()) { Declaration xPathDecl = pattern.getXPathDeclaration(); if (xPathDecl != null) { for ( Declaration decl : constraint.getRequiredDeclarations() ) { if (xPathDecl.equals( decl )) { declFromXpath = decl; break; } } } } return declFromXpath; }

Target:
..and change as well the variable name `declFromXpath` to `declCorrXpath` also here.
Source:
public void setQueryTimeout( int seconds ) throws AlreadyClosedSqlException, InvalidParameterSqlException, SQLException { throwIfClosed(); super.setQueryTimeout(seconds); }

Target:
the parent setQueryTimeout will throw a SQLException if the parameter is invalid, so this method now no longer throws an InvalidParameterSqlException
Source:
private List<Disk> manualAggregateSnapshots() { List<Disk> Param = new ArrayList<>(); DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); Param.add(diskWithSnapshots); Param.add(diskWithoutSnapshots); Param.add(ovfImage); Param.add(cinderDisk); return Param; }

Target:
Please use Java conventions - param
Source:
public IndexingConfigurationBuilder autoConfig(boolean autoConfig) { enable(); attributes.attribute(AUTO_CONFIG).set(autoConfig); return this; }

Target:
Enabling indexing even if autoConfig == false? Maybe this auto-enabling should happen only if autoConfig==true?
Source:
private boolean shouldBeDirectlyAttached(String vfName, Guid vmId) { return CollectionUtils .isNotEmpty(vmDeviceDao.getVmDeviceByVmIdTypeAndDevice(vmId, VmDeviceGeneralType.HOSTDEV, vfName)); }

Target:
dao will return either an empty list or populated one, but never null.
Source:
private void safeCloseStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { // swallow error in this case Logger.e(TAG, "Failed to close the stream: ", "", ADALError.IO_EXCEPTION, e); } } }

Target:
static
Source:
public static String zkSecuritySysConfigString() { String loginConfig = System.getProperty(JAVA_LOGIN_CONFIG_PARAM); String clientEnabled = System.getProperty(ZK_SASL_CLIENT); String contextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY); return "[" + JAVA_LOGIN_CONFIG_PARAM + "=" + loginConfig + ", " + ZK_SASL_CLIENT + "=" + (clientEnabled == null ? "default:" + DEFAULT_ZK_SASL_CLIENT : clientEnabled) + ", " + ZK_LOGIN_CONTEXT_NAME_KEY + "=" + (contextName == null ? "default:" + DEFAULT_ZK_LOGIN_CONTEXT_NAME : contextName) + "]"; }

Target:
How about the following to simplify the string construction below: ```java String clientEnabled = System.getProperty(ZK_SASL_CLIENT, "default:" + DEFAULT_ZK_SASL_CLIENT); String contextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY, "default:" + DEFAULT_ZK_LOGIN_CONTEXT_NAME); ```
Source:
public void updateNode(final @Nonnull Node node) throws IOException { if (node == nodes.get(node.getNodeName())) { Queue.withLock(new Runnable() { @Override public void run() { jenkins.trimLabels(); } }); persistNode(node); } }

Target:
I would recommend returning a boolean, `true` for a successful update and `false` for the "no-op" case
Source:
public void onSaveInstanceState(Bundle outState) { if (backStack != null) { // update the topmost entry in the backstack updateCurrentBackStackItem(); outState.putParcelableArrayList("backStack", backStack); } }

Target:
The rest of this class expects backStack to be nonnull. I recommend we initialize backStack to an empty mutable list and specify @NonNull in the setter.
Source:
public Trader(String name, double cashInHand) { super(); this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }

Target:
Is this necessary?
Source:
private Iterable<ITask> getTasksAssosciatedWithReviewTask(ITask reviewTask) { String lookupUrl = reviewTask.getUrl(); // TODO: Fetch from mapping with the lookupUrl String taskUrl = "http://someurl"; AbstractRepositoryConnector repository = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(taskUrl); String taskId = repository.getTaskIdFromTaskUrl(taskUrl); String repositoryUrl = repository.getRepositoryUrlFromTaskUrl(taskUrl); ITask assosciatedTask = taskList.getTask(repositoryUrl, taskId); if (assosciatedTask == null) { return Collections.emptyList(); } return ImmutableSet.of(assosciatedTask); }

Target:
There can only be one associated task.
Source:
protected void toLegacyText(StringBuilder builder) { builder.append(this.value); }

Target:
Override
Source:
public static boolean isRoute(URL url) { return ROUTE_PROTOCOL.equals(url.getProtocol()) || ROUTERS_CATEGORY.equals(url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY)); }

Target:
`public static boolean isRoute(final URL url)`
Source:
void thread2() { int[] vs1; synchronized (lock) { vs1 = values; state = 1; } int s; do { synchronized (lock) { s = state; } } while (s != 2); // Busy loop. int[] vs2; synchronized (lock) { vs2 = values; } int v1 = vs1[0]; int v2 = vs2[0]; System.out.println("b17689750TestMonitor failed: " + v1 + ", " + v2); }

Target:
I would delete this synchronized block. Values cannot be modified while we're reading it since we already saw state as 2. It's also OK to move the prior accesses to values to before the synchronized blocks they are currently in, but it may be a better test without doing that.
Source:
public void testWriteAndReadObject() throws Exception { InternalSerializationService serializationService = new DefaultSerializationServiceBuilder().build(); String expected = "test input"; String actual = (String) writeAndReadObject(serializationService, expected); assertNotNull(actual); assertEquals(expected, actual); }

Target:
Isn't it easier to have the serializationService as a field on this test? Are there any serializationServices created with different settings? Having it as field instead of local variable, will simplify the test methods.
Source:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final ArArchiveEntry other = (ArArchiveEntry) obj; if (name == null) { return other.name == null; } else return name.equals(other.name); }

Target:
please add braces for the else block.
Source:
public ByteBufferReadableStreamChannel(List<ByteBuffer> bufferList) { if (bufferList == null || bufferList.isEmpty()) { throw new IllegalArgumentException("Input List of ByteBuffer cannot be null/empty for ByteBufferReadableStreamChannel"); } buffers = new ArrayList<>(bufferList); size = computeSize(bufferList); }

Target:
why do you need to wrap it in a new `ArrayList`? Seems wasteful.
Source:
boolean areRequiredNetworksAvailable(final List<VmNetworkInterface> vmNetworkInterfaces, final List<VdsNetworkInterface> allInterfacesForVds) { for (final VmNetworkInterface vmIf : vmNetworkInterfaces) { boolean found = false; for (final VdsNetworkInterface vdsIf : allInterfacesForVds) { if (StringUtils.equals(vmIf.getNetworkName(), vdsIf.getNetworkName())) { found = true; break; } } if (!found) { log.debug("VDS is not ok for running the VM as network is missing"); return false; } } return true; }

Target:
I don't know if it's necessary to log this message for each host, since for other unmet conditions we don't log anything. If it looks necessary to you then at least VDS ID would be helpful to know (assuming VM ID is already printed elsewehere).