auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getTemplatePage().countListedTemplates(); START Thread.sleep(50000); END Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); } Why need this test need such a high timeout value?

Target:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getProjectsPage().countListedTemplates(); Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }
Source:
public Long countDocuments(String query) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.countDocuments(overrideNullQuery(query)); if (!response.equals("")) { START JsonReader jsonReader = Json.createReader(new StringReader(response)); END JsonObject result = jsonReader.readObject(); return result.getJsonNumber("count").longValue(); } else { return 0L; } } `JsonReader` is a closeable class but the created object is never closed. Maybe you can use a try-with-resources statement?

Target:
public Long countDocuments(String query) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.countDocuments(overrideNullQuery(query)); if (!response.equals("")) { try (JsonReader jsonReader = Json.createReader(new StringReader(response))) { JsonObject result = jsonReader.readObject(); return result.getJsonNumber("count").longValue(); } } else { return 0L; } }
Source:
public JsonObject findDocument(Integer id) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.getDocument(id); if (!response.equals("")) { START JsonReader jsonReader = Json.createReader(new StringReader(response)); END return jsonReader.readObject(); } else { return Json.createObjectBuilder().build(); } } Same here. `JsonReader` is closeable so using a try-with-resources statement for closing the object is maybe a good idea.

Target:
public JsonObject findDocument(Integer id) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.getDocument(id); if (!response.equals("")) { try (JsonReader jsonReader = Json.createReader(new StringReader(response))) { return jsonReader.readObject(); } } else { return Json.createObjectBuilder().build(); } }
Source:
public JsonObject aggregateDocuments(String query, String aggregation) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.aggregateDocuments(overrideNullQuery(query), aggregation); if (!response.equals("")) { START JsonReader jsonReader = Json.createReader(new StringReader(response)); END JsonObject result = jsonReader.readObject(); return result.getJsonObject("aggregations"); } else { return Json.createObjectBuilder().build(); } } Same here. `JsonReader` is closeable so using a try-with-resources statement for closing the object is maybe a good idea.

Target:
public JsonObject aggregateDocuments(String query, String aggregation) throws DataException { SearchRestClient restClient = initiateRestClient(); String response = restClient.aggregateDocuments(overrideNullQuery(query), aggregation); if (!response.equals("")) { try (JsonReader jsonReader = Json.createReader(new StringReader(response))) { JsonObject result = jsonReader.readObject(); return result.getJsonObject("aggregations"); } } else { return Json.createObjectBuilder().build(); } }
Source:
private void saveTask(String processTitle, Task task) { try { serviceManager.getTaskService().save(task); } catch (DataException e) { START Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving - " + processTitle, e); END logger.error(KITODO_SCRIPT_FIELD + "Error while saving - " + processTitle, e); } } Please first log the error and then inform the user.

Target:
private void saveTask(String processTitle, Task task) { try { serviceManager.getTaskService().save(task); } catch (DataException e) { logger.error(KITODO_SCRIPT_FIELD + "Error while saving - " + processTitle, e); Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Error while saving - " + processTitle, e); } }
Source:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } START Helper.setMeldung(null, "ExportFinished", ""); END logger.info(Helper.getTranslation("ExportFinished")); } If you add a log message it should be logged before the user get the information. Please move this log call in front of the `Helper.setMeldung()` call.

Target:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } logger.info(Helper.getTranslation("ExportFinished")); Helper.setMeldung(null, "ExportFinished", ""); }
Source:
protected void initUserList() { try { this.user.addAll(serviceManager.getUserService().getAllActiveUsersSortedByNameAndSurname()); } catch (RuntimeException rte) { START Helper.setErrorMessage("errorLoadingMany", new String[] {Helper.getTranslation("aktiveBenutzer") }); END logger.warn("RuntimeException caught. List of users could be empty!"); } } Same here. Please first log the error message / reason and then display it to the user.

Target:
protected void initUserList() { try { this.user.addAll(serviceManager.getUserService().getAllActiveUsersSortedByNameAndSurname()); } catch (RuntimeException rte) { logger.warn("RuntimeException caught. List of users could be empty!"); Helper.setErrorMessage("errorLoadingMany", new Object[] {Helper.getTranslation("aktiveBenutzer") }); } }
Source:
public ArrayList<Property> getWorkpieceProperties() { if (Objects.isNull(workpieceProperties)) { START return new ArrayList<>(); END } return workpieceProperties; } Why did you not assign this empty list and return it?

Target:
public ArrayList<Property> getWorkpieceProperties() { if (Objects.isNull(workpieceProperties)) { workpieceProperties = new ArrayList<>(); } return workpieceProperties; }
Source:
private MetadataInterface findMetadatumIn(DocStructInterface node) { START List<? extends MetadataInterface> metadataInterface = node.getAllMetadataByType(selector); END for (MetadataInterface metadatum : metadataInterface) { if (selector.getName().equals(metadatum.getMetadataType().getName())) { return metadatum; } } return null; } Interface appended to variable name

Target:
private MetadataInterface findMetadatumIn(DocStructInterface node) { List<? extends MetadataInterface> metadata = node.getAllMetadataByType(selector); for (MetadataInterface metadatum : metadata) { if (selector.getName().equals(metadatum.getMetadataType().getName())) { return metadatum; } } return null; }
Source:
public static FileformatInterface parsePicaFormat(Node pica, PrefsInterface prefs) START throws ReadException, PreferencesException, TypeNotAllowedForParentException { END PicaPlusInterface pp = UghImplementation.INSTANCE.createPicaPlus(prefs); pp.read(pica); DigitalDocumentInterface dd = pp.getDigitalDocument(); FileformatInterface ff = UghImplementation.INSTANCE.createXStream(prefs); ff.setDigitalDocument(dd); /* BoundBook hinzufügen */ DocStructTypeInterface dst = prefs.getDocStrctTypeByName("BoundBook"); DocStructInterface dsBoundBook = dd.createDocStruct(dst); dd.setPhysicalDocStruct(dsBoundBook); return ff; } TypeNotAllowedForParentException - not used exception.

Target:
public static FileformatInterface parsePicaFormat(Node pica, PrefsInterface prefs) throws ReadException, PreferencesException { PicaPlusInterface pp = UghImplementation.INSTANCE.createPicaPlus(prefs); pp.read(pica); DigitalDocumentInterface dd = pp.getDigitalDocument(); FileformatInterface ff = UghImplementation.INSTANCE.createXStream(prefs); ff.setDigitalDocument(dd); /* BoundBook hinzufügen */ DocStructTypeInterface dst = prefs.getDocStrctTypeByName("BoundBook"); DocStructInterface dsBoundBook = dd.createDocStruct(dst); dd.setPhysicalDocStruct(dsBoundBook); return ff; }
Source:
public boolean equals(Object o) { START if (this == o) END return true; if (o == null || getClass() != o.getClass()) return false; Authority authority = (Authority) o; return title != null ? title.equals(authority.title) : authority.title == null; } Wrong formatting in whole method. Please fix it.

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Authority authority = (Authority) o; return title != null ? title.equals(authority.title) : authority.title == null; }
Source:
private Actuate(String name) { START this.name = name; END } Modifier 'private' is redundant for Enum constructor - needs to be removed.

Target:
Actuate(String name) { this.name = name; }
Source:
private Type(String name) { START this.name = name; END } Modifier 'private' is redundant for Enum constructor - needs to be removed.

Target:
Type(String name) { this.name = name; }
Source:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { // This NPE gets thrown - and therefore must be caught - when "RulesetForm" is // used from it's integration test // class "RulesetFormIT", where no "FacesContext" is available! START return "/pages/ProjekteBearbeiten" + urlSuffix; END } } This looks wrong. Why should edit page for projects be returned if we are in ruleset editing?

Target:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { // This NPE gets thrown - and therefore must be caught - when "RulesetForm" is // used from it's integration test // class "RulesetFormIT", where no "FacesContext" is available! return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } }
Source:
public SelectItem[] getAddableDocStructTypes() { switch (positionOfNewDocStrucElement) { case BEFOR_CURRENT_ELEMENT: case AFTER_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, true); case FIRST_CHILD_OF_CURRENT_ELEMENT: case LAST_CHILD_OF_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, false); default: logger.error("Invalid positionOfNewDocStrucElement"); START return null; END } } Returning null should be avoided as it introduce unnecessary null pointer checks. Could not a empty object be returned?

Target:
public SelectItem[] getAddableDocStructTypes() { switch (positionOfNewDocStrucElement) { case BEFOR_CURRENT_ELEMENT: case AFTER_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, true); case FIRST_CHILD_OF_CURRENT_ELEMENT: case LAST_CHILD_OF_CURRENT_ELEMENT: return this.metaHelper.getAddableDocStructTypen(this.docStruct, false); default: logger.error("Invalid positionOfNewDocStrucElement"); return new SelectItem[0]; } }
Source:
START private ObjectType findNextNode() { END while (true) { if ((inner == null) || !inner.hasNext()) { if (outer.hasNext()) { inner = outer.next().getValue().iterator(); } else { return null; } } while (inner.hasNext()) { return inner.next(); } } } Return empty object instead of null.

Target:
private Optional<ObjectType> findNextNode() { while (true) { if ((inner == null) || !inner.hasNext()) { if (outer.hasNext()) { inner = outer.next().getValue().iterator(); } else { return Optional.empty(); } } while (inner.hasNext()) { return Optional.of(inner.next()); } } }
Source:
public static Boolean updateHistoryForProcess(Process inProc) { Boolean updated; try { //TODO: updateHistoryForSteps overwrites result of updateHistory updated = updateHistory(inProc); updated = updateHistoryForSteps(inProc); } catch (Exception ex) { logger.warn("Updating history failed.", ex); START logger.error(ex.getStackTrace()); END updated = false; } return updated; } Is this error log call necessary as in the warning call is the stack trace included.

Target:
public static Boolean updateHistoryForProcess(Process inProc) { Boolean updated; try { //TODO: updateHistoryForSteps overwrites result of updateHistory updated = updateHistory(inProc); updated = updateHistoryForSteps(inProc); } catch (Exception ex) { logger.warn("Updating history failed.", ex); updated = false; } return updated; }
Source:
public File generateDocket(DocketData docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); START try { END exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.flush(); fileOutputStream.close(); } return file; } Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.

Target:
public File generateDocket(DocketData docketData, URI xslFileUri) throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { exportDocket.startExport(docketData, fileOutputStream, new File(xslFileUri)); } catch (IOException e) { throw new IOException(e.getMessage()); } return file; }
Source:
public void testStartExport() throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); FileOutputStream fileOutputStream = new FileOutputStream(file); File xslFile = new File("src/test/resources/docket.xsl"); START try { END exportDocket.startExport(docketDataGenerator.createDocketData("processId", "signature", "doctype"), fileOutputStream, xslFile); } catch (IOException e) { throw new IOException(e.getMessage()); } finally { fileOutputStream.close(); } } Please use [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement instead of handling this manually.

Target:
public void testStartExport() throws IOException { ExportDocket exportDocket = new ExportDocket(); File file = new File("docket.pdf"); File xslFile = new File("src/test/resources/docket.xsl"); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { exportDocket.startExport(docketDataGenerator.createDocketData("processId", "signature", "doctype"), fileOutputStream, xslFile); } catch (IOException e) { throw new IOException(e.getMessage()); } }
Source:
public Long getNumberOfPagesPerIssue() { if (course.countIndividualIssues() != 0) { return numberOfPages != null ? numberOfPages / course.countIndividualIssues() : null; } else { START return null; END } } We would never return `null` as this value cause null pointer exceptions or add a lot of null value checks.

Target:
public Long getNumberOfPagesPerIssue() { if (course.countIndividualIssues() != 0) { return numberOfPages != null ? numberOfPages / course.countIndividualIssues() : null; } else { return new Long(0); } }
Source:
public boolean isSelected() { START return (this.selected); END } Why did you add the round braces?

Target:
public boolean isSelected() { return this.selected; }
Source:
private void manageProcessDependenciesForIndex(Template template) throws CustomResponseException, IOException { Process process = template.getProcess(); START if (template.getIndexAction() == IndexAction.DELETE) { END if (process != null) { process.getTemplates().remove(template); serviceManager.getProcessService().saveToIndex(process); } } else { if (process != null) { serviceManager.getProcessService().saveToIndex(process); } } } A template should never exists without a corresponding process. It could be possible that a process has no template.

Target:
private void manageProcessDependenciesForIndex(Template template) throws CustomResponseException, IOException { Process process = template.getProcess(); if (template.getIndexAction() == IndexAction.DELETE) { process.getTemplates().remove(template); serviceManager.getProcessService().saveToIndex(process); } else { serviceManager.getProcessService().saveToIndex(process); } }
Source:
<F extends BaseBean> JSONArray addObjectRelation(List<F> objects) { JSONArray jsonArray = new JSONArray(); START if (objects != null && objects.size() > 0) { END for (F property : objects) { jsonArray.add(addIdForRelation(property.getId())); } } return jsonArray; } Why did you add this empty list check (null check is OK)? I think it is not necessary as an empty list will do nothing in later for statement.

Target:
<F extends BaseBean> JSONArray addObjectRelation(List<F> objects) { JSONArray jsonArray = new JSONArray(); if (objects != null) { for (F property : objects) { jsonArray.add(addIdForRelation(property.getId())); } } return jsonArray; }
Source:
private boolean isValidProcessProperty() { if (this.processProperty.isValid()) { return true; } else { List<String> param = new ArrayList<String>(); param.add(processProperty.getName()); START String value = Helper.getTranslation("propertyNotValid", param); END Helper.setFehlerMeldung(value); Helper.setFehlerMeldung("Property " + this.processProperty.getName() + " is not valid"); return false; } } What about `String value = Helper.getTranslation("propertyNotValid", Arrays.asList(new String[]{ processProperty.getName() }));`

Target:
private boolean isValidProcessProperty() { if (this.processProperty.isValid()) { return true; } else { String value = Helper.getTranslation("propertyNotValid", Arrays.asList(new String[] {processProperty.getName() })); Helper.setFehlerMeldung(value); Helper.setFehlerMeldung("Property " + this.processProperty.getName() + " is not valid"); return false; } }
Source:
public void test() throws Exception { ServiceManager serviceManager = new ServiceManager(); long counted = serviceManager.getProcessService().count("from Process"); Assert.assertNotNull("No Process found", counted); Assert.assertEquals(4, counted); String title = serviceManager.getProcessService().find(1).getTitle(); START Assert.assertEquals("DBConnectionTest", title); END } This test could not work, as you are search for first process but your test data is inserted as 4th.

Target:
public void test() throws Exception { ServiceManager serviceManager = new ServiceManager(); long counted = serviceManager.getProcessService().count("from Process"); Assert.assertNotNull("No Process found", counted); Assert.assertEquals(4, counted); String title = serviceManager.getProcessService().find(4).getTitle(); Assert.assertEquals("DBConnectionTest", title); }
Source:
public static String getKitodoConfigDirectory() { START return ConfigCore.getParameter(CONFIG_DIR); END } This could be simplified to `return getParameter(CONFIG_DIR);` or did I miss something?

Target:
public static String getKitodoConfigDirectory() { return getParameter(CONFIG_DIR); }
Source:
START public int getWorkpiecesSize() { END if (this.getWorkpieces() == null) { return 0; } else { return this.getWorkpieces().size(); } } Why did you leave changes for this method out? This method looks like the other changed methods.

Target:
public int getWorkpiecesSize() { return this.getWorkpieces().size(); }
Source:
START public void setTimeout(long timeout) { END this.timeout = timeout; } missing JavaDoc statement

Target:
void setTimeout(long timeout) { this.timeout = timeout; }
Source:
public ProcessProperty() { START this.container = new Integer(0); END this.value = ""; this.possibleValues = new ArrayList<String>(); this.projects = new ArrayList<String>(); this.showStepConditions = new ArrayList<ShowStepCondition>(); this.prozesseigenschaft = new Prozesseigenschaft(); } IntelliJ IDEA tolds me to remove this unnecessary boxing.

Target:
public ProcessProperty() { this.container = 0; this.value = ""; this.possibleValues = new ArrayList<String>(); this.projects = new ArrayList<String>(); this.showStepConditions = new ArrayList<ShowStepCondition>(); this.prozesseigenschaft = new Prozesseigenschaft(); }
Source:
public void setDest(final RandomAccessOutputStream stream, final int imageIndex, final SCIFIOConfig config) throws FormatException, IOException { super.setDest(stream, imageIndex, config); START if (getStream().length() == 0) { writeHeader(); } END } This is not ImageJ style. When curly braces are present, the opening brace goes on the same line, the statement(s) go on following line(s), and closing brace on its own line. The Eclipse code style formatter does this.

Target:
public void setDest(final RandomAccessOutputStream stream, final int imageIndex, final SCIFIOConfig config) throws FormatException, IOException { super.setDest(stream, imageIndex, config); if (getStream().length() == 0) writeHeader(); }
Source:
public void close() throws IOException { START if (getStream() != null) { writeFooter(); } END super.close(); } Not ImageJ style.

Target:
public void close() throws IOException { if (getStream() != null) writeFooter(); super.close(); }
Source:
public void writeEntityToNBT(NBTTagCompound n) { START n.setInteger("frogType", (byte)getType().ordinal()); END super.writeEntityToNBT(n); } setInteger(byte) :thinking:

Target:
public void writeEntityToNBT(NBTTagCompound n) { n.setInteger("frogType", getType().ordinal()); super.writeEntityToNBT(n); }
Source:
public void onRenderTick(RenderWorldLastEvent event) { if(Minecraft.getMinecraft().player != null && !Minecraft.getMinecraft().player.isDead) { if (Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 || Minecraft.getMinecraft().currentScreen != null) { EntityPlayer p = Minecraft.getMinecraft().player; START if(!p.isInWater()) END updateSwimDataAngles(p); updateSwimRenderAngles(p); } } } This is sketchy. Should this encompass both of these? just one?

Target:
public void onRenderTick(RenderWorldLastEvent event) { EntityPlayer p = Minecraft.getMinecraft().player; if (p != null && !p.isDead) { if (Minecraft.getMinecraft().gameSettings.thirdPersonView == 0 || Minecraft.getMinecraft().currentScreen != null) { if (!p.isInWater()) { updateSwimDataAngles(p); } updateSwimRenderAngles(p); } } }
Source:
public void doRender(EntityTropicraftWaterBase entityliving, double d, double d1, double d2, float f, float f1) { if(refreshModel && entityliving.ticksExisted % 20 == 0) { START this.mainModel = new ModelDolphin(); END this.dolphin = new ModelDolphin(); refreshModel = false; } //refreshModel = true; this.renderWaterMob((EntityTropicraftWaterBase) entityliving, d, d1, d2, f1); } Why do you use mainModel and dolphin, since dolphin is just equal to mainModel?

Target:
public void doRender(EntityTropicraftWaterBase entityliving, double d, double d1, double d2, float f, float f1) { this.renderWaterMob((EntityTropicraftWaterBase) entityliving, d, d1, d2, f1); }
Source:
public void assignRandomTexture() { if(!world.isRemote) { START if(getTexturePool().length > 0) { END setTexture(getTexturePool()[rand.nextInt(getTexturePool().length)]); } } } Since getTexturePool can return null, you should add a null check here.

Target:
public void assignRandomTexture() { if(!world.isRemote && getTexturePool() != null) { if(getTexturePool().length > 0) { setTexture(getTexturePool()[rand.nextInt(getTexturePool().length)]); } } }
Source:
private boolean shouldRedirect(ContainerRequestContext requestContext) { String maybeVehicle = requestContext.getUriInfo().getQueryParameters().getFirst("vehicle"); if (maybeVehicle != null && maybeVehicle.equals("pt")) { return true; } String maybeProfile = requestContext.getUriInfo().getQueryParameters().getFirst("profile"); START if (maybeProfile != null && maybeProfile.equals("pt")) { return true; } return false; END } this could be a bit shorter ;) `return "pt".equals(maybeProfile)` And should we also remove the profile param in the filter method above? (`replaceQueryParam("profile")`)

Target:
private boolean shouldRedirect(ContainerRequestContext requestContext) { String maybeVehicle = requestContext.getUriInfo().getQueryParameters().getFirst("vehicle"); String maybeProfile = requestContext.getUriInfo().getQueryParameters().getFirst("profile"); return "pt".equals(maybeVehicle) || "pt".equals(maybeProfile); }
Source:
START public static BBox createBBox(NodeAccess na, EdgeIteratorState edgeState) { END return BBox.fromPoints(na.getLatitude(edgeState.getBaseNode()), na.getLongitude(edgeState.getBaseNode()), na.getLatitude(edgeState.getAdjNode()), na.getLongitude(edgeState.getAdjNode())); } This would be better to duplicate and keep private

Target:
private static BBox createBBox(NodeAccess na, EdgeIteratorState edgeState) { return BBox.fromPoints(na.getLatitude(edgeState.getBaseNode()), na.getLongitude(edgeState.getBaseNode()), na.getLatitude(edgeState.getAdjNode()), na.getLongitude(edgeState.getAdjNode())); }
Source:
START public CHProfileConfig setProfile(String profile) { END validateProfileName(profile); this.profile = profile; return this; } Should we better make this method package protected to only allow jackson access to it?

Target:
CHProfileConfig setProfile(String profile) { validateProfileName(profile); this.profile = profile; return this; }
Source:
protected void fillEdgesToUsingFilter(EdgeFilter edgeFilter) { // we temporarily ignore the additionalEdgeFilter EdgeFilter tmpFilter = additionalEdgeFilter; additionalEdgeFilter = edgeFilter; finishedTo = !fillEdgesTo(); additionalEdgeFilter = tmpFilter; START } END What are the use cases for the EdgeFilter for non-CH algos? (For CH there is the CHLevelEdgeFilter, but here?) Is it just regarding the vehicle edge and we can remove this code with #1835 ?

Target:
protected void fillEdgesToUsingFilter(EdgeFilter edgeFilter) { additionalEdgeFilter = edgeFilter; finishedTo = !fillEdgesTo(); additionalEdgeFilter = null; }
Source:
public OSMMaxAxleLoadParser() { START this.maxAxleLoadEncoder = MaxAxleLoad.create(); END } I would not remove this. I think the additional constructor is a meaningful addition, so that the user could increase or decrease the precision. (same for the other parsers)

Target:
public OSMMaxAxleLoadParser() { this(MaxAxleLoad.create()); }
Source:
public boolean acceptsTurnRelation(OSMTurnRelation relation) { START if (relation.isVehicleTypeConcernedByTurnRestriction(restrictions)) { END return true; } return false; } just `return relation.isVehicleTypeConcernedByTurnRestriction(restrictions)` (here and in other encoders)

Target:
public boolean acceptsTurnRelation(OSMTurnRelation relation) { return relation.isVehicleTypeConcernedByTurnRestriction(restrictions); }
Source:
private JsonNode parseRequestResponse (Response response) throws IOException { START response.bufferEntity(); END String body = response.readEntity(String.class); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(body); } Why is this necessary?

Target:
private JsonNode parseRequestResponse (Response response) throws IOException { String body = response.readEntity(String.class); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(body); }
Source:
private Weighting createWeighting(FlagEncoder encoder, double uTurnCosts) { TurnWeighting result = new TurnWeighting(new FastestWeighting(encoder), tcs); if (!Double.isInfinite(uTurnCosts)) { result.setUTurnCost(uTurnCosts); START } END return result; } Can this be moved into the new constructor?

Target:
private Weighting createWeighting(FlagEncoder encoder, double uTurnCosts) { return new TurnWeighting(new FastestWeighting(encoder), tcs, uTurnCosts); }
Source:
public static String join(String delimiter, List<String> strings) { START StringJoiner joiner = new StringJoiner(delimiter); END for (CharSequence cs : strings) { joiner.add(cs); } return joiner.toString(); } That would cause problem on Android compatibility, since [StringJoiner](https://developer.android.com/reference/java/util/StringJoiner) being a Java 8 class, was added in API level 24 (Android 7 Nougat).

Target:
public static String join(String delimiter, List<String> strings) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < strings.size(); i++) { if (i > 0) { sb.append(delimiter); } sb.append(strings.get(i)); } return sb.toString(); }
Source:
public GraphHopper() { chFactoryDecorator.setEnabled(true); lmFactoryDecorator.setEnabled(false); START arFactoryDecorator.setEnabled(true); END // order is important to use CH as base algo and set the approximation in the followed lm factory decorator. // AR must be the last factory decorator because it need both other decorators during preparation algoDecorators.add(chFactoryDecorator); algoDecorators.add(lmFactoryDecorator); algoDecorators.add(arFactoryDecorator); } I would not enable this by default. Then there is also no need to change the many tests.

Target:
public GraphHopper() { chFactoryDecorator.setEnabled(true); lmFactoryDecorator.setEnabled(false); arFactoryDecorator.setEnabled(false); // order is important to use CH as base algo and set the approximation in the followed lm factory decorator. // AR must be the last factory decorator because it need both other decorators during preparation algoDecorators.add(chFactoryDecorator); algoDecorators.add(lmFactoryDecorator); algoDecorators.add(arFactoryDecorator); }
Source:
private int distToInt(double distance) { START if (distance < 0) END throw new IllegalArgumentException("Distance cannot be negative: " + distance); if (distance > MAX_DIST) { distance = MAX_DIST; // throw new IllegalArgumentException("Distance too large leading to overflowed integer (#435): " + distance + " "); } int integ = Math.round((float) (distance * INT_DIST_FACTOR)); assert integ >= 0 : "distance out of range"; return integ; } Ok, yes. It looks that we do not have a test for this. So when I remove "if (integ >= Integer.MAX_VALUE) return Integer.MAX_VALUE;" everything is fine, which I would fix before doing the refactoring.

Target:
private int distToInt(double distance) { if (distance < 0) throw new IllegalArgumentException("Distance cannot be negative: " + distance); if (distance > MAX_DIST) { distance = MAX_DIST; } int integ = (int) Math.round(distance * INT_DIST_FACTOR); assert integ >= 0 : "distance out of range"; return integ; }
Source:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) { return; } BiFunction<Long, Long, Long> overwriteFunc = (oldFlags, newFlags) -> { return newFlags; START }; END setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, overwriteFunc); } It would be better to avoid creating this function on every method call.

Target:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, false, false); }
Source:
public ConnectionNotFoundException(List<Path> paths, PointList waypoints) { START super(unconnectedListString(paths), unconnectedInfo(paths, waypoints)); END } Wouldn't it be better to call `this(unconnectedListString(paths), unconnectedInfo(paths, waypoints));` in this case?

Target:
public ConnectionNotFoundException(List<Path> paths, PointList waypoints) { this(unconnectedListString(paths), unconnectedInfo(paths, waypoints)); }
Source:
public void readGraph() throws IOException { // TODO why 1000? START graphStorage.create(1000); END processJunctions(); processRoads(); } In very early version we gave a hint how large the graph can get, but this is no longer really necessary. Can be removed in another issue ;)

Target:
public void readGraph() { graphStorage.create(1000); processJunctions(); processRoads(); }
Source:
protected String removeRelation(String edgeName){ if(edgeName != null && edgeName.contains(", ")){ START edgeName = edgeName.substring(0, edgeName.lastIndexOf(',')); END } return edgeName; } Nice hack :) !

Target:
private String removeRelation(String edgeName){ if(edgeName != null && edgeName.contains(", ")){ edgeName = edgeName.substring(0, edgeName.lastIndexOf(',')); } return edgeName; }
Source:
boolean isPushingSection( OSMWay way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return way.hasTag("highway", pushingSections) || way.hasTag("railway", "platform") START || way.hasTag("bicycle", "dismount") END || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); } here we should use `isPushingSection` instead (?)

Target:
boolean isPushingSection( OSMWay way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return super.isPushingSection(way) || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); }
Source:
private boolean appendValue(final StringBuilder rval, final Long value, final String key, final boolean nonzeroFragmentVisited) { boolean append = nonzeroFragmentVisited; if (value == null) { return nonzeroFragmentVisited; } START if (!nonzeroFragmentVisited && value.longValue() > 0) { END append = true; } if (append) { rval.append(value.longValue()).append(key); return true; } return false; } Is boolean append necessary? nozeroFragmentVisited || value.longValue() > 0 would be more simple. Please check.

Target:
private boolean appendValue(final StringBuilder rval, final Long value, final String key, final boolean nonzeroFragmentVisited) { if (value == null) { return nonzeroFragmentVisited; } if (nonzeroFragmentVisited || value.longValue() > 0) { rval.append(value.longValue()).append(key); return true; } return false; }
Source:
private boolean loadDataFromSession() { HttpSession session = getHttpSession(); Object data = session.getAttribute(SESSION_KEY); START if ((data != null) && (data instanceof ReportSessionData)) { END ReportSessionData reportSessionData = (ReportSessionData) data; currentUser = reportSessionData.currentUser; dateFrom = reportSessionData.dateFrom; dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); dateTo = reportSessionData.dateTo; dateToFormated = DateTimeConverterUtil.dateToString(dateTo); return true; } else { return false; } } How about this: if (data == null || !(data instanceof ReportSessionData)) { return false }

Target:
private boolean loadDataFromSession() { HttpSession session = getHttpSession(); Object data = session.getAttribute(SESSION_KEY); if (!(data instanceof ReportSessionData)) { return false; } ReportSessionData reportSessionData = (ReportSessionData) data; currentUser = reportSessionData.currentUser; dateFrom = reportSessionData.dateFrom; dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); dateTo = reportSessionData.dateTo; dateToFormated = DateTimeConverterUtil.dateToString(dateTo); return true; }
Source:
private void dateFromDefaultInit() { START final Calendar calendarFrom = Calendar.getInstance(); END calendarFrom.add(Calendar.WEEK_OF_MONTH, -1); dateFrom = calendarFrom.getTime(); dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); } Remove the unnecessary final modifier from the local variables.

Target:
private void dateFromDefaultInit() { Calendar calendarFrom = Calendar.getInstance(); calendarFrom.add(Calendar.WEEK_OF_MONTH, -1); dateFrom = calendarFrom.getTime(); dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); }
Source:
public static String getPluginVersion() { START final String pluginVersion = ComponentAccessor.getPluginAccessor() END .getPlugin("org.everit.jira.timetracker.plugin") .getPluginInformation().getVersion(); return pluginVersion; } Remove all of the unnecessary final modifier from the local variables from all of the modified classes.

Target:
public static String getPluginVersion() { String pluginVersion = ComponentAccessor.getPluginAccessor() .getPlugin("org.everit.jira.timetracker.plugin") .getPluginInformation().getVersion(); return pluginVersion; }
Source:
public CookieFilter(CookieSpec cookieSpec) { START this.cookieSpec = cookieSpec; END this.allowMultipleCookiesWithTheSameName = false; this.cookieStore = new BasicCookieStore(); } re-use existing constructors: ``` this(cookieSpec, false); ```

Target:
public CookieFilter(CookieSpec cookieSpec) { this(cookieSpec, false); }
Source:
public StockSaver(final HibernateSessionProvider sessionProviderForLocal) { super(sessionProviderForLocal); START this.studyGermplasmListService = new StudyGermplasmListServiceImpl(sessionProviderForLocal); END } Better to autowire _studyGermplasmListService_ instead

Target:
public StockSaver(final HibernateSessionProvider sessionProviderForLocal) { super(sessionProviderForLocal); }
Source:
public FormulaDto save(final FormulaDto formulaDto) { Formula formula = FormulaUtils.convertToFormula(formulaDto); START formula = this.daoFactory.getFormulaDAO().save(formula); END final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; } @nahuel-soldevilla does not hibernate set the id to the object once the transaction is committed?

Target:
public FormulaDto save(final FormulaDto formulaDto) { final Formula formula = FormulaUtils.convertToFormula(formulaDto); this.daoFactory.getFormulaDAO().save(formula); final FormulaDto result = FormulaUtils.convertToFormulaDto(formula); return result; }
Source:
public MeasurementData(final String label, final String value) { super(); this.label = label; this.value = value; START this.changed = false; END } It's easiest to initiate the field directly, and I'm not sure it's needed, the primitive should be false by default

Target:
public MeasurementData(final String label, final String value) { super(); this.label = label; this.value = value; }
Source:
private static List<MarkerMetadataSet> buildMarkerMetadataSet(final Dataset dataset, final Map<String, Marker> markerMap) { START List<MarkerMetadataSet> markerMetadataSetList = new ArrayList<>(); END for (final Marker marker : markerMap.values()) { final MarkerMetadataSet mdb = new MarkerMetadataSet(); mdb.setDataset(dataset); mdb.setMarkerId(marker.getMarkerId()); mdb.setMarkerSampleId(1); markerMetadataSetList.add(mdb); } return markerMetadataSetList; } Please add final

Target:
private static List<MarkerMetadataSet> buildMarkerMetadataSet(final Dataset dataset, final Map<String, Marker> markerMap) { final List<MarkerMetadataSet> markerMetadataSetList = new ArrayList<>(); for (final Marker marker : markerMap.values()) { final MarkerMetadataSet mdb = new MarkerMetadataSet(); mdb.setDataset(dataset); mdb.setMarkerId(marker.getMarkerId()); mdb.setMarkerSampleId(1); markerMetadataSetList.add(mdb); } return markerMetadataSetList; }
Source:
public ProjectProperty(DmsProject project, Integer typeId, String value, Integer rank, Integer variableId, String alias) { this.project = project; this.typeId = typeId; this.value = value; this.rank = rank; this.variableId = variableId; this.alias = alias; START this.description = description; END } We can remove assignment to local variable description

Target:
public ProjectProperty(DmsProject project, Integer typeId, String value, Integer rank, Integer variableId, String alias) { this.project = project; this.typeId = typeId; this.value = value; this.rank = rank; this.variableId = variableId; this.alias = alias; }
Source:
public void setVariableTypeIfNull(){ if(this.getVariableType() != null) { return; } if(this.getRole() == null){ return; } START String propertyName = this.getStandardVariable().getProperty().getName(); END this.setVariableType(OntologyDataHelper.mapFromPhenotype(this.getRole(), propertyName)); } add final

Target:
public void setVariableTypeIfNull(){ if(this.getVariableType() != null) { return; } if(this.getRole() == null){ return; } final String propertyName = this.getStandardVariable().getProperty().getName(); this.setVariableType(OntologyDataHelper.mapFromPhenotype(this.getRole(), propertyName)); }
Source:
public Workbook strictParseWorkbook(final File file, final String programUUID) throws WorkbookParserException { final WorkbookParser parser = new WorkbookParser(this.maxRowLimit); final OntologyDataManagerImpl ontology = new OntologyDataManagerImpl(this.getSessionProvider()); START final GermplasmDataManager germplasmDataManager = new GermplasmDataManagerImpl(this.getSessionProvider()); END // partially parse the file to parse the description sheet only at first return this.strictParseWorkbook(file, parser, parser.parseFile(file, true), ontology, germplasmDataManager, programUUID); } Boy Scout Cleanup: ``` final OntologyDataManagerImpl ontology = new OntologyDataManagerImpl(this.getSessionProvider()); final GermplasmDataManager germplasmDataManager = new GermplasmDataManagerImpl(this.getSessionProvider()); ``` Instead of manual local creation of service dependencies like this, we should follow the standard pattern of having the OntologyDataManager and GermplasmDataManager interface typed class member variables and inject the services via spring auto wiring.

Target:
public Workbook strictParseWorkbook(final File file, final String programUUID) throws WorkbookParserException { final WorkbookParser parser = new WorkbookParser(this.maxRowLimit); // partially parse the file to parse the description sheet only at first return this.strictParseWorkbook(file, parser, parser.parseFile(file, true), programUUID); }
Source:
protected void initTiffParser() { super.initTiffParser(); // older .scn files require color correction // newer files from Versa systems do not if (handler != null) { Image i = handler.imageMap.get(0); START tiffParser.setYCbCrCorrection(!"versa".equalsIgnoreCase(i.devModel) && !"leica scn400".equalsIgnoreCase(i.devModel); END } } ```suggestion tiffParser.setYCbCrCorrection(!("versa".equalsIgnoreCase(i.devModel) || "leica scn400".equalsIgnoreCase(i.devModel))); ```

Target:
protected void initTiffParser() { super.initTiffParser(); // older .scn files require color correction // newer files from Versa systems do not if (handler != null) { Image i = handler.imageMap.get(0); tiffParser.setYCbCrCorrection(!("versa".equalsIgnoreCase(i.devModel) || "leica scn400".equalsIgnoreCase(i.devModel))); } }
Source:
public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); START if (jhdf != null) { END jhdf.close(); } jhdf = null; lastChannel = 0; } } if ``super.close`` throws an exception then ``jhdf`` is never closed

Target:
public void close(boolean fileOnly) throws IOException { try { super.close(fileOnly); } finally { if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); if (jhdf != null) { jhdf.close(); } jhdf = null; lastChannel = 0; } } }
Source:
protected void addGlobalMeta(String key, boolean value) { START addGlobalMeta(key, new Boolean(value)); END } The static `valueOf` methods are the ones to use here and below.

Target:
protected void addGlobalMeta(String key, boolean value) { addGlobalMeta(key, Boolean.valueOf(value)); }
Source:
public NodeValue exec(NodeValue nv) { START System.out.println(nv); END Node n = nv.asNode(); if ( ! n.isNodeTriple() ) throw new ExprEvalException(getClass().getSimpleName()+": Not a triple term: "+nv); Triple t = Node_Triple.triple(n); Node x = function(t); return NodeValue.makeNode(x); } Debug left-over?

Target:
public NodeValue exec(NodeValue nv) { Node n = nv.asNode(); if ( ! n.isNodeTriple() ) throw new ExprEvalException(getClass().getSimpleName()+": Not a triple term: "+nv); Triple t = Node_Triple.triple(n); Node x = function(t); return NodeValue.makeNode(x); }
Source:
public void run() { try { log.info(format("[Task %d] >> Sleep start", actionId)); for ( int i = 0 ; i < 10 ; i++ ) START Lib.sleep(sleepMilli/10); END log.info(format("[Task %d] << Sleep finish", actionId)); } catch (Exception ex) { log.info(format("[Task %d] **** Exception", actionId), ex); } } Out of curiosity, why `/ 10`? Is it to yield control so other things get a chance to run after every 1/10th of the sleep time?

Target:
public void run() { try { log.info(format("[Task %d] >> Sleep start", actionId)); Lib.sleep(sleepMilli); log.info(format("[Task %d] << Sleep finish", actionId)); } catch (Exception ex) { log.info(format("[Task %d] **** Exception", actionId), ex); } }
Source:
private static Iterator<Node> singleStep(Graph graph, boolean forward, Node node, Node property) { START Iter<Node> iter2 = null ; END if ( forward ) return G.find(graph, node, property, Node.ANY).mapWith(Triple::getObject); else return G.find(graph, Node.ANY, property, node).mapWith(Triple::getSubject); } Not used `iter2`

Target:
private static Iterator<Node> singleStep(Graph graph, boolean forward, Node node, Node property) { if ( forward ) return G.find(graph, node, property, Node.ANY).mapWith(Triple::getObject); else return G.find(graph, Node.ANY, property, node).mapWith(Triple::getSubject); }
Source:
private static void doJsonQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) { START JsonArray results = queryExecution.execJson();; END JSON.write(System.out, results); } Double `;`. Nit-pick, as it's normally harmelss (unless after some "end" statements like `return`, `break`, etc, I think?)

Target:
private static void doJsonQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) { JsonArray results = queryExecution.execJson(); JSON.write(System.out, results); }
Source:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; START return ngCache.getOrFill(gn, ()->GraphViewSwitchable.createNamedGraph(this, key)); END } Shouldn't the first `gn` reference on this line also be changed to `key` otherwise you are adding a potentially `null` key to the cache

Target:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(key, ()->GraphViewSwitchable.createNamedGraph(this, key)); }
Source:
public void testPerformAdd_Triple() { GraphWithPerform g = (GraphWithPerform) graphWith( producer.newInstance(), "S P O; S2 P2 O2"); g.getEventManager().register(GL); txnBegin(g); g.performAdd(triple("S3 P3 O3")); txnCommit(g); GL.assertEmpty(); START txnRun( g, new Runnable() { END @Override public void run() { assertTrue(g.contains(triple("S3 P3 O3"))); }}); } There is no need to explicitly have a `Runnable` here or in the other uses: ``` txnRun( g, ()->assertTrue(g.contains(triple("S3 P3 O3"))) ); ``` makes the tests shorter and clearer.

Target:
public void testPerformAdd_Triple() { GraphWithPerform g = (GraphWithPerform) graphWith( producer.newInstance(), "S P O; S2 P2 O2"); g.getEventManager().register(GL); txnBegin(g); g.performAdd(triple("S3 P3 O3")); txnCommit(g); GL.assertEmpty(); assertTrue(g.contains(triple("S3 P3 O3"))); }
Source:
public static void setupServer(boolean updateable, SecurityHandler sh) { // Clean datasets. dsgTesting = DatasetGraphFactory.createTxnMem(); server = FusekiEmbeddedServer.create() START .add(datasetPath(), dsgTesting) END .setPort(port()) .setSecurityHandler(sh) .build() .start(); } Looks like all of the test server instances will be in-memory datasets, which is great for speed. Will there be any places where the test server instances touch the disk?

Target:
public static void setupServer(boolean updateable, SecurityHandler sh) { setupServer(updateable, sh, DatasetGraphFactory.createTxnMem()); }