auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void updateFromSmartDashboard(String prefix) { if (!(SmartDashboard.containsKey(prefix + "_P") && SmartDashboard.containsKey(prefix + "_I") && SmartDashboard.containsKey(prefix + "_D") && SmartDashboard.containsKey(prefix + "_F"))) { SmartDashboard.putNumber(prefix + "_P", getP()); SmartDashboard.putNumber(prefix + "_I", getI()); SmartDashboard.putNumber(prefix + "_D", getD()); SmartDashboard.putNumber(prefix + "_F", getD()); return; } <START> setPIDF(SmartDashboard.getNumber(prefix + "_P", getP()), <END> SmartDashboard.getNumber(prefix + "_I", getI()), SmartDashboard.getNumber(prefix + "_D", getD()), SmartDashboard.getNumber(prefix + "_F", getF())); }</code><technical_language>Do want two-argument version a default value? done this in while testing (with default 0)</technical_language>

Target:
public void updateFromSmartDashboard(String prefix) { if (!(SmartDashboard.containsKey(prefix + "_P") && SmartDashboard.containsKey(prefix + "_I") && SmartDashboard.containsKey(prefix + "_D") && SmartDashboard.containsKey(prefix + "_F"))) { SmartDashboard.putNumber(prefix + "_P", getP()); SmartDashboard.putNumber(prefix + "_I", getI()); SmartDashboard.putNumber(prefix + "_D", getD()); SmartDashboard.putNumber(prefix + "_F", getF()); return; } setPIDF(SmartDashboard.getNumber(prefix + "_P", getP()), SmartDashboard.getNumber(prefix + "_I", getI()), SmartDashboard.getNumber(prefix + "_D", getD()), SmartDashboard.getNumber(prefix + "_F", getF())); }
Source:
<code>private String getJenkinsReportsUrl() { String build_url = System.getProperty("BUILD_URL"); if (isEmpty(build_url)) { build_url = System.getenv("BUILD_URL"); } String workspace = System.getProperty("WORKSPACE"); if (isEmpty(workspace)) { workspace = System.getenv("WORKSPACE"); <START> } <END> if (!isEmpty(build_url)) { String reportRelativePath = ""; if (!isEmpty(workspace)) { Path pathAbsoluteReportsFolder = Paths.get("").normalize().toAbsolutePath(); Path pathAbsoluteWorkSpace = Paths.get(workspace).normalize().toAbsolutePath(); Path pathRelative = pathAbsoluteWorkSpace.relativize(pathAbsoluteReportsFolder); reportRelativePath = pathRelative.toString() + '/'; } return resolveUrlSource("%s/artifact/%s", build_url, reportRelativePath); } else { return null; } }</code><technical_language>simplified: String workspace = System.getProperty("WORKSPACE", System.getenv("WORKSPACE"));</technical_language>

Target:
private String getJenkinsReportsUrl() { String build_url = System.getProperty("BUILD_URL"); if (!isEmpty(build_url)) { String workspace = System.getProperty("WORKSPACE", System.getenv("WORKSPACE")); String reportRelativePath = ""; if (!isEmpty(workspace)) { Path pathAbsoluteReportsFolder = Paths.get("").normalize().toAbsolutePath(); Path pathAbsoluteWorkSpace = Paths.get(workspace).normalize().toAbsolutePath(); Path pathRelative = pathAbsoluteWorkSpace.relativize(pathAbsoluteReportsFolder); reportRelativePath = pathRelative.toString().replace('\\', '/') + '/'; } return resolveUrlSource("%s/artifact/%s", build_url, reportRelativePath); } else { return null; } }
Source:
<code>private TickingTimer createTickingTimer(UI ui) { return new TickingTimer("Browser Request Delay Timer", BROWSER_REQUEST_DELAY, integer -> { }, () -> { Platform.runLater(() -> { <START> System.out.println("\nREQUEST DELAY TIMER\n"); <END> if (nextRepoId.isPresent() && nextIssueId.isPresent() && isPullRequest.isPresent()) { ui.getBrowserComponent().showIssue(nextRepoId.get(), nextIssueId.get(), isPullRequest.get(), false); } }); timer.pause(); }, TimeUnit.MILLISECONDS); }</code><technical_language>Is this left out of clean up? logger</technical_language>

Target:
private TickingTimer createTickingTimer(UI ui) { return new TickingTimer("Browser Request Delay Timer", BROWSER_REQUEST_DELAY, integer -> { }, () -> { Platform.runLater(() -> { if (nextRepoId.isPresent() && nextIssueId.isPresent() && isPullRequest.isPresent()) { ui.getBrowserComponent().showIssue(nextRepoId.get(), nextIssueId.get(), isPullRequest.get(), false); } }); timer.pause(); }, TimeUnit.MILLISECONDS); }
Source:
<code>public void shouldCollectDefinedValueUsingPartialFunction() { final PartialFunction<Integer, String> pf = new PartialFunction<Integer, String>() { @Override public String apply(Integer i) { return String.valueOf(i); } @Override public boolean isDefinedAt(Integer i) { return i % 2 == 1; } <START> }; <END> final Future<String> future = Future.of(zZz(3)).collect(pf); waitUntil(future::isCompleted); assertThat(future.getValue().get()).isEqualTo(Try.success("3")); }</code><technical_language>Please reduce duplicate code in tests diff + final PartialFunction<Integer, String> pf = new PartialFunction<Integer, String>() { + @Override + public String apply(Integer i) { + return String.valueOf(i); + } + @Override + public boolean isDefinedAt(Integer i) { + return i % 2 == 1; + } + }; this more concise variant: java final PartialFunction<Integer, String> pf = Function1.<Integer, String> of(String::valueOf).partial(i -> i % 2 == 1); (or Function1.of(String::valueOf).partial(i -> i % 2 == 1); ???)</technical_language>

Target:
public void shouldCollectDefinedValueUsingPartialFunction() { final PartialFunction<Integer, String> pf = Function1.<Integer, String> of(String::valueOf).partial(i -> i % 2 == 1); final Future<String> future = Future.of(zZz(3)).collect(pf); waitUntil(future::isCompleted); assertThat(future.getValue().get()).isEqualTo(Try.success("3")); }
Source:
<code>protected abstract void processIncoming() throws IOException, ClientConnectionException; private void processHeartbeat() { <START> if (!this.isInInit() && this.policy.isIncomingHeartbeat() && this.lastIncomingHeartbeat + this.policy.getIncomingHeartbeat() < System.currentTimeMillis()) { <END> log.debug("Heartbeat exeeded. Closing channel"); this.disconnect("Heartbeat exeeded"); } }</code><technical_language>extract part of condition local variable ?i.e. boolean heartbeatExceeded = this.lastIncomingHeartbeat + this.policy.getIncomingHeartbeat() < System.currentTimeMillis() condition reversed</technical_language>

Target:
protected abstract void processIncoming() throws IOException, ClientConnectionException; private void processHeartbeat() { if (!this.isInInit() && this.policy.isIncomingHeartbeat() && this.isIncomingHeartbeatExeeded()) { log.debug("Heartbeat exeeded. Closing channel"); this.disconnect("Heartbeat exeeded"); } }
Source:
<code>public String toString() { String AddInfo = getAdditionalInformation(); return String.format("%s(%s %s)", super.toString(), <START> (!StringUtils.isEmpty(AddInfo) ? AddInfo + "," : ""), <END> (getParameters() != null ? getParameters().toString() : "null")); }</code><technical_language>need for string utils. if want it, I a isNotEmpty method well</technical_language>

Target:
public String toString() { String AddInfo = getAdditionalInformation(); return String.format("%s(%s %s)", super.toString(), (!AddInfo.isEmpty() ? AddInfo + "," : ""), (getParameters() != null ? getParameters().toString() : "null")); }
Source:
<code>public void run() { try { serverChannel.register(nioSelector, SelectionKey.OP_ACCEPT); startupComplete(); int currentProcessor = 0; while (isRunning()) { int ready = nioSelector.select(selectTimeOutMs); if (ready > 0) { Set<SelectionKey> keys = nioSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key, processors.get(currentProcessor)); } else { throw new IllegalStateException("Unrecognized key state for acceptor thread."); } currentProcessor = (currentProcessor + 1) % processors.size(); } catch (Exception e) { key.cancel(); metrics.acceptConnectionErrorCount.inc(); logger.debug("Error in accepting new connection", e); } } } } logger.debug("Closing server socket and selector."); <START> serverChannel.socket().close(); <END> serverChannel.close(); nioSelector.close(); shutdownComplete(); } catch (Exception e) { metrics.acceptorShutDownErrorCount.inc(); logger.error("Error during shutdown of acceptor thread", e); } }</code><technical_language>add this line? serverChannel.close() close underlying socket</technical_language>

Target:
public void run() { try { serverChannel.register(nioSelector, SelectionKey.OP_ACCEPT); startupComplete(); int currentProcessor = 0; while (isRunning()) { int ready = nioSelector.select(selectTimeOutMs); if (ready > 0) { Set<SelectionKey> keys = nioSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext() && isRunning()) { SelectionKey key = null; try { key = iter.next(); iter.remove(); if (key.isAcceptable()) { accept(key, processors.get(currentProcessor)); } else { throw new IllegalStateException("Unrecognized key state for acceptor thread."); } currentProcessor = (currentProcessor + 1) % processors.size(); } catch (Exception e) { key.cancel(); metrics.acceptConnectionErrorCount.inc(); logger.debug("Error in accepting new connection", e); } } } } logger.debug("Closing server socket and selector."); serverChannel.close(); nioSelector.close(); shutdownComplete(); } catch (Exception e) { metrics.acceptorShutDownErrorCount.inc(); logger.error("Error during shutdown of acceptor thread", e); } }
Source:
<code>private Optional<ConnectionSlot> acquireConnectionSlot(final String client, final String eventType, final String partition) throws ConnectionSlotOccupiedException { final String parent = zkPathForConsumer(client, eventType, partition); <START> List<String> children = ImmutableList.of(); <END> try { children = zkHolder.get() .getChildren() .forPath(parent); } catch (final KeeperException.NoNodeException e) { } catch (Exception e) { LOG.error("Zookeeper error when getting consumer nodes", e); throw new NakadiRuntimeException(e); } if (children.size() >= maxConnections) { return Optional.empty(); } final List<String> occupiedSlots = children; final List<String> availableSlots = SLOT_NAMES.stream() .filter(slot -> !occupiedSlots.contains(slot)) .collect(Collectors.toList()); final int slotIndex = new Random().nextInt(availableSlots.size()); final String slot = availableSlots.get(slotIndex); final String zkPath = parent + "/" + slot; try { zkHolder.get() .create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .forPath(zkPath); } catch (final KeeperException.NodeExistsException e) { throw new ConnectionSlotOccupiedException(); } catch (Exception e) { LOG.error("Zookeeper error when creating consumer node", e); throw new NakadiRuntimeException(e); } return Optional.of(new ConnectionSlot(client, eventType, partition, slot)); }</code><technical_language>init in case of KeeperException.NoNodeException</technical_language>

Target:
private ConnectionSlot acquireConnectionSlot(final String client, final String eventType, final String partition) { final String parent = zkPathForConsumer(client, eventType, partition); final String slotId = UUID.randomUUID().toString(); final String zkPath = parent + "/" + slotId; try { zkHolder.get() .create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .forPath(zkPath); } catch (Exception e) { LOG.error("Zookeeper error when creating consumer node", e); throw new NakadiRuntimeException(e); } final ConnectionSlot acquiredSlot = new ConnectionSlot(client, eventType, partition, slotId); ACQUIRED_SLOTS.add(acquiredSlot); return acquiredSlot; }
Source:
<code>protected void appendToTablePopupMenu(IMenuManager manager, IStructuredSelection sel) { Object element = sel.getFirstElement(); <START> if ((element instanceof TmfGenericTreeEntry)) { <END> SegmentStoreStatisticsModel model = ((TmfGenericTreeEntry<SegmentStoreStatisticsModel>) element).getModel(); IAction gotoStartTime = new Action(Messages.SegmentStoreStatisticsViewer_GotoMinAction) { @Override public void run() { long start = model.getMinStart(); long end = model.getMinEnd(); broadcast(new TmfSelectionRangeUpdatedSignal(AbstractSegmentsStatisticsViewer.this, TmfTimestamp.fromNanos(start), TmfTimestamp.fromNanos(end), getTrace())); updateContent(start, end, true); } }; IAction gotoEndTime = new Action(Messages.SegmentStoreStatisticsViewer_GotoMaxAction) { @Override public void run() { long start = model.getMaxStart(); long end = model.getMaxEnd(); broadcast(new TmfSelectionRangeUpdatedSignal(AbstractSegmentsStatisticsViewer.this, TmfTimestamp.fromNanos(start), TmfTimestamp.fromNanos(end), getTrace())); updateContent(start, end, true); } }; manager.add(gotoStartTime); manager.add(gotoEndTime); } }</code><technical_language>SegmentStoreStatisticsEntry HiddenTreeViewerEntry deprecated needs work if element is of this type</technical_language>

Target:
protected void appendToTablePopupMenu(IMenuManager manager, IStructuredSelection sel) { Object element = sel.getFirstElement(); if ((element instanceof TmfGenericTreeEntry || element instanceof SegmentStoreStatisticsEntry) && !(element instanceof HiddenTreeViewerEntry) ) { IAction gotoStartTime = new Action(Messages.SegmentStoreStatisticsViewer_GotoMinAction) { @Override public void run() { long start; long end; if (element instanceof TmfGenericTreeEntry) { SegmentStoreStatisticsModel model = ((TmfGenericTreeEntry<SegmentStoreStatisticsModel>) element).getModel(); start = model.getMinStart(); end = model.getMinEnd(); } else { ISegment minObject = ((SegmentStoreStatisticsEntry) element).getEntry().getMinObject(); start = minObject == null ? 0 : minObject.getStart(); end = minObject == null ? 0 : minObject.getEnd(); } broadcast(new TmfSelectionRangeUpdatedSignal(AbstractSegmentsStatisticsViewer.this, TmfTimestamp.fromNanos(start), TmfTimestamp.fromNanos(end), getTrace())); updateContent(start, end, true); } }; IAction gotoEndTime = new Action(Messages.SegmentStoreStatisticsViewer_GotoMaxAction) { @Override public void run() { long start; long end; if (element instanceof TmfGenericTreeEntry) { SegmentStoreStatisticsModel model = ((TmfGenericTreeEntry<SegmentStoreStatisticsModel>) element).getModel(); start = model.getMaxStart(); end = model.getMaxEnd(); } else { ISegment maxObject = ((SegmentStoreStatisticsEntry) element).getEntry().getMaxObject(); start = maxObject == null ? 0 : maxObject.getStart(); end = maxObject == null ? 0 : maxObject.getEnd(); } broadcast(new TmfSelectionRangeUpdatedSignal(AbstractSegmentsStatisticsViewer.this, TmfTimestamp.fromNanos(start), TmfTimestamp.fromNanos(end), getTrace())); updateContent(start, end, true); } }; manager.add(gotoStartTime); manager.add(gotoEndTime); } }
Source:
<code>protected Set<CDOID> confirming(CDODataInput in, OMMonitor monitor) throws IOException { if (monitor == null) { monitor = new EclipseMonitor(new NullProgressMonitor()); <START> } <END> Set<CDOID> result = new HashSet<CDOID>(); int size = in.readInt(); monitor.begin(size + infos); try { for (int i = 0; i < size; i++) { CDOID id = in.readCDOID(); result.add(id); monitor.worked(); } readRevisionAvailabilityInfo(in, targetInfo, result, monitor.fork()); readRevisionAvailabilityInfo(in, sourceInfo, result, monitor.fork()); if (infos > 2) { readRevisionAvailabilityInfo(in, targetBaseInfo, result, monitor.fork()); } if (infos > 3) { readRevisionAvailabilityInfo(in, sourceBaseInfo, result, monitor.fork()); } return result; } finally { monitor.done(); } }</code><technical_language>Change caller give a valid monitor</technical_language>

Target:
protected Set<CDOID> confirming(CDODataInput in, OMMonitor monitor) throws IOException { Set<CDOID> result = new HashSet<CDOID>(); int size = in.readInt(); if (monitor != null) { monitor.begin(size + infos); } try { for (int i = 0; i < size; i++) { CDOID id = in.readCDOID(); result.add(id); if (monitor != null) { monitor.worked(); } } readRevisionAvailabilityInfo(in, targetInfo, result, monitor != null ? monitor.fork() : null); readRevisionAvailabilityInfo(in, sourceInfo, result, monitor != null ? monitor.fork() : null); if (infos > 2) { readRevisionAvailabilityInfo(in, targetBaseInfo, result, monitor != null ? monitor.fork() : null); } if (infos > 3) { readRevisionAvailabilityInfo(in, sourceBaseInfo, result, monitor != null ? monitor.fork() : null); } return result; } finally { if (monitor != null) { monitor.done(); } } }
Source:
<code>public int getEffectiveMaxBatchChangesLimit(CurrentUser user) { int maxBatchChangesLimitOfUser = <START> user.getCapabilities().getRange(GlobalCapability.BATCH_CHANGES_LIMIT) <END> .getMax(); if (maxBatchChangesLimitOfUser > 0) return maxBatchChangesLimitOfUser; if (maxBatchChangesOfSystem > 0) return maxBatchChangesOfSystem; return 0; }</code><technical_language>Optional: save a line making this a static import</technical_language>

Target:
public int getEffectiveMaxBatchChangesLimit(CurrentUser user) { if (user.getCapabilities().canPerform(BATCH_CHANGES_LIMIT)) { return user.getCapabilities().getRange(BATCH_CHANGES_LIMIT).getMax(); } return systemMaxBatchChangesOf; }
Source:
<code>public WallThermostatStateMsg(String rawMsg) { super(rawMsg); logger.debug(this.msgType+" Payload Len -> "+this.payload.length); if (this.payload.length == WALL_THERMOSTAT_STATE_SHORT_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_PAIR_THERM_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_UNTIL_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_TEMP_PAYLOAD_LEN) { ctrlMode = ThermostatControlMode.values()[(this.payload[0]&0x3)]; dstActive = extractBitFromByte(this.payload[0], 3);; lanGateway = extractBitFromByte(this.payload[0], 4); lockedForManualSetPoint = extractBitFromByte(this.payload[0], 5); rfError = extractBitFromByte(this.payload[0], 6); batteryLow = extractBitFromByte(this.payload[0], 7); displayMeasuredTemp = (this.payload[1]==0?false:true); desiredTemperature = (this.payload[2] & 0x7f) / 2.0; if (this.payload.length == WALL_THERMOSTAT_STATE_PAIR_THERM_PAYLOAD_LEN) { int mTemp = this.payload[3]; mTemp &= 0x01; mTemp <<= 8; mTemp |= (this.payload[4]&0xff); this.measuredTemperature = mTemp/10.0; } else if (this.payload.length == WALL_THERMOSTAT_STATE_UNTIL_PAYLOAD_LEN) { } else if (this.payload.length ==WALL_THERMOSTAT_STATE_TEMP_PAYLOAD_LEN) { int mTemp = this.payload[2]; mTemp &= 0x80; mTemp <<= 1; mTemp |= (this.payload[6]&0xff); this.measuredTemperature = mTemp/10.0; } } <START> else logger.error("Got "+this.msgType+" message with incorrect length!"); <END> }</code><technical_language>please add curly braces</technical_language>

Target:
public WallThermostatStateMsg(String rawMsg) { super(rawMsg); logger.debug(this.msgType + " Payload Len -> " + this.payload.length); if (this.payload.length == WALL_THERMOSTAT_STATE_SHORT_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_PAIR_THERM_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_UNTIL_PAYLOAD_LEN || this.payload.length == WALL_THERMOSTAT_STATE_TEMP_PAYLOAD_LEN) { ctrlMode = ThermostatControlMode.values()[(this.payload[0] & 0x3)]; dstActive = extractBitFromByte(this.payload[0], 3); ; lanGateway = extractBitFromByte(this.payload[0], 4); lockedForManualSetPoint = extractBitFromByte(this.payload[0], 5); rfError = extractBitFromByte(this.payload[0], 6); batteryLow = extractBitFromByte(this.payload[0], 7); displayMeasuredTemp = (this.payload[1] == 0 ? false : true); desiredTemperature = (this.payload[2] & 0x7f) / 2.0; if (this.payload.length == WALL_THERMOSTAT_STATE_PAIR_THERM_PAYLOAD_LEN) { int mTemp = this.payload[3]; mTemp &= 0x01; mTemp <<= 8; mTemp |= (this.payload[4] & 0xff); this.measuredTemperature = mTemp / 10.0; } else if (this.payload.length == WALL_THERMOSTAT_STATE_UNTIL_PAYLOAD_LEN) { } else if (this.payload.length == WALL_THERMOSTAT_STATE_TEMP_PAYLOAD_LEN) { int mTemp = this.payload[2]; mTemp &= 0x80; mTemp <<= 1; mTemp |= (this.payload[6] & 0xff); this.measuredTemperature = mTemp / 10.0; } } else { logger.error("Got " + this.msgType + " message with incorrect length!"); } }
Source:
<code>boolean cleanup() default false; } private static final String CENTRAL_LABEL = "Red Hat Central"; <START> private static final String MAVEN_SETTINGS_PATH = System.getProperty("maven.config.file") == null <END> ? "./target/classes/settings.xml" : System.getProperty("maven.config.file");; private static Map<org.jboss.tools.central.reddeer.projects.Project, List<String>> projectWarnings = new HashMap<org.jboss.tools.central.reddeer.projects.Project, List<String>>(); private static final Logger log = Logger.getLogger(ExamplesOperator.class); private static final String BLACKLIST_ERRORS_REGEXES_FILE = "resources/blacklist-test-errors-regexes.json"; public static JSONObject blacklistErrorsFileContents; @BeforeClass public static void setup() { String mvnConfigFileName = new File(MAVEN_SETTINGS_PATH).getAbsolutePath(); WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); TreeItem t = new DefaultTreeItem(new DefaultTree(preferenceDialog), "Java", "Installed JREs"); t.select(); List<TableItem> tis = new DefaultTable(0).getItems(); for (TableItem ti : tis) { if (ti.getText(0).startsWith("Java SE 8") || ti.getText(0).startsWith("openjdk-1.8")) { ti.setChecked(true); new PushButton("Apply").click(); } } MavenSettingsPreferencePage prefPage = new MavenSettingsPreferencePage(preferenceDialog); preferenceDialog.select(prefPage); prefPage.setUserSettingsLocation(mvnConfigFileName); preferenceDialog.ok(); new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); new DefaultEditor(CENTRAL_LABEL); }</code><technical_language>I this maven settings file support removed some time ago, please remove too</technical_language>

Target:
boolean cleanup() default false; } private static final String CENTRAL_LABEL = "Red Hat Central"; private static Map<org.jboss.tools.central.reddeer.projects.Project, List<String>> projectWarnings = new HashMap<org.jboss.tools.central.reddeer.projects.Project, List<String>>(); private static final Logger log = Logger.getLogger(ExamplesOperator.class); private static final String BLACKLIST_ERRORS_REGEXES_FILE = "resources/blacklist-test-errors-regexes.json"; public static JSONObject blacklistErrorsFileContents; @BeforeClass public static void setup() { WorkbenchPreferenceDialog preferenceDialog = new WorkbenchPreferenceDialog(); preferenceDialog.open(); JREsPreferencePage jrePreferencePage = new JREsPreferencePage(preferenceDialog); preferenceDialog.select(jrePreferencePage); List<TableItem> tis = new DefaultTable(0).getItems(); for (TableItem ti : tis) { if (ti.getText(0).startsWith("Java SE 8") || ti.getText(0).startsWith("openjdk-1.8")) { ti.setChecked(true); jrePreferencePage.apply(); } } preferenceDialog.ok(); new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); new DefaultEditor(CENTRAL_LABEL); }
Source:
<code>public Coin getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE || balanceType == BalanceType.AVAILABLE_SPENDABLE) { List<TransactionOutput> candidates = calculateAllSpendCandidates(true, balanceType == BalanceType.AVAILABLE_SPENDABLE); <START> CoinSelection selection = DefaultCoinSelector.get().select(NetworkParameters.MAX_MONEY, candidates); <END> return selection.valueGathered; } else if (balanceType == BalanceType.ESTIMATED || balanceType == BalanceType.ESTIMATED_SPENDABLE) { List<TransactionOutput> all = calculateAllSpendCandidates(false, balanceType == BalanceType.ESTIMATED_SPENDABLE); Coin value = Coin.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); } } finally { lock.unlock(); } }</code><technical_language>I consider a protected final default coin selector allow subclasses override, hardcoding DefaultCoinSelector</technical_language>

Target:
public Coin getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE || balanceType == BalanceType.AVAILABLE_SPENDABLE) { List<TransactionOutput> candidates = calculateAllSpendCandidates(true, balanceType == BalanceType.AVAILABLE_SPENDABLE); CoinSelection selection = coinSelector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } else if (balanceType == BalanceType.ESTIMATED || balanceType == BalanceType.ESTIMATED_SPENDABLE) { List<TransactionOutput> all = calculateAllSpendCandidates(false, balanceType == BalanceType.ESTIMATED_SPENDABLE); Coin value = Coin.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); } } finally { lock.unlock(); } }
Source:
<code><START> public void populateDecisionTable( final GuidedDecisionTable52 dtable, final int maxRowCount ) { <END> if ( this.values.size() < maxRowCount ) { for ( int iRow = this.values.size(); iRow < maxRowCount; iRow++ ) { this.values.add( new DTCellValue52( "" ) ); } } for ( int iRow = 0; iRow < this.values.size(); iRow++ ) { dtable.getData().get( iRow ).add( GuidedDecisionTable52.RULE_NAME_COLUMN_INDEX, this.values.get( iRow ) ); } }</code><technical_language>this is new class, I apply kiegroup codestyling , i.e. white space method parameters ..</technical_language>

Target:
public void populateDecisionTable(final GuidedDecisionTable52 dtable, final int maxRowCount) { if (values.size() < maxRowCount) { for (int iRow = values.size(); iRow < maxRowCount; iRow++) { values.add(new DTCellValue52("")); } } for (int iRow = 0; iRow < values.size(); iRow++) { dtable.getData().get(iRow).add(GuidedDecisionTable52.RULE_NAME_COLUMN_INDEX, values.get(iRow)); } }
Source:
<code>public static void refreshRadius(IPapyrusEditPart editpart, int defaultCornerWidth, int defaultCornerHeight) { if (editpart.getPrimaryShape() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure roundedRectangleFigure = (IRoundedRectangleFigure) editpart.getPrimaryShape(); if (((GraphicalEditPart) editpart).getModel() instanceof View) { int width = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_WIDTH, defaultCornerWidth); int height = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_HEIGHT, defaultCornerHeight); if (!xor(width == 0, height == 0)) { <START> roundedRectangleFigure.setCornerDimensions(new Dimension(width, height)); <END> } } } }</code><technical_language>OK, I get it. (0, 1) (1, 0) is equivalent (0, 0). This fixed in figure directly. Avoid xor() obvious understand is required. if (width == 0 || height == 0){ width = 0; height = 0; } Is more natural</technical_language>

Target:
public static void refreshRadius(IPapyrusEditPart editpart, int defaultCornerWidth, int defaultCornerHeight) { if (editpart.getPrimaryShape() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure roundedRectangleFigure = (IRoundedRectangleFigure) editpart.getPrimaryShape(); if (((GraphicalEditPart) editpart).getModel() instanceof View) { int width = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_WIDTH, defaultCornerWidth); int height = NotationUtils.getIntValue((View) ((GraphicalEditPart) editpart).getModel(), RADIUS_HEIGHT, defaultCornerHeight); roundedRectangleFigure.setCornerDimensions(new Dimension(width, height)); } } }
Source:
<code>private void printSwitchNode(SwitchNode n, Void arg) { printComment(n.getComment(), arg); printer.print("switch("); n.getSelector().accept(this, arg); printer.println(") {"); if (n.getEntries() != null) { if(configuration.isIndentInSwitch()) { printer.indent(); } for (final SwitchEntry e : n.getEntries()) { e.accept(this, arg); } if(configuration.isIndentInSwitch()) { printer.unindent(); } <START> } <END> printer.print("}"); }</code><technical_language>Personally, I a cleaner/tidier alternative be: java printer.indent(configuration.isIndentInSwitch()); a helper method indentIf(boolean shouldIndent) (or similar)</technical_language>

Target:
private void printSwitchNode(SwitchNode n, Void arg) { printComment(n.getComment(), arg); printer.print("switch("); n.getSelector().accept(this, arg); printer.println(") {"); if (n.getEntries() != null) { indentIf(configuration.isIndentCaseInSwitch()); for (final SwitchEntry e : n.getEntries()) { e.accept(this, arg); } unindentIf(configuration.isIndentCaseInSwitch()); } printer.print("}"); }
Source:
<code>public Cagemail(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{W}"); this.subtype.add("Aura"); TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); <START> this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(2, 2, Duration.WhileOnBattlefield))); <END> this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new CantBlockAttachedEffect(AttachmentType.AURA))); }</code><technical_language>Add effects ability effect.setText() set correct rule text</technical_language>

Target:
public Cagemail(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{W}"); this.subtype.add("Aura"); TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); Ability ability1 = new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(2, 2, Duration.WhileOnBattlefield)); Effect effect = new CantBlockAttachedEffect(AttachmentType.AURA); effect.setText("and can't block."); ability1.addEffect(effect); this.addAbility(ability1); }
Source:
<code>AttemptResult<Void> evaluateResult(List<AttemptResult<Void>> results) { Optional<AttemptResult<Void>> error = results.stream() .filter(it -> it.getState() == AttemptState.BREAK).findFirst(); if (error.isPresent()) { return error.get(); } <START> long count = results.stream().filter(it -> it.getState() == AttemptState.CONTINUE).count(); if (count > 0) { <END> return AttemptResults.justContinue(); } return AttemptResults.finishWith(null); }</code><technical_language>I anyMatch instead of count filter if I understand code</technical_language>

Target:
AttemptResult<Void> evaluateResult(List<AttemptResult<Void>> results) { Optional<AttemptResult<Void>> error = results.stream() .filter(it -> it.getState() == AttemptState.BREAK).findFirst(); if (error.isPresent()) { return error.get(); } if (shouldContinue(results)) { return AttemptResults.justContinue(); } return AttemptResults.finishWith(null); }
Source:
<code>private Map<String, List<Pair<VDS, LUNs>>> createLunMap(boolean sameLunSizesPerHost) { RandomUtils rnd = RandomUtils.instance(); String lunId = <START> rnd.nextString(34); <END> int lunSize = rnd.nextInt(); List<Pair<VDS, LUNs>> lunList = new ArrayList<>(); for (int i = 0; i < 10; i++) { LUNs lun = new LUNs(); if (!sameLunSizesPerHost) { lunSize++; } lun.setDeviceSize(lunSize); lunList.add(new Pair<>(new VDS(), lun)); } return new SingletonMap(lunId, lunList); }</code><technical_language>Consider Guid.newGuid().toString()</technical_language>

Target:
private Map<String, List<Pair<VDS, LUNs>>> createLunMap(boolean sameLunSizesPerHost) { RandomUtils rnd = RandomUtils.instance(); String lunId = rnd.nextString(34); int lunSize = rnd.nextInt(); List<Pair<VDS, LUNs>> lunList = new ArrayList<>(); for (int i = 0; i < 10; i++) { LUNs lun = new LUNs(); if (!sameLunSizesPerHost) { lunSize++; } lun.setDeviceSize(lunSize); lunList.add(new Pair<>(new VDS(), lun)); } return Collections.singletonMap(lunId, lunList); }
Source:
<code>public static void createDBServer() { dsProps = ExecutorTestUtil.getDatasourceProperties(); <START> dsProps.setProperty("url", "jdbc:h2:tcp://localhost/target/jbpm-exec-test;MVCC=TRUE"); <END> PersistenceUtil.startH2TcpServer(dsProps); }</code><technical_language>checking, setting port, default (or a random, if use), no? previously started 9123</technical_language>

Target:
public static void createDBServer() { dsProps = ExecutorTestUtil.getDatasourceProperties(); dsProps.setProperty("url", "jdbc:h2:tcp://localhost:9123/target/jbpm-exec-test;MVCC=TRUE"); dsProps.setProperty("tcpPort", "9123"); PersistenceUtil.startH2TcpServer(dsProps); }
Source:
<code><START> private boolean emitNoResolvedType(NoType type, String defaultEmit) { <END> if (!opts.partialInput || !type.isNoResolvedType()) { emit(defaultEmit); return true; } NoResolvedType nType = (NoResolvedType) type; if (nType.getReferenceName() != null) { String displayName = type.getDisplayName(); emit(Constants.INTERNAL_NAMESPACE + "." + displayName); List<JSType> templateTypes = nType.getTemplateTypes(); if (templateTypes != null && templateTypes.size() > 0) { emitGenericTypeArguments(type.getTemplateTypes().iterator()); } } else { emit(defaultEmit); } return false; }</code><technical_language>maybeEmitNoResolvedType</technical_language>

Target:
private void emitNoResolvedType(NoType type, String defaultEmit) { if (!opts.partialInput || !type.isNoResolvedType()) { emit(defaultEmit); return; } NoResolvedType nType = (NoResolvedType) type; if (nType.getReferenceName() == null) { emit(defaultEmit); return; } String displayName = type.getDisplayName(); emit(Constants.INTERNAL_NAMESPACE + "." + displayName); List<JSType> templateTypes = nType.getTemplateTypes(); if (templateTypes != null && templateTypes.size() > 0) { emitGenericTypeArguments(type.getTemplateTypes().iterator()); } }
Source:
<code><START> private Map<String, Object> getEntityFieldsAsMap(JsonNode node) { <END> Map<String, Object> result = new HashMap<>(); for (Iterator<String> it = node.fieldNames(); it.hasNext();) { String fieldName = it.next(); result.put(fieldName, getEntityFieldAsObject(node, fieldName)); if (fieldName.endsWith(TablesConstants.ODATA_TYPE_KEY_SUFFIX) && TablesConstants.ODATA_TYPE_NULL.equals(node.get(fieldName).asText())) { String nullFieldName = fieldName.substring(0, fieldName.length() - TablesConstants.ODATA_TYPE_KEY_SUFFIX.length()); result.put(nullFieldName, null); } } return result; }</code><technical_language>I this static. rely state in class, iirc.i</technical_language>

Target:
private Map<String, Object> getEntityFieldsAsMap(JsonNode node) throws IOException { Map<String, Object> result = new HashMap<>(); for (Iterator<String> it = node.fieldNames(); it.hasNext();) { String fieldName = it.next(); result.put(fieldName, getEntityFieldAsObject(node, fieldName)); } return result; }
Source:
<code>public void start(String program) { <START> this.transport.start(program, new HashMap<String, String>()); <END> }</code><technical_language>Collections.emptyMap()</technical_language>

Target:
public void start(String program) { this.transport.start(program, Collections.<String, String> emptyMap()); }
Source:
<code>public void itThrowsAOrmExceptionForOtherErrors() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); String invalidKey = null; final Person.Key pk = new Person.Key(invalidKey); final Person bob = new Person(pk, 18); p.people().insert(Collections.singleton(bob)); fail("Expected " + OrmException.class); } catch (OrmException e) { <START> assertTrue(e.getCause() instanceof SQLException); <END> assertContainsString(e.getMessage(), p.people().getRelationName()); } finally { p.close(); } }</code><technical_language>OrmDuplicateKeyException is a subclass of OrmException I want assertFalse(e instanceof OrmDuplicateKeyException) add another catch clause fail() in body this one</technical_language>

Target:
public void itThrowsAOrmExceptionForOtherErrors() throws Exception { PhoneBookDb p = phoneBook.open(); try { p.updateSchema(executor); String invalidKey = null; final Person.Key pk = new Person.Key(invalidKey); final Person bob = new Person(pk, 18); p.people().insert(Collections.singleton(bob)); fail("Expected " + OrmException.class); } catch (OrmException e) { assertTrue(e.getCause() instanceof SQLException); assertFalse(e instanceof OrmDuplicateKeyException); assertContainsString(e.getMessage(), p.people().getRelationName()); } finally { p.close(); } }
Source:
<code>public void testR2dbcConnectionSuccessful() { <START> try (R2dbcPostgresContainer postgres = (R2dbcPostgresContainer) new R2dbcPostgresContainer() <END> .withInitScript("init_postgresql.sql")) { postgres.start(); R2dbc r2dbc = new R2dbc(postgres.getR2dbcConnectionFactory()); String queryResult = (String) r2dbc.inTransaction(handle -> handle.createQuery("SELECT foo FROM bar").mapResult(result -> result.map((row, metadata) -> row.get("foo"))) ).blockFirst(); assertEquals("Value from init script should equal real value", "hello world", queryResult); } }</code><technical_language>suggestion try (R2dbcPostgresContainer postgres = new R2dbcPostgresContainer()</technical_language>

Target:
public void testR2dbcConnectionSuccessful() { try (R2dbcPostgresContainer postgres = new R2dbcPostgresContainer() .withInitScript("init_postgresql.sql")) { postgres.start(); R2dbc r2dbc = new R2dbc(postgres.getR2dbcConnectionFactory()); String queryResult = (String) r2dbc.inTransaction(handle -> handle.createQuery("SELECT foo FROM bar").mapResult(result -> result.map((row, metadata) -> row.get("foo"))) ).blockFirst(); assertEquals("Value from init script should equal real value", "hello world", queryResult); } }
Source:
<code>public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); <START> LOG.error("received byle length ->" + value.length); <END> bff.put(value); int val1 = bff.getShort(0); int val2 = bff.getShort(2); return new ObjectLink(val1, val2); }</code><technical_language>LOG.error</technical_language>

Target:
public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); bff.put(value); int val1 = bff.getShort(0); int val2 = bff.getShort(2); return new ObjectLink(val1, val2); }
Source:
<code>public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { parseCommandLine(); boolean ok = true; for (final Change.Id changeId : changeIds) { try { ok = ok && modifyOne(changeId); } catch (Exception e) { ok = false; writeError("fatal: internal server error while modifying reviewers in " + changeId + "\n"); <START> log.error("internal error while modifying reviewers in " + changeId, e); <END> } } if (!ok) { throw new UnloggedFailure(1, "one or more modifications of reviewers failed; review output above"); } } }); }</code><technical_language>Log writeError()</technical_language>

Target:
public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { parseCommandLine(); if (changeIds.isEmpty()) { writeError("error: You must specify a change"); } boolean ok = true; for (final Change.Id changeId : changeIds) { try { ok = ok && modifyOne(changeId); } catch (Exception e) { ok = false; log.error("internal error while modifying reviewers in " + changeId, e); writeError("fatal: internal server error while modifying " + "reviewers in " + changeId + "\n"); } } if (!ok) { throw error("one or more modifications of reviewers failed; " + "review output above"); } } }); }
Source:
<code>protected final SunrisePageData pageData(final UserContext userContext, final PageContent content, final Http.Context ctx) { final Messages messages = messages(userContext); final PageHeader pageHeader = new PageHeader(content.getAdditionalTitle()); pageHeader.setLocation(new LocationSelector(projectContext(), userContext)); pageHeader.setNavMenu(new NavMenuData(categories(), userContext, reverseRouter(), saleCategoryExtId)); <START> pageHeader.setCustomerServiceNumber(configuration().getString("checkout.customerServiceNumber")); <END> return new SunrisePageData(pageHeader, new PageFooter(), content, getPageMeta(ctx, userContext)); }</code><technical_language>reason I want this solution is means time phone changes call developers change it. I opting for CMS, non-technical friendly</technical_language>

Target:
protected final SunrisePageData pageData(final UserContext userContext, final PageContent content, final Http.Context ctx) { final PageHeader pageHeader = new PageHeader(content.getAdditionalTitle()); pageHeader.setLocation(new LocationSelector(projectContext(), userContext)); pageHeader.setNavMenu(new NavMenuData(categoryTree(), userContext, reverseRouter(), saleCategoryExtId.orElse(null))); pageHeader.setMiniCart(new MiniCart(CartSessionUtils.getCartItemCount(session()))); pageHeader.setCustomerServiceNumber(configuration().getString("checkout.customerServiceNumber")); return new SunrisePageData(pageHeader, new PageFooter(), content, getPageMeta(ctx, userContext)); }
Source:
<code>protected <T extends Node> T pop(String location, FragmentBuilder builder, Class<T> cls, String uri) { if (builder == null) { if (log.isLoggable(Level.WARNING)) { log.warning("No fragment builder for this thread (" + Thread.currentThread() + ") - trying to pop node of type: " + cls); } return null; } if (builder.getCurrentNode() == null) { if (log.isLoggable(Level.FINEST)) { log.finest("WARNING: No 'current node' for this thread (" + Thread.currentThread() + ") - trying to pop node of type: " + cls); } return null; } processInContent(location, builder, -1); processOutContent(location, builder, -1); Node node = builder.popNode(cls, uri); if (node != null) { <START> node.setDuration(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()) - node.getBaseTime()); <END> return cls.cast(node); } if (log.isLoggable(Level.FINEST)) { log.finest("Current node (type=" + builder.getCurrentNode().getClass() + ") does not match required cls=" + cls + " and uri=" + uri + " at location=" + location); } return null; }</code><technical_language>This needs System.nanoTime, converted microseconds, subtract node.getBaseTime</technical_language>

Target:
protected <T extends Node> T pop(String location, FragmentBuilder builder, Class<T> cls, String uri) { if (builder == null) { if (log.isLoggable(Level.WARNING)) { log.warning("No fragment builder for this thread (" + Thread.currentThread() + ") - trying to pop node of type: " + cls); } return null; } if (builder.getCurrentNode() == null) { if (log.isLoggable(Level.FINEST)) { log.finest("WARNING: No 'current node' for this thread (" + Thread.currentThread() + ") - trying to pop node of type: " + cls); } return null; } processInContent(location, builder, -1); processOutContent(location, builder, -1); Node node = builder.popNode(cls, uri); if (node != null) { node.setDuration(TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) - node.getBaseTime()); return cls.cast(node); } if (log.isLoggable(Level.FINEST)) { log.finest("Current node (type=" + builder.getCurrentNode().getClass() + ") does not match required cls=" + cls + " and uri=" + uri + " at location=" + location); } return null; }
Source:
<code>public XYChartConsumer createChartConsumer() { List<XYSeriesConsumer> series = new ArrayList<>(); getData().getChartSeries().stream().forEach(s -> { IDataConsumer xConsumer; IDataConsumer yConsumer; IDataResolver<?, ?> xResolver = s.getX().getResolver(); Predicate<@Nullable Number> xPredicate; if (getModel().isXLogscale()) { INumericalResolver<Object, Number> resolver = INumericalResolver.class.cast(xResolver); xPredicate = new LogarithmicPredicate(resolver); } else { xPredicate = Objects::nonNull; } if (getXDescriptorsInfo().areNumerical()) { <START> INumericalResolver<Object, Number> resolver = INumericalResolver.class.cast(xResolver); <END> xConsumer = new NumericalConsumer(resolver, xPredicate); } else { IStringResolver<Object> resolver = IStringResolver.class.cast(xResolver); xConsumer = new ScatterStringConsumer(resolver, fXStringMap); } IDataResolver<?, ?> yResolver = s.getY().getResolver(); Predicate<@Nullable Number> yPredicate; if (getModel().isYLogscale()) { INumericalResolver<Object, Number> resolver = INumericalResolver.class.cast(yResolver); yPredicate = new LogarithmicPredicate(resolver); } else { yPredicate = Objects::nonNull; } if (getYDescriptorsInfo().areNumerical()) { INumericalResolver<Object, Number> resolver = INumericalResolver.class.cast(yResolver); yConsumer = new NumericalConsumer(resolver, yPredicate); } else { IStringResolver<Object> resolver = IStringResolver.class.cast(yResolver); yConsumer = new ScatterStringConsumer(resolver, fYStringMap); } series.add(new XYSeriesConsumer(s, xConsumer, yConsumer)); }); NumericalConsumerAggregator xAggregator; if (getXDescriptorsInfo().areNumerical()) { xAggregator = new NumericalConsumerAggregator(); } else { xAggregator = null; } NumericalConsumerAggregator yAggregator; if (getYDescriptorsInfo().areNumerical()) { yAggregator = new NumericalConsumerAggregator(); } else { yAggregator = null; } return new XYChartConsumer(series, xAggregator, yAggregator); }</code><technical_language>cast is moved here. this give classCastExceptions? need do instanceof check before</technical_language>

Target:
public XYChartConsumer createChartConsumer() { List<XYSeriesConsumer> series = new ArrayList<>(); createConsumerVisitor visitor = new createConsumerVisitor(); getData().getChartSeries().stream().forEach(s -> { visitor.setXAxis(true); s.getX().accept(visitor); IDataConsumer xConsumer = visitor.getConsumer(); visitor.setXAxis(false); s.getY().accept(visitor); IDataConsumer yConsumer = visitor.getConsumer(); series.add(new XYSeriesConsumer(s, xConsumer, yConsumer)); }); NumericalConsumerAggregator xAggregator; if (getXDescriptorsInfo().areNumerical()) { xAggregator = new NumericalConsumerAggregator(); } else { xAggregator = null; } NumericalConsumerAggregator yAggregator; if (getYDescriptorsInfo().areNumerical()) { yAggregator = new NumericalConsumerAggregator(); } else { yAggregator = null; } return new XYChartConsumer(series, xAggregator, yAggregator); }