auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void getChildCollection_shouldThrowAPIExceptionIfGetterMethodNotFound() throws Exception { ClassWithBadGetter oo = new ClassWithBadGetter(); oo.setMyLocations(new HashSet<>()); START Assertions.assertThrows(APIException.class,() ->RequiredDataAdvice.getChildCollection(oo, ClassWithBadGetter.class.getDeclaredField("locations"))); END } also a tiny thing, but sometimes you miss a whitespace after the `->`

Target:
public void getChildCollection_shouldThrowAPIExceptionIfGetterMethodNotFound() throws Exception { ClassWithBadGetter oo = new ClassWithBadGetter(); oo.setMyLocations(new HashSet<>()); RequiredDataAdvice.getChildCollection(oo, ClassWithBadGetter.class.getDeclaredField("locations")); }
Source:
protected void configure() { START DynamicSet.setOf(binder(), CacheRemovalListener.class); END install(new FactoryModule() { @Override protected void configure() { factory(ForwardingRemovalListener.Factory.class); } }); bind(DefaultCacheFactory.class); bind(MemoryCacheFactory.class).to(DefaultCacheFactory.class); bind(PersistentCacheFactory.class).to(H2CacheFactory.class); listener().to(H2CacheFactory.class); } This should be declared in GerritGlobalModule.

Target:
protected void configure() { install(new FactoryModule() { @Override protected void configure() { factory(ForwardingRemovalListener.Factory.class); } }); bind(DefaultCacheFactory.class); bind(MemoryCacheFactory.class).to(DefaultCacheFactory.class); bind(PersistentCacheFactory.class).to(H2CacheFactory.class); listener().to(H2CacheFactory.class); }
Source:
private void createDisabledImage() { START if (this.disabledImage != null && !this.disabledImage.isDisposed()) END disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); } This doesn't seem right: we're building `disabledImage` from `image`, so we need to check that `image` has not been disabled. I think something like the following? if (this.image != null && !this.image.isDisposed()) { if (this.disabledImage != null && !this.disabledImage.isDisposed()) { this.disabledImage.dispose(); } disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }

Target:
private void createDisabledImage() { // Only create a new disabledImage when the disabledImage==null or // disposed to avoid a GDI Handler leak See Bug 486531 if (this.disabledImage == null || this.disabledImage.isDisposed()) if (this.image != null && !this.image.isDisposed()) disabledImage = new Image(this.image.getDevice(), this.image, SWT.IMAGE_DISABLE); }
Source:
public synchronized void releaseSample(DecoderInputBuffer sample) { START sample.data.clear(); END mSamplePool.offerLast(sample); } Should probably be sample.clear().

Target:
public synchronized void releaseSample(DecoderInputBuffer sample) { sample.clear(); mSamplePool.offerLast(sample); }
Source:
private String buildClipboardMessage(Row row) { START StringBuilder builder = new StringBuilder(); END builder.append(row.getLevel()) .append(", ") .append(row.getMessage()); return builder.toString(); } Looks like this builder just concatenate 3 strings without any loops. I guess, it is unnecessary here.

Target:
private String buildClipboardMessage(Row row) { return row.getLevel() + ", " + row.getMessage(); }
Source:
START public RepositoryObject getParent() { END return driver.getParentObject(this); } Since a Tombstone is no longer in the hierarchy (result of removing the proxy), this method should probably either return a null or throw an exception

Target:
public RepositoryObject getParent() { // tombstone is not in the hierarchy, so doesn't have a parent return null; }
Source:
private void setLastUsedBranch() { String lastBranch = settings.get(lastBranchKey); START if (lastBranch != null) { END branchText.setText(lastBranch); } } no braces here, more occurrences in this file

Target:
private void setLastUsedBranch() { String lastBranch = settings.get(lastBranchKey); if (lastBranch != null) branchText.setText(lastBranch); }
Source:
public String toString() { return toStringHelper(this) .omitNullValues() START .add("equiCriteria", this.equiCriteria) END .add("filter", filter.orElse(null)) .toString(); } `this` is not needed?

Target:
public String toString() { return toStringHelper(this) .omitNullValues() .add("equiCriteria", equiCriteria) .add("filter", filter.orElse(null)) .toString(); }
Source:
private void validateKeyPatternsInConfig(Dictionary<String, ?> config) { Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_PLUGWISE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("Given plugwise-config-key '" + key START + "' does not follow the expected pattern '<PlugwiseId>.<mac|type|port|interval>'"); END continue; } } } Seems more appropriately `logger.warn`.

Target:
private void validateKeyPatternsInConfig(Dictionary<String, ?> config) { Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_PLUGWISE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.warn("Given plugwise-config-key '" + key + "' does not follow the expected pattern '<PlugwiseId>.<mac|type|port|interval>'"); continue; } } }
Source:
public Void visitFilter(FilterNode node, Void context) { START String expression = isExpression(node.getPredicate()) ? node.getPredicate().toString() : formatter.formatRowExpression(node.getPredicate()); END printNode(node, "Filter", expression, NODE_COLORS.get(NodeType.FILTER)); return node.getSource().accept(this, context); } `GraphvizPrinter` (and all other plan printer) should not expect an `Expression`. Rather than having `isExpression` here, let's fix the tests if they are failing.

Target:
public Void visitFilter(FilterNode node, Void context) { String expression = formatter.formatRowExpression(node.getPredicate()); printNode(node, "Filter", expression, NODE_COLORS.get(NodeType.FILTER)); return node.getSource().accept(this, context); }
Source:
public void run() { resetGlobalProgress(); indexingAll = true; for (ObjectType objectType : ObjectType.values()) { startIndexing(objectType); } try { sleep(pause); } catch (InterruptedException e) { START Thread.currentThread().interrupt(); END logger.error("Thread interrupted: " + e.getMessage()); } currentIndexState = ObjectType.NONE; indexingAll = false; pollingChannel.send(INDEXING_FINISHED_MESSAGE); } Move this line after logging the error, so in any case the error get logged.

Target:
public void run() { resetGlobalProgress(); indexingAll = true; for (ObjectType objectType : ObjectType.values()) { startIndexing(objectType); } try { sleep(pause); } catch (InterruptedException e) { logger.error("Thread interrupted: " + e.getMessage()); Thread.currentThread().interrupt(); } currentIndexState = ObjectType.NONE; indexingAll = false; pollingChannel.send(INDEXING_FINISHED_MESSAGE); }
Source:
public boolean isAC3() { START return getCodecA() != null && ("ac3".equals(getCodecA()) || "a52".equals(getCodecA()) || "liba52".equals(getCodecA())); END } `return getCodecA() != null && ("ac3".equals(getCodecA()) || "a52".contains(getCodecA()));`

Target:
public boolean isAC3() { return getCodecA() != null && ("ac3".equals(getCodecA()) || getCodecA().contains("a52")); }
Source:
ShardRewriter createShardRewriter( FileSystemContext fileSystemContext, FileSystem fileSystem, long transactionId, OptionalInt bucketNumber, UUID shardUuid, int shardRowCount, Optional<UUID> deltaShardUuid, boolean tableSupportsDeltaDelete, Map<String, Type> columns) { if (tableSupportsDeltaDelete) { return new DeltaShardRewriter( shardUuid, shardRowCount, deltaShardUuid, deletionExecutor, transactionId, bucketNumber, this, fileSystemContext, fileSystem); } START else { END return new InplaceShardRewriter( shardUuid, columns, deletionExecutor, transactionId, bucketNumber, nodeId, this, fileSystem, storageService, shardRecorder, backupManager); } } redundant

Target:
ShardRewriter createShardRewriter( FileSystemContext fileSystemContext, FileSystem fileSystem, long transactionId, OptionalInt bucketNumber, UUID shardUuid, int shardRowCount, Optional<UUID> deltaShardUuid, boolean tableSupportsDeltaDelete, Map<String, Type> columns) { if (tableSupportsDeltaDelete) { return new DeltaShardRewriter( shardUuid, shardRowCount, deltaShardUuid, deletionExecutor, transactionId, bucketNumber, this, fileSystemContext, fileSystem); } return new InplaceShardRewriter( shardUuid, columns, deletionExecutor, transactionId, bucketNumber, nodeId, this, fileSystem, storageService, shardRecorder, backupManager); }
Source:
public void init() { setLabel("Plugin"); addAttribute(ID, ROLE_ID).setLabel("Identifier"); addAttribute(LABEL, ROLE_LABEL, ROLE_LOOKUP).setNillable(false).setUnique(true).setLabel("Label"); START addAttribute(DESCRIPTION, ROLE_LOOKUP).setLabel("Description").setDataType(HTML); END } TEXT datatype would be more appropriate.

Target:
public void init() { setLabel("Plugin"); addAttribute(ID, ROLE_ID).setLabel("Identifier"); addAttribute(LABEL, ROLE_LABEL, ROLE_LOOKUP).setNillable(false).setUnique(true).setLabel("Label"); addAttribute(DESCRIPTION, ROLE_LOOKUP).setLabel("Description"); }
Source:
START @Override public Long call() throws IOException{ END String oldname = Thread.currentThread().getName(); Thread.currentThread().setName(oldname+"Decode-"+this.parent.columnChunkMetaData.toString()); this.parent.processPages(recordsToReadInThisPass); Thread.currentThread().setName(oldname); return recordsToReadInThisPass; } Space between IOException and {

Target:
@Override public Long call() throws IOException{ String oldname = Thread.currentThread().getName(); try { Thread.currentThread().setName(oldname + "Decode-" + this.parent.columnChunkMetaData.toString()); this.parent.processPages(recordsToReadInThisPass); return recordsToReadInThisPass; } finally { Thread.currentThread().setName(oldname); } }
Source:
public CompositeMetricsCollector(MetricsCollector... collectors) { START this.collectors = new ArrayList<>(asList(collectors)); END } Does additional list creation (`new ArrayList<>()`) provide any benefits when compared with the following? ```java this.collectors = asList(collectors); ```

Target:
public CompositeMetricsCollector(MetricsCollector... collectors) { this.collectors = asList(collectors); }
Source:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { loadContacts(); } else { START Toast.makeText(getApplicationContext(), "Read contacts permission denied", END Toast.LENGTH_LONG).show(); finish(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } to nitpick: just use `this` instead of the application.

Target:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { loadContacts(); } else { Toast.makeText(this, "Read contacts permission denied", Toast.LENGTH_LONG).show(); finish(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
Source:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB bgRGB) { StringBuilder fg= new StringBuilder(); appendColor(fg, fgRGB); StringBuilder bg= new StringBuilder(); appendColor(bg, bgRGB); START buffer.append("body {color:" + fg.toString() + "; background-color:" + bg.toString() + ";}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ END } I must be missing something. Why not simply buffer.append("body {color:"); appendColor(buffer, fgRGB); buffer.append("; background-color:"); appendColor(buffer, bgRGB); buffer.append(";}"); ?

Target:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB bgRGB) { StringBuilder fg= new StringBuilder(); appendColor(fg, fgRGB); StringBuilder bg= new StringBuilder(); appendColor(bg, bgRGB); buffer.append("body {color:"); //$NON-NLS-1$ appendColor(buffer, fgRGB); buffer.append("; background-color:"); //$NON-NLS-1$ appendColor(buffer, bgRGB); buffer.append(";}"); //$NON-NLS-1$ }
Source:
START public static synchronized VoltDBInterface instance() { END if (singleton == null) { singleton = new RealVoltDB(); } return singleton; } what .... synchronized access to the VoltDB instance not cool. it has transaction performance impact if you want to initialize without invoking the full thing we can do that without having to resource to this

Target:
public static VoltDBInterface instance() { return singleton; }
Source:
public int getRenderState() { int state = speed.ordinal(); if (getReverse()) state = 14; if (isPowered()) { if (getReverse()) state += 1; else state += 7; START } END return state; } You can simplify this by reordering the states.

Target:
public int getRenderState() { int state = speed.ordinal(); if (getReverse()) state = 4; if (isPowered()) state += 5; return state; }
Source:
public void ensureSettingsSavedShowsFormIfValidationFails() throws Exception { doAnswer(invocation -> { START Errors errors = (Errors) invocation.getArgument(1); END errors.rejectValue("absenceSettings", "error"); return null; }).when(settingsValidator).validate(any(), any()); perform(post("/web/settings")) .andExpect(view().name("settings/settings_form")); } Den cast auf (Errors) ist hier überflüssig.

Target:
public void ensureSettingsSavedShowsFormIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("absenceSettings", "error"); return null; }).when(settingsValidator).validate(any(), any()); perform(post("/web/settings")) .andExpect(view().name("settings/settings_form")); }
Source:
private String extractConnectionKey(final iOSVariant iOSVariant) { final StringBuilder sb = new StringBuilder() START .append(iOSVariant.getVariantID()) END .append(iOSVariant.isProduction() ? "-prod" : "-dev"); return sb.toString(); } I know this is not directly part of this PR, but this could be changed to `new StringBuilder(iOSVariant.getVariantID())` to avoid one useless `append` (the `StringBuilder()` constructor create StringBuilder with capacity 16, that we immediately expand with the next append)

Target:
private String extractConnectionKey(final iOSVariant iOSVariant) { final StringBuilder sb = new StringBuilder(iOSVariant.getVariantID()) .append(iOSVariant.isProduction() ? "-prod" : "-dev"); return sb.toString(); }
Source:
public void printCertificates() { DefaultTable table = new DefaultTable(); for (int i = 0; i < table.rowCount(); i++) { START System.out.println("On index " + i + " is : " + table.getItem(i).getText(1)); END } } Use logger instead for sysout for logging.

Target:
public void printCertificates() { DefaultTable table = new DefaultTable(); for (int i = 0; i < table.rowCount(); i++) { log.info("On index " + i + " is : " + table.getItem(i).getText(1)); } }
Source:
public void lockEdge() throws Exception { edgeLockTest(LockResource.LockMode.WRITE, LockResource.LockMode.READ, true); edgeLockTest(LockResource.LockMode.READ, LockResource.LockMode.WRITE, true); edgeLockTest(LockResource.LockMode.WRITE, LockResource.LockMode.WRITE, true); START edgeLockTest(LockResource.LockMode.READ, LockResource.LockMode.READ, false); END } can we revert back to using `LockMode.X` instead of `LockResource.LockMode.X`?

Target:
public void lockEdge() throws Exception { edgeLockTest(LockMode.WRITE, LockMode.READ, true); edgeLockTest(LockMode.READ, LockMode.WRITE, true); edgeLockTest(LockMode.WRITE, LockMode.WRITE, true); edgeLockTest(LockMode.READ, LockMode.READ, false); }
Source:
private String getClientId() { START return ( (ClientMessageBusImpl) clientMessageBus ).getClientId(); END } cast to busimpl should not be needed. getClientId is on the ClientMessageBus interface, no?

Target:
String getClientId() { return clientMessageBus.getClientId(); }
Source:
private void configureManagementNetwork() { final NetworkConfigurator networkConfigurator = new NetworkConfigurator(getVds()); if (networkConfigurator.awaitVdsmResponse()) { try { networkConfigurator.refreshNetworkConfiguration(); networkConfigurator.createManagementNetworkIfRequired(); } catch (VDSNetworkException e) { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host"); START } catch (VdsInstallException e) { END throw new VdsInstallException(VDSStatus.NonOperational, "Failed to configure manamgent network on the host"); } } else { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host"); } } Are you sure VdsInstallException is the right exception here?

Target:
private void configureManagementNetwork() { final NetworkConfigurator networkConfigurator = new NetworkConfigurator(getVds()); if (!networkConfigurator.awaitVdsmResponse()) { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host"); } try { networkConfigurator.refreshNetworkConfiguration(); networkConfigurator.createManagementNetworkIfRequired(); } catch (VDSNetworkException e) { throw new VdsInstallException(VDSStatus.NonResponsive, "Network error during communication with the host", e); } catch (Exception e) { throw new VdsInstallException(VDSStatus.NonOperational, "Failed to configure manamgent network on the host", e); } }
Source:
START public static Response newResetResponse(Header header) { return newRestartResponse(header, newNoServerError()); } END I think you forgot to change this to - `return newResetResponse(header, newNoServerError());`

Target:
public static Response newResetResponse(Header header) { return newResetResponse(header, newNoServerError()); }
Source:
START private static Optional<TimeValue> getTimeValue(Optional<TimeValue> primaryValue, Optional<TimeValue> safetyValue) { END if (!primaryValue.isPresent()) { return safetyValue; } return primaryValue; } Why does this need to be `static`?

Target:
private Optional<TimeValue> getTimeValue(Optional<TimeValue> primaryValue, Optional<TimeValue> safetyValue) { if (!primaryValue.isPresent()) { return safetyValue; } return primaryValue; }
Source:
public Uris(String scheme, String host) { this.scheme = scheme; this.host = host; this.port = 0; START this.rcnamespace = "0|120"; END } This should be a constant, not a magic string.

Target:
public Uris(String scheme, String host) { this.scheme = scheme; this.host = host; this.port = 0; }
Source:
private void carryOntoHistory(RevCommit c, int carry) { stack = null; for (;;) { carryOntoHistoryInnerLoop(c, carry); CarryStack s = stack; if (s != null) { START stack = s.prev; c = s.c; carry = s.carry; END continue; } break; } } can change the order to save a temp variable s.

Target:
private void carryOntoHistory(RevCommit c, int carry) { stack = null; for (;;) { carryOntoHistoryInnerLoop(c, carry); if (stack != null) { c = stack.c; carry = stack.carry; stack = stack.prev; continue; } break; } }
Source:
private FactHandle[] insertFacts(KieSession ksession, int n) { FactHandle[] fhs = new FactHandle[n]; for (int i = 0; i < n; i++) { fhs[i] = ksession.insert(i); START ksession.insert("" + String.valueOf(i)); END } return fhs; } Could be just ksession.insert(String.valueOf(i));

Target:
private FactHandle[] insertFacts(KieSession ksession, int n) { FactHandle[] fhs = new FactHandle[n]; for (int i = 0; i < n; i++) { fhs[i] = ksession.insert(i); ksession.insert(String.valueOf(i)); } return fhs; }
Source:
public SecureStore get() { START return injector.getInstance(getSecureStoreImpl()); END } This will create a new instance every time. Cache the instance in a member variable?

Target:
public SecureStore get() { if (instance == null) { instance = injector.getInstance(getSecureStoreImpl()); } return instance; }
Source:
protected void handleSwingDropTargetChanged(TreePath path, Transferable swingTransferable) { if (getUpdateSwingFromScoutLock().isAcquired()) { return; } // if (swingTransferable != null) { START if (getScoutObject() != null) { END final ITreeNode scoutNode = treePathToScoutNode(path); // notify Scout (asynchronous !) Runnable t = new Runnable() { @Override public void run() { getScoutObject().getUIFacade().fireNodeDropTargetChangedFromUI(scoutNode); } }; getSwingEnvironment().invokeScoutLater(t, 0); // end notify } } } if (swingTransferable != null && getScoutObject() != null) {...}

Target:
protected void handleSwingDropTargetChanged(TreePath path, Transferable swingTransferable) { if (getUpdateSwingFromScoutLock().isAcquired()) { return; } // if (swingTransferable != null && getScoutObject() != null) { final ITreeNode scoutNode = treePathToScoutNode(path); // notify Scout (asynchronous !) Runnable t = new Runnable() { @Override public void run() { getScoutObject().getUIFacade().fireNodeDropTargetChangedFromUI(scoutNode); } }; getSwingEnvironment().invokeScoutLater(t, 0); // end notify } }
Source:
START public void setDiskSpaceThreshold(float diskSpaceThreshold, float diskUsageWarnThreshold) { END validateThreshold(diskSpaceThreshold, diskUsageWarnThreshold); this.diskUsageThreshold = diskSpaceThreshold; this.diskUsageWarnThreshold = diskUsageWarnThreshold; } I don't see this called anywhere in the patch. Is there a reason to make it public?

Target:
void setDiskSpaceThreshold(float diskSpaceThreshold, float diskUsageWarnThreshold) { validateThreshold(diskSpaceThreshold, diskUsageWarnThreshold); this.diskUsageThreshold = diskSpaceThreshold; this.diskUsageWarnThreshold = diskUsageWarnThreshold; }
Source:
public static void setInstance(Object source, @MappingTarget Object target) { Integer level = LEVEL.get(); fireMethodCalled( level, "setInstance", source, target ); if ( level == null ) { LEVEL.set( 1 ); MAPPING.set( new IdentityHashMap<Object, Object>() ); } else { START LEVEL.set( level.intValue() + 1 ); END } MAPPING.get().put( source, target ); } not needed unboxing

Target:
public static void setInstance(Object source, @MappingTarget Object target) { Integer level = LEVEL.get(); fireMethodCalled( level, "setInstance", source, target ); if ( level == null ) { LEVEL.set( 1 ); MAPPING.set( new IdentityHashMap<Object, Object>() ); } else { LEVEL.set( level + 1 ); } MAPPING.get().put( source, target ); }
Source:
START public List<StandardPreset> getAllStandardPresets() throws MiddlewareQueryException { END return this.workbenchDataManager.getStandardPresetDAO().getAll(); } Remove throws MiddlewareQueryException

Target:
public List<StandardPreset> getAllStandardPresets() { return this.workbenchDataManager.getStandardPresetDAO().getAll(); }
Source:
protected void executeVDSCommand() { if (_vdsManager != null) { try { START _vdsManager.getLockObj().lock(); END executeVdsIdCommand(); } finally { _vdsManager.getLockObj().unlock(); } } else { executeVdsIdCommand(); } } why did you change this?

Target:
protected void executeVDSCommand() { if (_vdsManager != null) { synchronized (_vdsManager.getLockObj()) { executeVdsIdCommand(); } } else { executeVdsIdCommand(); } }
Source:
public void whenTemplateWithGivenInputTemplate_String_shouldRenderBlobAsIt() throws IOException { TemplateSourceDocument templateSrc = createTemplateSourceDoc("We are introducing ${myStringInCtxt} !", WEBVIEW_RENDITION); TemplateBasedDocument templateBase = createTemplateBasedDoc(templateSrc.getAdaptedDoc()); START List<TemplateInput> params = Arrays.asList( END factory("myStringInCtxt", StringValue, "Beautiful String") ); templateBase.saveParams(TEMPLATE_NAME, params, true); Blob result = templateBase.renderWithTemplate(TEMPLATE_NAME); assertNotNull(result); assertEquals("We are introducing Beautiful String !", result.getString()); } Could you use `List#of` or `Collections#singletonList`?

Target:
public void whenTemplateWithGivenInputTemplate_String_shouldRenderBlobAsIt() throws IOException { TemplateSourceDocument templateSrc = createTemplateSourceDoc("We are introducing ${myStringInCtxt} !", WEBVIEW_RENDITION); TemplateBasedDocument templateBase = createTemplateBasedDoc(templateSrc.getAdaptedDoc()); List<TemplateInput> params = List.of( factory("myStringInCtxt", StringValue, "Beautiful String") ); templateBase.saveParams(TEMPLATE_NAME, params, true); Blob result = templateBase.renderWithTemplate(TEMPLATE_NAME); assertNotNull(result); assertEquals("We are introducing Beautiful String !", result.getString()); }
Source:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { PDPrintStyle style = new PDPrintStyle(); START JSONObject stroke = JSONHelper.optJSONObject(oskariStyle, "stroke", () -> new JSONObject()); END setStrokeStyle(style, stroke); // polygon doesn't have cap style setLabelStyle(style, oskariStyle); style.setLineCap(LINE_CAP_STYLE.getOrDefault(JSONHelper.optString(stroke,"lineCap"), 0)); return style; } Wonder if this would work/read better if PDPrintStyle had the default values itself and we could just return early instead of creating new objects to make the rest of the code work properly.

Target:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { JSONObject stroke = oskariStyle.optJSONObject("stroke"); PDPrintStyle style = new PDPrintStyle(); setStrokeStyle(style, stroke); setLabelStyle(style, oskariStyle); return style; }
Source:
public static void init(Configuration conf) { if (!initDone) { DefaultConfiguration.conf = conf; DefaultConfiguration.initDone = true; START } END } All of the methods on this class should be `synchronized`. Otherwise this change looks good.

Target:
public static synchronized void init(Configuration conf) { if (!initDone) { DefaultConfiguration.conf = conf; DefaultConfiguration.initDone = true; } }
Source:
private void rollBackToTimestamp(long timestamp) { if (getVersionUnsafe() > timestamp) { try { rollbackObjectUnsafe(timestamp); // Rollback successfully got us to the right // version, we're done. START if (getVersionUnsafe() == timestamp) { END return; } } catch (NoRollbackException nre) { log.warn("Rollback[{}] to failed {}", this, timestamp, nre); resetUnsafe(); } } } We return even if this is false. Should we do something in the else case?

Target:
private void rollBackToTimestamp(long timestamp) { if (getVersionUnsafe() > timestamp) { try { rollbackObjectUnsafe(timestamp); } catch (NoRollbackException nre) { log.warn("Rollback[{}] to failed {}", this, timestamp, nre); resetUnsafe(); } } }
Source:
public void prepare(Properties options) { Objects.requireNonNull(mapper, "mapper can not be null"); Objects.requireNonNull(topicSelector, "topicSelector can not be null"); START producer = new KafkaProducer<K, V>(options); END } Nit: I think `new KafkaProducer<>(options)` will work here

Target:
public void prepare(Properties options) { Objects.requireNonNull(mapper, "mapper can not be null"); Objects.requireNonNull(topicSelector, "topicSelector can not be null"); producer = new KafkaProducer<>(options); }
Source:
protected Control createSWTControl(Composite parent) throws DatabindingFailedException { final Control control = super.createSWTControl(parent); START final ComposedAdapterFactory composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { END new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory); return control; } this must be disposed

Target:
protected Control createSWTControl(Composite parent) throws DatabindingFailedException { final Control control = super.createSWTControl(parent); composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] { new ReflectiveItemProviderAdapterFactory(), new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) }); adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory); return control; }
Source:
public boolean isRegistered(VeluxProduct product) { logger.trace("isRegistered(VeluxProduct {}) called.", product.toString()); if (product.isV2()) { return isRegistered(product.getSerialNumber()); START } else { END return isRegistered(product.getProductUniqueIndex()); } } `else` is redundant here.

Target:
public boolean isRegistered(VeluxProduct product) { logger.trace("isRegistered(VeluxProduct {}) called.", product.toString()); if (product.isV2()) { return isRegistered(product.getSerialNumber()); } return isRegistered(product.getProductUniqueIndex()); }
Source:
public void tearDown() throws Exception { FileUtils.deleteQuietly(nuxeoHome); // Restore or clear all the system properties manipulated by the current test START originSystemProps.forEach((key, originValue) -> { END if (originValue == null) { System.clearProperty(key); } else { System.setProperty(key, originValue); } }); originSystemProps.clear(); } You can call the value just `value`

Target:
public void tearDown() throws Exception { FileUtils.deleteQuietly(nuxeoHome); // Restore or clear all the system properties manipulated by the current test originSystemProps.forEach((key, value) -> { if (value == null) { System.clearProperty(key); } else { System.setProperty(key, value); } }); originSystemProps.clear(); }
Source:
private void checkDeployedProject(String projectName) { ServersView2 serversView = new ServersView2(); serversView.open(); ServerModule module = serversView.getServer(FULL_SERVER_NAME) .getModule(new RegexMatcher(".*" + projectName + ".*")); new WaitUntil(new ServerModuleHasState(module, ServerState.STARTED), TimePeriod.getCustom(30)); ModuleLabel moduleLabel = module.getLabel(); ServerState moduleState = moduleLabel.getState(); START assertTrue("Module has not been started!", moduleState == ServerState.STARTED); END } Are these two lines of definitions necessary? Isn't it shorter to just use module.getLabel().getState() in assert?

Target:
private void checkDeployedProject(String projectName) { ServersView2 serversView = new ServersView2(); serversView.open(); ServerModule module = serversView.getServer(FULL_SERVER_NAME) .getModule(new RegexMatcher(".*" + projectName + ".*")); new WaitUntil(new ServerModuleHasState(module, ServerState.STARTED), TimePeriod.getCustom(30)); ModuleLabel moduleLabel = module.getLabel(); assertTrue("Module has not been started!", moduleLabel.getState() == ServerState.STARTED); }
Source:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String room) { START return new StandardSlackService(baseUrl, teamDomain, null, authTokenCredentialId, botUser, room); END } Oh please, no! Don't ship a null object! :cry:

Target:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String room) { return new StandardSlackService(baseUrl, teamDomain, authTokenCredentialId, botUser, room); }
Source:
private boolean isAnnotationPresent(AnnotatedType annotatedType, Set<Annotation> processedAnnotations) { if ( annotatedType instanceof AnnotatedParameterizedType ) { for ( AnnotatedType type : ( (AnnotatedParameterizedType) annotatedType ).getAnnotatedActualTypeArguments() ) { if ( isAnnotationPresent( type, processedAnnotations ) ) { return true; } } } START if ( isAnnotationPresentIn( annotatedType.getDeclaredAnnotations(), processedAnnotations ) ) { END return true; } return false; } I would move this one first.

Target:
private boolean isAnnotationPresent(AnnotatedType annotatedType, Set<Annotation> processedAnnotations) { if ( isAnnotationPresentIn( annotatedType.getDeclaredAnnotations(), processedAnnotations ) ) { return true; } if ( annotatedType instanceof AnnotatedParameterizedType ) { for ( AnnotatedType type : ( (AnnotatedParameterizedType) annotatedType ).getAnnotatedActualTypeArguments() ) { if ( isAnnotationPresent( type, processedAnnotations ) ) { return true; } } } return false; }
Source:
static int staticFunc() { InvokeStatic f = new InvokeStatic() { // Noncompliant @Override START public String func(int n) { END unknown(); staticFunc(); return 0; } }; return f.func(); } int func();

Target:
static int staticFunc() { InvokeStatic f = new InvokeStatic() { // Noncompliant @Override public int func() { unknown(); staticFunc(); return 0; } }; return f.func(); }
Source:
private synchronized void resetGeneration() { this.generation = Generation.NO_GENERATION; rejoinNeeded = true; // only reset the state to un-joined when it is not already in rebalancing START if (state != MemberState.REBALANCING) END state = MemberState.UNJOINED; } But we are moving to UNJOINED anyway, so it won't affect the result right?

Target:
private synchronized void resetGeneration() { this.rejoinNeeded = true; this.generation = Generation.NO_GENERATION; }
Source:
public Path generateArtifact(URI uri, int size) throws IOException { START new NpmPackageGenerator(Paths.get(uri)); END buildPublishJson(); return getPackagePath(); } why you need this here?

Target:
public Path generateArtifact(URI uri, int size) throws IOException { buildPublishJson(); return getPackagePath(); }
Source:
public void nextTuple() { Utils.sleep(100); START Random rand = new Random(); END Integer value = rand.nextInt(1000); collector.emit(new Values(value)); } Minor nit, declaring a new Random each time is not really good practice.

Target:
public void nextTuple() { Utils.sleep(100); collector.emit(new Values(rand.nextInt(1000))); }
Source:
START public void register(final Class<?> clazz, final Object converter) { END otherWord = ""; } these 3 methods are `public` do you really need them?

Target:
private void register(final Class<?> clazz, final Object converter) { otherWord = ""; }
Source:
public void testMarkerOnLastLineNoNewline_495842() throws Exception { try(BufferedWriter writer = new BufferedWriter(new FileWriter(loadcode("", false)))) { writer.write(getAboveComment().trim()); } START PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, true); END indexFiles(); PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, false); String result = runQuickFixOneFile(); assertContainedIn("int func() { } // @suppress(\"No return\")", result); } Why are we setting it to true during indexing?

Target:
public void testMarkerOnLastLineNoNewline_495842() throws Exception { try(BufferedWriter writer = new BufferedWriter(new FileWriter(loadcode("", false)))) { writer.write(getAboveComment().trim()); } PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, false); indexFiles(); String result = runQuickFixOneFile(); PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.ENSURE_NEWLINE_AT_EOF, true); assertContainedIn("int func() { } // @suppress(\"No return\")", result); }
Source:
public void onLanguageTabSelected(String selectedLanguageCode) { START Log.e("####", "HERE"); END searchLanguageCode = selectedLanguageCode; startSearch(query, query != null && query.length() > 1); } What is the Log.e for?

Target:
public void onLanguageTabSelected(String selectedLanguageCode) { searchLanguageCode = selectedLanguageCode; startSearch(query, query != null && query.length() > 1); }
Source:
public T insert(SQLiteDatabase db, T entityAdapter, boolean isSyncAdapter) { START Log.d("Logging EntityProcessor", "before insert"); END T result = mDelegate.insert(db, entityAdapter, isSyncAdapter); Log.d("Logging EntityProcessor", "after insert on " + entityAdapter.id()); return result; } Move the tag to a constant?

Target:
public T insert(SQLiteDatabase db, T entityAdapter, boolean isSyncAdapter) { Log.d(TAG, "before insert"); T result = mDelegate.insert(db, entityAdapter, isSyncAdapter); Log.d(TAG, "after insert on " + entityAdapter.id()); return result; }
Source:
protected UfsStatus(UfsStatus status) { mIsDirectory = status.mIsDirectory; mName = status.mName; mOwner = status.mOwner; mGroup = status.mGroup; mMode = status.mMode; mLastModifiedTimeMs = status.mLastModifiedTimeMs; START mXAttr = status.mXAttr; END } This won't copy the map?

Target:
protected UfsStatus(UfsStatus status) { mIsDirectory = status.mIsDirectory; mName = status.mName; mOwner = status.mOwner; mGroup = status.mGroup; mMode = status.mMode; mLastModifiedTimeMs = status.mLastModifiedTimeMs; mXAttr = status.mXAttr == null ? null : new HashMap<>(status.mXAttr); }
Source:
boolean isProjectStyle() { if (myIsFrameworkStyle) { return false; } ProjectResourceRepository repository = ProjectResourceRepository.getProjectResources(myConfiguration.getModule(), true); assert repository != null : START repository.getDisplayName(); END return repository.hasResourceItem(ResourceType.STYLE, myStyleName); } if repository is null, this will throw an NPE.

Target:
boolean isProjectStyle() { if (myIsFrameworkStyle) { return false; } ProjectResourceRepository repository = ProjectResourceRepository.getProjectResources(myConfiguration.getModule(), true); assert repository != null : myConfiguration.getModule().getName(); return repository.hasResourceItem(ResourceType.STYLE, myStyleName); }
Source:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); START Context.clearCacheForCurrentUser(); END } Let's use @CacheEvict(value="userSearchLocales") public User saveUser(User user, String password) instead. We will get rid of CacheManager in Context as well. It would be better to evict just for the specified user, but our key consists of user and currentLocale. SaveUser is not called that often so invalidating all entries is no issue anyway.

Target:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); }
Source:
JarFileUtils(IPostProcessor processor, String xmlPathInJar, List<String> testNames) { this.processor = processor; this.xmlPathInJar = xmlPathInJar; //Ensure that dynamic list operations supported START this.testNames = (testNames == null ? null : new ArrayList<>(testNames)); END } You can revert this change because you don't need it in this specific class.

Target:
JarFileUtils(IPostProcessor processor, String xmlPathInJar, List<String> testNames) { this.processor = processor; this.xmlPathInJar = xmlPathInJar; this.testNames = testNames; }
Source:
public String resolve(String variable, String defaultValue) { IVariableResolver delegate = new ExpressionResolver.SystemPropertiesVariableResolver(); //ignoring argument here, as we want to fall back on the propertiesProvider. String result = delegate.resolve(variable, null); if (result == null) { try { START result = propertiesProvider.getValue(variable, defaultValue, new NullProgressMonitor()); END } catch (CoreException e) { throw new ExpressionResolutionException(e); } } return result; } will properties provider return the defaultValue in case of no network or value not found ?

Target:
public String resolve(String variable, String defaultValue) { IVariableResolver delegate = new ExpressionResolver.SystemPropertiesVariableResolver(); // ignoring default value first, as we want to fall back on the // propertiesProvider later. String result = delegate.resolve(variable, null); if (result == null) { result = propertiesProvider.getValue(variable, defaultValue); } return result; }
Source:
public static boolean isVirtIoScsiDiskInterfaceExists(VmBase vmBase) { if (vmBase.getImages().stream().anyMatch(i -> i.getDiskVmElementForVm(vmBase.getId()) .getDiskInterface() == DiskInterface.VirtIO_SCSI)) { return true; } START return false; END } you can simply return the result of anyMatch without the 'if' and 'return true/false' statements. imo, it would also be nicer to extract the "i -> i.getDiskVmElementForVm(vmBase.getId()).getDiskInterface() == DiskInterface.VirtIO_SCSI" part to a separate method "isVirtioScsiDisk" to make it easier to read

Target:
public static boolean isVirtIoScsiDiskInterfaceExists(VmBase vmBase) { return vmBase.getImages().stream().anyMatch(i -> i.getDiskVmElementForVm(vmBase.getId()) .getDiskInterface() == DiskInterface.VirtIO_SCSI); }
Source:
public void setContext(String context){ START typingRule.setContext(BloodTestContext.valueOf(context.replaceAll("\\s","").toUpperCase(Locale.FRENCH))); END } Is there a reason for using `Locale.FRENCH`? Also, why is it needed to remove all spaces? Are you just trying to do a `trim()`, or are you removing spaces between words?

Target:
public void setContext(String context){ typingRule.setContext(BloodTestContext.valueOf(context.replaceAll("\\s","").toUpperCase())); }
Source:
private String readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); try { return Util.read(is); } finally { if (is != null) { START is.close(); END } } } close already done in Util.read(..)

Target:
private String readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); return Util.read(is); }
Source:
protected void build(UnitVmModel frontend, VM backend) { START String name = (String) frontend.getName().getEntity(); END VmTemplate template = (VmTemplate) frontend.getTemplate().getSelectedItem(); backend.setVmtGuid(template.getId()); backend.setName(name); backend.setVmDescription((String) frontend.getDescription().getEntity()); backend.setCustomProperties(frontend.getCustomPropertySheet().getEntity()); } can be inlined

Target:
protected void build(UnitVmModel frontend, VM backend) { VmTemplate template = (VmTemplate) frontend.getTemplate().getSelectedItem(); backend.setVmtGuid(template.getId()); backend.setName((String) frontend.getName().getEntity()); backend.setVmDescription((String) frontend.getDescription().getEntity()); backend.setCustomProperties(frontend.getCustomPropertySheet().getEntity()); }
Source:
public void getAllDrugs_shouldReturnAListOfAllDrugs() throws Exception { int resultWhenTrue = 4; int resultWhenFalse = 2; List<Drug> allDrugs = conceptService.getAllDrugs(); assertEquals(resultWhenTrue, allDrugs.size()); START allDrugs = conceptService.getAllDrugs(false); END assertEquals(resultWhenFalse, allDrugs.size()); } @mavrk one test should only be for one method and one combination of parameters. and the goal is that every public method in the service layer is tested. so you should write tests for the methods * getAllDrugs() * getAllDrugs(includeRetired) and for the latter you need one test passing true and one passing false. another case is also what if there are no drugs will it return an empty list? I know this is tedious but thats because when this was written [TDD|https://en.wikipedia.org/wiki/Test-driven_development] which would start with tests wasnt used.

Target:
public void getAllDrugs_shouldReturnAListOfAllDrugs() throws Exception { int resultWhenTrue = 4; List<Drug> allDrugs = conceptService.getAllDrugs(); assertEquals(resultWhenTrue, allDrugs.size()); }
Source:
public List<BithumbTransactionHistoryResponse.BithumbTransactionHistory> getBithumbTrades( CurrencyPair currencyPair) throws IOException { START final BithumbResponse<List<BithumbTransactionHistoryResponse.BithumbTransactionHistory>> END transactionHistory = bithumb.transactionHistory(BithumbUtils.getBaseCurrency(currencyPair)); return transactionHistory.getData(); } those inner classes make reading all of this much worse

Target:
public List<BithumbTransactionHistory> getBithumbTrades(CurrencyPair currencyPair) throws IOException { final BithumbResponse<List<BithumbTransactionHistory>> transactionHistory = bithumb.transactionHistory(BithumbUtils.getBaseCurrency(currencyPair)); return transactionHistory.getData(); }
Source:
public void addChild(String name, Long id) { START if (mChildren.put(name, id) == null) { END mWeight.incrementAndGet(); } } `mChildren` could be `null`

Target:
public void addChild(String name, Long id) { if (mChildren != null && mChildren.put(name, id) == null) { mWeight.incrementAndGet(); } }
Source:
static void reTryKerberos(boolean enabled) { if (enabled) { log.debug("Try relogin kerberos at first!"); try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } catch (IOException e) { START log.error("Try relogin kerberos failed!"); END throw new RuntimeException(e); } } } nit: This will result in double logging

Target:
static void reTryKerberos(boolean enabled) { if (enabled) { log.debug("Try relogin kerberos at first!"); try { if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else if (UserGroupInformation.isLoginTicketBased()) { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
void resetLogic() { for (int i = 0; i < fieldSize; i++) START for (int j = 0; j < fieldSize; j++) fieldArray[i][j] = 0; END playerMark = CROSS_MARK; aIMark = ZERO_MARK; turn = 0; //first turn autoGameEnabled = false; } braces

Target:
void resetLogic() { for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) { fieldArray[i][j] = 0; } playerMark = CROSS_MARK; aIMark = ZERO_MARK; turn = 0; //first turn autoGameEnabled = false; }
Source:
protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return Stream.empty(); } else { START return Arrays.stream(list.split("[, \t\n\r\f]")).map(bundle::getEntry).filter(Objects::nonNull); END } } Could you replace `Arrays#stream` by `Stream#of` for consistency ?

Target:
protected Stream<URL> listBundleComponents(Bundle bundle) { String list = OSGiRuntimeService.getComponentsList(bundle); String name = bundle.getSymbolicName(); log.debug("PartialBundle: " + name + " components: " + list); if (list == null) { return Stream.empty(); } else { return Stream.of(list.split("[, \t\n\r\f]")).map(bundle::getEntry).filter(Objects::nonNull); } }
Source:
public void testLoadDataObjectsWithNonNullWorkspaceProject() { START assertTrue(dataObjectsService.loadDataObjects(workspaceProject).isEmpty()); END } Please use assertj assertion. In case of fail it gives error message explaining different list sizes. Current implementation will just print assertion error, expected true but was false with no reference to list size.

Target:
public void testLoadDataObjectsWithNonNullWorkspaceProject() { assertThat(dataObjectsService.loadDataObjects(workspaceProject)).isEmpty(); }
Source:
START public Graphics2D prepareImageRenderer(MapTransform mt, BufferedImage img, ProgressMonitor pm) { END Graphics2D g2 = img.createGraphics(); if (backgroundColor != null) { g2.setBackground(backgroundColor); g2.clearRect(0, 0, width, height); } ImageRenderer renderer = new ImageRenderer(); renderer.draw(mt, g2, width, height, rootLayer, pm); return g2; } Why this function is public ? It will be used outside of this class ?

Target:
private Graphics2D prepareImageRenderer(MapTransform mt, BufferedImage img, ProgressMonitor pm) { Graphics2D g2 = img.createGraphics(); if (backgroundColor != null) { g2.setBackground(backgroundColor); g2.clearRect(0, 0, width, height); } ImageRenderer renderer = new ImageRenderer(); renderer.draw(mt, g2, width, height, rootLayer, pm); return g2; }
Source:
public static void refreshResources(IResource[] resources, IProgressMonitor monitor) throws CoreException { try { SubMonitor progress = SubMonitor.convert(monitor, CoreText.ProjectUtil_refreshing, resources.length); for (IResource resource : resources) { if (progress.isCanceled()) break; resource.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); START progress.worked(1); END } } finally { monitor.done(); } } Not needed, delete.

Target:
public static void refreshResources(IResource[] resources, IProgressMonitor monitor) throws CoreException { try { SubMonitor progress = SubMonitor.convert(monitor, CoreText.ProjectUtil_refreshing, resources.length); for (IResource resource : resources) { if (progress.isCanceled()) break; resource.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } } finally { monitor.done(); } }