auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onError(Throwable t) { START L.logRemoteErrorIfProd(t); END Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } Won't we land here for expected network errors as well? Should this be in the catch block itself?

Target:
public void onError(Throwable t) { Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); }
Source:
public static Object awaitLatch(Object payload, CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); START return payload; END } return payload; } remove "return payload" in the catch.

Target:
public static Object awaitLatch(Object payload, CountDownLatch latch) { try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); } return payload; }
Source:
private CheckBox renderCheckBox(LabeledWidgetsGrid g, ConfigParameterInfo param) { CheckBox checkBox = new CheckBox(); checkBox.setValue(Boolean.parseBoolean(param.value())); START g.add(getDisplayName(param), checkBox); END saveEnabler.listenTo(checkBox); return checkBox; } 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.

Target:
private CheckBox renderCheckBox(LabeledWidgetsGrid g, ConfigParameterInfo param) { CheckBox checkBox = new CheckBox(getDisplayName(param)); checkBox.setValue(Boolean.parseBoolean(param.value())); g.add(null, checkBox); saveEnabler.listenTo(checkBox); return checkBox; }
Source:
public void completeTaskCmdExecutorTest() { Map<String, Object> variables = new HashMap<>(); CompleteTaskCmd completeTaskCmd = new CompleteTaskCmd("taskId", variables); START assertThat(completeTaskCmdExecutor).isNotNull(); END assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskCmd.class); completeTaskCmdExecutor.execute(completeTaskCmd); verify(processEngine).completeTask(completeTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<CompleteTaskResults>>any()); } Can be removed.

Target:
public void completeTaskCmdExecutorTest() { Map<String, Object> variables = new HashMap<>(); CompleteTaskCmd completeTaskCmd = new CompleteTaskCmd("taskId", variables); assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskCmd.class); completeTaskCmdExecutor.execute(completeTaskCmd); verify(processEngine).completeTask(completeTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<CompleteTaskResults>>any()); }
Source:
public void checkDeploymentOrder(boolean set) { boolean orderIsBlank = StringUtils.isBlank(deploymentOrder.getText()); START if (set) { assertFalse(orderIsBlank); } else { assertTrue(orderIsBlank); } END } ```suggestion assertEquals(!set, orderIsBlank); ``` (same elsewhere)

Target:
public void checkDeploymentOrder(boolean set) { assertEquals(!set, StringUtils.isBlank(deploymentOrder.getText())); }
Source:
START public int serialize(ByteBuffer bb) { END 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(); } call super.serialize() so it serializes the ethernet headers, the ip headers, the udp headers and finally the elasticdata

Target:
public int serialize(ByteBuffer bb) { int start = bb.position(); if (cachedFlowStateEthernetHeader == null) { putFlowStateEthernetHeader(); } bb.put(cachedFlowStateEthernetHeader); final ElasticData elasticData = getCore(); if (elasticData.getLength() > 0) { putElasticData(bb, start, elasticData); } return FLOW_STATE_ETHERNET_OVERHEAD + getElasticDataLength(); }
Source:
protected boolean canDoAction() { ProviderValidator validator = new ProviderValidator(getProvider()); START return validate(validator.providerIsSet()) && super.canDoAction(); END } what's the point in calling the super.canDoAction() if it always return true ?

Target:
protected boolean canDoAction() { ProviderValidator validator = new ProviderValidator(getProvider()); return validate(validator.providerIsSet()); }
Source:
private void synchCTFState(MArea areaModel) { START List<MPartStack> stacks = findDirectStacks(areaModel); END 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); } 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?

Target:
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, stacks); else ensureComposite(areaModel, stacks); }
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; START for (int i = 0; i < n; i += Long.BYTES) { END usedFlagBuffer.putLong(i, 0L); } for (int i = n; i < usedFlagBufferCapacity; i++) { usedFlagBuffer.put(i, (byte) 0); } } 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); }

Target:
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) * 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); } }
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()) { START if (storageDevice.getCanCreateBrick()) { END totalSize += storageDevice.getSize(); } } } Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(totalSize, SizeUnit.MB); setBrickSize(convertedSize); } Isn't this check is redundant?

Target:
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()) { totalSize += storageDevice.getSize(); } } Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(totalSize, SizeUnit.MB); setBrickSize(convertedSize); }
Source:
public void start() throws Exception { logger.info("Starting Gerrit-Trigger Plugin"); doXStreamRegistrations(); logger.trace("Loading configs"); load(); START if (servers == null) { END 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(); } } It would be a tiiny bit safer/nicer if you put the config -> servers conversion inside the load method.

Target:
public void start() throws Exception { logger.info("Starting Gerrit-Trigger Plugin"); doXStreamRegistrations(); logger.trace("Loading configs"); load(); for (GerritServer s : servers) { s.start(); } }
Source:
private boolean isClozeType() { int noteModelType; try { noteModelType = getCurrentlySelectedModel().getInt("type"); START } catch (JSONException e) { END throw new RuntimeException(e); } return noteModelType == Consts.MODEL_CLOZE; } 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

Target:
private boolean isClozeType() { return getCurrentlySelectedModel().getInt("type") == Consts.MODEL_CLOZE; }
Source:
public void setUp() { START final Handle h = this.dbRule.getSharedHandle(); END h.execute("CREATE TABLE uniq (id INTEGER PRIMARY KEY)"); } I believe we can avoid declaring this handle and directly invoke `execute` on the shared handle.

Target:
public void setUp() { this.dbRule.getSharedHandle().execute("CREATE TABLE uniq (id INTEGER PRIMARY KEY)"); }
Source:
public void simulateUsbUnplug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "unplug")) { Stream.flushRead(stream); START stream.close(); END } } No, need for close here as you use try-with-resource?

Target:
public void simulateUsbUnplug() throws IOException, JadbException { try (InputStream stream = device.executeShell("dumpsys", "battery", "unplug")) { Stream.flushRead(stream); } }
Source:
private void createIndex() { try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE INDEX ON " + indexDefinition ); tx.success(); } try ( Transaction tx = db.beginTx() ) { START db.schema().awaitIndexesOnline( 1, TimeUnit.SECONDS ); END tx.success(); } } this can be not enough on latest 3.3 version

Target:
private void createIndex() { try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE INDEX ON " + indexDefinition ); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 5, TimeUnit.SECONDS ); tx.success(); } }
Source:
public int compareTo(ApplicationInfoEx other) { START if (mContext == null) END 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())); } Why is this needed? Storing a context for later use is not a good idea in general.

Target:
public int compareTo(ApplicationInfoEx other) { // Locale respecting sorter Collator collator = Collator.getInstance(Locale.getDefault()); return collator.compare(TextUtils.join(", ", getApplicationName()), TextUtils.join(", ", other.getApplicationName())); }
Source:
void resetCounter() { START versionCounter.compareAndSet(versionCounter.get(), 0); END } 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.

Target:
void resetCounter() { versionCounter.set(0); }
Source:
private boolean isDraft(final ReceiveCommand cmd) { START String refName = cmd.getRefName(); END if (refName.startsWith(NEW_DRAFT_CHANGE)) { return true; } return false; } What about making the method implementation be: return cmd.getRefName().startsWith(NEW_DRAFT_CHANGE); ?

Target:
private boolean isDraft(final ReceiveCommand cmd) { return cmd.getRefName().startsWith(NEW_DRAFT_CHANGE); }
Source:
public void tearDown() throws Exception { START setAutoBuildEnabled(true); END ValidationFramework.getDefault().suspendAllValidation(false); JobUtils.waitForIdle(100); ServerCreationTestUtils.deleteAllServersAndRuntimes(); ProjectUtility.deleteAllProjects(); ASMatrixTests.clearStateLocation(); JobUtils.waitForIdle(); } no, you need to capture the autobuild state during setup and restore it during teardown

Target:
public void tearDown() throws Exception { JobUtils.waitForIdle(100); ServerCreationTestUtils.deleteAllServersAndRuntimes(); ProjectUtility.deleteAllProjects(); ASMatrixTests.clearStateLocation(); JobUtils.waitForIdle(); }
Source:
public byte[] getCacheKey() { byte[] previousStopBytes = previousStop == null ? new byte[]{} : StringUtils.toUtf8(previousStop); START byte[] orderingBytes = StringUtils.toUtf8(ordering.toString()); END int totalLen = 2 + previousStopBytes.length + orderingBytes.length; return ByteBuffer.allocate(totalLen) .put(CACHE_TYPE_ID) .put(previousStopBytes) .put(STRING_SEPARATOR) .put(orderingBytes) .array(); } I think this line means that StringComparator needs a getCacheKey method.

Target:
public byte[] getCacheKey() { byte[] previousStopBytes = previousStop == null ? new byte[]{} : StringUtils.toUtf8(previousStop); byte[] orderingBytes = ordering.getCacheKey(); int totalLen = 2 + previousStopBytes.length + orderingBytes.length; return ByteBuffer.allocate(totalLen) .put(CACHE_TYPE_ID) .put(previousStopBytes) .put(STRING_SEPARATOR) .put(orderingBytes) .array(); }
Source:
public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this.consumerProperties = consumerProperties; this.sortingMapper = sortingMapper; this.consumer = getKafkaConsumer(); START this.closed = false; END this.records = new LinkedBlockingQueue<>(); } Technically setting closed = false isn't needed since this is the default for a boolean

Target:
public KafkaRecordSupplier( Map<String, Object> consumerProperties, ObjectMapper sortingMapper ) { this.consumerProperties = consumerProperties; this.sortingMapper = sortingMapper; this.consumer = getKafkaConsumer(); }
Source:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; START java.time.Instant instant = java.time.Instant.ofEpochMilli(timestamp - (timestamp % groupByInterval)); END out.value = instant.toEpochMilli(); } Looks like creating `Instant` here may be also omitted.

Target:
public void eval() { // Get the timestamp in milliseconds long timestamp = inputDate.value; // Get the interval in milliseconds long groupByInterval = interval.value; out.value = (timestamp - (timestamp % groupByInterval)); }
Source:
public V process(Map.Entry<K, V> entry) { action.accept(entry.getKey(), entry.getValue()); START return entry.getValue(); END } Since `forEach` doesn't use these values, maybe we can avoid sending them back to the caller by simply returning `null`.

Target:
public V process(Map.Entry<K, V> entry) { action.accept(entry.getKey(), entry.getValue()); return null; }
Source:
private ProjectControl user(AccountGroup.Id... memberOf) { RefControl.Factory refControlFactory = new RefControl.Factory() { @Override public RefControl create(final ProjectControl projectControl, final String ref) { START return new RefControl(systemConfig, projectControl, ref, null); END } }; return new ProjectControl(Collections.<AccountGroup.Id> emptySet(), Collections.<AccountGroup.Id> emptySet(), refControlFactory, new MockUser(memberOf), newProjectState()); } Please implement a mock version of the RegExpCache using a normal HashMap.

Target:
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); } }; return new ProjectControl(systemConfig, Collections.<AccountGroup.Id> emptySet(), Collections.<AccountGroup.Id> emptySet(), refControlFactory, new MockUser(memberOf), newProjectState()); }
Source:
private boolean executeBatch( BoltConnection connection ) { Thread currentThread = Thread.currentThread(); String originalName = currentThread.getName(); START String newName = String.format( "%s [%s] ", originalName, connection.remoteAddress(), connector ); END currentThread.setName( newName ); try { return connection.processNextBatch(); } finally { currentThread.setName( originalName ); } } Pattern does not match the arguments

Target:
private boolean executeBatch( BoltConnection connection ) { Thread currentThread = Thread.currentThread(); String originalName = currentThread.getName(); String newName = String.format( "%s [%s] ", originalName, connection.remoteAddress() ); currentThread.setName( newName ); try { return connection.processNextBatch(); } finally { currentThread.setName( originalName ); } }
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); } START if (!validateVmPoolProperties()) { END return false; } return validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface()); } return true; } Why is it needed here if it's already called from line 176? Not to mention that in the CDA it's run twice

Target:
protected boolean validateCanUpdateReadOnly(DiskValidator diskValidator) { if (updateReadOnlyRequested()) { if(getVm().getStatus() != VMStatus.Down && vmDeviceForVm.getIsPlugged()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); } return validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface()); } return true; }
Source:
public TmfEdge(TmfVertex from, TmfVertex to) { this.fVertexFrom = from; START this.fVertexTo = to; END this.fType = EdgeType.DEFAULT; } while you're at it, you can remove the thises.

Target:
public TmfEdge(TmfVertex from, TmfVertex to) { fVertexFrom = from; fVertexTo = to; fType = EdgeType.DEFAULT; }
Source:
public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; WorkProcessor<Page> resultPages = getSortedPages( new SimplePageWithPositionComparator(sourceTypes, sortChannels, sortOrder)); START resultPages.process(); END sortedPages = resultPages.iterator(); } } remove `resultPages.process()` -- `resultPages.iterator()` calls `process` and `getResult` as appropriate

Target:
public void finish() { if (state == State.NEEDS_INPUT) { state = State.HAS_OUTPUT; WorkProcessor<Page> resultPages = getSortedPages( new SimplePageWithPositionComparator(sourceTypes, sortChannels, sortOrder)); sortedPages = resultPages.iterator(); } }
Source:
public void exit() { START super.exit(); END removeMessages(BREDR_STOP_TIMEOUT); } Should this be called at the end of child class' exit() method?

Target:
public void exit() { removeMessages(BREDR_STOP_TIMEOUT); super.exit(); }
Source:
public ActualProperties build() { START List<LocalProperty<Symbol>> localProperties = unordered ? filteredCopy(this.localProperties, property -> !property.isOrderSensitive()) : this.localProperties; END return new ActualProperties(global, localProperties, constants); } 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); ```

Target:
public ActualProperties build() { List<LocalProperty<Symbol>> localProperties = this.localProperties; if (unordered) { localProperties = filteredCopy(this.localProperties, property -> !property.isOrderSensitive()); } return new ActualProperties(global, localProperties, constants); }
Source:
public String getHeader(CharSequence headerName) { START return headers().get(headerName.toString()); END } why toString() ?

Target:
public String getHeader(CharSequence headerName) { return headers().get(headerName); }
Source:
START public synchronized Uri insert(Uri uri, ContentValues initialValues) { END 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; } } Why are you synchronizing on "this" here if you are synchronizing on the lock below?

Target:
public 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; } }
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}); START IFilesystemController controller = getFilesystemController(); END boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(getServer()); if( useAS7Behavior) { DeploymentMarkerUtils.removedDeployedMarker(archiveDestination, controller); DeploymentMarkerUtils.removedDeployFailedMarker(archiveDestination, controller); } } catch(CoreException ce) { JBossServerCorePlugin.log(ce); } } you only need the controller inside the if block :-)

Target:
protected void completeRemoval(IModule m) { try { IPath archiveDestination = getModuleDeployRoot(new IModule[]{m}); boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(getServer()); // AS7-derived requires the .deployed markers to be removed. Other servers require no action if( useAS7Behavior) { IFilesystemController controller = getFilesystemController(); DeploymentMarkerUtils.removedDeployedMarker(archiveDestination, controller); DeploymentMarkerUtils.removedDeployFailedMarker(archiveDestination, controller); } } catch(CoreException ce) { JBossServerCorePlugin.log(ce); } }
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/" START + "InputMainViolationsForGoogleXpathSuppressions.xml"); END 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("")); } Why can't `getPath` be used instead?

Target:
public void testViolationsByGoogleAndXpathSuppressions(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws Exception { System.setProperty("org.checkstyle.google.suppressionxpathfilter.config", getPath("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("")); }
Source:
private static Map<String, String> asMap(final KeyValueStore<String, String> store) { final HashMap<String, String> result = new HashMap<>(); store.all().forEachRemaining(kv -> { START System.out.println(kv); END result.put(kv.key, kv.value); }); return result; } Did you mean to remove this println?

Target:
private static Map<String, String> asMap(final KeyValueStore<String, String> store) { final HashMap<String, String> result = new HashMap<>(); store.all().forEachRemaining(kv -> result.put(kv.key, kv.value)); return result; }
Source:
public Attribute createAttribute(HttpRequest request, String name, long definedSize) { START Attribute attribute; END 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; } nit: make this final

Target:
public Attribute createAttribute(HttpRequest request, String name, long definedSize) { final 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; }
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(); } START if (dateActivated == null || !isActivated(checkDate) || dateStopped == null) { END return false; } return checkDate.after(dateStopped); } isActivated() already checks if dateActivated == null, so you don't need to check if it is null again here

Target:
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 (!isActivated(checkDate) || dateStopped == null) { return false; } return checkDate.after(dateStopped); }
Source:
private void operationExecuted(MatchingFrame frame) { START if (!adapters.isEmpty()) for END (ILocalSearchAdapter adapter : adapters) { adapter.operationExecuted(this, frame); } } For readability reasons, please add braces.

Target:
private void operationExecuted(MatchingFrame frame) { if (!adapters.isEmpty()){ for (ILocalSearchAdapter adapter : adapters) { adapter.operationExecuted(this, frame); } } }
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(); START event.stopPropagation(); END } 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.)

Target:
public void onClick(ClickEvent event) { event.preventDefault(); event.stopPropagation(); 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(); } }
Source:
START public void setLevel(LogLevel level) throws IllegalStateException { END 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()); } For consistency, we have never declared to throw IllegalStateException for null checking. I think we should remove it for consistency.

Target:
public void setLevel(LogLevel level) { 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()); }
Source:
START public synchronized Long getLogTail() { END return logMetadata.getGlobalTail(); } please use `long` don't need to wrap and unwrap the primitive value

Target:
public synchronized long getLogTail() { return logMetadata.getGlobalTail(); }
Source:
public FilteringXmlStreamWriter(XMLStreamWriter writer, String encoding) { this.writer = writer; START this.encoding = encoding != null ? encoding.toUpperCase() : null; END } Could you please explain why we would need to store it upper case please ?

Target:
public FilteringXmlStreamWriter(XMLStreamWriter writer, String encoding) { this.writer = writer; this.encoding = encoding; }
Source:
public String getPropertyString() { START return ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + ""; END } Use String.valueOf() here instead of appending an empty string

Target:
public String getPropertyString() { return String.valueOf(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()); }
Source:
public static Object[][] interstitialOasis() { return new Object[][]{ { new Page("project43", "SyntheticTests/Slots/InvisibleHighImpact/Interstitial"), START "#INVISIBLE_HIGH_IMPACT_2 .provider-container iframe", END new Dimension(728, 90) }, }; } I believe we can have the same selector on mobile and desktop. Please use: `.invisible-high-impact-wrapper.interstitial .provider-container iframe`

Target:
public static Object[][] interstitialOasis() { return new Object[][]{ { new Page("project43", "SyntheticTests/Slots/InvisibleHighImpact/Interstitial"), new Dimension(728, 90) }, }; }
Source:
protected CaseInsensitiveMap(final Map<String, VALUE> underlyingMap) { START this.underlyingMap = underlyingMap; END } 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.

Target:
private CaseInsensitiveMap(final Map<String, VALUE> underlyingMap) { this.underlyingMap = underlyingMap; }
Source:
public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { START return (readPending && maybeMoreDataToRead()) || delegate.continueReading(maybeMoreDataSupplier); END } 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`).

Target:
public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) { return delegate.continueReading(maybeMoreDataSupplier); }
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) { START double ncloc = context.getMeasure(resource, CoreMetrics.NCLOC).getValue(); END context.saveMeasure(resource, getZeroCoverageLineHitsDataMetric(resource, context)); context.saveMeasure(resource, linesToCoverMetric, ncloc); context.saveMeasure(resource, uncoveredLinesMetric, ncloc); } } @pynicolas why `context.getMeasure(resource, CoreMetrics.NCLOC)` again?

Target:
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 = nclocMeasure.getValue(); context.saveMeasure(resource, getZeroCoverageLineHitsDataMetric(resource, context)); context.saveMeasure(resource, linesToCoverMetric, ncloc); context.saveMeasure(resource, uncoveredLinesMetric, ncloc); } }
Source:
CorsConfiguration findCorsConfiguration(String lookupPath) { ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath)); START if (resource != null) { END return createConfiguration( repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()); } return null; } Ternary if?

Target:
CorsConfiguration findCorsConfiguration(String lookupPath) { ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath)); return resource != null ? createConfiguration( repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()) : null; }
Source:
public void setUp() { fixture = new AggregateTestFixture<>(AnnotatedAggregate.class); mockCommandTargetResolver = mock(CommandTargetResolver.class); START END } Super nit: being nit-picky here, but this empty line is not necessary I think.

Target:
public void setUp() { fixture = new AggregateTestFixture<>(AnnotatedAggregate.class); }
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) { START if (!innerComposite.isDisposed()) { END doClearControls(); return false; } return true; } return false; } Is that really possible here given that the button is not disposed?

Target:
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) { doClearControls(); return true; } return false; }
Source:
public Void apply(KVariable k) { START hasConfigVar = true; END return null; } why was this done?

Target:
public void apply(KVariable k) { hasConfigVar = true; }
Source:
public boolean willEnter(Object request, Object target) { int modifierKeys = START 0; END if (request instanceof SelectionRequest) { modifierKeys = ((SelectionRequest) request).getModifiers(); } else if (request instanceof MouseEvent) { modifierKeys = ((MouseEvent) request).stateMask; } return (modifierKeys == SWT.CONTROL + SWT.SHIFT); } What's the meaning of 0 ?

Target:
public boolean willEnter(Object request, Object target) { int modifierKeys = SWT.NONE; if (request instanceof SelectionRequest) { modifierKeys = ((SelectionRequest) request).getModifiers(); } else if (request instanceof MouseEvent) { modifierKeys = ((MouseEvent) request).stateMask; } return (modifierKeys == SWT.CONTROL + SWT.SHIFT); }
Source:
public Object fromStorage(Object stored) { START checkConverters(); END if (stored == null) return null; return encoder.fromStorage(wrapper.unwrap(stored)); } I would check first if the value is null

Target:
public Object fromStorage(Object stored) { if (stored == null) return null; checkConverters(); return encoder.fromStorage(wrapper.unwrap(stored)); }
Source:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { START List<ScalarImplementationChoice> implementationChoices = new ArrayList<>(); END for (PolymorphicScalarFunctionChoice choice : choices) { implementationChoices.add(getScalarFunctionImplementationChoice(boundVariables, typeManager, functionRegistry, choice)); } return new ScalarFunctionImplementation(implementationChoices, deterministic); } You can use ImmutableList.builder().

Target:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { ImmutableList.Builder<ScalarImplementationChoice> implementationChoices = ImmutableList.builder(); for (PolymorphicScalarFunctionChoice choice : choices) { implementationChoices.add(getScalarFunctionImplementationChoice(boundVariables, typeManager, functionRegistry, choice)); } return new ScalarFunctionImplementation(implementationChoices.build(), deterministic); }
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(); START return null != arg0 ? type : DataTypes.UNDEFINED.getName(); END } I think even in the `null` case we can return the type, see: ``` select pg_typeof(null::bigint); pg_typeof ----------- bigint ```

Target:
public final String evaluate(TransactionContext txnCtx, Input<Object>... args) { assert args.length == 1 : "typeof expects exactly 1 argument, got: " + args.length; return type; }
Source:
public Document getInnerDocument() { IRubyObject innerDocument = getRubyProperty("inner_document"); if (innerDocument.isNil()) return null; START return (Document) NodeConverter.createASTNode(innerDocument); END } 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.

Target:
public Document getInnerDocument() { IRubyObject innerDocument = getRubyProperty("inner_document"); if (innerDocument.isNil()) { return null; } return (Document) NodeConverter.createASTNode(innerDocument); }
Source:
private Callback<Long> fetchStitchRequestBodyCallback(CopyingAsyncWritableChannel channel, BlobInfo blobInfo) { return buildCallback(frontendMetrics.postReadStitchRequestMetrics, bytesRead -> router.stitchBlob(blobInfo.getBlobProperties(), blobInfo.getUserMetadata(), START getChunksToStitch(blobInfo.getBlobProperties(), FrontendUtils.readJsonFromChannel(channel)), END routerStitchBlobCallback(blobInfo)), uri, LOGGER, finalCallback); } FrontendUtils is already imported at the beginning, looks like we can directly use `readJsonFromChannel` here.

Target:
private Callback<Long> fetchStitchRequestBodyCallback(CopyingAsyncWritableChannel channel, BlobInfo blobInfo) { return buildCallback(frontendMetrics.postReadStitchRequestMetrics, bytesRead -> router.stitchBlob(blobInfo.getBlobProperties(), blobInfo.getUserMetadata(), getChunksToStitch(blobInfo.getBlobProperties(), readJsonFromChannel(channel)), routerStitchBlobCallback(blobInfo)), uri, LOGGER, finalCallback); }
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()); START assertEquals("ephemeral_key", resource.getObject()); END } why not use stripe-mock?

Target:
public void testDeserialize() throws Exception { final String json = getResourceAsString("/api_fixtures/ephemeral_key.json"); final EphemeralKey resource = APIResource.GSON.fromJson(json, EphemeralKey.class); assertNotNull(resource); assertEquals("ephkey_123", resource.getId()); assertEquals("ephemeral_key", resource.getObject()); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; START throw new RuntimeException("Only one PropertiesModule may be installed"); END } Log the conflicting classes found for easier tracking.

Target:
public boolean equals(Object obj) { // equals() is used by Guice to dedup multiple installs. This is module has state so we only // allow one instance of it to ever be installed. This equals() implementation // forces guice to dedup as long as it is the same exact object. Installing multiple // PropertiesPropertySource instances will result in duplicate binding errors for PropertySource // where the errors will provide details about where the multiple installs came from. return this == obj; }
Source:
public void send(Message<?> message, ScopeDescriptor scopeDescription) throws Exception { if (canResolve(scopeDescription)) { String aggregateIdentifier = ((AggregateScopeDescriptor) scopeDescription).getIdentifier().toString(); Aggregate<T> aggregate = load(aggregateIdentifier); START if (aggregate != null) { END aggregate.handle(message); } else { logger.debug("Aggregate (with id: [{}]) cannot be loaded. Hence, message '[{}]' cannot be handled.", aggregateIdentifier, message); } } } 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.

Target:
public void send(Message<?> message, ScopeDescriptor scopeDescription) throws Exception { if (canResolve(scopeDescription)) { String aggregateIdentifier = ((AggregateScopeDescriptor) scopeDescription).getIdentifier().toString(); load(aggregateIdentifier).handle(message); } }
Source:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() START && vdsGroup.getcompatibility_version() != null END && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); } Minor - Version's compareTo does a null check, so you may not need the vdsGroup.getcompatibility_version() != null

Target:
protected void UpdateDetailsAvailability() { super.UpdateDetailsAvailability(); VDSGroup vdsGroup = (VDSGroup) getSelectedItem(); getClusterServiceModel().setIsAvailable(vdsGroup != null && vdsGroup.supportsGlusterService() && Version.v3_2.compareTo(vdsGroup.getcompatibility_version()) <= 0); }
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); } START this.generateDroolsTestOnError = generateDroolsTestOnError; END } 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

Target:
public void setGenerateDroolsTestOnError(Boolean generateDroolsTestOnError) { this.generateDroolsTestOnError = generateDroolsTestOnError; }
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; } START return null; END } You could save a few lines by moving the return null into the default case instead of break.

Target:
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: return null; } }
Source:
protected boolean shouldSkipCommandExecution() { START return StringUtils.equals(getVm().getCurrentCd(), getParameters().getCdImagePath()); END } 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

Target:
protected boolean shouldSkipCommandExecution() { if (getVm() == null) { return false; } return StringUtils.equals(getVm().getCurrentCd(), getParameters().getCdImagePath()); }
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; } START TimeUnit.SECONDS.sleep(5); END } return false; } ``` 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) { ```

Target:
public static boolean verifyOozieJobStatus(OozieClient client, String processName, ENTITY_TYPE entityType, Job.Status expectedStatus) throws OozieClientException, InterruptedException { for (int seconds = 0; seconds < 100; seconds+=5) { Job.Status status = getOozieJobStatus(client, processName, entityType); logger.info("Current status: " + status); if (status == expectedStatus) { return true; } TimeUnit.SECONDS.sleep(5); } return false; }
Source:
public void init() throws KalturaManagerException { START KalturaEventsManager.registerEventConsumer(this, KalturaEventType.STREAM_PUBLISHED, KalturaEventType.STREAM_UNPUBLISHED, KalturaMediaEventType.APPLICATION_INSTANCE_STARTED); END liveManager = KalturaServer.getManager(ILiveManager.class); setInitialized(); } You forgot to call super.init()

Target:
public void init() throws KalturaManagerException { super.init(); KalturaEventsManager.registerEventConsumer(this, KalturaEventType.STREAM_PUBLISHED, KalturaEventType.STREAM_UNPUBLISHED, KalturaMediaEventType.APPLICATION_INSTANCE_STARTED); liveManager = KalturaServer.getManager(ILiveManager.class); setInitialized(); }
Source:
public static final void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } for (Group altG : group.getAltLocs()) { START for (Atom atom : altG.getAtoms()) { END transform(atom, m); } } } Recursive call to `transform(g, m)` could also be possible here.

Target:
public static final void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } for (Group altG : group.getAltLocs()) { transform(altG, m); } }
Source:
public void updateReviewItem(ChangeInfo task) { START fReviewList.put(task.getChange_id(), task); //Here we keep the change_id because it is shown to the user END } Here we use it as the same key as we use to create the fReviewList

Target:
public void updateReviewItem(ChangeInfo task) { fReviewList.put(task.getId(), task); }
Source:
public static Protocol fromValue(String value) { START Protocol[] items = Protocol.values(); END for (Protocol item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return (Protocol) GetEnumValue.fromValueOrDefault(value, UNRECOGNIZED); } 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);

Target:
public static Protocol fromValue(String value) { 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) { START Map<KeyExtent,List<Range>> tablets = binnedRanges.computeIfAbsent(location, k -> new HashMap<>()); List<Range> tabletsRanges = tablets.computeIfAbsent(ke, k -> new ArrayList<>()); END tabletsRanges.add(range); } These look like they can simplify to: ```java binnedRanges.computeIfAbsent(location, k -> new HashMap<>()) .computeIfAbsent(ke, k -> new ArrayList<>()) .add(range); ```

Target:
protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { binnedRanges.computeIfAbsent(location, k -> new HashMap<>()) .computeIfAbsent(ke, k -> new ArrayList<>()).add(range); }