auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addNotificationEvent(NotificationEvent entry) throws MetaException { if (addNotificationEventModifier != null) { Boolean success = addNotificationEventModifier.apply(entry); if ((success != null) && !success) { throw new MetaException("InjectableBehaviourObjectStore: Invalid addNotificationEvent operation on DB: " + entry.getDbName() + " table: " + entry.getTableName() + " event : " + entry.getEventType()); } } else { super.addNotificationEvent(entry); } }

Target:
DB and table name need not be set always. shall use String.valueOf(entry.getDbName()) as it return "null" string if null.
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { return Collections.singletonList(new PermissionSubject(getParameters().getProfile().getStorageDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); }

Target:
if the profile isn't set you'll have NPE here.
Source:
public void onError(Throwable t) { L.logRemoteErrorIfProd(t); Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); }

Target:
Won't we land here for expected network errors as well? Should this be in the catch block itself?
Source:
public static Object awaitLatch(Object payload, CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); return payload; } return payload; }

Target:
remove "return payload" in the catch.
Source:
private CheckBox renderCheckBox(LabeledWidgetsGrid g, ConfigParameterInfo param) { CheckBox checkBox = new CheckBox(); checkBox.setValue(Boolean.parseBoolean(param.value())); g.add(getDisplayName(param), checkBox); saveEnabler.listenTo(checkBox); return checkBox; }

Target:
You want g.add(null, checkBox) and put the display name onto the CheckBox widget. This way it shows [x] Foo instead of Foo [x] and users get a bigger click target (the label text) to mash with the mouse.
Source:
public void completeTaskCmdExecutorTest() { Map<String, Object> variables = new HashMap<>(); CompleteTaskCmd completeTaskCmd = new CompleteTaskCmd("taskId", variables); assertThat(completeTaskCmdExecutor).isNotNull(); assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskCmd.class); completeTaskCmdExecutor.execute(completeTaskCmd); verify(processEngine).completeTask(completeTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<CompleteTaskResults>>any()); }

Target:
Can be removed.
Source:
public void checkDeploymentOrder(boolean set) { boolean orderIsBlank = StringUtils.isBlank(deploymentOrder.getText()); if (set) { assertFalse(orderIsBlank); } else { assertTrue(orderIsBlank); } }

Target:
```suggestion assertEquals(!set, orderIsBlank); ``` (same elsewhere)
Source:
public int serialize(ByteBuffer bb) { int start = bb.position(); if (!cachedFlowStateEthernetHeader.isPresent()) { putFlowStateEthernetHeader(); } bb.put(cachedFlowStateEthernetHeader.get()); final ElasticData elasticData = getCore(); if (elasticData.getLength() > 0) { putElasticData(bb, start, elasticData); } return FLOW_STATE_ETHERNET_OVERHEAD + getElasticDataLength(); }

Target:
call super.serialize() so it serializes the ethernet headers, the ip headers, the udp headers and finally the elasticdata
Source:
protected boolean canDoAction() { ProviderValidator validator = new ProviderValidator(getProvider()); return validate(validator.providerIsSet()) && super.canDoAction(); }

Target:
what's the point in calling the super.canDoAction() if it always return true ?
Source:
private void synchCTFState(MArea areaModel) { List<MPartStack> stacks = findDirectStacks(areaModel); int count = 0; for (MPartStack stack : stacks) { if (stack.isToBeRendered()) count++; } // If there's more than one stack visible we use a CTF if (count > 1) ensureCTF(areaModel); else ensureComposite(areaModel); }

Target:
There are two more calls to findElements in the AreaRender, both in methods only called from sychCTFState. Shouldn't they also be updated? Or could the stacks be passed as parameter to these methods?
Source:
public void reset() { // Clear the entire usedFlagBuffer final int usedFlagBufferCapacity = usedFlagBuffer.capacity(); // putLong() instead of put() can boost the performance of clearing the buffer final int n = usedFlagBufferCapacity / Long.BYTES; for (int i = 0; i < n; i += Long.BYTES) { usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } }

Target:
Seems that there is a bug in this logic, it will clear using putLong() only 1/8-th of the buffer capacity, instead of the buffer capacity without, at most, 7 bytes. The classic pattern of implementing such things is ```java int i = 0; for (; i <= usedFlagBufferCapacity - Long.BYTES; i += Long.BYTES) { usedFlagBuffer.putLong(i, 0L); } for (; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); }
Source:
private void updateBrickSize() { long totalSize = 0; // Calculate and show the total size of all selected device so that user can get an idea of what will be his // brick // capacity. if (getStorageDevices().getSelectedItems() != null) { for (StorageDevice storageDevice : getStorageDevices().getSelectedItems()) { if (storageDevice.getCanCreateBrick()) { totalSize += storageDevice.getSize(); } } } Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(totalSize, SizeUnit.MB); setBrickSize(convertedSize); }

Target:
Isn't this check is redundant?
Source:
public void start() throws Exception { logger.info("Starting Gerrit-Trigger Plugin"); doXStreamRegistrations(); logger.trace("Loading configs"); load(); if (servers == null) { servers = new ArrayList<GerritServer>(); if (config != null) { //have loaded data in old format, so add a new server with the old config to the list. GerritServer defaultServer = new GerritServer(DEFAULT_SERVER_NAME); defaultServer.setConfig(config); servers.add(defaultServer); } } for (GerritServer s : servers) { s.start(); } }

Target:
It would be a tiiny bit safer/nicer if you put the config -> servers conversion inside the load method.
Source:
private boolean isClozeType() { int noteModelType; try { noteModelType = getCurrentlySelectedModel().getInt("type"); } catch (JSONException e) { throw new RuntimeException(e); } return noteModelType == Consts.MODEL_CLOZE; }

Target:
I thought all of these were changed to com.ichi2.anki JSON classes to avoid the try/catch since we just throw RuntimException anyway? #5550
Source:
public void setUp() { final Handle h = this.dbRule.getSharedHandle(); h.execute("CREATE TABLE uniq (id INTEGER PRIMARY KEY)"); }

Target:
I believe we can avoid declaring this handle and directly invoke `execute` on the shared handle.
Source:
public void simulateUsbUnplug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "unplug")) { Stream.flushRead(stream); stream.close(); } }

Target:
No, need for close here as you use try-with-resource?
Source:
private void createIndex() { try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE INDEX ON " + indexDefinition ); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 1, TimeUnit.SECONDS ); tx.success(); } }

Target:
this can be not enough on latest 3.3 version
Source:
public int compareTo(ApplicationInfoEx other) { if (mContext == null) return TextUtils.join(", ", getApplicationName()).compareToIgnoreCase( TextUtils.join(", ", other.getApplicationName())); // Locale respecting sorter Collator collator = Collator.getInstance(Locale.getDefault()); return collator.compare(TextUtils.join(", ", getApplicationName()), TextUtils.join(", ", other.getApplicationName())); }

Target:
Why is this needed? Storing a context for later use is not a good idea in general.
Source:
void resetCounter() { versionCounter.compareAndSet(versionCounter.get(), 0); }

Target:
This should really just be versionCounter.set(0);. This has a race condition that if generateNew method was invoked at the same time it could be possible that the CAS operation doesn't work properly because the get returned a value just before it was incremented but before the CAS occur, causing a missed reset.
Source:
private boolean isDraft(final ReceiveCommand cmd) { String refName = cmd.getRefName(); if (refName.startsWith(NEW_DRAFT_CHANGE)) { return true; } return false; }

Target:
What about making the method implementation be: return cmd.getRefName().startsWith(NEW_DRAFT_CHANGE); ?
Source:
public void tearDown() throws Exception { setAutoBuildEnabled(true); ValidationFramework.getDefault().suspendAllValidation(false); JobUtils.waitForIdle(100); ServerCreationTestUtils.deleteAllServersAndRuntimes(); ProjectUtility.deleteAllProjects(); ASMatrixTests.clearStateLocation(); JobUtils.waitForIdle(); }

Target:
no, you need to capture the autobuild state during setup and restore it during teardown
Source:
public byte[] getCacheKey() { byte[] previousStopBytes = previousStop == null ? new byte[]{} : StringUtils.toUtf8(previousStop); byte[] orderingBytes = StringUtils.toUtf8(ordering.toString()); int totalLen = 2 + previousStopBytes.length + orderingBytes.length; return ByteBuffer.allocate(totalLen) .put(CACHE_TYPE_ID) .put(previousStopBytes) .put(STRING_SEPARATOR) .put(orderingBytes) .array(); }

Target:
I think this line means that StringComparator needs a getCacheKey method.
Source:
public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this.consumerProperties = consumerProperties; this.sortingMapper = sortingMapper; this.consumer = getKafkaConsumer(); this.closed = false; this.records = new LinkedBlockingQueue<>(); }

Target:
Technically setting closed = false isn't needed since this is the default for a boolean
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; java.time.Instant instant = java.time.Instant.ofEpochMilli(timestamp - (timestamp % groupByInterval)); out.value = instant.toEpochMilli(); }

Target:
Looks like creating `Instant` here may be also omitted.
Source:
public V process(Map.Entry<K, V> entry) { action.accept(entry.getKey(), entry.getValue()); return entry.getValue(); }

Target:
Since `forEach` doesn't use these values, maybe we can avoid sending them back to the caller by simply returning `null`.
Source:
private ProjectControl user(AccountGroup.Id... memberOf) { RefControl.Factory refControlFactory = new RefControl.Factory() { @Override public RefControl create(final ProjectControl projectControl, final String ref) { return new RefControl(systemConfig, projectControl, ref, null); } }; return new ProjectControl(Collections.<AccountGroup.Id> emptySet(), Collections.<AccountGroup.Id> emptySet(), refControlFactory, new MockUser(memberOf), newProjectState()); }

Target:
Please implement a mock version of the RegExpCache using a normal HashMap.
Source:
private boolean executeBatch( BoltConnection connection ) { Thread currentThread = Thread.currentThread(); String originalName = currentThread.getName(); String newName = String.format( "%s [%s] ", originalName, connection.remoteAddress(), connector ); currentThread.setName( newName ); try { return connection.processNextBatch(); } finally { currentThread.setName( originalName ); } }

Target:
Pattern does not match the arguments
Source:
protected boolean validateCanUpdateReadOnly(DiskValidator diskValidator) { if (updateReadOnlyRequested()) { if(getVm().getStatus() != VMStatus.Down && vmDeviceForVm.getIsPlugged()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } if (!validateVmPoolProperties()) { return false; } return validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface()); } return true; }

Target:
Why is it needed here if it's already called from line 176? Not to mention that in the CDA it's run twice
Source:
public TmfEdge(TmfVertex from, TmfVertex to) { this.fVertexFrom = from; this.fVertexTo = to; this.fType = EdgeType.DEFAULT; }

Target:
while you're at it, you can remove the thises.
Source:
public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; WorkProcessor<Page> resultPages = getSortedPages( new SimplePageWithPositionComparator(sourceTypes, sortChannels, sortOrder)); resultPages.process(); sortedPages = resultPages.iterator(); } }

Target:
remove `resultPages.process()` -- `resultPages.iterator()` calls `process` and `getResult` as appropriate
Source:
public void exit() { super.exit(); removeMessages(BREDR_STOP_TIMEOUT); }

Target:
Should this be called at the end of child class' exit() method?
Source:
public ActualProperties build() { List<LocalProperty<Symbol>> localProperties = unordered ? filteredCopy(this.localProperties, property -> !property.isOrderSensitive()) : this.localProperties; return new ActualProperties(global, localProperties, constants); }

Target:
I find this easier to read: ```java List<LocalProperty<Symbol>> localProperties = this.localProperties; if (unordered) { localProperties = filteredCopy(localProperties, property -> !property.isOrderSensitive()); } return new ActualProperties(global, localProperties, constants); ```
Source:
public String getHeader(CharSequence headerName) { return headers().get(headerName.toString()); }

Target:
why toString() ?
Source:
public synchronized Uri insert(Uri uri, ContentValues initialValues) { SqlArguments args = new SqlArguments(uri); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final long rowId = db.insert(args.table, null, initialValues); if (rowId <= 0) return null; uri = ContentUris.withAppendedId(uri, rowId); sendNotify(uri); return uri; } }

Target:
Why are you synchronizing on "this" here if you are synchronizing on the lock below?
Source:
protected void completeRemoval(IModule m) { // AS7 requires the .deployed markers to be removed. Other servers require no action try { IPath archiveDestination = getModuleDeployRoot(new IModule[]{m}); IFilesystemController controller = getFilesystemController(); boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(getServer()); if( useAS7Behavior) { DeploymentMarkerUtils.removedDeployedMarker(archiveDestination, controller); DeploymentMarkerUtils.removedDeployFailedMarker(archiveDestination, controller); } } catch(CoreException ce) { JBossServerCorePlugin.log(ce); } }

Target:
you only need the controller inside the if block :-)
Source:
public void testViolationsByGoogleAndXpathSuppressions(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws Exception { System.setProperty("org.checkstyle.google.suppressionxpathfilter.config", "src/test/resources/com/puppycrawl/tools/checkstyle/main/" + "InputMainViolationsForGoogleXpathSuppressions.xml"); Main.main("-c", "/google_checks.xml", getPath("InputMainViolationsForGoogle.java")); assertThat("Unexpected output log", systemOut.getCapturedData(), is(noViolationsOutput)); assertThat("Unexpected system error log", systemErr.getCapturedData(), is("")); }

Target:
Why can't `getPath` be used instead?
Source:
private static Map<String, String> asMap(final KeyValueStore<String, String> store) { final HashMap<String, String> result = new HashMap<>(); store.all().forEachRemaining(kv -> { System.out.println(kv); result.put(kv.key, kv.value); }); return result; }

Target:
Did you mean to remove this println?
Source:
public Attribute createAttribute(HttpRequest request, String name, long definedSize) { Attribute attribute; if (useDisk) { attribute = new DiskAttribute(name, definedSize, charset); } else if (checkSize) { attribute = new MixedAttribute(name, definedSize, minSize, charset); } else { attribute = new MemoryAttribute(name, definedSize); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; }

Target:
nit: make this final
Source:
public boolean isDiscontinued(Date checkDate) { if (dateStopped != null && autoExpireDate != null && dateStopped.after(autoExpireDate)) { throw new APIException("Order.error.invalidDateStoppedAndAutoExpireDate", (Object[]) null); } if (isVoided()) { return false; } if (checkDate == null) { checkDate = new Date(); } if (dateActivated == null || !isActivated(checkDate) || dateStopped == null) { return false; } return checkDate.after(dateStopped); }

Target:
isActivated() already checks if dateActivated == null, so you don't need to check if it is null again here
Source:
private void operationExecuted(MatchingFrame frame) { if (!adapters.isEmpty()) for (ILocalSearchAdapter adapter : adapters) { adapter.operationExecuted(this, frame); } }

Target:
For readability reasons, please add braces.
Source:
public void onClick(ClickEvent event) { ExpandableListViewItem eventItem = null; if (event.getSource() instanceof ExpandableListViewItem) { eventItem = (ExpandableListViewItem)event.getSource(); } if (eventItem != null) { boolean active = eventItem.isActive(); // Hide all, then unhide the one clicked. hideAllDetails(); eventItem.toggleExpanded(!active); toggleExpanded(); } else { // Clicked a close icon hideAllDetails(); } event.preventDefault(); event.stopPropagation(); }

Target:
Nit-pick: please consider putting these two at the top instead of having them at the bottom. (I think we should first prevent/stop the event and then handle it.)
Source:
public void setLevel(LogLevel level) throws IllegalStateException { if(_config == null) { throw new IllegalStateException("Cannot set logging level without a configuration"); } if(level == null) { level = LogLevel.NONE; } if(_level.equals(level)) { return; } _level = level; C4Log.setBinaryFileLevel(level.getValue()); }

Target:
For consistency, we have never declared to throw IllegalStateException for null checking. I think we should remove it for consistency.
Source:
public synchronized Long getLogTail() { return logMetadata.getGlobalTail(); }

Target:
please use `long` don't need to wrap and unwrap the primitive value
Source:
public FilteringXmlStreamWriter(XMLStreamWriter writer, String encoding) { this.writer = writer; this.encoding = encoding != null ? encoding.toUpperCase() : null; }

Target:
Could you please explain why we would need to store it upper case please ?
Source:
public String getPropertyString() { return ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + ""; }

Target:
Use String.valueOf() here instead of appending an empty string
Source:
public static Object[][] interstitialOasis() { return new Object[][]{ { new Page("project43", "SyntheticTests/Slots/InvisibleHighImpact/Interstitial"), "#INVISIBLE_HIGH_IMPACT_2 .provider-container iframe", new Dimension(728, 90) }, }; }

Target:
I believe we can have the same selector on mobile and desktop. Please use: `.invisible-high-impact-wrapper.interstitial .provider-container iframe`
Source:
protected CaseInsensitiveMap(final Map<String, VALUE> underlyingMap) { this.underlyingMap = underlyingMap; }

Target:
Would it be worth enforcing that the map being wrapped is empty? As the newImmuatableMap() method makes a copy of the map, properly importing the keys, someone may get the wrong impression that this constructor would remove and re-insert the values currently in the map so that they will be accessible. Right now it would be possible to wrap a map that has uppercase in the key names and those members would not be able to be extracted through this interface.
Source:
public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { return (readPending && maybeMoreDataToRead()) || delegate.continueReading(maybeMoreDataSupplier); }

Target:
this will skip the criteria enforced by the delegate (e.g. [MaxMessageHandle](https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/DefaultMaxMessagesRecvByteBufAllocator.java#L142-L145)). The delegate may not respect "maybe more data" and may have other criteria to determine it doesn't want to continue reading. The delegate also checks "auto read" which seems like a more natural fit for the "read pending" check (e.g. `is auto read enabled || someone asked to read`).
Source:
private void saveZeroValueForResource(org.sonar.api.resources.File resource, SensorContext context) { // use non comment lines of code for coverage calculation Measure<Integer> nclocMeasure = context.getMeasure(resource, CoreMetrics.NCLOC); if (nclocMeasure != null) { double ncloc = context.getMeasure(resource, CoreMetrics.NCLOC).getValue(); context.saveMeasure(resource, getZeroCoverageLineHitsDataMetric(resource, context)); context.saveMeasure(resource, linesToCoverMetric, ncloc); context.saveMeasure(resource, uncoveredLinesMetric, ncloc); } }

Target:
@pynicolas why `context.getMeasure(resource, CoreMetrics.NCLOC)` again?
Source:
CorsConfiguration findCorsConfiguration(String lookupPath) { ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath)); if (resource != null) { return createConfiguration( repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()); } return null; }

Target:
Ternary if?
Source:
public void setUp() { fixture = new AggregateTestFixture<>(AnnotatedAggregate.class); mockCommandTargetResolver = mock(CommandTargetResolver.class); }

Target:
Super nit: being nit-picky here, but this empty line is not necessary I think.
Source:
public boolean handleExtraButtonPressed(int buttonId) { if (buttonId == QueryWizardDialog.REFRESH_BUTTON_ID) { if (getTaskRepository() != null) { refreshConfiguration(true); } else { MessageDialog.openInformation( Display.getCurrent().getActiveShell(), Messages.AbstractRepositoryQueryPage2_Update_Attributes_Failed, Messages.AbstractRepositoryQueryPage2_No_repository_available_please_add_one_using_the_Task_Repositories_view); } return true; } else if (buttonId == QueryWizardDialog.CLEAR_BUTTON_ID) { if (!innerComposite.isDisposed()) { doClearControls(); return false; } return true; } return false; }

Target:
Is that really possible here given that the button is not disposed?
Source:
public Void apply(KVariable k) { hasConfigVar = true; return null; }

Target:
why was this done?
Source:
public boolean willEnter(Object request, Object target) { int modifierKeys = 0; if (request instanceof SelectionRequest) { modifierKeys = ((SelectionRequest) request).getModifiers(); } else if (request instanceof MouseEvent) { modifierKeys = ((MouseEvent) request).stateMask; } return (modifierKeys == SWT.CONTROL + SWT.SHIFT); }

Target:
What's the meaning of 0 ?
Source:
public Object fromStorage(Object stored) { checkConverters(); if (stored == null) return null; return encoder.fromStorage(wrapper.unwrap(stored)); }

Target:
I would check first if the value is null
Source:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { List<ScalarImplementationChoice> implementationChoices = new ArrayList<>(); for (PolymorphicScalarFunctionChoice choice : choices) { implementationChoices.add(getScalarFunctionImplementationChoice(boundVariables, typeManager, functionRegistry, choice)); } return new ScalarFunctionImplementation(implementationChoices, deterministic); }

Target:
You can use ImmutableList.builder().
Source:
public final String evaluate(TransactionContext txnCtx, Input<Object>... args) { assert args.length == 1 : "typeof expects exactly 1 argument, got: " + args.length; Object arg0 = args[0].value(); return null != arg0 ? type : DataTypes.UNDEFINED.getName(); }

Target:
I think even in the `null` case we can return the type, see: ``` select pg_typeof(null::bigint); pg_typeof ----------- bigint ```
Source:
public Document getInnerDocument() { IRubyObject innerDocument = getRubyProperty("inner_document"); if (innerDocument.isNil()) return null; return (Document) NodeConverter.createASTNode(innerDocument); }

Target:
Gotcha! :-) Could you please add braces around the `return null`? I probably automatically put them in there mentally around both returns that have the same indentation.
Source:
private Callback<Long> fetchStitchRequestBodyCallback(CopyingAsyncWritableChannel channel, BlobInfo blobInfo) { return buildCallback(frontendMetrics.postReadStitchRequestMetrics, bytesRead -> router.stitchBlob(blobInfo.getBlobProperties(), blobInfo.getUserMetadata(), getChunksToStitch(blobInfo.getBlobProperties(), FrontendUtils.readJsonFromChannel(channel)), routerStitchBlobCallback(blobInfo)), uri, LOGGER, finalCallback); }

Target:
FrontendUtils is already imported at the beginning, looks like we can directly use `readJsonFromChannel` here.
Source:
public void testDeserialize() throws Exception { String json = getResourceAsString("/api_fixtures/ephemeral_key.json"); EphemeralKey resource = APIResource.GSON.fromJson(json, EphemeralKey.class); assertNotNull(resource); assertEquals("ephkey_123", resource.getId()); assertEquals("ephemeral_key", resource.getObject()); }

Target:
why not use stripe-mock?
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; throw new RuntimeException("Only one PropertiesModule may be installed"); }

Target:
Log the conflicting classes found for easier tracking.
Source:
public void send(Message<?> message, ScopeDescriptor scopeDescription) throws Exception { if (canResolve(scopeDescription)) { String aggregateIdentifier = ((AggregateScopeDescriptor) scopeDescription).getIdentifier().toString(); Aggregate<T> aggregate = load(aggregateIdentifier); if (aggregate != null) { aggregate.handle(message); } else { logger.debug("Aggregate (with id: [{}]) cannot be loaded. Hence, message '[{}]' cannot be handled.", aggregateIdentifier, message); } } }

Target:
Note that the load method throws `AggregateNotFoundException` instead of returning `null` when an aggregate isn't found. Please create a test case to verify this behavior.
Source:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() && vdsGroup.getcompatibility_version() != null && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }

Target:
Minor - Version's compareTo does a null check, so you may not need the vdsGroup.getcompatibility_version() != null
Source:
public void setGenerateDroolsTestOnError(Boolean generateDroolsTestOnError) { if (BooleanUtils.isTrue(generateDroolsTestOnError)) { System.setProperty(GENERATE_DROOLS_TEST_ON_ERROR_PROPERTY_NAME, "true"); } else { System.clearProperty(GENERATE_DROOLS_TEST_ON_ERROR_PROPERTY_NAME); } this.generateDroolsTestOnError = generateDroolsTestOnError; }

Target:
This should be a simple setter (that is now deprecated). It shouldn't mess with the system property, in favor of which it is deprecated, because System.setProperty() is dangerous: presume that a single JVM process runs 2 solver configs, constructed by java (not by xml) and the first one calls setGenerateDroolsTestOnError(true), but the second one doesn't. The second one would feel it too. => remove that if-else block
Source:
public static String getMessageFromValue(final int value) { switch (value) { case INVALID_DATE: return "Can only access during valid times:"; case INVALID_PERMISSION: return "Can only perform task with valid permission"; case NO_AUTH_SENT: return "No Authentication Information was received"; default: break; } return null; }

Target:
You could save a few lines by moving the return null into the default case instead of break.
Source:
protected boolean shouldSkipCommandExecution() { return StringUtils.equals(getVm().getCurrentCd(), getParameters().getCdImagePath()); }

Target:
need to check that getVm() is not null and also use it in canDoAction and also new audit log for the user to know it was skipped. please see usage example in StopVmCommandBase and ShutdownVmCommand
Source:
public static boolean verifyOozieJobStatus(OozieClient client, String processName, ENTITY_TYPE entityType, Job.Status expectedStatus) throws OozieClientException, InterruptedException { for (int seconds = 0; seconds < 20; seconds++) { Job.Status status = getOozieJobStatus(client, processName, entityType); logger.info("Current status: " + status); if (status == expectedStatus) { return true; } TimeUnit.SECONDS.sleep(5); } return false; }

Target:
``` java for (int seconds = 0; seconds < 20; seconds++) { ``` this also have to be changed. Maybe to this code: ``` java for (int seconds = 0; seconds < 100; seconds+=5) { ```
Source:
public void init() throws KalturaManagerException { KalturaEventsManager.registerEventConsumer(this, KalturaEventType.STREAM_PUBLISHED, KalturaEventType.STREAM_UNPUBLISHED, KalturaMediaEventType.APPLICATION_INSTANCE_STARTED); liveManager = KalturaServer.getManager(ILiveManager.class); setInitialized(); }

Target:
You forgot to call super.init()
Source:
public static final void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } for (Group altG : group.getAltLocs()) { for (Atom atom : altG.getAtoms()) { transform(atom, m); } } }

Target:
Recursive call to `transform(g, m)` could also be possible here.
Source:
public void updateReviewItem(ChangeInfo task) { fReviewList.put(task.getChange_id(), task); //Here we keep the change_id because it is shown to the user }

Target:
Here we use it as the same key as we use to create the fReviewList
Source:
public static Protocol fromValue(String value) { Protocol[] items = Protocol.values(); for (Protocol item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return (Protocol) GetEnumValue.fromValueOrDefault(value, UNRECOGNIZED); }

Target:
Could use the same pattern as https://github.com/jclouds/jclouds-labs/blob/master/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ComputeNode.java#L28, i.e. return (Protocol) GetEnumValue.fromValueOrDefault(value, Protocol.UNRECOGNIZED);
Source:
protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { Map<KeyExtent,List<Range>> tablets = binnedRanges.computeIfAbsent(location, k -> new HashMap<>()); List<Range> tabletsRanges = tablets.computeIfAbsent(ke, k -> new ArrayList<>()); tabletsRanges.add(range); }

Target:
These look like they can simplify to: ```java binnedRanges.computeIfAbsent(location, k -> new HashMap<>()) .computeIfAbsent(ke, k -> new ArrayList<>()) .add(range); ```
Source:
public ChannelWriteController( ApplicationConfigurationFetcher appConfigFetcher, ChannelStore store, ModelReader reader, ChannelModelTransformer channelTransformer ) { this.appConfigFetcher = checkNotNull(appConfigFetcher); this.store = checkNotNull(store); this.reader = checkNotNull(reader); this.channelTransformer = checkNotNull(channelTransformer); }

Target:
Constructor should be private. Make a static factory method
Source:
public TestGerritClient(TaskRepository repository, AbstractWebLocation location) { super(repository, GerritFixture.current().getGerritVersion()); System.out.println("Testing against Gerrit " + GerritFixture.current().getGerritVersion()); initialize(location, null, null, null, null); }

Target:
replace this file with "previous version" and commit again - it should remove it from this review
Source:
private String GetLocalStoragesFormattedString() { StringBuilder localStorages = new StringBuilder(""); //$NON-NLS-1$ for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) { if (a.getStorageType() == StorageType.LOCALFS) { localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$ } } return localStorages.substring(0, localStorages.length() - 2); }

Target:
The empty string here is redundent
Source:
public void setup() { generator = new SequentialIdentifierGenerator(); handler = new SequentialIdentifierGeneratorResourceHandler(); }

Target:
Why are you setting these from here? Why are they class level variables?
Source:
void onChangeRevision(@SuppressWarnings("unused") ChangeEvent e) { int idx = diffBase.getSelectedIndex(); if (0 <= idx && fileTableMode == FileTable.Mode.REVIEW) { String n = diffBase.getValue(idx); loadConfigInfo(changeInfo, !n.isEmpty() ? n : null); } }

Target:
I don't understand how ignoring the UI event when the Diff base popup selects another field in edit mode fixes the linked issue. A more descriptive commit message would help. Is the diffBase widget just supposed to be disabled or invisible in edit mode?
Source:
public String getFingerprint(Schema schema) { if (theClient == null) { theClient = initializeClient(); } String subject = schema.getName(); final int guid; try { guid = theClient.register(subject, schema); System.out.println("GUID: [" + guid + "]"); } catch (IOException | RestClientException e) { throw new RuntimeException(e); } return Integer.toString(guid); }

Target:
this should be removed
Source:
private boolean declaringTypeIsLocalOrImported(CtTypeReference declaringType) { if (declaringType != null) { if (!isTypeInCollision(declaringType, false) && (isImportedInClassImports(declaringType) || classNamePresentInJavaLang(declaringType))) { return true; } if (!isTypeInCollision(declaringType, false) && addClassImport(declaringType)) { return true; } while (declaringType != null) { if (declaringType.equals(targetType)) { return true; } declaringType = declaringType.getDeclaringType(); } } return false; }

Target:
Actually I was testing that and trying to import the declaring type just below. So I assume you had a problem somewhere importing a declaring type: the condition below is useless then...
Source:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); for (int index = 0; index < quantity; index += 1) { this.notifications.add(index, new MkNotification(index)); } }

Target:
@prondzyn `++ index`
Source:
@Override public String setCity(String city) { return city; }

Target:
The left side should be the preferred style (annotations in an extra line).
Source:
private static SSLFactory getSSLFactoryIfRequired(VerifiableProperties verifiableProperties) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { boolean sslRequired = new NettyConfig(verifiableProperties).nettyServerEnableSSL || new ClusterMapConfig(verifiableProperties).clusterMapSslEnabledDatacenters.length() > 0; return sslRequired? SSLFactory.getNewInstance(new SSLConfig(verifiableProperties)) : null; }

Target:
`throws Exception`
Source:
public T LIMIT(int value) { sql().limit = String.valueOf(value); sql().limitingRowsStrategy = SQLStatement.LimitingRowsStrategy.OFFSET_LIMIT; return getSelf(); }

Target:
The newly added line makes me think about DRY for some reason. :D How about... ```java return LIMIT(String.valueOf(value)); ```
Source:
@Override public void testSiteBuildWithForkedMojo() throws Exception { // TODO currently failing, apparently from NPE in DefaultDependencyGraphBuilder.canFindCoreClass after failing to resolve an artifact from the test project }

Target:
Please follow existed coding style and put new line after Override
Source:
boolean spends(Transaction txA, Transaction txB) { boolean spends = false; for (TransactionInput txInput : txA.getInputs()) { spends |= txInput.getOutpoint().getHash().equals(txB.getHash()); } return spends; }

Target:
This can just be "if (txInput.....) return true" right? No need to continue looping after finding that the condition is correct.
Source:
public void setup() throws Exception { sslFactory = TestUtils.createSSLFactory(); SSLContext sslContext = sslFactory.createSSLContext(); sslSocketFactory = sslContext.getSocketFactory(); sslEchoServer = new SSLBlockingEchoServer(sslFactory, sslPort); sslEchoServer.start(); }

Target:
new echo server for every test or will a single one for all tests suffice? If a single one will suffice, then you could declare all variables used here as static and turn these two functions into @BeforeClass and @AfterClass
Source:
public boolean isFinished() { checkState(initialized.get(), "Driver is not initialized"); checkLockNotHeld("Can not check finished status while holding the driver lock"); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown Optional<Boolean> result = tryWithLock(this::isFinishedInternal); return result.orElseGet(() -> state.get() != State.ALIVE || driverContext.isDone()); }

Target:
not needed in this method?
Source:
public Node(String address, String logPath) { this.address = address; this.logPath = logPath; this.shutdown = new ShutdownAction(this); this.start = new StartAction(this); }

Target:
There is a 3 param constructor, we can call this to reduce code rep..
Source:
private double cumulativeProbability(double x) { try { NormalDistribution normDist = new NormalDistribution(); return normDist.cumulativeProbability(x); } catch (Exception ex) { return Double.NaN; } }

Target:
What kind of Exception can be thrown here? Could this be made more specific? Also, is it possible to use some other mechanism of detecting whatever problem this exception is detecting? Exceptions are quite slow compared to other forms of flow control and so I'm concerned about using them in a post-aggregator `compute` function.
Source:
public Response afterLRA(@HeaderParam(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER) URI endedLRAId) { if (afterLRACounter.getAndIncrement() < 2) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } return Response.ok().build(); }

Target:
Actually I see the code may well apply if the scan is in progress
Source:
public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException { OpenmrsUtil.validatePassword(user.getUsername(), hashedPassword, user.getSystemId()); dao.changeHashedPassword(user, hashedPassword, salt); }

Target:
Does this really work? That validate method i think expects non hashed passwords, probably you shouldn't validate this, the ticket says changePassword methods. I also think these should delegate to the changePassword method that validates the password to centralize the code
Source:
public void updateSystemMemoryUsage(long deltaMemoryInBytes) { if (taskContext == null) { Optional<TaskContext> taskContext = queryContext.getTaskContextByTaskId(taskId); verify(taskContext.isPresent(), "task does not exist"); this.taskContext = taskContext.get(); } if (deltaMemoryInBytes > 0) { taskContext.reserveSystemMemory(deltaMemoryInBytes); } else { taskContext.freeSystemMemory(-deltaMemoryInBytes); } }

Target:
Consider adding `queryContext.getRequiredTaskContext(taskId)` to do this in one shot without the `Optional`
Source:
public void testAllOutputsReferenced() throws Exception { tester().assertThat(new PruneAggregationColumns()) .on(p -> buildProjectedAggregation(p, Predicates.alwaysTrue())) .doesNotFire(); }

Target:
static import
Source:
public void setSessionRollbackCount(int count) { sessionRollbackCount = count; }

Target:
synchronized
Source:
public PermissionTypeColumn() { makeSortable(Comparator.comparing(p -> !resources.userImage().equals(p))); }

Target:
This doesn't seem aligned with the original implementation
Source:
private boolean hasSameSeparateDerivedEncodings() { return (separateDerivedEncodingsButton == null) || (separateDerivedEncodingsButton.getSelection() == getStoredSeparateDerivedEncodingsValue()); }

Target:
we can also get rid of the parenthesis by the way.
Source:
void setMetric(Object metric) { this.metric = metric; }

Target:
not synchronized?
Source:
public ProgramState stackValue(SymbolicValue sv) { Deque<SymbolicValue> newStack = new LinkedList<>(stack); newStack.push(sv); return new ProgramState(this, newStack); }

Target:
Why public ?
Source:
private CertificateDTO addCertByChild(List<CertificateDTO> toList, List<CertificateDTO> fromList, CertificateDTO child){ if (null != child && CollectionUtils.isNotEmpty(fromList)) { for(CertificateDTO cert : fromList){ if(child.getAuthorityKeyID().compareTo(cert.getSubjectKeyID())==0){ toList.add(cert); fromList.remove(cert); return cert; } } } return null; }

Target:
Can we use .equals() instead of .compareTo?
Source:
private void analyzeClass(final byte[] source) { final long classId = CRC64.classId(source); final int version = BytecodeVersion.read(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(version, source); final ClassReader reader = new ClassReader(b); final ClassVisitor visitor = createAnalyzingVisitor(classId, reader.getClassName()); reader.accept(visitor, 0); }

Target:
Move this private method below the public analyze* methods?
Source:
public void close() throws ItemStreamException { if (!ignoreItemStream && delegate instanceof ItemStream) { ((ItemStream) delegate).close(); } }

Target:
Removing the configuration option above simplifies all three of these methods.
Source:
public FileMode getMode(File f, FS.Attributes attributes) { if (attributes.isSymbolicLink()) return FileMode.SYMLINK; else if (attributes.isDirectory()) { return FileMode.TREE; } else if (attributes.isExecutable()) return FileMode.EXECUTABLE_FILE; else return FileMode.REGULAR_FILE; }

Target:
style nit: missing braces
Source:
protected UserException typeConversionError(ColumnMetadata schema, ValueDef valueDef) { String type = valueDef.type().name().toLowerCase(); if (valueDef.isArray()) { for (int i = 0; i < valueDef.dimensions(); i++) { type += "[]"; } } return typeConversionError(schema, type); }

Target:
Please use StringBuilder.
Source:
public void testStructWithNull() throws Exception { runTest( "test_flat_map/flat_map_struct_with_null.dwrf", INTEGER, STRUCT_TYPE, ExpectedValuesBuilder.get(Function.identity(), TestMapFlatSelectiveStreamReader::intToList).setNullValuesFrequency(TestMapFlatSelectiveStreamReader.ExpectedValuesBuilder.Frequency.SOME)); }

Target:
static import TestMapFlatSelectiveStreamReader.ExpectedValuesBuilder.Frequency.SOME
Source:
protected void refreshVisuals() { Connector connector = (Connector) getNotationView(); NamedStyle namedStyle = connector.getNamedStyle(NotationPackage.Literals.INT_VALUE_STYLE, "delta"); if (namedStyle instanceof IntValueStyle) { refreshArrowDelta((IntValueStyle) namedStyle); } else { // no style - reset value ((DurationLinkFigure) getFigure()).setArrowPositionDelta(0); } super.refreshVisuals(); }

Target:
As a convention, it is typically the responsibility of the refreshSomething() method to extract the style and change the figure. #refreshVisuals() typically calls all #refreshSomething() methods, then each method reads its own style from the notation, and calls #setSomething() on the Figure Also, #refreshSomething() methods are usually protected, so subclasses may adapt the behavior, without having to install their own listeners (Although in that case, I doubt we'll ever have to override the DurationLink EditParts)
Source:
@Override public void changeKey(@Nullable State outgoingState, State incomingState, Flow.Direction direction, Context incomingStateContext, Flow.TraversalCallback callback) { if (textView == null) { textView = new TextView(activity); textView.setGravity(Gravity.CENTER); } textView.setText(incomingState.getKey().toString()); activity.setContentView(textView); callback.onTraversalCompleted(); }

Target:
Weird that you're calling setContentView over and over again.
Source:
public String toHex(DiscreteElement<?> element) { return ""; }

Target:
Should return the same value it would have returned had it not called toHex
Source:
public TestNGTestListener() { EnvironmentCheck.checkJVMVersion(); progressLogger = new TestSuiteProgress(); }

Target:
For TestNG modules we can throw an exception in `TestNGSuiteChecksTest.beforeSuite()` instead of calling `System.exit()`
Source:
void setTo( String to ) { if ( to != null && !"".equals( to ) ) { to = to.replaceAll( ";", "," ); props.put( "to", to ); } }

Target:
@cravobranco, `removing` the public access modifier makes these methods invisible outside of the package and will break code using these methods from other packages. Please update the PR with the `public` access modifier. See: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Source:
private void prepareMockFileUrls() throws URISyntaxException { when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE)).thenReturn(new URI(SOURCE_VERSION_URL)); when(fileServiceClient.getFileUri(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE + FILE2)).thenReturn(new URI(SOURCE_VERSION_URL_FILE2)); }

Target:
I wonder why this method is not final while the others similar to it are. What is the reason for having final methods here?
Source:
public IStatus validate(Object[] selection) { String errorMessage = ""; //$NON-NLS-1$ if (selection.length == 0) { errorMessage = NO_SELECTION; } else { final Object firstSelection = selection[0]; if (selection.length != 1 || false == firstSelection instanceof Property || (firstSelection instanceof Property && false == ((Property) firstSelection).getType() instanceof PrimitiveType)) { errorMessage = Messages.SinglePropertyAttributeValidator_errorMessage; } } return buildIStatus(errorMessage); }

Target:
Just notice: It's preferable to manage the comparison '<=' instead of '=='
Source:
public boolean isItemValidForSlot(int slot, ItemStack stack) { if (slot == SLOT_INPUT) { boolean b1 = FluidItemHelper.isContainer(stack); boolean b2 = FluidItemHelper.isEmptyContainer(stack); FluidStack filter = getFilterFluid(); boolean b3 = filter == null; boolean b4 = FluidItemHelper.containsFluid(stack, filter); return b1 && (b2 || b3 || b4); } return false; }

Target:
This is less efficient because it looses the short circuit property of Boolean logic.
Source:
public MigratableTableTranslation<DBOColumnModel, DBOColumnModel> getTranslator() { return new BasicMigratableTableTranslation<DBOColumnModel>(){ @TemporaryCode(author="ziming", comment = "one-time migration change. remove after stack 309") @Override public DBOColumnModel createDatabaseObjectFromBackup(DBOColumnModel backup) { //doing this round trip will assign default value to maxListLength ColumnModel columnModel = ColumnModelUtils.createDTOFromDBO(backup); if(ColumnTypeListMappings.isList(columnModel.getColumnType())){ columnModel.setMaximumListLength(ColumnConstants.MAX_ALLOWED_LIST_LENGTH); } DBOColumnModel modifiedDBO = ColumnModelUtils.createDBOFromDTO(columnModel, StackConfigurationSingleton.singleton().getTableMaxEnumValues()); return modifiedDBO; } }; }

Target:
let ColumnModelUtils.createDTOFromDBO(backup); handle the set to default (not setting it here)
Source:
private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } } }); }

Target:
use lambda instead private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }
Source:
private static boolean performImportWithoutUI(VirtualFile importSource, Project destinationProject) throws IOException { for (ModuleImporter importer : ModuleImporter.getAllImporters(destinationProject)) { if (importer.canImport(importSource)) { HashMap<String, VirtualFile> modules = Maps.newHashMap(); for (ModuleToImport module : importer.findModules(importSource)) { modules.put(module.name, module.location); } importer.importProjects(modules); return true; } } return false; }

Target:
nit - use Map instead of HashMap on left hand side
Source:
public static InputStream getContactPhotoStream(ContentResolver contentResolver, Uri uri) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { final Uri contactUri = uri.toString().startsWith( ContactsContract.Contacts.CONTENT_LOOKUP_URI.toString()) ? ContactsContract.Contacts.lookupContact(contentResolver, uri) : uri; return openContactPhotoInputStream(contentResolver, contactUri); } else { return ContactPhotoStreamIcs.get(contentResolver, uri); } }

Target:
I would rather this be something like: ``` java if (uri.toString().startsWith(Contacts.CONTENT_LOOKUP_URI.toString()) { uri = Contacts.lookupContact(contentResolver, uri); } ``` to avoid the unnecessary assignment when the `Uri` does not match.
Source:
public Collection<String> getReviewUrls(String taskUrl) { List<String> reviewUrls = taskReviewsMap.get(taskUrl); if (reviewUrls == null) { return Collections.emptyList(); } return reviewUrls; }

Target:
Multimap never returns null, so we could get rid of this method.