auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SegmentStoreDataModel() { <START> fDescriptors = new ArrayList<>(); <END> String start = checkNotNull(Messages.SegmentStoreDataModel_Start); String end = checkNotNull(Messages.SegmentStoreDataModel_End); String length = checkNotNull(Messages.SegmentStoreDataModel_Length); fDescriptors.add(new DataChartTimestampDescriptor<>(start, new StartResolver(), null)); fDescriptors.add(new DataChartTimestampDescriptor<>(end, new EndResolver(), null)); fDescriptors.add(new DataChartDurationDescriptor<>(length, new LengthResolver())); }</code><technical_language>this immutable list too? accessed copyOf? ImmutableList.Builder<IDataChartDescriptor<T, ?>></technical_language>

Target:
public SegmentStoreDataModel() { String start = checkNotNull(Messages.SegmentStoreDataModel_Start); String end = checkNotNull(Messages.SegmentStoreDataModel_End); String length = checkNotNull(Messages.SegmentStoreDataModel_Length); fDescriptors.add(new DataChartTimestampDescriptor<>(start, new StartResolver())); fDescriptors.add(new DataChartTimestampDescriptor<>(end, new EndResolver())); fDescriptors.add(new DataChartDurationDescriptor<>(length, new LengthResolver())); }
Source:
<code>public void testWithRootUrl_configured() { assertTrue(StringUtils.isNotBlank(JenkinsLocationConfiguration.get().getUrl())); RootUrlNotSetMonitor monitor = j.jenkins.getExtensionList(AdministrativeMonitor.class).get(RootUrlNotSetMonitor.class); <START> assertFalse("Monitor must be activated", monitor.isActivated()); <END> }</code><technical_language>"not activated"</technical_language>

Target:
public void testWithRootUrl_configured() { JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get(); assertTrue(StringUtils.isNotBlank(config.getUrl())); RootUrlNotSetMonitor monitor = j.jenkins.getExtensionList(AdministrativeMonitor.class).get(RootUrlNotSetMonitor.class); assertFalse("Monitor must not be activated", monitor.isActivated()); config.setUrl(null); assertTrue("Monitor must be activated", monitor.isActivated()); config.setUrl("ftp://localhost:8080/jenkins"); assertTrue("Monitor must be activated", monitor.isActivated()); config.setUrl("http://localhost:8080/jenkins"); assertFalse("Monitor must be activated", monitor.isActivated()); }
Source:
<code>public void saveVisit_shouldNotPersistNewEncounter() throws Exception { VisitService vs = Context.getVisitService(); Visit visit = vs.getVisit(1); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(new Date()); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.setPatient(visit.getPatient()); encounter.setLocation(visit.getLocation()); visit.addEncounter(encounter); <START> vs.saveVisit(visit); <END> assertNull(encounter.getEncounterId()); Context.getEncounterService().saveEncounter(encounter); Integer encounterId = encounter.getEncounterId(); Context.flushSession(); Context.clearSession(); visit = Context.getVisitService().getVisit(1); assertEquals(1, visit.getEncounters().size()); assertEquals(encounterId, ((Encounter) visit.getEncounters().toArray()[0]).getEncounterId()); }</code><technical_language>this test pass changes? I passes flushing session checking encounter id. I test needs ensure visit is flushed, exception is thrown flushed visit referencing a transient encounter</technical_language>

Target:
public void saveVisit_shouldNotPersistNewEncounter() throws Exception { VisitService vs = Context.getVisitService(); Visit visit = vs.getVisit(1); Encounter encounter = new Encounter(); encounter.setEncounterDatetime(new Date()); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.setPatient(visit.getPatient()); encounter.setLocation(visit.getLocation()); visit.addEncounter(encounter); vs.saveVisit(visit); Context.flushSession(); }
Source:
<code>public void setRemoteLegendGraphicRequest( org.geotools.ows.wms.request.GetLegendGraphicRequest remoteLegendGraphicRequest) { this.remoteLegendGraphicRequest = remoteLegendGraphicRequest; Map<String, String> params = request.getRawKvp(); params.keySet() .forEach( k -> { if (!k.equalsIgnoreCase("layer")) this.remoteLegendGraphicRequest.setProperty( k, String.valueOf(params.get(k))); }); super.getLegendInfo() .setOnlineResource(this.remoteLegendGraphicRequest.getFinalURL().toExternalForm()); LOGGER.fine( <START> String.format( <END> "Cascaded GetLegend Request URL:%s", super.getLegendInfo().getOnlineResource())); }</code><technical_language>I for more efficient clean + concatenation instead of format, I format show some hard facts :yum:</technical_language>

Target:
public void setRemoteLegendGraphicRequest( org.geotools.ows.wms.request.GetLegendGraphicRequest remoteLegendGraphicRequest) { this.remoteLegendGraphicRequest = remoteLegendGraphicRequest; Map<String, String> params = request.getRawKvp(); params.keySet() .forEach( k -> { if (!k.equalsIgnoreCase("layer")) this.remoteLegendGraphicRequest.setProperty( k, String.valueOf(params.get(k))); }); super.getLegendInfo() .setOnlineResource(this.remoteLegendGraphicRequest.getFinalURL().toExternalForm()); LOGGER.fine("Cascaded GetLegend Request URL: " + super.getLegendInfo().getOnlineResource()); }
Source:
<code>static boolean isHMSAvailable() { <START> return OSUtils.isHuaweiDeviceType(); <END> }</code><technical_language>wrap OSUtils.isHuaweiDeviceType(); directly</technical_language>

Target:
static boolean isHMSAvailable() { return OSUtils.isHuaweiDeviceType() && OSUtils.hasHMSLocationLibrary(); }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { showAbortedByHook(e.getCause()); return Status.CANCEL_STATUS; } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { <START> commitSucceeded = true; <END> if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }</code><technical_language>I find more natural return IStatus is OK_STATUS in case commit failed. need add some artificial boolean in this Job class track of result</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { RevCommit commit = null; try { commitOperation.execute(monitor); commit = commitOperation.getCommit(); CommitMessageComponentStateManager.deleteState(repository); RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repository); if (mapping != null) mapping.fireRepositoryChanged(); } catch (CoreException e) { if (e.getCause() instanceof JGitInternalException) { return Activator.createErrorStatus(e.getLocalizedMessage(), e.getCause()); } if (e.getCause() instanceof AbortedByHookException) { showAbortedByHook(e.getCause()); return Status.CANCEL_STATUS; } else { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } } finally { GitLightweightDecorator.refresh(); } if (commit != null) { if (openCommitEditor) openCommitEditor(commit); if (pushUpstream) pushUpstream(commit); } return Status.OK_STATUS; }
Source:
<code>public static Thread[] findThreadsByName(final String threadName, final ThreadGroup threadGroup) { if (threadName == null) { throw new IllegalArgumentException("The threadName must not be null"); } if (threadGroup == null) { throw new IllegalArgumentException("The threadGroupName must not be null"); } final Thread[] threads = findThreadsByName(threadName); if(threads.length == 0) { return EMPTY_THREAD_ARRAY; } <START> final List<Thread> matchedThreads = new ArrayList<Thread>(); <END> for (int i = 0; i < threads.length; i++) { final Thread thread = threads[i]; if(thread != null && threadGroup.equals(thread.getThreadGroup())) { matchedThreads.add(thread); } } return matchedThreads.toArray(new Thread[matchedThreads.size()]); }</code><technical_language>i put in threads.lengths initial capacity micro optimization</technical_language>

Target:
public static Collection<Thread> findThreadsByName(final String threadName, final ThreadGroup threadGroup) { return selectThreads(threadGroup, false, new NamePredicate(threadName)); }
Source:
<code>default void inputDetail() { optional(network().comment()); optional(network().description()); optional(network().display()); optional(network().ip().address()); optional(network().ip().gateway()); optional(network().ip().netmask()); optional(network().mtu()); optional(network().name()); optional(network().stp()); optional(network().vlan().id()); <START> optional(network().externalProvider().id()); <END> }</code><technical_language>This existing network updated a network provider. Is intent</technical_language>

Target:
default void inputDetail() { optional(network().comment()); optional(network().description()); optional(network().display()); optional(network().ip().address()); optional(network().ip().gateway()); optional(network().ip().netmask()); optional(network().mtu()); optional(network().name()); optional(network().stp()); optional(network().vlan().id()); }
Source:
<code><START> public LinkedHashSet<String> getIncludePaths() { <END> return myProperties.myIncludePaths; }</code><technical_language>Collection Set more preferable</technical_language>

Target:
public List<String> getIncludePaths() { return Collections.unmodifiableList(myProperties.myIncludePaths); }
Source:
<code>public DocumentModel run(DocumentModel doc) { String n = name; if (name == null || name.length() == 0) { <START> n = doc.getName(); <END> } if (Boolean.TRUE.equals(resetLifeCycle)) { return session.copy(doc.getRef(), target, n, CopyOption.RESET_LIFE_CYCLE); } return session.copy(doc.getRef(), target, n); }</code><technical_language>add @since 11.1 for new properties</technical_language>

Target:
public DocumentModel run(DocumentModel doc) { String n = name; if (StringUtils.isEmpty(name)) { n = doc.getName(); } List<CopyOption> options = new ArrayList<>(); if (resetLifeCycle) { options.add(CopyOption.RESET_LIFE_CYCLE); } return session.copy(doc.getRef(), target, n, options.toArray(CopyOption[]::new)); }
Source:
<code>public void testPkToJsonHash() throws IOException { long timestampMillis = 1496712943447L; List<String> pKeys = new ArrayList<>(); pKeys.add("id"); pKeys.add("name"); <START> Position position = new Position(new BinlogPosition(1L, "binlog-0001"), 0L); <END> RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", timestampMillis, pKeys, position); rowMap.putData("id", "9001"); rowMap.putData("name", "example"); String jsonString = rowMap.pkToJson(RowMap.KeyFormat.HASH); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"pk.id\":\"9001\",\"pk.name\":\"example\"}", jsonString); }</code><technical_language>timestampMillis position in test, care values. In case hoist a field instead of setting in test</technical_language>

Target:
public void testPkToJsonHash() throws IOException { List<String> pKeys = new ArrayList<>(); pKeys.add("id"); pKeys.add("name"); RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", TIMESTAMP_MILLISECONDS, pKeys, POSITION); rowMap.putData("id", "9001"); rowMap.putData("name", "example"); String jsonString = rowMap.pkToJson(RowMap.KeyFormat.HASH); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"pk.id\":\"9001\",\"pk.name\":\"example\"}", jsonString); }
Source:
<code>@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); RelDistribution tableDist = tableScan.getTable().getDistribution(); if (tableDist.getType() == RelDistribution.Type.RANDOM_DISTRIBUTED) { throw new PlannerFallbackException("MP query not supported in Calcite planner."); } if (tableDist.getType() != RelDistribution.Type.SINGLETON && (calc.getProgram().getCondition() == null || ! isSinglePartitioned(calc.getProgram(), calc.getProgram().getCondition(), tableDist.getKeys()))) { throw new PlannerFallbackException("MP query not supported in Calcite planner."); } RelNode newTableScan = tableScan.copy(tableScan.getTraitSet().replace(tableDist), tableScan.getInputs()); <START> call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist), newTableScan, calc.getProgram())); <END> } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }</code><technical_language>I understand issue, do a plan</technical_language>

Target:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof Calc && call.rel(1) instanceof TableScan) { final Calc calc = call.rel(0); final TableScan tableScan = call.rel(1); final Pair<Boolean, RexNode> r = RelDistributionUtils.isCalcScanSP(tableScan, calc); final RelDistribution tableDist = tableScan.getTable().getDistribution(); call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist.with( tableDist.getType(), RelDistributionUtils.adjustProjection(calc.getProgram(), tableDist.getKeys()), r.getSecond(), r.getFirst())), calc.getInputs())); } else { final RelDistribution childDist = call.rel(1).getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { final SingleRel node = call.rel(0); final RelDistribution dist; if (node instanceof Calc) { dist = childDist.with(childDist.getType(), RelDistributionUtils.adjustProjection(((Calc) node).getProgram(), childDist.getKeys()), childDist.getPartitionEqualValue(), childDist.getIsSP()); } else { dist = childDist; } call.transformTo(node.copy(node.getTraitSet().replace(dist), node.getInputs())); } } }
Source:
<code>public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); <START> Login bcp = this.bridgeAPI().login(); <END> bcp.setPassword(this.bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }</code><technical_language>Drop unnecessary of this. throughout</technical_language>

Target:
public synchronized boolean bridgeLogin() { logger.trace("bridgeLogin() called."); Login bcp = bridgeAPI().login(); bcp.setPassword(bridgeInstance.veluxBridgeConfiguration().bridgePassword); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogin(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogin(): storing authentication token for further access."); authenticationToken = bcp.getAuthToken(); return true; } } return false; }
Source:
<code>public void acknowledge(OutputBufferId bufferId, long token) { OutputBuffer outputBuffer; synchronized (this) { if (delegate == null) { <START> return; <END> } outputBuffer = delegate; } outputBuffer.acknowledge(bufferId, token); }</code><technical_language>throw here... this happen is sign of a programming error</technical_language>

Target:
public void acknowledge(OutputBufferId bufferId, long token) { OutputBuffer outputBuffer; synchronized (this) { checkState(delegate != null, "delegate is null"); outputBuffer = delegate; } outputBuffer.acknowledge(bufferId, token); }
Source:
<code>public static ParamConfig fromJSON(JsonReader jsonReader) { <START> if (jsonReader == null) { <END> return null; } ParamConfig paramConfig = new ParamConfig(); jsonReader.readStringIfPresent("name", paramConfig::setName); jsonReader.readStringIfPresent("value", paramConfig::setValue); return paramConfig; }</code><technical_language>Do need a null check? Is place reader is null</technical_language>

Target:
private static ParamConfig fromJSON(JsonReader jsonReader) { ParamConfig paramConfig = new ParamConfig(); jsonReader.readStringIfPresent("name", paramConfig::setName); jsonReader.readStringIfPresent("value", paramConfig::setValue); return paramConfig; }
Source:
<code><START> public void addProject(final String projectName) { <END> File srcRoot = env.getSourceRootFile(); File projDir = new File(srcRoot, projectName); if (!env.getProjects().containsKey(projectName)) { Project project = new Project(projectName, "/" + projectName, env.getConfiguration()); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); env.addRepositories(repos); env.getProjectRepositoriesMap().put(project, repos); env.getProjects().put(projectName, project); Set<Project> projectSet = new TreeSet<>(); projectSet.add(project); env.populateGroups(env.getGroups(), projectSet); } else { Project project = env.getProjects().get(projectName); Map<Project, List<RepositoryInfo>> map = env.getProjectRepositoriesMap(); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); List<RepositoryInfo> allrepos = env.getRepositories(); synchronized (allrepos) { for (RepositoryInfo repo : repos) { if (!allrepos.contains(repo)) { allrepos.add(repo); } } for (RepositoryInfo repo : map.get(project)) { if (!repos.contains(repo)) { allrepos.remove(repo); } } } map.put(project, repos); } }</code><technical_language>this a POST (creating a new entity semantically recreating) return 202 CREATED</technical_language>

Target:
public Response addProject(final String projectName) { File srcRoot = env.getSourceRootFile(); File projDir = new File(srcRoot, projectName); if (!env.getProjects().containsKey(projectName)) { Project project = new Project(projectName, "/" + projectName, env.getConfiguration()); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); env.addRepositories(repos); env.getProjectRepositoriesMap().put(project, repos); env.getProjects().put(projectName, project); Set<Project> projectSet = new TreeSet<>(); projectSet.add(project); env.populateGroups(env.getGroups(), projectSet); } else { Project project = env.getProjects().get(projectName); Map<Project, List<RepositoryInfo>> map = env.getProjectRepositoriesMap(); List<RepositoryInfo> repos = getRepositoriesInDir(projDir); List<RepositoryInfo> allrepos = env.getRepositories(); synchronized (allrepos) { for (RepositoryInfo repo : repos) { if (!allrepos.contains(repo)) { allrepos.add(repo); } } for (RepositoryInfo repo : map.get(project)) { if (!repos.contains(repo)) { allrepos.remove(repo); } } } map.put(project, repos); } return Response.status(Response.Status.CREATED).build(); }
Source:
<code>ReflogEntry readLogEntry() { if ((valueType & VALUE_TYPE_MASK) == LOG_NONE) { return null; } ObjectId oldId; ObjectId newId; PersonIdent who; String msg; if ((valueType & VALUE_TYPE_MASK) == LOG_DATA) { logNewIdPtr = ptr; oldId = readValueId(); newId = readValueId(); long timeSecs = readVarint64(); logCommitterPtr = ptr; who = readPersonIdent(timeSecs); logMessagePtr = ptr; msg = readValueString(); } else if ((valueType & LOG_CHAINED) == LOG_CHAINED) { newId = ObjectId.fromRaw(buf, logNewIdPtr); logNewIdPtr = ptr; oldId = readValueId(); long timeSecs = readVarint64(); if ((valueType & LOG_SAME_IDENT) == LOG_SAME_IDENT) { int savePtr = ptr; ptr = logCommitterPtr; who = readPersonIdent(timeSecs); ptr = savePtr; } else { <START> who = readPersonIdent(timeSecs); <END> } if ((valueType & LOG_SAME_MESSAGE) == LOG_SAME_MESSAGE) { int savePtr = ptr; ptr = logMessagePtr; msg = readValueString(); ptr = savePtr; } else { msg = readValueString(); } } else { throw new IllegalStateException(); } return new ReflogEntry() { @Override public ObjectId getOldId() { return oldId; } @Override public ObjectId getNewId() { return newId; } @Override public PersonIdent getWho() { return who; } @Override public String getComment() { return msg; } @Override public CheckoutEntry parseCheckout() { return null; } }; }</code><technical_language>identity is chained, need reset logCommitterPtr = ptr</technical_language>

Target:
ReflogEntry readLogEntry() { if ((valueType & VALUE_TYPE_MASK) == LOG_NONE) { return null; } ObjectId oldId = readValueId(); ObjectId newId = readValueId(); PersonIdent who = readPersonIdent(); String msg = readValueString(); return new ReflogEntry() { @Override public ObjectId getOldId() { return oldId; } @Override public ObjectId getNewId() { return newId; } @Override public PersonIdent getWho() { return who; } @Override public String getComment() { return msg; } @Override public CheckoutEntry parseCheckout() { return null; } }; }
Source:
<code>private static void processDilutions(String dilutionMolarity, Library library, Pool p, User u) throws Exception { if (!isStringEmptyOrNull(dilutionMolarity)) { try { LibraryDilution ldi = new LibraryDilution(); ldi.setLibrary(library); ldi.setSecurityProfile(library.getSecurityProfile()); ldi.setConcentration(Double.valueOf(dilutionMolarity)); ldi.setCreationDate(new Date()); ldi.setDilutionCreator(u.getLoginName()); if (!library.getLibraryDilutions().contains(ldi)) { library.addDilution(ldi); log.info("Added library dilution: {}", ldi.toString()); } if (p != null) { p.getPoolDilutions().add(new PoolDilution(p, PoolableElementView.fromDilution(ldi))); <START> log.info("Added library dilution to pool: {}", p.toString()); <END> } } catch (NumberFormatException nfe) { throw new InputFormException("Supplied LibraryDilution concentration for library '" + library.getAlias() + "' (" + library.getSample().getAlias() + ") is invalid", nfe); } } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Invoke method(s) conditionally. [![rule](<LINK_1>](<LINK_3> ![MAJOR](<LINK_0> 'Severity: MAJOR') need call "toString()" method formatting string conversion is done Formatter. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private static void processDilutions(String dilutionMolarity, Library library, Pool p, User u) throws Exception { if (!isStringEmptyOrNull(dilutionMolarity)) { try { LibraryDilution ldi = new LibraryDilution(); ldi.setLibrary(library); ldi.setSecurityProfile(library.getSecurityProfile()); ldi.setConcentration(Double.valueOf(dilutionMolarity)); ldi.setCreationDate(new Date()); ldi.setDilutionCreator(u.getLoginName()); if (!library.getLibraryDilutions().contains(ldi)) { library.addDilution(ldi); log.info("Added library dilution: {}", ldi); } if (p != null) { p.getPoolDilutions().add(new PoolDilution(p, PoolableElementView.fromDilution(ldi))); log.info("Added library dilution to pool: {}", p); } } catch (NumberFormatException nfe) { throw new InputFormException("Supplied LibraryDilution concentration for library '" + library.getAlias() + "' (" + library.getSample().getAlias() + ") is invalid", nfe); } } }
Source:
<code>public BeanCollection<E> getShallowCopy() { BeanList<E> copy = new BeanList<>(new CopyOnFirstWriteList<>(list)); <START> copy.setFromOriginal(copy); <END> return copy; }</code><technical_language>copy.setFromOriginal(this); -- this</technical_language>

Target:
public BeanCollection<E> getShallowCopy() { BeanList<E> copy = new BeanList<>(new CopyOnFirstWriteList<>(list)); copy.setFromOriginal(this); return copy; }
Source:
<code>public static StubCalculation ofIborInterpolatedRate(IborIndex index1, IborIndex index2) { <START> ArgChecker.notNull(index1, "startIndex"); <END> ArgChecker.notNull(index2, "endIndex"); return new StubCalculation(null, index1, index2); }</code><technical_language>stick variable name. Especially order matter start/end apply</technical_language>

Target:
public static StubCalculation ofIborInterpolatedRate(IborIndex index1, IborIndex index2) { ArgChecker.notNull(index1, "index1"); ArgChecker.notNull(index2, "index2"); return new StubCalculation(null, index1, index2); }
Source:
<code>@Test public void testDateCanCompare() { <START> final String sql = "select a.v1, a.v2, a.v3\n" <END> + "from (select \"sqlDate\" v1, \"sqlTime\" v2, \"sqlTimestamp\" v3\n" + " from \"s\".\"everyTypes\" " + " group by \"sqlDate\", \"sqlTime\", \"sqlTimestamp\") a," + " (select \"sqlDate\" v1, \"sqlTime\" v2, \"sqlTimestamp\" v3\n" + " from \"s\".\"everyTypes\"\n" + " group by \"sqlDate\", \"sqlTime\", \"sqlTimestamp\") b\n" + "where a.v1 >= b.v1 and a.v2 >= b.v2 and a.v3 >= b.v3\n" + "group by a.v1, a.v2, a.v3"; CalciteAssert.that() .withSchema("s", CATCHALL) .query(sql) .returnsUnordered("V1=1970-01-01; V2=00:00:00; V3=1970-01-01 00:00:00"); }</code><technical_language>Oops, this test is messed up, i split 3 tests: testDateCanCompare testTimeCanCompare testTimestampCanCompare</technical_language>

Target:
@Test public void testDateCanCompare() { final String sql = "select a.v\n" + "from (select \"sqlDate\" v\n" + " from \"s\".\"everyTypes\" " + " group by \"sqlDate\") a," + " (select \"sqlDate\" v\n" + " from \"s\".\"everyTypes\"\n" + " group by \"sqlDate\") b\n" + "where a.v >= b.v\n" + "group by a.v"; CalciteAssert.that() .withSchema("s", CATCHALL) .query(sql) .returnsUnordered("V=1970-01-01"); }
Source:
<code>private void handleNotificationData(Intent intent) { JSONObject json = new JSONObject(); Bundle extras = intent.getExtras(); if (extras != null) { Set<String> keys = extras.keySet(); for (String key : keys) { try { json.put(key, JSONObject.wrap(extras.get(key))); } catch (JSONException e) { } } } <START> this.webView.getEngine().evaluateJavascript("window.dispatchEvent(new CustomEvent('CDVnotificationClicked', { detail: "+ json +"}));", null); <END> }</code><technical_language>For threadsafety, need wrap this in cordova.getActivity().runOnUiThread(new Runnable() { ... })</technical_language>

Target:
private void handleNotificationData(Intent intent) { JSONObject json = new JSONObject(); Bundle extras = intent.getExtras(); if (extras != null) { Set<String> keys = extras.keySet(); for (String key : keys) { try { json.put(key, JSONObject.wrap(extras.get(key))); } catch (JSONException e) { } } } this.lastPushIntent = null; cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.getEngine().evaluateJavascript("window.dispatchEvent(new CustomEvent('CDVnotificationClicked', { detail: "+ json +"}));", null); } }); }
Source:
<code>void completePlayerSetup(boolean asked) { if(asked) { skinLayout = (OoyalaSkinLayout)findViewById(R.id.ooyalaPlayer); <START> PlayerDomain domain1 = new PlayerDomain(domain); <END> Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, domain1, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaIMAManager imaManager = new OoyalaIMAManager(player, skinLayout); if (player.setEmbedCode(embedCode)) { } } }</code><technical_language>rename playerDomain</technical_language>

Target:
void completePlayerSetup(boolean asked) { if(asked) { skinLayout = (OoyalaSkinLayout)findViewById(R.id.ooyalaPlayer); PlayerDomain playerDomain = new PlayerDomain(domain); Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, playerDomain, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaIMAManager imaManager = new OoyalaIMAManager(player, skinLayout); if (player.setEmbedCode(embedCode)) { } } }
Source:
<code>public void write(JsonGenerator jg, DocumentModel document) throws IOException { if (!document.isFolder()) { jg.writeBooleanField(NAME, false); return; } try (SessionWrapper wrapper = ctx.getSession(document)) { FacetFilter facetFilter = new FacetFilter(Arrays.asList(FacetNames.FOLDERISH), Arrays.asList(FacetNames.HIDDEN_IN_NAVIGATION)); LifeCycleFilter lfFilter = new LifeCycleFilter(LifeCycleConstants.DELETED_STATE, false); <START> Filter filters = new CompoundFilter(facetFilter, lfFilter); <END> DocumentModelList children = wrapper.getSession().query( "SELECT * FROM Document WHERE ecm:parentId = " + NXQL.escapeString(document.getId()), filters, 1); jg.writeBooleanField(NAME, !children.isEmpty()); } }</code><technical_language>Is advantage put query string itself</technical_language>

Target:
public void write(JsonGenerator jg, DocumentModel document) throws IOException { if (!document.isFolder()) { jg.writeBooleanField(NAME, false); return; } try (SessionWrapper wrapper = ctx.getSession(document)) { String fetchFolderishChildQuery = "SELECT * FROM Document WHERE ecm:mixinType = 'Folderish'" + " AND ecm:mixinType != 'HiddenInNavigation' AND ecm:currentLifeCycleState != 'deleted'" + " AND ecm:parentId = " + NXQL.escapeString(document.getId()); DocumentModelList children = wrapper.getSession().query(fetchFolderishChildQuery, 1); jg.writeBooleanField(NAME, !children.isEmpty()); } }
Source:
<code>public static int hashCode( AnyValue[] array ) { <START> int len = array.length; <END> switch ( len ) { case 0: return 42; case 1: return hashCode( array[0] ); case 2: return 31 * hashCode( array[0] ) + hashCode( array[1] ); case 3: return (31 * hashCode( array[0] ) + hashCode( array[1] )) * 31 + hashCode( array[2] ); default: return len * (31 * hashCode( array[0] ) + hashCode( array[len / 2] ) * 31 + hashCode( array[len - 1] )); } }</code><technical_language>Arrays.hashCode( array ); I this trick</technical_language>

Target:
public static int hashCode( AnyValue[] array ) { return Arrays.hashCode( array ); }
Source:
<code>private static void checkLengthIs2(int actualLength) { <START> assert actualLength == 2 <END> : "The value of a GeoPoint must be a double array with 2 items, not " + actualLength; }</code><technical_language>this a runtime check method validate assertions enabled</technical_language>

Target:
private static void checkLengthIs2(int actualLength) { if (actualLength != 2) { throw new IllegalArgumentException( "The value of a GeoPoint must be a double array with 2 items, not " + actualLength); } }
Source:
<code>public void setUp() throws Exception { super.setUp(); loadBalancer = createStockLoadBalancer(); <START> PoolResName = FuncTest.isCompatApiEnabled() ? "Pool" : "pool"; HmResName = FuncTest.isCompatApiEnabled() ? "HealthMonitor" : "health monitor"; <END> }</code><technical_language>running v1 tests anymore, v2 option</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); loadBalancer = createStockLoadBalancer(); }
Source:
<code>@Override public Object evaluate(List args) throws XPathFunctionException { String result = ""; if (args.size() == 1 && args.get(0) instanceof ArrayList) { ArrayList nodeList = (ArrayList) args.get(0); for (int i = 0; i < nodeList.size(); i++) { try { String item = (((Element) nodeList.get(i))).getTextContent(); result = result.concat(item); } catch (DOMException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + ", for function concat()", e); } catch (ClassCastException e) { <START> throw new HumanTaskRuntimeException( <END> "Invalid arguments:" + args.get(0) + " , for function concat()"); } } } else { throw new HumanTaskRuntimeException("Invalid arguments:" + args + " , for function concat()"); } return result; }</code><technical_language>add exception newly created exception</technical_language>

Target:
public Object evaluate(List args) throws XPathFunctionException { String result = ""; if (args.size() == 1 && args.get(0) instanceof ArrayList) { ArrayList nodeList = (ArrayList) args.get(0); for (int i = 0; i < nodeList.size(); i++) { try { String item = (((Element) nodeList.get(i))).getTextContent(); result = result.concat(item); } catch (DOMException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + ", for function concat()", e); } catch (ClassCastException e) { throw new HumanTaskRuntimeException( "Invalid arguments:" + args.get(0) + " , for function concat()",e); } } } else { throw new HumanTaskRuntimeException("Invalid arguments:" + args + " , for function concat()"); } return result; }
Source:
<code>void verifySubObservationsInputVariablesInAggregateFunction(final int variableId, final int studyId, final int datasetId, final Map<Integer, Integer> inputVariableDatasetMap) { Integer plotDatasetId = this.datasetService.getDatasets(studyId, new HashSet<>(Arrays.asList(DatasetTypeEnum.PLOT_DATA.getId()))).get(0).getDatasetId(); if(!plotDatasetId.equals(datasetId)) { return; } final Optional<FormulaDto> formulaOptional = this.formulaService.getByTargetId(variableId); if (formulaOptional.isPresent()) { <START> final List<DatasetDTO> subobsDatasets = this.datasetService.getDatasets(studyId, new HashSet<>(Arrays.asList(DatasetTypeEnum.PLANT_SUBOBSERVATIONS.getId(), DatasetTypeEnum.QUADRAT_SUBOBSERVATIONS.getId(), DatasetTypeEnum.TIME_SERIES_SUBOBSERVATIONS.getId(), DatasetTypeEnum.CUSTOM_SUBOBSERVATIONS.getId()))); <END> final List<Integer> subobservationIds = new ArrayList<>(); for(DatasetDTO dataset: subobsDatasets) { subobservationIds.add(dataset.getDatasetId()); } for (final FormulaVariable formulaVariable : formulaOptional.get().getInputs()) { if(subobservationIds.contains(inputVariableDatasetMap.get(formulaVariable.getId()))) { validateSubobservationInputVariable(formulaOptional, formulaVariable); } } } }</code><technical_language>DatasetTypeService#getObservationDatasetTypeIds</technical_language>

Target:
void verifySubObservationsInputVariablesInAggregateFunction(final int variableId, final int studyId, final int datasetId, final Map<Integer, Integer> inputVariableDatasetMap) { final Integer plotDatasetId = this.datasetService.getDatasets(studyId, new HashSet<>(Arrays.asList(DatasetTypeEnum.PLOT_DATA.getId()))).get(0).getDatasetId(); if (!plotDatasetId.equals(datasetId)) { return; } final Optional<FormulaDto> formulaOptional = this.formulaService.getByTargetId(variableId); if (formulaOptional.isPresent()) { final List<DatasetDTO> subobsDatasets = this.datasetService.getDatasets(studyId, new HashSet<>(this.datasetTypeService.getSubObservationDatasetTypeIds())); final List<Integer> subobservationIds = subobsDatasets.stream().map(DatasetDTO::getDatasetId).collect(Collectors.toList()); for (final FormulaVariable formulaVariable : formulaOptional.get().getInputs()) { if (subobservationIds.contains(inputVariableDatasetMap.get(formulaVariable.getId()))) { this.validateSubobservationInputVariable(formulaOptional, formulaVariable); } } } }
Source:
<code>private void limitEntriesCount() { int limit = Integer.MAX_VALUE; if (fMemento.getString(LogView.P_USE_LIMIT).equals("true")) { limit = fMemento.getInteger(LogView.P_LOG_LIMIT).intValue(); } int entriesCount = getEntriesCount(); if (entriesCount <= limit) { return; } <START> Comparator<AbstractEntry> dateComparator = (o1, o2) -> { <END> if (o1 instanceof LogEntry && o2 instanceof LogEntry) { Date l1 = ((LogEntry)o1).getDate(); Date l2 = ((LogEntry)o2).getDate(); if ((l1 != null) && (l2 != null)) { return l1.before(l2) ? -1 : 1; } else if ((l1 == null) && (l2 == null)) { return 0; } else return (l1 == null) ? -1 : 1; } return 0; }; synchronized (elements) { if (fMemento.getInteger(P_GROUP_BY).intValue() == GROUP_BY_NONE) { elements.subList(0, elements.size() - limit).clear(); } else { List<AbstractEntry> copy = new ArrayList<>(entriesCount); for (AbstractEntry group : elements) { List<AbstractEntry> children = Arrays.asList(group.getChildren(group)); copy.addAll(children); } Collections.sort(copy, dateComparator); List<AbstractEntry> toRemove = copy.subList(0, copy.size() - limit); for (AbstractEntry group : elements) { group.removeChildren(toRemove); } } } }</code><technical_language>glance, comparator replaced Comparator.comparing(LogEntry::getDate, Comparator.nullsLast((d1, d2) -> d1.before(d2) ? -1 : 1)); add instanceof check call</technical_language>

Target:
private void limitEntriesCount() { int limit = Integer.MAX_VALUE; if (fMemento.getString(LogView.P_USE_LIMIT).equals("true")) { limit = fMemento.getInteger(LogView.P_LOG_LIMIT).intValue(); } int entriesCount = getEntriesCount(); if (entriesCount <= limit) { return; } Comparator<AbstractEntry> dateComparator = Comparator.comparing( entry -> entry instanceof LogEntry ? ((LogEntry) entry).getDate() : null, Comparator.nullsLast((d1, d2) -> d1.before(d2) ? -1 : 1)); synchronized (elements) { if (fMemento.getInteger(P_GROUP_BY).intValue() == GROUP_BY_NONE) { elements.subList(0, elements.size() - limit).clear(); } else { List<AbstractEntry> copy = new ArrayList<>(entriesCount); for (AbstractEntry group : elements) { List<AbstractEntry> children = Arrays.asList(group.getChildren(group)); copy.addAll(children); } Collections.sort(copy, dateComparator); List<AbstractEntry> toRemove = copy.subList(0, copy.size() - limit); for (AbstractEntry group : elements) { group.removeChildren(toRemove); } } } }
Source:
<code>protected void finalize() throws Throwable { <START> super.finalize(); <END> if (managementRealm != null || permissionRealm != null) { RealmLog.error("PermissionManager was not correctly closed before being finalized."); close(); } }</code><technical_language>Call last</technical_language>

Target:
protected void finalize() throws Throwable { if (!closed) { RealmLog.warn("PermissionManager was not correctly closed before being finalized."); } super.finalize(); }
Source:
<code><START> public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { <END> if (obj == null) { throw new NamingException("Invalid JNDI object reference"); } Class<ConfigurationObject> clazz = ConfigurationObject.class; ConfigurationObject config = clazz.newInstance(); Reference ref = (Reference) obj; Enumeration<RefAddr> props = ref.getAll(); while (props.hasMoreElements()) { RefAddr addr = props.nextElement(); String propName = addr.getType(); String propValue = addr.getContent().toString(); Field[] fields = ConfigurationObject.class.getFields(); for (Field field : fields) { if (propName.equals(field.getName())) { Class<?> type = field.getType(); if (mapper.containsKey(type)) { type = mapper.get(type); } Object value = null; if (type.isAssignableFrom(Long.class)) { try { value = Long.valueOf(propValue); } catch (NumberFormatException e) { throw new NamingException(field.getName() + " is not an long value"); } } else if (type.isAssignableFrom(Integer.class)) { try { value = Integer.parseInt(propValue); } catch (NumberFormatException e) { throw new NamingException(field.getName() + " is not an integer value"); } } else if (type.isAssignableFrom(Boolean.class)) { if ("true".equalsIgnoreCase(propValue)) { value = true; } else if ("false".equalsIgnoreCase(propValue)) { value = false; } else { throw new NamingException(field.getName() + " is not a boolean value"); } } else if (type.isAssignableFrom(String.class)) { value = propValue; } if (value != null) { field.set(config, value); } } } } return config; }</code><technical_language>reduce method complexity, e.g. extract while body / for loop body methods</technical_language>

Target:
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { if (obj == null) { throw new NamingException("Invalid JNDI object reference"); } Class<ConfigurationObject> clazz = ConfigurationObject.class; ConfigurationObject config = clazz.newInstance(); Reference ref = (Reference) obj; Enumeration<RefAddr> props = ref.getAll(); while (props.hasMoreElements()) { RefAddr addr = props.nextElement(); String propName = addr.getType(); String propValue = addr.getContent().toString(); Field[] fields = ConfigurationObject.class.getFields(); for (Field field : fields) { checkForValue(config, propName, propValue, field); } } return config; }
Source:
<code>private static ImmutableSet<Flavor> getInvalidFlavors(Flavored flavored, BuildTarget target) { ImmutableSet.Builder<Flavor> builder = ImmutableSet.builder(); for (Flavor flavor : target.getFlavors()) { if (!flavored.hasFlavors(ImmutableSet.of(flavor))) { builder.add(flavor); } } <START> return builder.build(); <END> }</code><technical_language>this replaced a stream filter operation</technical_language>

Target:
private static ImmutableSet<Flavor> getInvalidFlavors(Flavored flavored, BuildTarget target) { return target .getFlavors() .stream() .filter(flavor -> !flavored.hasFlavors(ImmutableSet.of(flavor))) .collect(ImmutableSet.toImmutableSet()); }
Source:
<code>public static ArrayList<Guid> getGuidListFromStringArray(List<String> strings) { <START> ArrayList<Guid> guidList = new ArrayList<Guid>(); <END> if (strings != null && !strings.isEmpty()) { for (String guidString : strings) { guidList.add(Guid.createGuidFromString(guidString)); } } return guidList; }</code><technical_language>org.apache.commons.collections.CollectionUtils.isEmpty(Collection) - returns true for nulls</technical_language>

Target:
public static ArrayList<Guid> getGuidListFromStringArray(List<String> strings) { ArrayList<Guid> guidList = new ArrayList<Guid>(); if (CollectionUtils.isEmpty(strings)) { for (String guidString : strings) { guidList.add(Guid.createGuidFromString(guidString)); } } return guidList; }
Source:
<code><START> private static SampleTissueDto asTissueSampleDto(SampleTissue from) { <END> SampleTissueDto dto = new SampleTissueDto(); dto.setPassageNumber(from.getPassageNumber()); dto.setTimesReceived(from.getTimesReceived()); dto.setExternalInstituteIdentifier(from.getExternalInstituteIdentifier()); dto.setRegion(from.getRegion()); dto.setTubeNumber(from.getTubeNumber()); if (from.getLab() != null) { dto.setLabId(from.getLab().getId()); } if (from.getTissueOrigin() != null) { dto.setTissueOriginId(from.getTissueOrigin().getId()); } if (from.getTissueType() != null) { dto.setTissueTypeId(from.getTissueType().getId()); } return dto; }</code><technical_language>tissueMaterial set in</technical_language>

Target:
private static SampleTissueDto asTissueSampleDto(SampleTissue from) { SampleTissueDto dto = new SampleTissueDto(); dto.setPassageNumber(from.getPassageNumber()); dto.setTimesReceived(from.getTimesReceived()); dto.setExternalInstituteIdentifier(from.getExternalInstituteIdentifier()); dto.setRegion(from.getRegion()); dto.setTubeNumber(from.getTubeNumber()); if (from.getLab() != null) { dto.setLabId(from.getLab().getId()); } if (from.getTissueOrigin() != null) { dto.setTissueOriginId(from.getTissueOrigin().getId()); } if (from.getTissueType() != null) { dto.setTissueTypeId(from.getTissueType().getId()); } if (from.getTissueMaterial() != null) { dto.setTissueMaterialId(from.getTissueMaterial().getId()); } return dto; }
Source:
<code>private String getSenderConfiguration() { try { Field reporterField = this.tracer.getClass().getDeclaredField("reporter"); reporterField.setAccessible(true); Object reporter = reporterField.get(this.tracer); if ("RemoteReporter".equals(reporter.getClass().getSimpleName())) { Field senderField = reporter.getClass().getDeclaredField("sender"); senderField.setAccessible(true); Object sender = senderField.get(reporter); if ("UdpSender".equals(sender.getClass().getSimpleName())) { Field transportField = sender.getClass().getDeclaredField("udpTransport"); transportField.setAccessible(true); Object transport = transportField.get(sender); if ("ThriftUdpTransport".equals(transport.getClass().getSimpleName())) { Field socketField = transport.getClass().getDeclaredField("socket"); socketField.setAccessible(true); DatagramSocket socket = (DatagramSocket) socketField.get(transport); return "sender-binding=" + NetworkUtils.formatIPAddressForURI(socket.getInetAddress()) + ":" + socket.getPort(); } } } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { <START> ex.printStackTrace(); <END> } return ""; }</code><technical_language>throwing error here</technical_language>

Target:
private String getSenderConfiguration() { try { Field reporterField = this.tracer.getClass().getDeclaredField("reporter"); reporterField.setAccessible(true); Object reporter = reporterField.get(this.tracer); if (checkClass(reporter, "RemoteReporter")) { Field senderField = reporter.getClass().getDeclaredField("sender"); senderField.setAccessible(true); Object sender = senderField.get(reporter); if (checkClass(sender, "UdpSender")) { Field transportField = sender.getClass().getDeclaredField("udpTransport"); transportField.setAccessible(true); Object transport = transportField.get(sender); if (checkClass(transport, "ThriftUdpTransport")) { Field socketField = transport.getClass().getDeclaredField("socket"); socketField.setAccessible(true); DatagramSocket socket = (DatagramSocket) socketField.get(transport); return "sender-binding=" + NetworkUtils.formatIPAddressForURI(socket.getInetAddress()) + ":" + socket.getPort(); } } } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException("Error getting network configuration details", ex); } return ""; }
Source:
<code>protected final String doIt() throws Exception { final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(getCtx(), ClientAndOrgId.ofClientAndOrg(receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID())); final ReceiptScheduleHUGenerator huGenerator = ReceiptScheduleHUGenerator.newInstance(huContextInitial) .addM_ReceiptSchedule(receiptSchedule) .setUpdateReceiptScheduleDefaultConfiguration(isUpdateReceiptScheduleDefaultConfiguration()); final I_M_HU_LUTU_Configuration lutuConfigurationOrig = getCurrentLUTUConfiguration(receiptSchedule); final I_M_HU_LUTU_Configuration lutuConfiguration = createM_HU_LUTU_Configuration(lutuConfigurationOrig); Services.get(ILUTUConfigurationFactory.class).save(lutuConfiguration); huGenerator.setM_HU_LUTU_Configuration(lutuConfiguration); final ILUTUProducerAllocationDestination lutuProducer = huGenerator.getLUTUProducerAllocationDestination(); final Quantity qtyCUsTotal = lutuProducer.calculateTotalQtyCU(); if (qtyCUsTotal.isInfinite()) { throw new TerminalException("LU/TU configuration is resulting to infinite quantity: " + lutuConfiguration); } huGenerator.setQtyToAllocateTarget(qtyCUsTotal); final List<I_M_HU> hus = huGenerator.generateWithinOwnTransaction(); hus.forEach(hu -> { <START> setAttributeBBD(hu, receiptSchedule); <END> setAttributeLotNumber(hu); }); openHUsToReceive(hus); return MSG_OK; }</code><technical_language>introduce method calls</technical_language>

Target:
protected final String doIt() throws Exception { final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(getCtx(), ClientAndOrgId.ofClientAndOrg(receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID())); final ReceiptScheduleHUGenerator huGenerator = ReceiptScheduleHUGenerator.newInstance(huContextInitial) .addM_ReceiptSchedule(receiptSchedule) .setUpdateReceiptScheduleDefaultConfiguration(isUpdateReceiptScheduleDefaultConfiguration()); final I_M_HU_LUTU_Configuration lutuConfigurationOrig = getCurrentLUTUConfiguration(receiptSchedule); final I_M_HU_LUTU_Configuration lutuConfiguration = createM_HU_LUTU_Configuration(lutuConfigurationOrig); Services.get(ILUTUConfigurationFactory.class).save(lutuConfiguration); huGenerator.setM_HU_LUTU_Configuration(lutuConfiguration); final ILUTUProducerAllocationDestination lutuProducer = huGenerator.getLUTUProducerAllocationDestination(); final Quantity qtyCUsTotal = lutuProducer.calculateTotalQtyCU(); if (qtyCUsTotal.isInfinite()) { throw new TerminalException("LU/TU configuration is resulting to infinite quantity: " + lutuConfiguration); } huGenerator.setQtyToAllocateTarget(qtyCUsTotal); final List<I_M_HU> hus = huGenerator.generateWithinOwnTransaction(); hus.forEach(hu -> { updateAttributes(hu, receiptSchedule); }); openHUsToReceive(hus); return MSG_OK; }