auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ItemStack getOveralls(Entity entity) { if (entity instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) entity); ItemStack pants = player.getItemStackFromSlot(EntityEquipmentSlot.LEGS); START if (pants != InvTools.emptyStack() && RailcraftItems.OVERALLS.isInstance(pants) && !((EntityPlayer) entity).capabilities.isCreativeMode) END return pants; } return InvTools.emptyStack(); } `!InvTools.isEmpty(pants)`

Target:
private ItemStack getOveralls(Entity entity) { if (entity instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) entity); ItemStack pants = player.getItemStackFromSlot(EntityEquipmentSlot.LEGS); if (!InvTools.isEmpty(pants) && RailcraftItems.OVERALLS.isInstance(pants) && !((EntityPlayer) entity).capabilities.isCreativeMode) return pants; } return InvTools.emptyStack(); }
Source:
public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { START ItemStack stack = trackKits.get(random.nextInt(trackKits.size())).getTrackKitItem(2); END if (stack == null) return; recipeList.add(new MerchantRecipe(stack, null, new ItemStack(Items.EMERALD, MathHelper.getRandomIntegerInRange(random, 1, 3)))); } This will crash if trackKits.size() == 0, which might be possible if everything is disabled.

Target:
public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { if (trackKits.size() == 0) return; ItemStack stack = trackKits.get(random.nextInt(trackKits.size())).getTrackKitItem(2); if (stack == null) return; recipeList.add(new MerchantRecipe(stack, null, new ItemStack(Items.EMERALD, MathHelper.getRandomIntegerInRange(random, 1, 3)))); }
Source:
public ItemIngot() { START super(Form.INGOT, true, true, CollectionTools.createIndexedLookupTable(STEEL, COPPER, TIN, BRONZE, LEAD, SILVER)); END setSmeltingExperience(1); } Add bronze to the end instead of in the middle.

Target:
public ItemIngot() { super(Form.INGOT, true, true, CollectionTools.createIndexedLookupTable(STEEL, COPPER, TIN, LEAD, SILVER, BRONZE)); setSmeltingExperience(1); }
Source:
protected void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); // Command block logic overrode this and the custom name is // somewhat set to the command block's name ("@") START compound.setString("CustomName", getCustomNameTag()); END } hasCustomNameTag()?

Target:
protected void writeEntityToNBT(NBTTagCompound compound) { super.writeEntityToNBT(compound); // Command block logic overrode this and the custom name is // somewhat set to the command block's name ("@") if (!getCustomNameTag().isEmpty()) { compound.setString("CustomName", getCustomNameTag()); } }
Source:
public void setFacing(@Nonnull EnumFacing facing) { TileSteamOven masterOven = (TileSteamOven) getMasterBlock(); if (masterOven != null) { START masterOven.facing = facing; END } this.facing = facing; WorldPlugin.setBlockState(worldObj, getPos(), getBlockState().withProperty(BlockMachineAlpha.FRONT, facing)); } I suspect they just ask the master

Target:
public void setFacing(@Nonnull EnumFacing facing) { TileSteamOven masterOven = (TileSteamOven) getMasterBlock(); if (masterOven != null) { masterOven.facing = facing; } this.facing = facing; }
Source:
START private static boolean isPrimitiveType(Type type) { END return (type instanceof Class) && ((Class)type).isPrimitive(); } You may be able to avoid compiler warnings about raw types by phrasing as: return type instanceof Class<?> && ((Class<?>) type).isPrimitive(); You can use the straight-wildcard form of a generic type in `instanceof` and casts without issue.

Target:
private static boolean isPrimitiveType(Type type) { return type instanceof Class<?> && ((Class<?>)type).isPrimitive(); }
Source:
static AssertionError counterexampleFound( String propertyName, START Object[] args, END long[] seeds, AssertionError e) { final String message = "Property named '%s' failed%s%n" + "With arguments: %s%n" + "Seeds for reproduction: %s"; return new AssertionError( String.format( message, propertyName, e.getMessage() == null ? ":" : " (" + e.getMessage() + "):", Arrays.deepToString(args), Arrays.toString(seeds)), e); } Certainly! I find that `final`-izing local vars and method parameters introduces noise into the code, and provides a benefit that I don't find very helpful (assurance that the values in question won't change). When coming into another code base that opts for marking these vars `final`, I'll gladly oblige. In junit-quickcheck and other personal projects of mine, I lean toward avoiding these declarations. I would likely lean on static analysis tools like FindBugs or Checkstyle to warn me of potentially confusing constructs where a local is getting modified a lot.

Target:
static AssertionError counterexampleFound( String propertyName, Object[] args, long[] seeds, AssertionError e) { String message = "Property named '%s' failed%s%n" + "With arguments: %s%n" + "Seeds for reproduction: %s"; return new AssertionError( String.format( message, propertyName, e.getMessage() == null ? ":" : " (" + e.getMessage() + "):", Arrays.deepToString(args), Arrays.toString(seeds)), e); }
Source:
@Test public void shrinkingMoreThanOnePropertyParameter() { assertThat( testResult(ShrinkingMoreThanOnePropertyParameter.class), hasSingleFailureContaining( START String.format("Shrunken args: [%s, %s]", new Foo(0), new Foo(1)))); END } In the pathological case, that could cause some issues. Consider a function that is not defined for 0 (that's why the author put the constraint), and a generator that always returns 0 as a shrink. In every failure case, shrinks will be useless.

Target:
@Test public void shrinkingMoreThanOnePropertyParameter() { assertThat( testResult(ShrinkingMoreThanOnePropertyParameter.class), hasSingleFailureContaining( String.format("Shrunken args: [%s, %s]", new Foo(1), new Foo(1)))); }
Source:
public Properties generate(SourceOfRandomness random, GenerationStatus status) { int size = status.size(); Properties properties = new Properties(); for (int i = 0; i < size; ++i) { properties.setProperty( START stringGenerator.generate(random, status), END stringGenerator.generate(random, status)); } return properties; } @brentvukmer Yeah, I'd prefer keeping both scope indent and long-line indent at four spaces. Thanks!

Target:
@Override public Properties generate(SourceOfRandomness random, GenerationStatus status) { int size = status.size(); Properties properties = new Properties(); for (int i = 0; i < size; ++i) { properties.setProperty( stringGenerator.generate(random, status), stringGenerator.generate(random, status)); } return properties; }
Source:
public String toString() { return "Capabilities{" START + "poolName='" + poolName + '\'' END + ", qosSupport='" + qosSupport + '\'' + ", allocatedCapacityGb='" + allocatedCapacityGb + '\'' + ", driverVersion='" + driverVersion + '\'' + ", freeCapacityGb='" + freeCapacityGb + '\'' + ", locationInfo='" + locationInfo + '\'' + ", timestamp='" + timestamp + '\'' + ", volumeBackendName='" + volumeBackendName + '\'' + ", totalCapacityGb='" + totalCapacityGb + '\'' + ", reservedPercentage='" + reservedPercentage + '\'' + ", vendorName='" + vendorName + '\'' + ", storageProtocol='" + storageProtocol + '\'' + ", extraSpecs='" + extraSpecs + '\'' + '}'; } The convention is to use ',' instead of '\'.

Target:
public String toString() { return "Capabilities{" + "poolName='" + poolName + ", qosSupport='" + qosSupport + ", allocatedCapacityGb='" + allocatedCapacityGb + ", driverVersion='" + driverVersion + ", freeCapacityGb='" + freeCapacityGb + ", locationInfo='" + locationInfo + ", timestamp='" + timestamp + ", volumeBackendName='" + volumeBackendName + ", totalCapacityGb='" + totalCapacityGb + ", reservedPercentage='" + reservedPercentage + ", vendorName='" + vendorName + ", storageProtocol='" + storageProtocol + ", extraSpecs='" + extraSpecs + '}'; }
Source:
START LazyIfNumber(List<LazyNumber> lazyParams) { END this.lazyParams = lazyParams; } Sorry, I missed this completely on my first review. Having a public class but a package-private constructor is slightly problematic from an API point of view. As it allows everyone to see the class, but not to use it. I'd suggest to make it `public` or the whole class `package-private`...but I'd need to do some more thinking about that one, so I'd go with `public`.

Target:
public LazyIfNumber(List<LazyNumber> lazyParams) { this.lazyParams = lazyParams; }
Source:
START public HashSet<Zoie<BoboIndexReader, ?>> getZoieSystems() END { return _core.getZoieSystems(); } is there a reason why we're changing from collection to hashset?

Target:
public Collection<Zoie<BoboIndexReader, ?>> getZoieSystems() { return _core.getZoieSystems(); }
Source:
public void testSimpleKafka() throws Exception{ START final StreamDataProvider<JSONObject> dataProvider = simpleKafkaGateway.buildDataProvider((DataSourceFilter)null, String.valueOf("0"), null, null); END BaseGatewayTestUtil.doTest(dataProvider); } What's the point of `String.valueOf("0")` ? Why not just `"0"` ?

Target:
public void testSimpleKafka() throws Exception{ final StreamDataProvider<JSONObject> dataProvider = simpleKafkaGateway.buildDataProvider((DataSourceFilter)null, "0", null, null); BaseGatewayTestUtil.doTest(dataProvider); }
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); if (queries != null) { for (Term q : queries) { buffer.append(q); buffer.append(","); } } buffer.append("^"); buffer.append(boost); START buffer.append("tieBraker:"); END buffer.append(tieBraker); return buffer.toString(); } this will be adjacent to the boost

Target:
public String toString() { StringBuilder builder = new StringBuilder(); if (queries != null) { for (Term q : queries) { builder.append(q).append(","); } } builder.append("^").append(boost).append("tieBraker:").append(tieBraker); return builder.toString(); }
Source:
public String toString() { START StringBuffer buffer = new StringBuffer(); END buffer.append(super.toString()); // for field buffer.append(":"); buffer.append(value == null ? "" : value); buffer.append("^"); buffer.append(boost); return buffer.toString(); } Use StringBuilder

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); // for field builder.append(value == null ? "" : value); builder.append("^").append(boost); return builder.toString(); }
Source:
public String toString() { START StringBuffer buffer = new StringBuffer(); END if (queries != null) { for (Term q : queries) { buffer.append(q).append(","); } } buffer.append("^").append(boost).append("tieBraker:").append(tieBraker); return buffer.toString(); } Use StringBuilder

Target:
public String toString() { StringBuilder builder = new StringBuilder(); if (queries != null) { for (Term q : queries) { builder.append(q).append(","); } } builder.append("^").append(boost).append("tieBraker:").append(tieBraker); return builder.toString(); }
Source:
START public JsonArray getTsnePlotMetaData(String experimentAccession) { END JsonObject result = new JsonObject(); result.add("metadata", getMetadata(experimentAccession)); return result.getAsJsonArray("metadata"); } What is this method actually doing? Why do you need to a create an JSON object, add something to it, then retrieve it immediately afterwards? What is the purpose of this intermediate step?

Target:
public JsonArray getTsnePlotMetaData(String experimentAccession) { return getMetadata(experimentAccession); }
Source:
void getTrackFile() throws Exception { this.mockMvc.perform(get(BASELINE_URL_TEMPLATE.format(new Object[] {"E-MTAB-5423", "g391"}))) .andExpect(status().isOk()) START .andReturn(); END } Again, probably out of scope for this PR, but I don't think these `andReturn()` statements are needed.

Target:
void getTrackFile() throws Exception { this.mockMvc.perform(get(BASELINE_URL_TEMPLATE.format(new Object[] {"E-MTAB-5423", "g391"}))) .andExpect(status().isOk()); }
Source:
private String getCollectionNameForAlias(NamedList<Object> response, String alias) { LinkedHashMap aliases = (LinkedHashMap) response.findRecursive("cluster", "aliases"); START Object collectionName = aliases.getOrDefault(alias, null); END if(collectionName != null) { return collectionName.toString(); } else { throw new RuntimeException("The alias " + alias + " does not match any collections in Solr"); } } `Map::get` will return `null` if the key isn’t found.

Target:
private String getCollectionNameForAlias(NamedList<Object> response, String alias) { LinkedHashMap aliases = (LinkedHashMap) response.findRecursive("cluster", "aliases"); Object collectionName = aliases.get(alias); if(collectionName != null) { return collectionName.toString(); } else { throw new RuntimeException("The alias " + alias + " does not match any collections in Solr"); } }
Source:
START public void loadTSnePlots(String experimentAccession) { END DataFileHub.SingleCellExperimentFiles files = dataFileHub.getSingleCellExperimentFiles(experimentAccession); try (TSnePlotStreamer tSnePlotStreamer = new TSnePlotStreamer(files.tSnePlotTsvs)) { tSnePlotStreamer.availablePerplexities() .forEach(p -> tSnePlotDao.loadTSnePlot(experimentAccession, p, tSnePlotStreamer.stream(p))); } } All the methods from here on could be private. Or if some other class will call them, shouldn't they also be `@Transactional`?

Target:
private void loadTSnePlots(String experimentAccession) { DataFileHub.SingleCellExperimentFiles files = dataFileHub.getSingleCellExperimentFiles(experimentAccession); try (TSnePlotStreamer tSnePlotStreamer = new TSnePlotStreamer(files.tSnePlotTsvs)) { tSnePlotStreamer.availablePerplexities() .forEach(p -> tSnePlotDao.loadTSnePlot(experimentAccession, p, tSnePlotStreamer.stream(p))); } }
Source:
private void drawText(Canvas canvas, PointF pos) { if (mText != null && mText != "") { START Iterator<Paint> iter = mTextStyle.iterator(); END while (iter.hasNext()) { Paint p = iter.next(); p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); } } } I think it is slightly easier and cleaner to just use for(Paint p : mTextStyle){ p.setTextSize(DEFAULT_TEXT_SIZE \* mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); }

Target:
private void drawText(Canvas canvas, PointF pos) { if (mText != null && mText != "") { for (Paint p : mTextStyle) { p.setTextSize(DEFAULT_TEXT_SIZE * mScaleFactor); canvas.drawText(mText, pos.x, pos.y, p); } } }
Source:
public void addLogo(View view) { Intent i = new Intent(this, LogoActivity.class); i.putExtra("photoByteArray", byteArray); i.putExtra("companyTag", companyTag); START i.putExtra("filePath", fileUri.getPath()); END i.putExtra("accessToken", getIntent().getExtras().getString("accessToken")); startActivity(i); } Once we start editing the picture, why do we need to pass around the original? The only reason we would need it is if we offer an option to reset all changes, but right now just passing the byte stream keeps track of the most up to date edited version.

Target:
public void addLogo(View view) { Intent i = new Intent(this, LogoActivity.class); i.putExtra("photoByteArray", byteArray); i.putExtra("filePath", fileUri.getPath()); startActivity(i); }
Source:
public void tagPicture(View view) { MapleApplication app = (MapleApplication) getApplication(); START END // save company tag companyTag = companySuggest.getText().toString(); app.setCurrentCompany(companyTag); // update header ((TextView) this.findViewById(R.id.header)) .setText("Customize Your Ad"); // set company Button ((Button) findViewById(R.id.changeTag)).setText(companyTag); toggleOptions(); } nit: This will probably need to be a private instance variable in the future. As functionality grows for MapleApplication we might just want to always get it in the <code>onCreate</code> function

Target:
public void tagPicture(View view) { // save company tag companyTag = companySuggest.getText().toString(); app.setCurrentCompany(companyTag); // update header ((TextView) this.findViewById(R.id.header)) .setText("Customize Your Ad"); // set company Button ((Button) findViewById(R.id.changeTag)).setText(companyTag); toggleOptions(); }
Source:
public void start(Xid xid, int flags) throws XAException { START System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_START [" + xid + "] Flags=" + flags); END } Not worth debugging for this QS

Target:
public void start(Xid xid, int flags) throws XAException { }
Source:
public void end(Xid xid, int flags) throws XAException { START System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_END [" + xid + "] Flags=" + flags); END } Not worth debugging for this QS

Target:
public void end(Xid xid, int flags) throws XAException { }
Source:
public void forget(Xid xid) throws XAException { START System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_FORGET[" + xid + "]"); END } Not worth debugging for this QS

Target:
public void forget(Xid xid) throws XAException { }
Source:
public void commit(Xid xid, boolean onePhase) throws XAException { if (LOG.isTraceEnabled()) { START LOG.trace("DummyXAResource.commit(xid=" + xid + ", onePhase=" + onePhase + ")"); END } counter.incrementAndGet(); } Can be info

Target:
public void commit(Xid xid, boolean onePhase) throws XAException { LOG.info("DummyXAResource.commit(xid=" + xid + ", onePhase=" + onePhase + ")"); counter.incrementAndGet(); }
Source:
public void rollback(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { START LOG.trace("DummyXAResource.rollback(xid=" + xid + ")"); END } } can be info

Target:
public void rollback(Xid xid) throws XAException { LOG.info("DummyXAResource.rollback(xid=" + xid + ")"); }
Source:
public Xid[] recover(int flag) throws XAException { if (LOG.isTraceEnabled()) { START LOG.trace("DummyXAResource.recover(flag=" + flag + ")"); END } return null; } can be info

Target:
public Xid[] recover(int flag) throws XAException { LOG.info("DummyXAResource.recover(flag=" + flag + ")"); return null; }
Source:
private IWorkbenchPage getActiveWorkbenchPage() { IWorkbenchPage result = null; IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow != null) { result = workbenchWindow.getActivePage(); } START if (result != null) { END } return result; } is something missing here?

Target:
private IWorkbenchPage getActiveWorkbenchPage() { IWorkbenchPage result = null; IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow != null) { result = workbenchWindow.getActivePage(); } return result; }
Source:
private void showFinalSelection(UIContextImpl context) { START UISelection<?> selection = context.getSelection(); END if (!selection.isEmpty()) { selectResourceFor(selection.get()); } } can the selection be null?

Target:
private void showFinalSelection(UIContextImpl context) { UISelection<?> selection = context.getSelection(); if (selection != null && !selection.isEmpty()) { selectResourceFor(selection.get()); } }
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); START deployProcess(parsedModel); END } This line can be removed. If you check the content method implementation, it's doing nothing.

Target:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); }
Source:
public boolean hasEnforcedAppVersion(){ START return this.enforcedAppVersion !=0; END } This doesn't seem right. The `enforcedAppVersion` is Integer, so by default is null, so there's an assumption that it is zero in a default setting

Target:
public boolean hasEnforcedAppVersion() { return this.enforcedAppVersion > 0; }
Source:
public ProcessExtensionModel getExtensionsForId(String processDefinitionId) { ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId); START System.out.println("processDefinition = " + processDefinition); END ProcessExtensionModel processExtensionModel = getExtensionsFor(processDefinition); return processExtensionModel != null ? processExtensionModel : EMPTY_EXTENSIONS; } Please, remove `println`.

Target:
public ProcessExtensionModel getExtensionsForId(String processDefinitionId) { ProcessDefinition processDefinition = repositoryService.getProcessDefinition(processDefinitionId); ProcessExtensionModel processExtensionModel = getExtensionsFor(processDefinition); return processExtensionModel != null ? processExtensionModel : EMPTY_EXTENSIONS; }
Source:
public boolean hasEmptyInputsMapping(String elementId) { ProcessVariablesMapping processVariablesMapping = mappings.get(elementId); ProcessConstantsMapping processConstantsMapping = constants.get(elementId); START return (processVariablesMapping != null && processVariablesMapping.getInputs().size() == 0) && END (processConstantsMapping != null && processConstantsMapping.size() == 0); } Constants should not be included there: this method is used to know if we should send none of the process variables to the task. And we still want to do it when the mappings section is empty, but constant is not empty.

Target:
public boolean hasEmptyInputsMapping(String elementId) { ProcessVariablesMapping processVariablesMapping = mappings.get(elementId); return processVariablesMapping != null && processVariablesMapping.getInputs().size() == 0; }
Source:
public void execute(DelegateExecution execution) { ThrowMessage throwMessage = getThrowMessage(execution); boolean isSent = send(execution, throwMessage); START if(isSent) END dispatchEvent(execution, throwMessage); super.execute(execution); } Please, use brackets around `if` body, even if it's a single line. BTW, you can install check style plugin in your IDE and configure it to use [this configuration file](https://github.com/Activiti/Activiti/blob/develop/checkstyle-rules.xml).

Target:
public void execute(DelegateExecution execution) { ThrowMessage throwMessage = getThrowMessage(execution); boolean isSent = send(execution, throwMessage); if(isSent) { dispatchEvent(execution, throwMessage); } super.execute(execution); }
Source:
START public void setTaskVariables(Map<String, Object> taskVariables) { END this.taskVariables = taskVariables; } This method is only used in the scope of this class, so you don't need a public setter for it. You can use the private field directly.

Target:
private void setTaskVariables(Map<String, Object> taskVariables) { this.taskVariables = taskVariables; }
Source:
public void onEvent(ActivitiEvent event) { START if (event.getType().equals(ActivitiEventType.TIMER_FIRED)) { END if (event instanceof ActivitiEntityEvent && JobEntity.class.isAssignableFrom(((ActivitiEntityEvent) event).getEntity().getClass())) { converter.from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerFiredEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } } Not necessary

Target:
public void onEvent(ActivitiEvent event) { converter.from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerFiredEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); }
Source:
public Optional<BPMNSignalReceivedEvent> from(ActivitiSignalEvent internalEvent) { BPMNSignalReceivedEventImpl event = new BPMNSignalReceivedEventImpl(toSignalConverter.from(internalEvent)); START if (event!=null) { END event.setProcessInstanceId(internalEvent.getProcessInstanceId()); event.setProcessDefinitionId(internalEvent.getProcessDefinitionId()); } return Optional.of(event); } I think you can remove this `if` as `event` cannot be null: you've just instantiate it. Or dit you mean to check something else?

Target:
public Optional<BPMNSignalReceivedEvent> from(ActivitiSignalEvent internalEvent) { BPMNSignalReceivedEventImpl event = new BPMNSignalReceivedEventImpl(toSignalConverter.from(internalEvent)); event.setProcessInstanceId(internalEvent.getProcessInstanceId()); event.setProcessDefinitionId(internalEvent.getProcessDefinitionId()); return Optional.of(event); }
Source:
public void testValidResources() { START cleanUp(); END final Resource[] resources = new Resource[]{new ClassPathResource(validName1)}; NeverFailAutoDeploymentStrategy deploymentStrategy = new NeverFailAutoDeploymentStrategy(); deploymentStrategy.deployResources(nameHint, resources, repositoryService); assertEquals(1, repositoryService.createDeploymentQuery().count()); cleanUp(); } @daisuke-yoshimoto You can use `@Before` and `@After` annotations on `setUp()` and `tearDown()` public method to reduce boilerplate code in tests for cleanup. It should be enough to rename `cleanUp()` with `tearDown()` and annotate it with `@After`.

Target:
public void testValidResources() { final Resource[] resources = new Resource[]{new ClassPathResource(validName1)}; NeverFailAutoDeploymentStrategy deploymentStrategy = new NeverFailAutoDeploymentStrategy(); deploymentStrategy.deployResources(nameHint, resources, repositoryService); assertEquals(1, repositoryService.createDeploymentQuery().count()); }
Source:
public void addCandidateUsers(CandidateUsersPayload candidateUsersPayload) { Task task; try { START task = task(candidateUsersPayload.getTaskId()); END } catch (IllegalStateException ex) { throw new IllegalStateException("The authenticated user cannot update the task" + candidateUsersPayload.getTaskId() + " due it is not the current assignee"); } if (candidateUsersPayload.getCandidateUsers() != null && !candidateUsersPayload.getCandidateUsers().isEmpty()) { for (String u : candidateUsersPayload.getCandidateUsers()) { taskService.addCandidateUser(task.getId(), u); } } } @CTI777 same here.. the check is only on then User endpoints.. if you are admin you can execute the operation no matter what..

Target:
public void addCandidateUsers(CandidateUsersPayload candidateUsersPayload) { if (candidateUsersPayload.getCandidateUsers() != null && !candidateUsersPayload.getCandidateUsers().isEmpty()) { for (String u : candidateUsersPayload.getCandidateUsers()) { taskService.addCandidateUser(candidateUsersPayload.getTaskId(), u); } } }
Source:
public void shouldConnectorMatchWithConnectorDefinition() throws IOException { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_IMAGE_CONNECTORS_PROCESS) .withVariable("input-variable-name-1", "input-variable-name-1") .withVariable("input-variable-name-2", "input-variable-name-2") .withVariable("expectedKey", true) START .build()); END } May I suggest you to use a process containing a user task after the connector so that you can check the variable updates after the connector execution?

Target:
public void shouldConnectorMatchWithConnectorDefinition() { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_IMAGE_CONNECTORS_PROCESS) .withVariable("input-variable-name-1", "input-variable-name-1") .withVariable("input-variable-name-2", "input-variable-name-2") .withVariable("expectedKey", true) .build()); }
Source:
public void connectorDefinitionEmptyDir() throws IOException { START processRuntime.start(ProcessPayloadBuilder.start() END .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", true) .build()); } Same here, using a process containing a user task would allow to check the variable valued after the connector execution.

Target:
public void connectorDefinitionEmptyDir() { processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", true) .build()); }
Source:
public Link discoverUnique(String rel) throws Exception { List<Link> discover = discover(rel); START assertThat(discover, hasSize(1)); END return discover.get(0); } Please, use AssertJ: `assertThat(discover).hasSize(1)`

Target:
public Link discoverUnique(String rel) throws Exception { List<Link> discover = discover(rel); assertThat(discover).hasSize(1); return discover.get(0); }
Source:
public void activateProcessInstanceCmdExecutorTest() { ActivateProcessInstanceCmd activateProcessInstanceCmd = new ActivateProcessInstanceCmd("x"); START assertThat(activateProcessInstanceCmdExecutor).isNotNull(); END assertThat(activateProcessInstanceCmdExecutor.getHandledType()).isEqualTo(ActivateProcessInstanceCmd.class); activateProcessInstanceCmdExecutor.execute(activateProcessInstanceCmd); verify(processEngine).activate(activateProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<ActivateProcessInstanceResults>>any()); } This assert is not necessary `activateProcessInstanceCmdExecutor` cannot be null because it's being instantiated by Mockito

Target:
public void activateProcessInstanceCmdExecutorTest() { ActivateProcessInstanceCmd activateProcessInstanceCmd = new ActivateProcessInstanceCmd("x"); assertThat(activateProcessInstanceCmdExecutor.getHandledType()).isEqualTo(ActivateProcessInstanceCmd.class); activateProcessInstanceCmdExecutor.execute(activateProcessInstanceCmd); verify(processEngine).activate(activateProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<ActivateProcessInstanceResults>>any()); }
Source:
public void claimTaskCmdExecutorTest() { ClaimTaskCmd claimTaskCmd = new ClaimTaskCmd("taskId", "assignee"); START assertThat(claimTaskCmdExecutor).isNotNull(); END assertThat(claimTaskCmdExecutor.getHandledType()).isEqualTo(ClaimTaskCmd.class); claimTaskCmdExecutor.execute(claimTaskCmd); verify(processEngine).claimTask(claimTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<ClaimTaskResults>>any()); } Can be removed.

Target:
public void claimTaskCmdExecutorTest() { ClaimTaskCmd claimTaskCmd = new ClaimTaskCmd("taskId", "assignee"); assertThat(claimTaskCmdExecutor.getHandledType()).isEqualTo(ClaimTaskCmd.class); claimTaskCmdExecutor.execute(claimTaskCmd); verify(processEngine).claimTask(claimTaskCmd); verify(commandResults).send(ArgumentMatchers.<Message<ClaimTaskResults>>any()); }
Source:
public ProcessModelResource getProcessModel(@PathVariable String id) { try (final InputStream resourceStream = repositoryService.getProcessModel(id)) { START String xml = new String(IoUtil.readInputStream(resourceStream, null), StandardCharsets.UTF_8); END return processModelResourceAssembler.toResource(new ProcessModel(id, xml)); } catch (IOException e) { throw new ActivitiException("Error occured while getting process model '" + id + "' : " + e.getMessage(), e); } } @daisuke-yoshimoto The endpoint should return the XML string, at least that is what I would expect as a client of this service. We don't need to return a resource. @erdemedeiros what do you think about that?

Target:
public String getProcessModel(@PathVariable String id) { try (final InputStream resourceStream = repositoryService.getProcessModel(id)) { return new String(IoUtil.readInputStream(resourceStream, null), StandardCharsets.UTF_8); } catch (IOException e) { throw new ActivitiException("Error occured while getting process model '" + id + "' : " + e.getMessage(), e); } }
Source:
public synchronized void receive(ProcessEngineEventEntity event) { START System.out.println(">>>> Recieved Event" + event); END System.out.println(">>>> \t Event Meta Data: " + event.getTimestamp() + " > " + event.getEventType()); System.out.println(">>>> \t Event Class: " + event.getClass().getCanonicalName()); eventsRepository.save(event); } @erdemedeiros let's remove all the system outs

Target:
public synchronized void receive(ProcessEngineEventEntity event) { eventsRepository.save(event); }
Source:
public void send(ProcessEngineEvent newEvent) { START System.out.println("Sending Event: " + newEvent); END producer.send(MessageBuilder.withPayload(newEvent).build()); } @erdemedeiros let's remove all the system outs

Target:
public void send(ProcessEngineEvent newEvent) { producer.send(MessageBuilder.withPayload(newEvent).build()); }
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); START BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); END validateModel(parsedModel); deployProcess(parsedModel); } We should also assert the parsedModel

Target:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); assertNotNull(parsedModel); validateModel(parsedModel); }
Source:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull("BPMN Model XML not found", bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); validateModel(parsedModel); START deployProcess(parsedModel); END } Is the deployProcess() method doing something? if not we should start getting rid of dead code.

Target:
public void convertModelToXML() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull("BPMN Model XML not found", bpmnModel); BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel); assertNotNull(parsedModel); validateModel(parsedModel); }
Source:
public void doubleConversionValidation() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); validateModel(bpmnModel); START bpmnModel = exportAndReadXMLFile(bpmnModel); END validateModel(bpmnModel); } This should be validated with an assertion as well

Target:
public void doubleConversionValidation() throws Exception { BpmnModel bpmnModel = readXMLFile(); assertNotNull(bpmnModel); validateModel(bpmnModel); bpmnModel = exportAndReadXMLFile(bpmnModel); assertNotNull(bpmnModel); validateModel(bpmnModel); }
Source:
public void testJobCanceledEventOnBoundaryEvent() throws Exception { Clock testClock = new DefaultClockImpl(); START assertNotNull(testClock); END processEngineConfiguration.setClock(testClock); testClock.setCurrentTime(new Date()); runtimeService.startProcessInstanceByKey("testTimerCancelledEvent"); listener.clearEventsReceived(); Task task = taskService.createTaskQuery().singleResult(); taskService.complete(task.getId()); checkEventCount(1, ActivitiEventType.JOB_CANCELED); } This one doesn't make much sense.. we just created the instance.

Target:
public void testJobCanceledEventOnBoundaryEvent() throws Exception { Clock testClock = new DefaultClockImpl(); processEngineConfiguration.setClock(testClock); testClock.setCurrentTime(new Date()); runtimeService.startProcessInstanceByKey("testTimerCancelledEvent"); listener.clearEventsReceived(); Task task = taskService.createTaskQuery().singleResult(); assertNotNull(task); taskService.complete(task.getId()); checkEventCount(1, ActivitiEventType.JOB_CANCELED); }
Source:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { START throw new IllegalStateException("parameterDefinitionName is null"); END } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); } I would still throw an `IllegalArgumentException` here

Target:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { throw new IllegalArgumentException("parameterDefinitionName is null"); } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }
Source:
START public String getLocation() { return bundle != null ? bundle.getLocation() : ""; } END Not sure that the `""` is the correct alternative? `null`?

Target:
public String getLocation() { return bundle.getLocation(); }
Source:
START public String getVersion() { return bundle != null ? bundle.getVersion().toString() : ""; } END Not sure that the `""` is the correct alternative? `null`?

Target:
public String getVersion() { return bundle.getVersion().toString(); }
Source:
private boolean shouldNotCache(@NotNull String path) { START Intrinsics.checkParameterIsNotNull(bundleContext, "path"); END return path.endsWith(".map"); } `path` ?

Target:
private boolean shouldNotCache(@NotNull String path) { Intrinsics.checkParameterIsNotNull(path, "path"); return path.endsWith(".map"); }
Source:
public HttpHeaders getHeaders() { START HttpHeaders headers = new HttpHeaders(); END return headers; } TODO: write headers

Target:
public HttpHeaders getHeaders() { return this.headers; }
Source:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); START LOG.info("\n\nRequest " + request.getMethod() END + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the UAC so the only request we get is the BYE. SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); } i would try to minize changes in the code. Apparently there lots of files affected just to rename the "logger" variable name. Even if we agree that name is better or not, I would prefer to stay with the previous name, in order to minimize the number of files changed. It would be different if we really take a new Log4j2 API to improve code readibility/performance like parameterized log https://logging.apache.org/log4j/2.0/manual/messages.html

Target:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); logger.info("\n\nRequest " + request.getMethod() + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the UAC so the only request we get is the BYE. SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }
Source:
private SIPDialog findSIPDialogFromInjectionListeners(String dialogId) { SIPDialog dialog = null; START synchronized (dialogInjectionListeners) { END for(SIPDialogInjectionListener listener : dialogInjectionListeners) { SIPDialog tempDialog = listener.getExternalSIPDialog(dialogId); if(tempDialog != null && tempDialog.getDialogId().equals(dialogId)) { dialog = tempDialog; // Take first valid Dialog and ignore following listener break; } } } return dialog; } what kind of concurrent access are you trying to sync? In this case, are you trying to prevent multiple invocations to findSIPDialogFromInjectionListeners to be concurrent?if yes, why, it seems to be readOnly scenario? If you are trying to sync with add/remove writing scenarios, so the iterator is protected against concurrent modifcation, shouldnt you use synchronize on those scenarios as well? Is it becuase the subsequent invocation to "putDialog"? if yes, why? dialogTable seems to be already synced with a concurrent Map.

Target:
private SIPDialog findSIPDialogFromInjectionListeners(String dialogId) { SIPDialog dialog = null; for(SIPDialogInjectionListener listener : dialogInjectionListeners) { SIPDialog tempDialog = listener.getExternalSIPDialog(dialogId); if(tempDialog != null && tempDialog.getDialogId().equals(dialogId)) { dialog = tempDialog; // Take first valid Dialog and ignore following listener break; } } return dialog; }
Source:
public static ModuleManager create() throws Exception { START ModuleManager moduleManager = new ModuleManagerImpl(""); return LoadModuleEnvironment(moduleManager); END } ```suggestion return create(""); ```

Target:
public static ModuleManager create() throws Exception { return create(""); }
Source:
public static Diamond3iIterable.Builder shell(Vector3ic origin, int radius) { START return new Diamond3iIterable.Builder(origin, radius).start(radius - 1); END } +/- 1 confusion: ```suggestion return new Diamond3iIterable.Builder(origin, radius).start(radius); ```

Target:
public static Diamond3iIterable.Builder shell(Vector3ic origin, int radius) { return new Diamond3iIterable.Builder(origin, radius).start(radius); }
Source:
public Diamond3iIterable.Builder start(int start) { START this.startDistance = start + 1; END return this; } +/- 1 confusion: ```suggestion this.startDistance = start; ``` that was the last one.

Target:
public Diamond3iIterable.Builder start(int start) { this.startDistance = start; return this; }
Source:
public void onEmission(TextureOffsetGeneratorComponent component, ParticleData particleData, Random random) { if (component.validOffsets.size() == 0) { return; } final int randomOffsetIndex = random.nextInt(component.validOffsets.size()); final Vector2f randomOffset = component.validOffsets.get(randomOffsetIndex); START particleData.textureOffset.set(randomOffset.x(), randomOffset.y()); END } Could be simplified: ```suggestion particleData.textureOffset.set(randomOffset); ```

Target:
public void onEmission(TextureOffsetGeneratorComponent component, ParticleData particleData, Random random) { if (component.validOffsets.size() == 0) { return; } final int randomOffsetIndex = random.nextInt(component.validOffsets.size()); final Vector2f randomOffset = component.validOffsets.get(randomOffsetIndex); particleData.textureOffset.set(randomOffset); }
Source:
private void updateSliderIfInteger(UISlider slider) { T settingValue = getSetting().getValue(); if (settingValue instanceof Float || settingValue instanceof Double) { return; } START slider.setIncrement(1.0f); END slider.setPrecision(0); } Doesn't this also trigger on `Byte`, `Short` and `Long` rather than `Integer`?

Target:
private void updateSliderIfInteger(UISlider slider) { T settingValue = getSetting().get(); if (settingValue instanceof Float || settingValue instanceof Double) { return; } slider.setIncrement(1.0f); slider.setPrecision(0); }
Source:
public String getText() { String arrayText = ""; START if(linesOfText != null) arrayText = String.join("\n", linesOfText); END if(text.get() != "") return text.get() + "\n" + arrayText; return text.get() + arrayText; } Try and avoid single line `if`s without the brackets. same applies for `for`s as well

Target:
public String getText() { String arrayText = ""; if(linesOfText.length > 0) { arrayText = String.join("\n", linesOfText); } if(text.get() != "") { return text.get() + "\n" + arrayText; } return text.get() + arrayText; }
Source:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); START linesOfText = null; END correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } } like above, i'd prefer a blank entry over null

Target:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); linesOfText = new String[]{}; correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }
Source:
private void changeValue(float delta) { START float newValue = TeraMath.clamp(getValue() + delta, 0, getRange() + getMinimum()); END setValue(newValue); } Wouldn't `getMinimum()` be more appropriate here than `0`.

Target:
private void changeValue(float delta) { float newValue = TeraMath.clamp(getValue() + delta, getMinimum(), getRange() + getMinimum()); setValue(newValue); }
Source:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } START if (active || (TabbingManager.focusedWidget != null && TabbingManager.focusedWidget.equals(this))) { END return ACTIVE_MODE; } else if (tickerListener.isMouseOver()) { return HOVER_MODE; } return DEFAULT_MODE; } If you do `this.equals(TabbingManager.focusedWidget)` then you don't need the bulky null check here, as `equals` returns false for null

Target:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } if (active || this.equals(TabbingManager.focusedWidget)) { return ACTIVE_MODE; } else if (tickerListener.isMouseOver()) { return HOVER_MODE; } return DEFAULT_MODE; }
Source:
public BaseStrictlySparseFieldFacet2D(Region3i targetRegion, Border3D border) { super(targetRegion, border); Vector2i size = getRelativeRegion().size(); START this.data = new ArrayList<>(Collections.nCopies(size.x * size.y, Optional.empty())); END } Forgive me if I'm mistaken but if you're pre-populating all positions with an optional then it's not particularly sparse? Could you not store a `Map<Integer, Float>` and then use the `getOrDefault` method to return either the float at the position or null, and wrap it in an optional just before it's actually returned.

Target:
public BaseStrictlySparseFieldFacet2D(Region3i targetRegion, Border3D border) { super(targetRegion, border); }
Source:
public static boolean containsConsole() { if (enabledWidgets != null) { boolean containsConsole = false; for (CoreScreenLayer layer : enabledWidgets) { if (layer instanceof ConsoleScreen) { START LoggerFactory.getLogger("").info("console open"); END containsConsole = true; } } return containsConsole; } return false; } This shouldn't be here

Target:
public static boolean containsConsole() { if (enabledWidgets != null) { boolean containsConsole = false; for (CoreScreenLayer layer : enabledWidgets) { if (layer instanceof ConsoleScreen) { return true; } } } return false; }
Source:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); // invalid characters are filtered, so if the file name is made up of entirely invalid characters, the path will have a blank name. START if (destinationPath == PathManager.getInstance().getRecordingPath("")) { END return false; } return !StringUtils.isBlank(name); } The `==` is a reference comparison, here you are checking if both objects point to the same memory location, and of course, they don't. The right way to compare these paths is using `equals()`. As shown below, for example, if I put "@" as the recording name, which does not match the `PathManager` regex (`[^A-Za-z0-9-_ ]`), the `isNameValid(name)` method returns `true`, again because you're not comparing the object value itself. Moreover, it can cause other bugs like the one shown in the pic, saying that a recording already exists when they don't. ![image](https://user-images.githubusercontent.com/26657147/48665079-4130c580-ea87-11e8-93be-8e58d6dd4227.png)

Target:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); // invalid characters are filtered from paths, so if the file name is made up of entirely invalid characters, the path will have a blank file name. // also acts as a check for blank input. return !destinationPath.equals(PathManager.getInstance().getRecordingPath("")); }
Source:
public void nextImage() { int size = images.size(); int prevIndex = index; if (size > 0) { if (index == size - 1) { if (infinite) { index = 0; } else { stop(); } } else { index++; } if (prevIndex != index) { START currentImage.set(images.get(index)); END } } } ### Option B Change this from setting `currentImage` to the new image, just set the _texture_ to the new texture. If you wanted to get really fancy you could also use a binding, and bind the texture to `images.get(index)` via `ReadOnlyBinding` this would make the texture automatically update without you having to set it.

Target:
public void nextImage() { int size = images.size(); if (size > 0) { if (index == size - 1) { if (infinite) { index = 0; } else { stop(); } } else { index++; } } }