auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Slice varcharToCharSaturatedFloorCast(@LiteralParameter("y") long y, @SqlType("varchar(x)") Slice slice) { List<Integer> codePoints = new ArrayList<>(toCodePoints(slice)); if (codePoints.size() >= y) { <START> trimTrailingSpaces(codePoints); <END> List<Integer> codePointsTruncated = codePoints.stream() .limit(y) .collect(toImmutableList()); return codePointsToSliceUtf8(codePointsTruncated); } int lastNonZeroCharIndex = codePoints.size() - 1; while (lastNonZeroCharIndex >= 0 && codePoints.get(lastNonZeroCharIndex) == 0) { codePoints.remove(lastNonZeroCharIndex); lastNonZeroCharIndex--; } if (lastNonZeroCharIndex < 0) { return codePointsToSliceUtf8(nCopies(toIntExact(y), 0)); } codePoints.set(lastNonZeroCharIndex, codePoints.get(lastNonZeroCharIndex) - 1); verify(codePoints.size() == lastNonZeroCharIndex + 1); codePoints.addAll(nCopies(toIntExact(y) - codePoints.size(), Character.MAX_CODE_POINT)); verify(!codePoints.isEmpty()); verify(codePoints.get(codePoints.size() - 1) != ' '); return codePointsToSliceUtf8(codePoints); }</code><technical_language>is reason for calling trimTrailingSpaces(codePoints) here</technical_language>

Target:
public static Slice varcharToCharSaturatedFloorCast(@LiteralParameter("y") long y, @SqlType("varchar(x)") Slice slice) { List<Integer> codePoints = new ArrayList<>(toCodePoints(slice)); if (codePoints.size() >= y) { codePoints = trimTrailing(codePoints, ' '); List<Integer> codePointsTruncated = codePoints.stream() .limit(y) .collect(toImmutableList()); return codePointsToSliceUtf8(codePointsTruncated); } codePoints = trimTrailing(codePoints, '\0'); if (codePoints.isEmpty()) { return codePointsToSliceUtf8(nCopies(toIntExact(y), (int) '\0')); } codePoints = new ArrayList<>(codePoints); codePoints.set(codePoints.size() - 1, codePoints.get(codePoints.size() - 1) - 1); codePoints.addAll(nCopies(toIntExact(y) - codePoints.size(), Character.MAX_CODE_POINT)); verify(codePoints.get(codePoints.size() - 1) != ' '); return codePointsToSliceUtf8(codePoints); }
Source:
<code>private String prepareStringBindValue(String filter, String value) { if (!(criteria.isStrict() || (null != criteria.getStrictFilters() && Arrays.asList(criteria.getStrictFilters()) .contains(filter)))) { <START> <END> value = "%" + QueryUtility.escapeSearchParameter(value) + "%"; } if (!(criteria.isCaseSensitive() || (null != criteria.getCaseSensitiveFilters() && Arrays.asList( criteria.getCaseSensitiveFilters()).contains(filter)))) { value = value.toLowerCase(); } return value; }</code><technical_language>If strictFilters a Set, this simplified to: java if (!criteria.isStrict() && !criteria.getStrictFilters().contains(filter)) { avoids creation of ArrayList time this method is called</technical_language>

Target:
private String prepareStringBindValue(String filter, String value) { if (!criteria.isStrict() && !arrayContains(criteria.getStrictFilters(), filter)) { value = "%" + QueryUtility.escapeSearchParameter(value) + "%"; } if (!criteria.isCaseSensitive() && !arrayContains(criteria.getCaseSensitiveFilters(), filter)) { value = value.toLowerCase(); } return value; }
Source:
<code>private void emitLineage(BatchSourceContext context) { Schema schema = sourceConfig.getSchema(context.getFailureCollector()); LineageRecorder lineageRecorder = new LineageRecorder(context, sourceConfig.referenceName); lineageRecorder.createExternalDataset(schema); if (schema != null && schema.getFields() != null) { lineageRecorder.recordRead("Read", "Read from DB.", <START> schema.getFields().stream().map(Schema.Field::getName).collect( <END> Collectors.toList())); } }</code><technical_language>indentation is wrong. align "Read" in previous line</technical_language>

Target:
private void emitLineage(BatchSourceContext context) { Schema schema = sourceConfig.getSchema(context.getFailureCollector()); if (schema == null) { schema = context.getOutputSchema(); } LineageRecorder lineageRecorder = new LineageRecorder(context, sourceConfig.referenceName); lineageRecorder.createExternalDataset(schema); if (schema != null && schema.getFields() != null) { lineageRecorder.recordRead("Read", "Read from DB.", schema.getFields().stream().map(Schema.Field::getName).collect(Collectors.toList())); } }
Source:
<code>public void VETemplateTests_004_CheckBlockedTransclusion() { articleName = PageContent.articleNamePrefix + base.getTimeStamp(); VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); String selectText = PageContent.articleText.substring(12, 13); int numBlockTransclusion = ve.getNumberOfBlockTransclusion(); int numInlineTransclusion = ve.getNumberOfInlineTransclusion(); ve.typeTextArea(PageContent.articleText); ve.selectText(selectText); VisualEditorInsertTemplateDialog templateDialog = (VisualEditorInsertTemplateDialog) ve.openDialogFromMenu(InsertDialog.TEMPLATE); <START> VisualEditorEditTemplateDialog editTemplateDialog = templateDialog.selectResultTemplate("book", 0); <END> ve = editTemplateDialog.clickDone(); ve.verifyNumberOfBlockTransclusion(++numBlockTransclusion); ve.verifyNumberOfInlineTransclusion(numInlineTransclusion); templateDialog = (VisualEditorInsertTemplateDialog) ve.openDialogFromMenu(InsertDialog.TEMPLATE); editTemplateDialog = templateDialog.selectResultTemplate("book", 0); ve = editTemplateDialog.clickDone(); ve.verifyNumberOfBlockTransclusion(++numBlockTransclusion); ve.verifyNumberOfInlineTransclusion(numInlineTransclusion); VisualEditorSaveChangesDialog saveDialog = ve.clickPublishButton(); ArticlePageObject article = saveDialog.savePage(); article.verifyVEPublishComplete(); article.logOut(wikiURL); }</code><technical_language>creating a VisualEditorContents class in ContentPatterns for constants for VE</technical_language>

Target:
public void VETemplateTests_004_CheckBlockedTransclusion() { articleName = PageContent.articleNamePrefix + base.getTimeStamp(); VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); String selectText = PageContent.articleText.substring(12, 13); int numBlockTransclusion = ve.getNumberOfBlockTransclusion(); int numInlineTransclusion = ve.getNumberOfInlineTransclusion(); ve.typeTextArea(PageContent.articleText); ve.selectText(selectText); VisualEditorInsertTemplateDialog templateDialog = (VisualEditorInsertTemplateDialog) ve.openDialogFromMenu(InsertDialog.TEMPLATE); VisualEditorEditTemplateDialog editTemplateDialog = templateDialog.selectResultTemplate(VEContent.templateSearchStr5, 0); ve = editTemplateDialog.clickDone(); ve.verifyNumberOfBlockTransclusion(++numBlockTransclusion); ve.verifyNumberOfInlineTransclusion(numInlineTransclusion); templateDialog = (VisualEditorInsertTemplateDialog) ve.openDialogFromMenu(InsertDialog.TEMPLATE); editTemplateDialog = templateDialog.selectResultTemplate(VEContent.templateSearchStr5, 0); ve = editTemplateDialog.clickDone(); ve.verifyNumberOfBlockTransclusion(++numBlockTransclusion); ve.verifyNumberOfInlineTransclusion(numInlineTransclusion); VisualEditorSaveChangesDialog saveDialog = ve.clickPublishButton(); ArticlePageObject article = saveDialog.savePage(); article.verifyVEPublishComplete(); article.logOut(wikiURL); }
Source:
<code>private static void loadAllStateItems() { if (stateItems.size() > 0) { return; } <START> <END> List<IConfigurationElement> elements = ExtensionPoints.getExtensionElements("org.eclipse.osee.ats.core.client.AtsStateItemCore", "AtsStateItemCore"); String classname = null; String bundleName = null; for (IConfigurationElement el : elements) { if (el.getName().equals("AtsStateItemCore")) { classname = el.getAttribute("classname"); bundleName = el.getContributor().getName(); if (classname != null && bundleName != null) { Bundle bundle = Platform.getBundle(bundleName); try { Class taskClass = bundle.loadClass(classname); Object obj = taskClass.newInstance(); if (obj == null) { OseeLog.log(Activator.class, Level.SEVERE, "Error Instantiating AtsStateItemCore extension \"" + classname + "\"", null); } else { stateItems.add((IAtsStateItemCore) obj); } } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Error loading AtsStateItemCore extension", ex); } } } } }</code><technical_language>ExtensionDefinedObject<IAtsStateItemCore> instead of this class. this class deleted</technical_language>

Target:
private static void loadAllStateItems() { if (stateItems.size() > 0) { return; } stateItems = new ExtensionDefinedObjects<IAtsStateItemCore>("org.eclipse.osee.ats.core.client.AtsStateItemCore", "AtsStateItemCore", "classname").getObjects(); }
Source:
<code>public Uri decode(Context context, Payload payload) throws PayloadDecodeException, PayloadNotFoundException { File file; if (payload instanceof LocalUriPayload) { <START> file = new File(context.getFilesDir() + "/tempFile_" + System.currentTimeMillis()); <END> InputStream resource = (InputStream) payload.prepare(context); OutputStream output = null; try { output = context.openFileOutput(file.getName(), Context.MODE_PRIVATE); byte[] buffer = new byte[4 * 1024]; int read; while ((read = resource.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { resource.close(); if (output != null) { output.close(); } } catch (IOException ignored) { } } } else if (payload instanceof FilePayload) { file = (File) payload.prepare(context); } else { throw new PayloadDecodeException(); } return Uri.fromFile(file); }</code><technical_language>I this needed current API, change API reduce complexity - add a T getData() method Payload class, instead of writing a new file get Uri directly, e.g. if (payload instanceof LocalUriPayload) { uri = ((LocalUriPayload)payload).getData(); }..</technical_language>

Target:
public Uri decode(Context context, Payload payload) throws PayloadDecodeException, PayloadNotFoundException { Uri uri; if (payload instanceof LocalUriPayload) { uri = ((LocalUriPayload) payload).getData(); } else if (payload instanceof FilePayload) { File file = (File) payload.prepare(context); uri = Uri.fromFile(file); } else { throw new PayloadDecodeException(); } return uri; }
Source:
<code>public BootstrapContextImpl clone() throws CloneNotSupportedException { BootstrapContextImpl bcbc = (BootstrapContextImpl)super.clone(); bcbc.setTransactionSynchronizationRegistry(getTransactionSynchronizationRegistry()); bcbc.setXATerminator(getXATerminator()); bcbc.setName(getName()); bcbc.setWorkManagerName(getWorkManagerName()); <START> <END> return bcbc; }</code><technical_language>Copy VF</technical_language>

Target:
public BootstrapContextImpl clone() throws CloneNotSupportedException { BootstrapContextImpl bcbc = (BootstrapContextImpl)super.clone(); bcbc.setTransactionSynchronizationRegistry(getTransactionSynchronizationRegistry()); bcbc.setXATerminator(getXATerminator()); bcbc.setName(getName()); bcbc.setWorkManagerName(getWorkManagerName()); bcbc.setValidatorFactory(getValidatorFactory()); return bcbc; }
Source:
<code>protected ValidationResult validate(Artifact artToValidate, IProgressMonitor monitor) throws OseeCoreException { Collection<String> errorMessages = new ArrayList<>(); boolean validationPassed = true; <START> try { <END> if (isDeleted(artToValidate)) { artToValidate.getRelatedArtifact(CoreRelationTypes.Default_Hierarchical__Parent); errorMessages.add(ValidationReportOperation.getRequirementHyperlink( artToValidate) + " (" + artToValidate.getGammaId() + ")" + " is deleted but still has a parent relation. Please delete the relation."); validationPassed = false; } } catch (ArtifactDoesNotExist ex) { } return new ValidationResult(errorMessages, validationPassed); }</code><technical_language>existing method artToValidate.getModType().isDeleted()</technical_language>

Target:
protected ValidationResult validate(Artifact artToValidate, IProgressMonitor monitor) throws OseeCoreException { Collection<String> errorMessages = new ArrayList<>(); boolean validationPassed = true; if (artToValidate.isDeleted()) { Artifact relatedArtifact = artToValidate.getRelatedArtifactOrNull(CoreRelationTypes.Default_Hierarchical__Parent); if (relatedArtifact != null) { errorMessages.add(ValidationReportOperation.getRequirementHyperlink( artToValidate) + " (" + artToValidate.getGammaId() + ")" + " is deleted but still has a parent relation. Please delete the relation."); validationPassed = false; } } return new ValidationResult(errorMessages, validationPassed); }
Source:
<code>public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { <START> if (operations.get(entry.getKey()).contains(name)) { <END> return true; } } } return false; }</code><technical_language>This is wrong, entry.getValue()</technical_language>

Target:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { if (entry.getValue().contains(name)) { return true; } } } return false; }
Source:
<code>void checkForSegmentHandoffs() { try { Iterator<Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>>> itr = handOffCallbacks.entrySet() .iterator(); while (itr.hasNext()) { Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry = itr.next(); SegmentDescriptor descriptor = entry.getKey(); try { <START> if (coordinatorClient.isSpecificIntervalDroppedByRule(dataSource, descriptor.getInterval())) { <END> log.info( "Segment already dropped by drop rules for dataSource[%s] Segment[%s], ignore it!", dataSource, descriptor ); entry.getValue().lhs.execute(entry.getValue().rhs); itr.remove(); continue; } List<ImmutableSegmentLoadInfo> loadedSegments = coordinatorClient.fetchServerView( dataSource, descriptor.getInterval(), true ); if (isHandOffComplete(loadedSegments, entry.getKey())) { log.info("Segment Handoff complete for dataSource[%s] Segment[%s]", dataSource, descriptor); entry.getValue().lhs.execute(entry.getValue().rhs); itr.remove(); } } catch (Exception e) { log.error( e, "Exception while checking handoff for dataSource[%s] Segment[%s], Will try again after [%d]secs", dataSource, descriptor, pollDurationMillis ); } } if (!handOffCallbacks.isEmpty()) { log.info("Still waiting for Handoff for Segments : [%s]", handOffCallbacks.keySet()); } } catch (Throwable t) { log.error( t, "Exception while checking handoff for dataSource[%s], Will try again after [%d]secs", dataSource, pollDurationMillis ); } }</code><technical_language>This require more HTTP calls. I a single API check this get server view below. API able notify caller handoff for requested segment happen. improve existing coordinator API, DataSourceResource.getSegmentDataSourceSpecificInterval() add a new for it</technical_language>

Target:
void checkForSegmentHandoffs() { try { Iterator<Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>>> itr = handOffCallbacks.entrySet() .iterator(); while (itr.hasNext()) { Map.Entry<SegmentDescriptor, Pair<Executor, Runnable>> entry = itr.next(); SegmentDescriptor descriptor = entry.getKey(); try { if (coordinatorClient.isHandOffComplete(dataSource, descriptor)) { log.info("Segment Handoff complete for dataSource[%s] Segment[%s]", dataSource, descriptor); entry.getValue().lhs.execute(entry.getValue().rhs); itr.remove(); } } catch (Exception e) { log.error( e, "Exception while checking handoff for dataSource[%s] Segment[%s], Will try again after [%d]secs", dataSource, descriptor, pollDurationMillis ); } } if (!handOffCallbacks.isEmpty()) { log.info("Still waiting for Handoff for Segments : [%s]", handOffCallbacks.keySet()); } } catch (Throwable t) { log.error( t, "Exception while checking handoff for dataSource[%s], Will try again after [%d]secs", dataSource, pollDurationMillis ); } }
Source:
<code>JSONObject toJSONObject() { JSONObject json = new JSONObject(); try { json.put(IAM_ID, this.messageId); JSONObject variants = new JSONObject(); for (String key : this.variants.keySet()) { HashMap<String, String> variant = this.variants.get(key); JSONObject converted = new JSONObject(); for (String variantKey : variant.keySet()) converted.put(variantKey, variant.get(variantKey)); variants.put(key, converted); } json.put(IAM_VARIANTS, variants); json.put(DISPLAY_DURATION, this.displayDuration); json.put(DISPLAY_LIMIT, this.displayLimit); json.put(DISPLAY_DELAY, this.displayDelay); <START> if (redisplayEnabled) <END> json.put(IAM_RE_DISPLAY, new JSONObject() {{ put(DISPLAY_LIMIT, displayLimit); put(DISPLAY_DELAY, displayDelay); }}); JSONArray orConditions = new JSONArray(); for (ArrayList<OSTrigger> andArray : this.triggers) { JSONArray andConditions = new JSONArray(); for (OSTrigger trigger : andArray) andConditions.put(trigger.toJSONObject()); orConditions.put(andConditions); } json.put(IAM_TRIGGERS, orConditions); } catch (JSONException exception) { exception.printStackTrace(); } return json; }</code><technical_language>Prefer adding curly braces if more line is if statement</technical_language>

Target:
JSONObject toJSONObject() { JSONObject json = new JSONObject(); try { json.put(IAM_ID, this.messageId); JSONObject variants = new JSONObject(); for (String key : this.variants.keySet()) { HashMap<String, String> variant = this.variants.get(key); JSONObject converted = new JSONObject(); for (String variantKey : variant.keySet()) converted.put(variantKey, variant.get(variantKey)); variants.put(key, converted); } json.put(IAM_VARIANTS, variants); json.put(DISPLAY_DURATION, this.displayDuration); if (displayStats.isRedisplayEnabled()) json.put(IAM_RE_DISPLAY, displayStats.toJSONObject()); JSONArray orConditions = new JSONArray(); for (ArrayList<OSTrigger> andArray : this.triggers) { JSONArray andConditions = new JSONArray(); for (OSTrigger trigger : andArray) andConditions.put(trigger.toJSONObject()); orConditions.put(andConditions); } json.put(IAM_TRIGGERS, orConditions); } catch (JSONException exception) { exception.printStackTrace(); } return json; }
Source:
<code>public CachedConnection reserveAny() { if (unreserved.size() > 0) { <START> CachedConnection cachedConnection = unreserved.pop(); <END> cachedConnection.reserve(); reserved.put(cachedConnection.transport, cachedConnection); if (log.isTraceEnabled()) { log.trace("Using existing connection to {}", cachedConnection.transport.cacheKey); } return cachedConnection; } return null; }</code><technical_language>This code a race condition. checking if size > 0, Dequeue empty calling pop. is a method called pollFirst do of this in a single operation. I 100% pop pollFirst end. java CachedConnection cachedConnection = unreserved.pollFirst(); if (cachedConnection != null) { cachedConnection.reserve(); reserved.put(cachedConnection.transport, cachedConnection); if (log.isTraceEnabled()) { log.trace("Using existing connection {}", cachedConnection.transport.cacheKey); } return cachedConnection; }</technical_language>

Target:
public CachedConnection reserveAny() { CachedConnection cachedConnection = unreserved.poll(); if (cachedConnection != null) { cachedConnection.reserve(); reserved.put(cachedConnection.transport, cachedConnection); if (log.isTraceEnabled()) { log.trace("Using existing connection to {}", cachedConnection.transport.cacheKey); } } return cachedConnection; }
Source:
<code>private void assertCoverage(final Line line, final int insnStatus, final int missedBranches, final int coveredBranches) { final ILine coverage = line.getCoverage(); <START> final String location = String.format("(%s:%d)", <END> source.getCoverage().getName(), line.getNr()); String msg = String.format("Instructions in %s: %s", location, line.getText()); final int actualStatus = coverage.getInstructionCounter().getStatus(); assertEquals(msg, STATUS_NAME[insnStatus], STATUS_NAME[actualStatus]); msg = String.format("Branches in %s: %s", location, line.getText()); assertEquals(msg, CounterImpl.getInstance(missedBranches, coveredBranches), coverage.getBranchCounter()); }</code><technical_language>making Line.toString() return <sourcename>:<nr></technical_language>

Target:
private void assertCoverage(final Line line, final int insnStatus, final int missedBranches, final int coveredBranches) { final ILine coverage = line.getCoverage(); String msg = String.format("Instructions (%s)", line); final int actualStatus = coverage.getInstructionCounter().getStatus(); assertEquals(msg, STATUS_NAME[insnStatus], STATUS_NAME[actualStatus]); msg = String.format("Branches (%s)", line); assertEquals(msg, CounterImpl.getInstance(missedBranches, coveredBranches), coverage.getBranchCounter()); }
Source:
<code>public void testAndThenRemoveOnFailure() throws TransactionFailureException { ds1.failCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(); context.start(); Assert.assertTrue(context.addTransactionAware(ds1)); ds1.addChange(A); try { context.finish(); <START> Assert.fail("persist failed - exception should be thrown"); <END> } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } Assert.assertTrue(context.removeTransactionAware(ds1)); Assert.assertTrue(ds1.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); }</code><technical_language>this "Persist failed - exception thrown"</technical_language>

Target:
public void testAndThenRemoveOnFailure() throws TransactionFailureException { ds1.failCommitTxOnce = InduceFailure.ThrowException; TransactionContext context = newTransactionContext(); context.start(); Assert.assertTrue(context.addTransactionAware(ds1)); ds1.addChange(A); try { context.finish(); Assert.fail("Persist should have failed - exception should be thrown"); } catch (TransactionFailureException e) { Assert.assertEquals("persist failure", e.getCause().getMessage()); } Assert.assertTrue(context.removeTransactionAware(ds1)); Assert.assertTrue(ds1.started); Assert.assertTrue(ds1.checked); Assert.assertTrue(ds1.committed); Assert.assertFalse(ds1.postCommitted); Assert.assertTrue(ds1.rolledBack); Assert.assertEquals(txClient.state, DummyTxClient.CommitState.Aborted); }
Source:
<code><START> public static boolean requiresNewCustomParser(final Struct struct, final Set<String> existingTypes, final ImmutableSet<String> enumNames) { <END> for (final StructMember member : struct.getStructMembers()) { if (!member.getType().isPrimitive()) { if (member.getType().getTypeRoot().equals("ds3_str")) continue; if (existingTypes.contains(member.getType().getTypeRoot())) continue; if (enumNames.contains(member.getType().getTypeRoot())) continue; return true; } } return false; }</code><technical_language>existingTypes ImmutableSet</technical_language>

Target:
public static boolean requiresNewCustomParser(final Struct struct, final Set<String> existingTypes, final ImmutableSet<String> enumNames) { for (final StructMember member : struct.getStructMembers()) { if (!member.getType().isPrimitive()) { if (member.getType().getTypeName().equals("ds3_str")) continue; if (existingTypes.contains(member.getType().getTypeName())) continue; if (enumNames.contains(member.getType().getTypeName())) continue; return true; } } return false; }
Source:
<code>public DefaultMutableThemeStyle(TextColor foreground, TextColor background, SGR... sgrs) { <START> this(foreground, background, sgrs.length > 0 ? EnumSet.copyOf(Arrays.asList(sgrs)) : EnumSet.allOf(SGR.class)); <END> }</code><technical_language>"noneOf", "allOf"</technical_language>

Target:
public DefaultMutableThemeStyle(TextColor foreground, TextColor background, SGR... sgrs) { this(foreground, background, sgrs.length > 0 ? EnumSet.copyOf(Arrays.asList(sgrs)) : EnumSet.noneOf(SGR.class)); }
Source:
<code>private String extractTag(Element element) { WakeLock annotation = element.getAnnotation(WakeLock.class); String tag = annotation.tag(); if (WakeLock.DEFAULT_TAG.equals(tag)) { tag = element.getEnclosingElement().getSimpleName().toString(); <START> tag += "." + element.getSimpleName().toString(); <END> } return tag; }</code><technical_language>concat thing, do +=</technical_language>

Target:
private String extractTag(Element element) { WakeLock annotation = element.getAnnotation(WakeLock.class); String tag = annotation.tag(); if (WakeLock.DEFAULT_TAG.equals(tag)) { tag = element.getEnclosingElement().getSimpleName().toString() + "." + element.getSimpleName().toString(); } return tag; }
Source:
<code>public void execution() throws Exception { final Project project = execute(ProjectGet.of()); assertThat(project.getKey()).isEqualTo(getSphereClientConfig().getProjectKey()); assertThat(project.getName()).overridingErrorMessage("name").isNotEmpty(); assertThat(project.getCountries()).overridingErrorMessage("countries").isNotEmpty(); assertThat(project.getLanguages()).overridingErrorMessage("languages").isNotEmpty(); assertThat(project.getCreatedAt()).overridingErrorMessage("createdAt").isNotNull(); <START> } <END></code><technical_language>do need remove this</technical_language>

Target:
public void execution() throws Exception { final Project project = execute(ProjectGet.of()); assertThat(project.getKey()).isEqualTo(getSphereClientConfig().getProjectKey()); assertThat(project.getName()).overridingErrorMessage("name").isNotEmpty(); assertThat(project.getCountries()).overridingErrorMessage("countries").isNotEmpty(); assertThat(project.getLanguages()).overridingErrorMessage("languages").isNotEmpty(); assertThat(project.getCreatedAt()).overridingErrorMessage("createdAt").isNotNull(); assertThat(project.getTrialUntil()).overridingErrorMessage("trialUntil").isNotNull(); }
Source:
<code>public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); String role = mRoleListAdapter.getSelectedRole(); <START> if (role != null) { <END> outState.putString(ROLE_TAG, role); } }</code><technical_language>extra careful hurt is need check for null this point. For simplicity's sake, recommend removing check is semantic in it. I step remove null-check line 136 (radioButton.setChecked(mSelectedRole.equalsIgnoreCase(role)) reversing equals role.equalsIgnoreCase(mSelectedRole) role is expected null. Cheers</technical_language>

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); String role = mRoleListAdapter.getSelectedRole(); outState.putString(ROLE_TAG, role); }
Source:
<code>public Builder(RetryOptions options) { <START> enableRetries = options.retriesEnabled; <END> initialBackoffMillis = options.initialBackoffMillis; backoffMultiplier = options.backoffMultiplier; maxElaspedBackoffMillis = options.maxElaspedBackoffMillis; streamingBufferSize = options.streamingBufferSize; streamingBatchSize = options.streamingBatchSize; readPartialRowTimeoutMillis = options.readPartialRowTimeoutMillis; maxScanTimeoutRetries = options.maxScanTimeoutRetries; statusToRetryOn = new HashSet<>(options.statusToRetryOn); allowRetriesWithoutTimestamp = options.allowRetriesWithoutTimestamp; }</code><technical_language>minor, constructor in BulkOptions this.<field> for everything. good consistent</technical_language>

Target:
public Builder(RetryOptions options) { this.enableRetries = options.retriesEnabled; this.initialBackoffMillis = options.initialBackoffMillis; this.backoffMultiplier = options.backoffMultiplier; this.maxElaspedBackoffMillis = options.maxElaspedBackoffMillis; this.streamingBufferSize = options.streamingBufferSize; this.streamingBatchSize = options.streamingBatchSize; this.readPartialRowTimeoutMillis = options.readPartialRowTimeoutMillis; this.maxScanTimeoutRetries = options.maxScanTimeoutRetries; this.statusToRetryOn = new HashSet<>(options.statusToRetryOn); this.allowRetriesWithoutTimestamp = options.allowRetriesWithoutTimestamp; }
Source:
<code>public PlanetConfigs(HullConfigManager hullConfigs, GameColors cols, ItemManager itemManager) { allConfigs = new HashMap<>(); easy = new ArrayList<>(); medium = new ArrayList<>(); hard = new ArrayList<>(); Set<ResourceUrn> planetJsonConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:planetsConfig"); for (ResourceUrn planetConfigJson : planetJsonConfigs) { String moduleName = planetConfigJson.getModuleName().toString(); Json json = Assets.getJson(planetConfigJson.toString()); JsonValue rootNode = json.getJsonValue(); for (JsonValue node : rootNode) { PlanetConfig planetConfig = PlanetConfig.load(node, hullConfigs, cols, itemManager, moduleName); allConfigs.put(node.name, planetConfig); for (String difficulty : planetConfig.difficultyLevels) { switch (difficulty) { case "easy": <START> easy.add(planetConfig); <END> case "medium": medium.add(planetConfig); case "hard": hard.add(planetConfig); } } } json.dispose(); } }</code><technical_language>Need break this</technical_language>

Target:
public PlanetConfigs(HullConfigManager hullConfigs, GameColors cols, ItemManager itemManager) { allConfigs = new HashMap<>(); easy = new ArrayList<>(); medium = new ArrayList<>(); hard = new ArrayList<>(); Set<ResourceUrn> planetJsonConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:planetsConfig"); for (ResourceUrn planetConfigJson : planetJsonConfigs) { String moduleName = planetConfigJson.getModuleName().toString(); Json json = Assets.getJson(planetConfigJson.toString()); JSONObject rootNode = json.getJsonValue(); Validator.validate(rootNode, "engine:schemaPlanetsConfig"); for (String s : rootNode.keySet()) { JSONObject node = rootNode.getJSONObject(s); PlanetConfig planetConfig = PlanetConfig.load(s, node, hullConfigs, cols, itemManager, moduleName); allConfigs.put(s, planetConfig); for (String difficulty : planetConfig.difficultyLevels) { switch (difficulty) { case "easy": easy.add(planetConfig); break; case "medium": medium.add(planetConfig); break; case "hard": hard.add(planetConfig); break; } } } json.dispose(); } }
Source:
<code>public List<GraphQLDirective> getDirectives() { <START> return Collections.unmodifiableList(directives); <END> }</code><technical_language>unmodifiable in this case? a copy life of caller easier</technical_language>

Target:
public List<GraphQLDirective> getDirectives() { return new ArrayList<>(directives); }
Source:
<code>public TaskStatusResponse getTaskStatus(String taskId) { return new TaskStatusResponse( taskId, new TaskStatusPlus( <START> taskId, <END> taskId, "testTask", DateTimes.EPOCH, DateTimes.EPOCH, tasks.get(taskId), RunnerTaskState.RUNNING, -1L, TaskLocation.unknown(), "testDataSource", null ) ); }</code><technical_language>is taskId passed in groupId argument? "groupId" a GROUP_ID named constant work here? If groupId is changed parentId, a named constant NO_PARENT_ID = "" work here</technical_language>

Target:
public TaskStatusResponse getTaskStatus(String taskId) { return new TaskStatusResponse( taskId, new TaskStatusPlus( taskId, "groupId", "testTask", DateTimes.EPOCH, DateTimes.EPOCH, tasks.get(taskId), RunnerTaskState.RUNNING, -1L, TaskLocation.unknown(), "testDataSource", null ) ); }
Source:
<code><START> JwtCredentials(Builder builder) { <END> this.privateKey = Preconditions.checkNotNull(builder.getPrivateKey()); this.privateKeyId = Preconditions.checkNotNull(builder.getPrivateKeyId()); this.claims = Preconditions.checkNotNull(builder.getClaims()); Preconditions.checkState(claims.isComplete(), JWT_INCOMPLETE_ERROR_MESSAGE); this.lifeSpanSeconds = Preconditions.checkNotNull(builder.getLifeSpanSeconds()); this.clock = Preconditions.checkNotNull(builder.getClock()); }</code><technical_language>this private a Builder</technical_language>

Target:
private JwtCredentials(Builder builder) { this.privateKey = Preconditions.checkNotNull(builder.getPrivateKey()); this.privateKeyId = Preconditions.checkNotNull(builder.getPrivateKeyId()); this.jwtClaims = Preconditions.checkNotNull(builder.getJwtClaims()); Preconditions.checkState(jwtClaims.isComplete(), JWT_INCOMPLETE_ERROR_MESSAGE); this.lifeSpanSeconds = Preconditions.checkNotNull(builder.getLifeSpanSeconds()); this.clock = Preconditions.checkNotNull(builder.getClock()); }
Source:
<code>private SubProcessPropertyWriter convertMultipleInstanceSubprocessNode(Node<View<MultipleInstanceSubprocess>, ?> n) { SubProcess process = bpmn2.createSubProcess(); process.setId(n.getUUID()); MultipleInstanceSubProcessPropertyWriter p = propertyWriterFactory.ofMultipleInstanceSubProcess(process); MultipleInstanceSubprocess definition = n.getContent().getDefinition(); BPMNGeneralSet general = definition.getGeneral(); p.setName(general.getName().getValue()); p.setDocumentation(general.getDocumentation().getValue()); ProcessData processData = definition.getProcessData(); p.setProcessVariables(processData.getProcessVariables()); MultipleInstanceSubprocessTaskExecutionSet executionSet = definition.getExecutionSet(); p.setIsSequential(executionSet.getMultipleInstanceExecutionMode().isSequential()); p.setCollectionInput(executionSet.getMultipleInstanceCollectionInput().getValue()); p.setInput(executionSet.getMultipleInstanceDataInput().getValue()); p.setCollectionOutput(executionSet.getMultipleInstanceCollectionOutput().getValue()); p.setOutput(executionSet.getMultipleInstanceDataOutput().getValue()); p.setCompletionCondition(executionSet.getMultipleInstanceCompletionCondition().getValue()); p.setOnEntryAction(executionSet.getOnEntryAction()); p.setOnExitAction(executionSet.getOnExitAction()); p.setAsync(executionSet.getIsAsync().getValue()); <START> p.setSlaDueDate(executionSet.getSlaDueDate()); <END> p.setSimulationSet(definition.getSimulationSet()); p.setAbsoluteBounds(n); return p; }</code><technical_language>This changes covered unitary tests in SubProcessConverterTests</technical_language>

Target:
protected SubProcessPropertyWriter convertMultipleInstanceSubprocessNode(Node<View<MultipleInstanceSubprocess>, ?> n) { SubProcess process = bpmn2.createSubProcess(); process.setId(n.getUUID()); MultipleInstanceSubProcessPropertyWriter p = propertyWriterFactory.ofMultipleInstanceSubProcess(process); MultipleInstanceSubprocess definition = n.getContent().getDefinition(); BPMNGeneralSet general = definition.getGeneral(); p.setName(general.getName().getValue()); p.setDocumentation(general.getDocumentation().getValue()); ProcessData processData = definition.getProcessData(); p.setProcessVariables(processData.getProcessVariables()); MultipleInstanceSubprocessTaskExecutionSet executionSet = definition.getExecutionSet(); p.setIsSequential(executionSet.getMultipleInstanceExecutionMode().isSequential()); p.setCollectionInput(executionSet.getMultipleInstanceCollectionInput().getValue()); p.setInput(executionSet.getMultipleInstanceDataInput().getValue()); p.setCollectionOutput(executionSet.getMultipleInstanceCollectionOutput().getValue()); p.setOutput(executionSet.getMultipleInstanceDataOutput().getValue()); p.setCompletionCondition(executionSet.getMultipleInstanceCompletionCondition().getValue()); p.setOnEntryAction(executionSet.getOnEntryAction()); p.setOnExitAction(executionSet.getOnExitAction()); p.setAsync(executionSet.getIsAsync().getValue()); p.setSlaDueDate(executionSet.getSlaDueDate()); p.setSimulationSet(definition.getSimulationSet()); p.setAbsoluteBounds(n); return p; }
Source:
<code>public Set<Assignment> getAssignmentsForPerson(String username, boolean includeInherited) { Set<Assignment> rslt = new HashSet<Assignment>(); IAuthorizationPrincipal authP = this.authorizationService.newPrincipal( username, EntityEnum.PERSON.getClazz()); IPermission[] directPermissions = permissionStore.select(null, authP.getPrincipalString(), null, null, null); for (IPermission permission : directPermissions) { if (authP.hasPermission(permission.getOwner(), permission.getActivity(), permission.getTarget())) { Assignment a = createAssignment(permission, authP, false); if (a != null) { rslt.add(a); } } } if (includeInherited) { IGroupMember member = GroupService.getGroupMember(authP.getKey(), authP.getType()); for (Iterator<IEntityGroup> iter = member.getAncestorGroups().iterator(); iter.hasNext();) { IEntityGroup parent = iter.next(); <START> <END> IAuthorizationPrincipal parentPrincipal = this.authorizationService.newPrincipal(parent); IPermission[] parentPermissions = permissionStore.select(null, parentPrincipal.getPrincipalString(), null, null, null); for (IPermission permission : parentPermissions) { if (authP.hasPermission(permission.getOwner(), permission.getActivity(), permission.getTarget())) { Assignment a = createAssignment(permission, authP, true); if (a != null) { rslt.add(a); } } } } } return rslt; }</code><technical_language>want refactor this a for (each) loop</technical_language>

Target:
public Set<Assignment> getAssignmentsForPerson(String username, boolean includeInherited) { Set<Assignment> rslt = new HashSet<Assignment>(); IAuthorizationPrincipal authP = this.authorizationService.newPrincipal( username, EntityEnum.PERSON.getClazz()); IPermission[] directPermissions = permissionStore.select(null, authP.getPrincipalString(), null, null, null); for (IPermission permission : directPermissions) { if (authP.hasPermission(permission.getOwner(), permission.getActivity(), permission.getTarget())) { Assignment a = createAssignment(permission, authP, false); if (a != null) { rslt.add(a); } } } if (includeInherited) { IGroupMember member = GroupService.getGroupMember(authP.getKey(), authP.getType()); for (IEntityGroup parent : member.getAncestorGroups()) { IAuthorizationPrincipal parentPrincipal = this.authorizationService.newPrincipal(parent); IPermission[] parentPermissions = permissionStore.select(null, parentPrincipal.getPrincipalString(), null, null, null); for (IPermission permission : parentPermissions) { if (authP.hasPermission(permission.getOwner(), permission.getActivity(), permission.getTarget())) { Assignment a = createAssignment(permission, authP, true); if (a != null) { rslt.add(a); } } } } } return rslt; }
Source:
<code>public int read(WritableByteChannel channel) throws IOException { int bytesWritten = -1; if (!channelOpen.get()) { throw new ClosedChannelException(); } else { try { <START> bufferReadLock.lock(); <END> if (buffer.hasRemaining()) { bytesWritten = channel.write(buffer); } } finally { bufferReadLock.unlock(); } } return bytesWritten; }</code><technical_language>I want lock try-finally</technical_language>

Target:
public int read(WritableByteChannel channel) throws IOException { int bytesWritten = -1; if (!channelOpen.get()) { throw new ClosedChannelException(); } else { bufferReadLock.lock(); try { if (buffer.hasRemaining()) { bytesWritten = channel.write(buffer); } } finally { bufferReadLock.unlock(); } } return bytesWritten; }
Source:
<code>public void logout_sameSyncUserMultipleSessions() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration1 = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .build(); Realm realm1 = Realm.getInstance(syncConfiguration1); SyncConfiguration syncConfiguration2 = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL_2) .build(); Realm realm2 = Realm.getInstance(syncConfiguration2); SyncSession session1 = SyncManager.getSession(syncConfiguration1); SyncSession session2 = SyncManager.getSession(syncConfiguration2); <START> SystemClock.sleep(TimeUnit.SECONDS.toMillis(2)); <END> assertNotEquals(session1, session2); assertEquals(SyncSession.State.ACTIVE, session1.getState()); assertEquals(SyncSession.State.ACTIVE, session2.getState()); assertEquals(session1.getUser(), session2.getUser()); try { user.logout(); fail("Should not be able to logout with two open Realm instances"); } catch (IllegalStateException e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("A Realm controlled by this user is still open. Close all Realms before logging out")); } realm1.close(); try { user.logout(); fail("Should not be able to logout with one open Realm instance"); } catch (IllegalStateException e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("A Realm controlled by this user is still open. Close all Realms before logging out")); } realm2.close(); user.logout(); }</code><technical_language>making a while loop check session state more efficient</technical_language>

Target:
public void logout_sameSyncUserMultipleSessions() { String uniqueName = UUID.randomUUID().toString(); SyncCredentials credentials = SyncCredentials.usernamePassword(uniqueName, "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); SyncConfiguration syncConfiguration1 = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .build(); Realm realm1 = Realm.getInstance(syncConfiguration1); SyncConfiguration syncConfiguration2 = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL_2) .build(); Realm realm2 = Realm.getInstance(syncConfiguration2); SyncSession session1 = SyncManager.getSession(syncConfiguration1); SyncSession session2 = SyncManager.getSession(syncConfiguration2); while(session1.getState() != SyncSession.State.ACTIVE || session2.getState() != SyncSession.State.ACTIVE) { SystemClock.sleep(200); } assertEquals(SyncSession.State.ACTIVE, session1.getState()); assertEquals(SyncSession.State.ACTIVE, session2.getState()); assertNotEquals(session1, session2); assertEquals(session1.getUser(), session2.getUser()); user.logout(); assertEquals(SyncSession.State.INACTIVE, session1.getState()); assertEquals(SyncSession.State.INACTIVE, session2.getState()); credentials = SyncCredentials.usernamePassword(uniqueName, "password", false); SyncUser.login(credentials, Constants.AUTH_URL); assertEquals(SyncSession.State.WAITING_FOR_ACCESS_TOKEN, session1.getState()); assertEquals(SyncSession.State.WAITING_FOR_ACCESS_TOKEN, session2.getState()); realm1.close(); realm2.close(); }
Source:
<code>private void removeDetachedServers(List<VDS> existingServers, Set<GlusterServerInfo> fetchedServers) { for (VDS server : existingServers) { if (isRemovableStatus(server.getstatus()) && serverDetached(server, fetchedServers)) { RemoveVdsStatisticsFromDb(server); RemoveVdsDynamicFromDb(server); RemoveVdsStaticFromDb(server); <START> ResourceManager.getInstance().RemoveVds(server.getId()); <END> log.debugFormat("Server {0} has been removed directly using the gluster CLI. Removing it from engine as well.", server.getvds_name()); logServerMessage(server, AuditLogType.GLUSTER_SERVER_REMOVED_FROM_CLI); } } }</code><technical_language>please use: Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(server.getId()));</technical_language>

Target:
private void removeDetachedServers(List<VDS> existingServers, Set<GlusterServerInfo> fetchedServers) { for (VDS server : existingServers) { if (isRemovableStatus(server.getstatus()) && serverDetached(server, fetchedServers)) { RemoveVdsStatisticsFromDb(server); RemoveVdsDynamicFromDb(server); RemoveVdsStaticFromDb(server); runVdsCommand(VDSCommandType.RemoveVds, new RemoveVdsVDSCommandParameters(server.getId())); log.debugFormat("Server {0} has been removed directly using the gluster CLI. Removing it from engine as well.", server.getvds_name()); logServerMessage(server, AuditLogType.GLUSTER_SERVER_REMOVED_FROM_CLI); } } }
Source:
<code>public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); boolean isSlotBeingRerolled = scheduleCtx.isReroll(parentSlotKey); for (Locator locator : locators) { if (IS_REROLL_ONLY_DELAYED_METRICS && isSlotBeingRerolled) { UpdateStamp updateStamp = scheduleCtx.getShardStateManager().getUpdateStamp(parentSlotKey); if (locator.getLastUpdatedTimestamp() > updateStamp.getLastRollupTimestamp()) { <START> rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator, true); <END> } } else { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator, isSlotBeingRerolled); Instrumentation.markLocatorRolled(); } } log.debug("For slotKey {}, number of locator's that were rolled up are {}", parentSlotKey, rollCount); drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }</code><technical_language>Do need a call Instrumentation.markLocatorReRolled() here</technical_language>

Target:
public void run() { final Timer.Context timerCtx = rollupLocatorExecuteTimer.time(); try { getGranularity().finer(); } catch (Exception ex) { log.error("No finer granularity available than " + getGranularity()); return; } if (log.isTraceEnabled()) log.trace("Getting locators for @ {}", new Object[]{parentSlotKey, parentRange.toString(), scheduleCtx.getCurrentTimeMillis()}); long waitStart = System.currentTimeMillis(); int rollCount = 0; final RollupExecutionContext executionContext = createRollupExecutionContext(); final RollupBatchWriter rollupBatchWriter = createRollupBatchWriter(executionContext); Set<Locator> locators = getLocators(executionContext); boolean isSlotBeingRerolled = scheduleCtx.isReroll(parentSlotKey); for (Locator locator : locators) { if (IS_REROLL_ONLY_DELAYED_METRICS && isSlotBeingRerolled) { UpdateStamp updateStamp = scheduleCtx.getShardStateManager().getUpdateStamp(parentSlotKey); if (locator.getLastUpdatedTimestamp() > updateStamp.getLastRollupTimestamp()) { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator, true); } } else { rollCount = processLocator(rollCount, executionContext, rollupBatchWriter, locator, isSlotBeingRerolled); } } log.debug("For slotKey [isReroll={}], number of locator's that were rolled up are out of {}", new Object[]{parentSlotKey, isSlotBeingRerolled, rollCount, locators.size()}); drainExecutionContext(waitStart, rollCount, executionContext, rollupBatchWriter); timerCtx.stop(); }
Source:
<code>public List<QuotaBalanceVO> findQuotaBalance(final Long accountId, final Long domainId, final Date startDate, final Date endDate) { final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); List<QuotaBalanceVO> quotaUsageRecords = null; try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB)) { SearchCriteria<QuotaBalanceVO> sc = createSearchCriteria(); if (accountId != null) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (domainId != null) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } if ((startDate != null) && (endDate != null) && startDate.before(endDate)) { sc.addAnd("updatedOn", SearchCriteria.Op.BETWEEN, startDate, endDate); } else { <START> return new ArrayList<QuotaBalanceVO>(); <END> } quotaUsageRecords = listBy(sc); if (quotaUsageRecords.size() == 0) { quotaUsageRecords.addAll(lastQuotaBalanceVO(accountId, domainId, startDate)); } } catch (Exception e) { throw new CloudRuntimeException("Unable to find quota balance"); } finally { TransactionLegacy.open(opendb).close(); } return quotaUsageRecords; }</code><technical_language>return Collections.emptyList() here</technical_language>

Target:
public List<QuotaBalanceVO> findQuotaBalance(final Long accountId, final Long domainId, final Date startDate, final Date endDate) { return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<List<QuotaBalanceVO>>() { @Override public List<QuotaBalanceVO> doInTransaction(final TransactionStatus status) { List<QuotaBalanceVO> quotaUsageRecords = null; QueryBuilder<QuotaBalanceVO> qb = QueryBuilder.create(QuotaBalanceVO.class); if (accountId != null) { qb.and(qb.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); } if (domainId != null) { qb.and(qb.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); } if ((startDate != null) && (endDate != null) && startDate.before(endDate)) { qb.and(qb.entity().getUpdatedOn(), SearchCriteria.Op.BETWEEN, startDate, endDate); } else { return Collections.<QuotaBalanceVO> emptyList(); } quotaUsageRecords = listBy(qb.create()); if (quotaUsageRecords.size() == 0) { quotaUsageRecords.addAll(lastQuotaBalanceVO(accountId, domainId, startDate)); } return quotaUsageRecords; } }); }