auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { START return initScore < other.getInitScore() ? -1 : 1; END } else { return Integer.compare(score, other.getScore()); } } Nitpick: we can use return Integer.compare(initScore, other.getInitScore()); here too

Target:
public int compareTo(SimpleScore other) { if (initScore != other.getInitScore()) { return Integer.compare(initScore, other.getInitScore()); } else { return Integer.compare(score, other.getScore()); } }
Source:
public List<Object> getJustificationList() { START return Collections.unmodifiableList(justificationList); END } We're duplicating it in the constructor and wrapping it here in an unmodifiable List on every call? Can we do that in the constructor then too? Still not sure if it's worth it though. This costs performance wise. 2 proposals: Proposal A): in constructor: Collections.unmodifiableList(new ArrayList<>(justificationList)) Proposal B: in constructor: Collections.unmodifiableList(justificationList) I suspect that for DRL and CS-B, proposal B is bugfree, so the duplication cost of proposal A is a perf loss. For CS-D we can duplicate before giving it to that constructor?

Target:
public List<Object> getJustificationList() { return justificationList; }
Source:
START public static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) { END return new DefaultSolverFactory<>(solverConfig); } I prefer shorter method names, when the important information can be said by the argument type - which is the case here. LGTM.

Target:
public static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) { // Does defensive copy of solverConfig, because the DefaultSolverFactory doesn't internalize it yet solverConfig = new SolverConfig(solverConfig); return new DefaultSolverFactory<>(solverConfig); }
Source:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { START super(constraintFactory, parent.getAnchor().filter(predicate)); END this.parent = parent; } ow, this could be dangerous. We need to bluejeans to discuss.

Target:
public DroolsFilterUniConstraintStream(DroolsConstraintFactory<Solution_> constraintFactory, DroolsAbstractUniConstraintStream<Solution_, A> parent, Predicate<A> predicate) { super(constraintFactory); this.parent = parent; this.predicate = predicate; }
Source:
public CompositeBiJoiner(List<SingleBiJoiner<A, B>> joinerList) { this.joinerList = joinerList; if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); START } END } Perhaps switch the store and the check?

Target:
public CompositeBiJoiner(List<SingleBiJoiner<A, B>> joinerList) { if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); } this.joinerList = joinerList; }
Source:
public CompositeTriJoiner(List<SingleTriJoiner<A, B, C>> joinerList) { this.joinerList = joinerList; if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); START } END } Possibly throw before assigning.

Target:
public CompositeTriJoiner(List<SingleTriJoiner<A, B, C>> joinerList) { if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); } this.joinerList = joinerList; }
Source:
protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(long unimprovedTimeMillisSpentLimit, Score unimprovedScoreDifferenceThreshold, START Clock clock) { END this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit; this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold; if (unimprovedTimeMillisSpentLimit <= 0L) { throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit + ") cannot be negative."); } this.clock = clock; } Suggestion: if you want to avoid the "align method parameters/call arguments when multiline or not" dilemma, format it like this: ```java protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination( long unimprovedTimeMillisSpentLimit, Score unimprovedScoreDifferenceThreshold, Clock clock ) { // body } ``` This is compatible with both "align ... when multiline" that's part of KIE Java Conventions and Geoffrey's IDE settings that keep ignoring KIE Java Conventions in this regard :wink:. I don't like the aligning either. I chose to follow KIE conventions so I have that rule checked but I always format like this which keeps the rule from applying.

Target:
protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination( long unimprovedTimeMillisSpentLimit, Score unimprovedScoreDifferenceThreshold, Clock clock) { this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit; this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold; if (unimprovedTimeMillisSpentLimit < 0L) { throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit + ") cannot be negative."); } this.clock = clock; }
Source:
public void stepEnded(LocalSearchStepScope stepScope) { super.stepEnded(stepScope); if (waterLevelIncrementScore != null) { currentWaterLevel = currentWaterLevel.subtract(waterLevelIncrementScore); } else { Score increment = currentWaterLevel.multiply(waterLevelIncrementRatio); currentWaterLevel = currentWaterLevel.subtract(increment); } START logger.debug(currentWaterLevel.toShortString()); END } @BorisKocian I think that this debug line needs to go away.

Target:
public void stepEnded(LocalSearchStepScope stepScope) { super.stepEnded(stepScope); if (waterLevelIncrementScore != null) { currentWaterLevel = currentWaterLevel.subtract(waterLevelIncrementScore); } else { Score increment = currentWaterLevel.multiply(waterLevelIncrementRatio); currentWaterLevel = currentWaterLevel.subtract(increment); } }
Source:
public void setWaterLevelIncrementScore(Score waterLevelIncrementScore) { this.waterLevelIncrementScore = waterLevelIncrementScore; START this.waterLevelIncrementRatio = null; END } Use a simple setter (notice that the setWaterLevelIncrementRatio doesn't have this side effect) and have either the AcceptorConfig set the default value, similar to how it sets 400 for Late Acceptance.

Target:
public void setWaterLevelIncrementScore(Score waterLevelIncrementScore) { this.waterLevelIncrementScore = waterLevelIncrementScore; }
Source:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; waterLevelIncrementRatio = DEFAULT_WATER_LEVEL_INCREMENT_RATIO; START waterLevelIncrementScore = null; END } Bug: running the phase twice (not really reproducible right now) will make it forget it's settings. remove these 2 lines.

Target:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; }
Source:
START public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { END // Listeners can only be removed/added from the solver thread: no ConcurrentModificationException if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent<Solution_> event = new SolvingStartedEvent<>(solver); for (SolverListener<Solution_> listener : eventListenerSet) { listener.solvingStarted(event); } } Unused parameter - maybe consistent but confusing.

Target:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { // Listeners can only be removed/added from the solver thread: no ConcurrentModificationException if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent event = new SolvingStartedEvent(solver); for (SolverListener listener : eventListenerSet) { listener.solvingStarted(event); } }
Source:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); START LocalTime endTime = LocalTime.ofSecondOfDay( END (timeGrain.getStartingMinuteOfDay() + timeGrain.GRAIN_LENGTH_IN_MINUTES) * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } } This variable is unused. It maybe a bug or useless code.

Target:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }
Source:
public boolean isGenerateDroolsTestOnError() { START return generateDroolsTestOnError != null && generateDroolsTestOnError.booleanValue(); END } The getter should return null if it's null. For all Config classes, it's important to distinguish between null (= not filled in) and the default value (the value it gets when it's null). This for example impacts the programmatic API after reading a solver config XML file. Also note that solver config files are sometimes written to XML (see benchmark report).

Target:
public Boolean isGenerateDroolsTestOnError() { return generateDroolsTestOnError; }
Source:
public String toString() { START return singleBenchmarkResult.toString() + "_" + problemStatisticType.toString(); END } when concatening strings with +, it's not needed to do .toString(). This gives the same result: ``` return singleBenchmarkResult + "_" + problemStatisticType; ``` Furthermore, it even avoids a nullpointerexception if for example problemStatisticType is null (which it never is in this particular case)

Target:
public String toString() { return singleBenchmarkResult + "_" + problemStatisticType; }
Source:
public void testKJarNotAvailable() { START boolean caughtException = false; END ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); //Use a non-existing version. config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); } Yes - the variable declared on line 80 is not used anywhere in the method.

Target:
public void testKJarNotAvailable() { ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); //Use a non-existing version. config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); }
Source:
protected int calculateActualMaximumSize(LocalSearchSolverPhaseScope scope) { START return this.calculateFadingTabuSize(scope) + this.calculateRegularTabuSize(scope); END } Mind removing the "this." so it matches the rest of the planner code style?

Target:
protected int calculateActualMaximumSize(LocalSearchSolverPhaseScope scope) { return calculateFadingTabuSize(scope) + calculateRegularTabuSize(scope); }
Source:
public void setup() throws Exception{ this.metadataStore = new HazelcastMetadataStore(map); START metadataStore.afterPropertiesSet(); END } `this.` must be used for properties access. The Checkstyle concern.

Target:
public void setup() throws Exception { this.metadataStore = new HazelcastMetadataStore(map); this.metadataStore.afterPropertiesSet(); }
Source:
private void verifyMembershipEvent(final Message<?> msg, final int membershipEvent) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof MembershipEvent); START assertEquals(((MembershipEvent) msg.getPayload()).getEventType(), membershipEvent); END assertNotNull(((MembershipEvent) msg.getPayload()).getMember()); } must be flipped. I mean you should exchange `expected` and `actual`. See `assertEquals` source code :smile:

Target:
private void verifyMembershipEvent(final Message<?> msg, final int membershipEvent) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof MembershipEvent); assertEquals(membershipEvent, ((MembershipEvent) msg.getPayload()).getEventType()); assertNotNull(((MembershipEvent) msg.getPayload()).getMember()); }
Source:
private void verifyDistributedObjectEvent(final Message<?> msg, final DistributedObjectEvent.EventType eventType, final String distributedObjectName) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof DistributedObjectEvent); assertEquals(((DistributedObjectEvent) msg.getPayload()).getEventType(), START eventType); END assertNotNull( (((DistributedObjectEvent) msg.getPayload()).getDistributedObject()) .getName(), distributedObjectName); } DITO

Target:
private void verifyDistributedObjectEvent(final Message<?> msg, final DistributedObjectEvent.EventType eventType, final String distributedObjectName) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof DistributedObjectEvent); assertEquals(eventType, ((DistributedObjectEvent) msg.getPayload()).getEventType()); assertNotNull( (((DistributedObjectEvent) msg.getPayload()).getDistributedObject()) .getName(), distributedObjectName); }
Source:
private void verifyLifecycleEvent(final Message<?> msg, final LifecycleState lifecycleState) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof LifecycleEvent); START assertEquals(((LifecycleEvent) msg.getPayload()).getState(), lifecycleState); END } OK. Revise, please, the whole project for this vulnerability.

Target:
private void verifyLifecycleEvent(final Message<?> msg, final LifecycleState lifecycleState) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof LifecycleEvent); assertEquals(lifecycleState, ((LifecycleEvent) msg.getPayload()).getState()); }
Source:
private void verifyDistributedQueue() { Assert.assertEquals(true, distributedQueue.size() == DATA_COUNT); Iterator<?> it = distributedQueue.iterator(); int index = 0; while (it.hasNext()) { Assert.assertEquals(index, it.next()); START index++; END } } Can be simplified: ``` int index = 0; for (Object o : distributedQueue) { Assert.assertEquals(index++, o); } ```

Target:
private void verifyDistributedQueue() { Assert.assertEquals(true, distributedQueue.size() == DATA_COUNT); int index = 0; for (Object o : distributedQueue) { Assert.assertEquals(index++, o); } }
Source:
private List<String> splitToLength(String text, int subStringSize) { START List<String> substrings = new ArrayList<String>(text.length() + subStringSize -1 / subStringSize); END for (int idx = 0; idx < text.length(); idx += subStringSize) { String substring = text.substring(idx, Math.min(text.length(), idx + subStringSize)); substrings.add(substring); } return substrings; } The mistake is here. `Div` operator has precedence over `minus`

Target:
private List<String> splitToLength(String text, int subStringSize) { List<String> substrings = new ArrayList<String>((text.length() + subStringSize -1) / subStringSize); for (int idx = 0; idx < text.length(); idx += subStringSize) { String substring = text.substring(idx, Math.min(text.length(), idx + subStringSize)); substrings.add(substring); } return substrings; }
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { START if (!this.initialized.getAndSet(true)) { END initialize(); } return exchanger.exchange(requestMessage); } An `AtomicBoolean` won't work here - you can get an NPE on the next statement. You need a synchronized block with a double null check.

Target:
protected Object handleRequestMessage(Message<?> requestMessage) { if (this.exchanger == null) { synchronized (this) { if (this.exchanger == null) { initialize(); } } } return this.exchanger.exchange(requestMessage); }
Source:
START public ImapMailInboundChannelAdapterSpec() { END this.receiver = new ImapMailReceiver(); } `Spec`s can't have `public` ctors: only access from factory methods.

Target:
ImapMailInboundChannelAdapterSpec() { this.receiver = new ImapMailReceiver(); }
Source:
public void handleMessage(Message<?> message) throws MessagingException { try { // todo support a gateway and have that gateway also handle message delivery receipt notifications // that will correlate this smsMessageId with the ID that comes back asynchronously from the SMSC indicating that // the message has been delivered. // this could require that we keep a correlation map since its possible upstream SMSC // unused return value -- see gateway SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); String[] smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); START logger.debug("message ID(s) for the sent message: " + Arrays.toString(smsMessageId)); END } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } } Having the `List<String> smsMessageId` it will be redundant to wrap array to String

Target:
public void handleMessage(Message<?> message) throws MessagingException { try { // todo support a gateway and have that gateway also handle message delivery receipt notifications // that will correlate this smsMessageId with the ID that comes back asynchronously from the SMSC indicating that // the message has been delivered. // this could require that we keep a correlation map since its possible upstream SMSC // unused return value -- see gateway SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); List<String> smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); logger.debug("message ID(s) for the sent message: " + smsMessageId); } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }
Source:
START private char[] fileToCharArray(File file) throws IOException { END FileInputStream is = new FileInputStream(file); try { return streamToCharArray(is); } finally { is.close(); } } Good catch!

Target:
private static char[] fileToCharArray(File file) throws IOException { FileInputStream is = new FileInputStream(file); try { return streamToCharArray(is); } finally { is.close(); } }
Source:
public void write(AsyncHttpRequest request, DataSink sink, CompletedCallback completed) { START Util.pump(stream, sink, completed); END } There's a variant of Util.pump that takes a length argument: ``` java public static void pump(final InputStream is, final int max, final DataSink ds, final CompletedCallback callback) ``` See: max. Specify that, and it won't read more than that many bytes from the stream.

Target:
public void write(AsyncHttpRequest request, DataSink sink, CompletedCallback completed) { Util.pump(stream, this.length, sink, completed); }
Source:
private DefaultHttpClient getHttpClient(MetricServiceAppConfiguration passedConfig) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); int maxTotalPoolConnections = passedConfig.getMetricServiceConfig().getMaxTotalPoolConnections(); int maxPoolConnectionsPerRoute = passedConfig.getMetricServiceConfig().getMaxPoolConnectionsPerRoute(); START log.info("Setting up pool with total connections and max connections per route.", maxTotalPoolConnections, maxPoolConnectionsPerRoute); END cm.setMaxTotal(maxTotalPoolConnections); cm.setDefaultMaxPerRoute(maxPoolConnectionsPerRoute); return new DefaultHttpClient(cm); } maybe debug?

Target:
private DefaultHttpClient getHttpClient(MetricServiceAppConfiguration passedConfig) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); int maxTotalPoolConnections = passedConfig.getMetricServiceConfig().getMaxTotalPoolConnections(); int maxPoolConnectionsPerRoute = passedConfig.getMetricServiceConfig().getMaxPoolConnectionsPerRoute(); log.debug("Setting up pool with total connections and max connections per route.", maxTotalPoolConnections, maxPoolConnectionsPerRoute); cm.setMaxTotal(maxTotalPoolConnections); cm.setDefaultMaxPerRoute(maxPoolConnectionsPerRoute); return new DefaultHttpClient(cm); }
Source:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); START System.out.println(formData.getJsonPayload()); END } catch (IOException e) { throw new FormDataSaveException(e); } } I think this log is no longer in use.

Target:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); } catch (IOException e) { throw new FormDataSaveException(e); } }
Source:
boolean uploadFormDataToServer(List<FormData> allFormData, boolean result) throws IOException { for (FormData formData : allFormData) { String rawPayload = formData.getJsonPayload(); START System.out.println(rawPayload); END // inject consultation.sourceUuid formData = injectUuidToPayload(formData); // replace media paths with base64 string formData = replaceMediaPathWithBase64String(formData); if (formService.syncFormData(formData)) { formData.setStatus(STATUS_UPLOADED); //DO NOT save base64 string in DB formData.setJsonPayload(rawPayload); formService.saveFormData(formData); } else { result = false; } } return result; } This is also no longer needed.

Target:
boolean uploadFormDataToServer(List<FormData> allFormData, boolean result) throws IOException { for (FormData formData : allFormData) { String rawPayload = formData.getJsonPayload(); // inject consultation.sourceUuid formData = injectUuidToPayload(formData); // replace media paths with base64 string formData = replaceMediaPathWithBase64String(formData); if (formService.syncFormData(formData)) { formData.setStatus(STATUS_UPLOADED); //DO NOT save base64 string in DB formData.setJsonPayload(rawPayload); formService.saveFormData(formData); } else { result = false; } } return result; }
Source:
public void saveOrUpdateCohorts(List<Cohort> cohorts) throws CohortSaveException { try { for(Cohort cohort: cohorts){ if(cohortService.getCohortByUuid(cohort.getUuid()) == null){ cohortService.saveCohort(cohort); } else { cohortService.updateCohort(cohort); } } START cohortService.saveCohorts(cohorts); END } catch (IOException e) { throw new CohortSaveException(e); } } Is this call supposed to be made after going through the loop?

Target:
public void saveOrUpdateCohorts(List<Cohort> cohorts) throws CohortSaveException { try { for(Cohort cohort:cohorts){ if(StringUtils.isEmpty(cohort.getUuid())){ cohortService.saveCohort(cohort); } else { cohortService.updateCohort(cohort); } } } catch (IOException e) { throw new CohortSaveException(e); } }
Source:
public Boolean isSHREnabled(){ START boolean enableSHR = true; END try { MuzimaSetting muzimaSHRStatus = getSettingByProperty(SHR_STATUS_SETTING); enableSHR = muzimaSHRStatus.getValueBoolean(); } catch (MuzimaSettingFetchException e){ Log.e(getClass().getSimpleName(), "Could not fetch requireMedicalRecordNumber setting. ", e); } return enableSHR; } Make enableSHR default value to false

Target:
public Boolean isSHREnabled(){ boolean enableSHR = false; try { MuzimaSetting muzimaSHRStatus = getSettingByProperty(SHR_STATUS_SETTING); enableSHR = muzimaSHRStatus.getValueBoolean(); } catch (MuzimaSettingFetchException e){ Log.e(getClass().getSimpleName(), "Could not fetch requireMedicalRecordNumber setting. ", e); } return enableSHR; }
Source:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { START Toast.makeText(observationsByEncounterAdapter.getContext(),"This patient does not have any SHR data.", Toast.LENGTH_SHORT).show(); END return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } } Shouldn't we have two Toast messages, one when using SHR and another when not using SHR using if condition as ones in doInBackground

Target:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }
Source:
public void setCardDetail(CardDetails cardDetail) { START CardDetail = cardDetail; END } Shouln't this be this.variable name. This is a Potential Null pointer Exception.

Target:
public void setCardDetail(CardDetails cardDetail) { this.cardDetail = cardDetail; }
Source:
protected void onPreExecute() { START System.out.println("onPreExecute"); END Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploading SHR Data", Toast.LENGTH_SHORT).show(); } Logging using standard output

Target:
protected void onPreExecute() { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploading SHR Data", Toast.LENGTH_SHORT).show(); }
Source:
protected void onPostExecute(Integer[] result){ START System.out.println("onPostExecute"); END if(result[0] == SUCCESS) { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploaded " + result[1] +" SHR Data items", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Error Uploading SHR Data. Uploaded " + result[1] + ", Failed " + result[2], Toast.LENGTH_SHORT).show(); } syncInProgress = false; } Logging using standard output

Target:
protected void onPostExecute(Integer[] result){ if(result[0] == SUCCESS) { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploaded " + result[1] +" SHR Data items", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Error Uploading SHR Data. Uploaded " + result[1] + ", Failed " + result[2], Toast.LENGTH_SHORT).show(); } syncInProgress = false; }
Source:
public void onBackPressed(){ patientAdapter.cancelBackgroundTask(); listView.clearFocus(); super.onBackPressed(); if(getCurrentFocus() != null) { START System.out.println("Current focusssssssss: " + getCurrentFocus().toString()); END } else { System.out.println("Current focusssssssss: null"); } } Do we need to remove this?

Target:
public void onBackPressed(){ patientAdapter.cancelBackgroundTask(); listView.clearFocus(); super.onBackPressed(); }
Source:
public void onKeyboardClosed() { fabSearchButton.setVisibility(View.VISIBLE); // fabSearchButton.setFocusable(true); // boolean f=fabSearchButton.requestFocus(); listView.clearChoices(); if(getCurrentFocus() != null) { System.out.println("Current focus: " + getCurrentFocus().toString()); } else { START System.out.println("Current focus: null"); END } } Do we need to remove this?

Target:
public void onKeyboardClosed() { fabSearchButton.setVisibility(View.VISIBLE); listView.clearChoices(); }
Source:
START public TermsOfUse getTermsOfUse() { END return termsOfUse; } Can't this just be a string, rather than an object?

Target:
public String getTermsOfUse() { return termsOfUse; }
Source:
public SegmentRef toRef() { START return new SegmentRef(checkNotNull(this.getId().toString(), END "Can't create reference for segment without ID")); } this is a bit weird, is calling the toString method actually the right thing to do?

Target:
public SegmentRef toRef() { return new SegmentRef(checkNotNull(this.getId(), "Can't create reference for segment without ID")); }
Source:
START public static void copyTo(Localized from, Localized to) { END to.locale = from.locale; } Should this be `protected` since if someone were to use this method on a sub-class, it wouldn't do the right thing.

Target:
protected static void copyTo(Localized from, Localized to) { to.locale = from.locale; }
Source:
public boolean equals(Object obj) { START if (obj instanceof ApplicationCredentials) { END ApplicationCredentials other = (ApplicationCredentials) obj; return Objects.equal(this.getApiKey(), other.getApiKey()); } return false; } And again with an instance equality. Does it make sense to have credentials without an API key?

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ApplicationCredentials) { ApplicationCredentials other = (ApplicationCredentials) obj; return this.getApiKey().equals(other.getApiKey()); } return false; }
Source:
public void sendLastNEndpointsChangeEvent( Collection<String> forwardedEndpoints, Collection<String> endpointsEnteringLastN, Collection<String> conferenceEndpoints) { // We want endpointsEnteringLastN to always to reported. Consequently, // we will pretend that all lastNEndpoints are entering if no explicit // endpointsEnteringLastN is specified. // XXX do we really want that? if (endpointsEnteringLastN == null) { endpointsEnteringLastN = forwardedEndpoints; } String msg = createLastNEndpointsChangeEvent( forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); sendMessage(msg); START notifyForwardedEndpointsChanged(forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); END } Hm, wondering if this feels a bit weird since this call already came from _outside_ the endpoint. If anything, it seems like we shouldn't forward this here and instead have BitrateController be the source of truth (like in your other PR)

Target:
private void sendLastNEndpointsChangeEvent( Collection<String> forwardedEndpoints, Collection<String> endpointsEnteringLastN, Collection<String> conferenceEndpoints) { // We want endpointsEnteringLastN to always to reported. Consequently, // we will pretend that all lastNEndpoints are entering if no explicit // endpointsEnteringLastN is specified. // XXX do we really want that? if (endpointsEnteringLastN == null) { endpointsEnteringLastN = forwardedEndpoints; } String msg = createLastNEndpointsChangeEvent( forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); sendMessage(msg); }
Source:
public int resetAt(int seq) { int delta = Vp8Utils.getExtendedPictureIdDelta(seq, highestSeqNumReceived); if (delta < 0) { roc++; START highestSeqNumReceived = seq; END } return getIndex(seq, true); } Should this also happen when `delta >= 0`?

Target:
public void resetAt(int seq) { int delta = Vp8Utils.getExtendedPictureIdDelta(seq, highestSeqNumReceived); if (delta < 0) { roc++; highestSeqNumReceived = seq; } getIndex(seq, true); }
Source:
public synchronized FrameInsertionResult insertPacket(@NotNull Vp8Packet packet) { int pictureId = packet.getPictureId(); VP8Frame frame = frameHistory.get(pictureId); if (frame != null) { return doFrameInsert(frame, packet); } frame = new VP8Frame(packet); START if (!frameHistory.insert(pictureId, frame)) END return null; return new FrameInsertionResult(frame, true); } braces please

Target:
public synchronized FrameInsertionResult insertPacket(@NotNull Vp8Packet packet) { int pictureId = packet.getPictureId(); VP8Frame frame = frameHistory.get(pictureId); if (frame != null) { return doFrameInsert(frame, packet); } frame = new VP8Frame(packet); if (!frameHistory.insert(pictureId, frame)) { return null; } return new FrameInsertionResult(frame, true); }
Source:
START public Integer getInteger(String key, int defaultValue) { END return parseValueOrDefault(key, Integer::parseInt, defaultValue); } а возвращать Integer зачем? int же

Target:
public int getInteger(String key, int defaultValue) { return parseValueOrDefault(key, Integer::parseInt, defaultValue); }
Source:
START public Response toResponseInternal(Response.StatusType status, LoggingLevel loggingLevel, T exception) { END logException(exception, loggingLevel); return serializeException(status, exception); } может тогда `protected`, раз он такой internal?

Target:
protected Response toResponseInternal(Response.StatusType status, LoggingLevel loggingLevel, T exception) { logException(exception, loggingLevel); return serializeException(status, exception); }
Source:
private static boolean isMasterDataSource() { String dataSourceName = DataSourceContextUnsafe.getDataSourceType(); START return dataSourceName == null || MASTER.equals(dataSourceName); END } быть может это более уместно в самом getDataSourceType ? чтоб он не возвращал никогда нуллов

Target:
private static boolean isMasterDataSource() { String dataSourceName = DataSourceContextUnsafe.getDataSourceType(); return MASTER.equals(dataSourceName); }
Source:
public String[] getPackagesToScan() { START return packagesToScan.toArray(new String[packagesToScan.size()]); END } лучше new String[0], по перформансу лучше будет. Как-то кто-то (Коля кажется) скидывал статью про это. Суть - new String[packagesToScan.size()] - создат и проинитит массив с дефолтными значениями, потом toArray поверх запишет новых значений. а new String[0] выполнится в момент, с минимумом инициализации, а toArray умеет создавать массив сразу с нужными значениями

Target:
public String[] getPackagesToScan() { return packagesToScan.toArray(new String[0]); }
Source:
public static Date parseDate(String date, String format) { START return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); END } Is a null check for the passed in "date" required here for safety?

Target:
public static Date parseDate(String date, String format) { if (date == null) { return null; } return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); }
Source:
public static KFunction<?> findKotlinFunction(Method method) { KFunction<?> kotlinFunction = ReflectJvmMapping.getKotlinFunction(method); START if (kotlinFunction == null) { END // Fallback to own lookup because there's no public Kotlin API for that kind of lookup until // https://youtrack.jetbrains.com/issue/KT-20768 gets resolved. return findKFunction(method).orElse(null); } return kotlinFunction; } Ternary if?

Target:
public static KFunction<?> findKotlinFunction(Method method) { KFunction<?> kotlinFunction = ReflectJvmMapping.getKotlinFunction(method); // Fallback to own lookup because there's no public Kotlin API for that kind of lookup until // https://youtrack.jetbrains.com/issue/KT-20768 gets resolved. return kotlinFunction == null ? findKFunction(method).orElse(null) : kotlinFunction; }
Source:
START public T getNullable() { END T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; } How about sticking following the `Optional` `orElse(…)` pattern? Staying with Java's names and `Optional` idioms gives more flexibility and it's a bit more familiar to users.

Target:
private T getNullable() { T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }
Source:
private Optional<MethodExecutor> getMethodExecutor(EvaluationContextExtensionAdapter adapter, String name, List<TypeDescriptor> argumentTypes) { FunctionsMap functions = adapter.getFunctions(); Optional<Function> function = functions.get(name, argumentTypes); START return function.map(FunctionMethodExecutor::new); END } Inline `function`?

Target:
private Optional<MethodExecutor> getMethodExecutor(EvaluationContextExtensionAdapter adapter, String name, List<TypeDescriptor> argumentTypes) { return adapter.getFunctions().get(name, argumentTypes).map(FunctionMethodExecutor::new); }
Source:
public Writing(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { START super(convertiblePair, function); END } Is public visibility modifier required?

Target:
Writing(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { super(convertiblePair, function); }
Source:
START Class<?> getRepositoryInterfaceFrom(BeanDefinition beanDefinition) { END if (beanDefinition instanceof ScannedGenericBeanDefinition) { try { return ((ScannedGenericBeanDefinition) beanDefinition).resolveBeanClass(beanClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not resolve bean class.", e); } } else { return getRepositoryInterfaceFromFactory(beanDefinition); } } Can this stay private?

Target:
private Class<?> getRepositoryInterfaceFrom(BeanDefinition beanDefinition) { if (beanDefinition instanceof ScannedGenericBeanDefinition) { try { return ((ScannedGenericBeanDefinition) beanDefinition).resolveBeanClass(beanClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not resolve bean class.", e); } } else { return getRepositoryInterfaceFromFactory(beanDefinition); } }
Source:
START private RootBeanDefinition createBeanDefinition() { END RootBeanDefinition beanDefinition = new RootBeanDefinition("com.acme.MyRepository"); ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(MyRepository.class); beanDefinition.setConstructorArgumentValues(constructorArgumentValues); return beanDefinition; } Static?

Target:
private static RootBeanDefinition createBeanDefinition() { RootBeanDefinition beanDefinition = new RootBeanDefinition("com.acme.MyRepository"); ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(MyRepository.class); beanDefinition.setConstructorArgumentValues(constructorArgumentValues); return beanDefinition; }
Source:
public DefaultRepositoryMetadata(Class<?> repositoryInterface) { super(repositoryInterface); Assert.isTrue(Repository.class.isAssignableFrom(repositoryInterface), MUST_BE_A_REPOSITORY); START Class<? extends Serializable> idType = resolveIdType(repositoryInterface); END Class<?> domainType = resolveDomainType(repositoryInterface); Assert.notNull(idType, "IdType must not be null!"); Assert.notNull(domainType, "DomainType must not be null!"); this.idType = idType; this.domainType = domainType; } Could be assigned to the field directly.

Target:
public DefaultRepositoryMetadata(Class<?> repositoryInterface) { super(repositoryInterface); Assert.isTrue(Repository.class.isAssignableFrom(repositoryInterface), MUST_BE_A_REPOSITORY); this.idType = resolveIdType(repositoryInterface); this.domainType = resolveDomainType(repositoryInterface); }
Source:
public Optional<SolrConfiguration> getSolrConfiguration() { START return null; END } Why not Optional.empty()?

Target:
public Optional<SolrConfiguration> getSolrConfiguration() { return Optional.empty(); }
Source:
public String renderArticle(HttpServletRequest request, Model model, @SiteParam Site site, RequestedDoiVersion articleId) throws IOException { ArticlePointer articlePointer = articleMetadataFactory.get(site, articleId) .validateVisibility("article") .populate(request, model) .fillAmendments(model) .getArticlePointer(); XmlContent xmlContent = getXmlContent(site, articlePointer); model.addAttribute("articleText", xmlContent.html); model.addAttribute("references", xmlContent.references); START model.addAttribute("isArticlePage", true); END return site + "/ftl/article/article"; } I would rather not involve controller code in this fix if we can help it. Could we just put ``` html <#assign isArticlePage = true /> ``` near the top of `article.ftl` instead? Also, won't this create inconsistency between the main article body tab and all the other article pages? As currently implemented, I think we would get "Journal Title: Journal Slogan" on non-article pages, "Article Title" on the main body tab, and "Journal Title: Article Title" on the other article pages.

Target:
public String renderArticle(HttpServletRequest request, Model model, @SiteParam Site site, RequestedDoiVersion articleId) throws IOException { ArticlePointer articlePointer = articleMetadataFactory.get(site, articleId) .validateVisibility("article") .populate(request, model) .fillAmendments(model) .getArticlePointer(); XmlContent xmlContent = getXmlContent(site, articlePointer); model.addAttribute("articleText", xmlContent.html); model.addAttribute("references", xmlContent.references); return site + "/ftl/article/article"; }
Source:
private String getParentArticleDoiFromComment(Map<String, Object> comment) { START return (String) ((Map<String, Object>) ((Map<String, Object>) comment.get("parentArticle")).get("doi")).get("doiName"); END } Yep, I poked around a little and it looks like we've just never serialized a `Doi` object before, apparently because we usually start with model classes that don't use the `Doi` wrapper. The best route here is probably just a global Gson adapter that serializes `Doi` to a primitive `JsonElement` (rather than an object). See `AdapterRegistry` and let me know if you'd like some help getting it wired.

Target:
private static String getParentArticleDoiFromComment(Map<String, Object> comment) { return (String) (((Map<String, Object>) comment.get("parentArticle")).get("doi")); }
Source:
public Map<?, ?> lookupArticlesByDois(List<String> dois) throws IOException { String doiQueryString = Joiner.on(" OR ").join(dois); ArticleSearchQuery.Builder query = ArticleSearchQuery.builder() .setQuery(doiQueryString) .setStart(0) .setRows(dois.size()) START .setDateRange(SolrSearchApiImpl.SolrEnumeratedDateRange.ALL_TIME); END return search(query.build()); } do we even need to set the dateRange?

Target:
public Map<?, ?> lookupArticlesByDois(List<String> dois) throws IOException { String doiQueryString = Joiner.on(" OR ").join(dois); ArticleSearchQuery.Builder query = ArticleSearchQuery.builder() .setQuery(doiQueryString) .setStart(0) .setRows(dois.size()); return search(query.build()); }
Source:
public CategoryView findCategory(CategoryView parentCategoryView, String category) throws IOException { String cacheKey = "singleCategory:" START + CacheParams.createKeyHash(category + parentCategoryView.hashCode()); END return CacheUtil.getOrCompute(cache, cacheKey, () -> findCategoryWithoutCache(parentCategoryView, category)); } `CategoryView.hashCode()` just returns the `hashCode` of its `name` field, and `String.hashCode()` is not collision-resistant. Meaning, there is a small chance (but not astronomically small as with SHA-1) that the cache key could collide with another parent of the same category. `CacheParams` already provides a way to make a collision-resistant key out of two strings. I recommend ``` java String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category, parentCategoryView.getName()); ```

Target:
public CategoryView findCategory(CategoryView parentCategoryView, String category) throws IOException { String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category, parentCategoryView.getName()); return CacheUtil.getOrCompute(cache, cacheKey, () -> findCategoryWithoutCache(parentCategoryView, category)); }
Source:
private boolean isSimpleSearch(String query) { START return Arrays.stream(AdvancedSearchTerms.class.getEnumConstants()) END .noneMatch(e -> query.contains(e.text)); } Based on this documentation https://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html you can use values() instead of "class.getEnumConstants()", which I think is cleaner.

Target:
private boolean isSimpleSearch(String query) { return Arrays.stream(AdvancedSearchTerms.values()).noneMatch(e -> query.contains(e.text)); }
Source:
public SiteRequestCondition(SiteResolver siteResolver, Set<String> validSites){ this.siteResolver = Preconditions.checkNotNull(siteResolver); START this.validSites = ImmutableSet.copyOf(Preconditions.checkNotNull(validSites)); END } You don't need the `checkNotNull` here. `ImmutableSet.copyOf` checks for null arguments on its own.

Target:
public SiteRequestCondition(SiteResolver siteResolver, Set<String> validSites){ this.siteResolver = Preconditions.checkNotNull(siteResolver); this.validSites = ImmutableSet.copyOf(validSites); }
Source:
public SiteRequestCondition combine(SiteRequestCondition other) { Set<String> combinedIncludedSites = new ImmutableSet.Builder<String>() .addAll(includedSites) .addAll(other.includedSites) .build(); Set<String> combinedExcludedSites = new ImmutableSet.Builder<String>() .addAll(excludedSites) .addAll(other.excludedSites) .build(); START return new SiteRequestCondition(siteSet, siteResolver, combinedIncludedSites, combinedExcludedSites); END } I'm less than 100% clear on how Spring uses this method, but do we need to guard here against `combinedIncludedSites` and `combinedExcludedSites` ending up with overlapping elements? (For that matter, maybe we should check that in the constructor also.)

Target:
public SiteRequestCondition combine(SiteRequestCondition other) { Set<String> combinedIncludedSites = new ImmutableSet.Builder<String>() .addAll(includedSites) .addAll(other.includedSites) .build(); Set<String> combinedExcludedSites = new ImmutableSet.Builder<String>() .addAll(excludedSites) .addAll(other.excludedSites) .build(); return create(siteSet, siteResolver, combinedIncludedSites, combinedExcludedSites); }
Source:
public List<Object> getArticles(HomeController context, SectionSpec section, Site site, int start) throws IOException { Map<?, ?> result = context.solrSearchService.getHomePageArticles( START Collections.singletonList(site.getJournalKey()), start, section.resultCount, END SolrSearchService.SolrSortOrder.DATE_NEWEST_FIRST); return sanitizeSolrResults(result); } Instead of altering these method signatures, would it be more readable if we had an overloaded method signature that accepts a singular site?

Target:
public List<Object> getArticles(HomeController context, SectionSpec section, Site site, int start) throws IOException { Map<?, ?> result = context.solrSearchService.getHomePageArticles(site.getJournalKey(), start, section.resultCount, SolrSearchService.SolrSortOrder.DATE_NEWEST_FIRST); return sanitizeSolrResults(result); }
Source:
START HtmlElementTransformation(String tagName, String attributeName) { END this.matchingTagName = tagName; this.matchingAttributeName = attributeName; } Similarly to the `static enum` thing, I subjectively like to make enum constructors explicitly `private` even though there's no practical difference. Any particular rationale for this change?

Target:
private HtmlElementTransformation(String tagName, String attributeName) { this.matchingTagName = tagName; this.matchingAttributeName = attributeName; }
Source:
private CacheParams(String cacheKey, Optional<Integer> timeToLive) { this.cacheKey = Preconditions.checkNotNull(cacheKey); START this.timeToLive = timeToLive; END } Just to be really style-conscious, `Preconditions.checkNotNull` would be good on `timeToLive` as well. Or you could move the `Optional.fromNullable` to this line and change the constructor argument from `Optional<Integer>` to `Integer`.

Target:
private CacheParams(String cacheKey, Optional<Integer> timeToLive) { this.cacheKey = Preconditions.checkNotNull(cacheKey); this.timeToLive = Preconditions.checkNotNull(timeToLive); }
Source:
private void addPatternToIndex(TripPattern tripPattern) { for (Stop stop: tripPattern.getStops()) { START if (!patternsForStop.containsEntry(stop, tripPattern)) { END patternsForStop.put(stop, tripPattern); } } } This conditional is probably not necessary, even from a performance point of view. The meaning might be clearer with only the put() call and no conditional.

Target:
private void addPatternToIndex(TripPattern tripPattern) { for (Stop stop: tripPattern.getStops()) { patternsForStop.put(stop, tripPattern); } }
Source:
private void assertOperators(Collection<Operator> operators) { Operator o = list(operators).get(0); assertEquals("RUT:Operator:130c", o.getId().getId()); assertEquals("Ruter", o.getName()); assertNull( o.getUrl()); assertNull(o.getPhone()); START assertEquals(1, operators.size()); END } I find the body more readable if the size is asserted first, because the Collection is not ordered, so the get(0) operation does not appear deterministic until you know its length is one.

Target:
private void assertOperators(Collection<Operator> operators) { assertEquals(1, operators.size()); Operator o = list(operators).get(0); assertEquals("RUT:Operator:130c", o.getId().getId()); assertEquals("Ruter", o.getName()); assertNull( o.getUrl()); assertNull(o.getPhone()); }
Source:
public static String convertStreamToString(java.io.InputStream is) { START java.util.Scanner scanner = null; END String result=""; try { scanner = new java.util.Scanner(is).useDelimiter("\\A"); result = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } finally { if(scanner!=null) scanner.close(); } return result; } `public`?

Target:
private static String convertStreamToString(java.io.InputStream is) { java.util.Scanner scanner = null; String result=""; try { // The delimiter is \A which means "beginning of input". That can't match anything later in the input. // So it will read everything in to the end of the stream. scanner = new java.util.Scanner(is).useDelimiter("\\A"); result = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } finally { if(scanner!=null) { scanner.close(); } } return result; }