auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected Matcher getRegexMatcher(String regex, String stringToMatch) { Matcher result = regexMatchers.get(regex); if (result == null) { result = Pattern.compile(regex).matcher(stringToMatch); regexMatchers.put(regex, result); } else { <START> result.reset(stringToMatch); <END> } return result; }</code><technical_language>this 'put' ensure a re-used regex is treated new in list</technical_language>

Target:
protected Matcher getRegexMatcher(String regex, String stringToMatch) { final Map<String, Matcher> cache = getRegexCache(); Matcher result = cache.get(regex); if (result == null) { result = Pattern.compile(regex).matcher(stringToMatch); cache.put(regex, result); } else { result.reset(stringToMatch); } return result; }
Source:
<code>private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, CosmosDiagnostics cosmosDiagnostics, int statusCode, Integer objectSize, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setRegionsContacted(BridgeInternal.getRegionContacted(cosmosDiagnostics).toString()); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); if (objectSize != null) { <START> reportPayload.setGreaterThan1Kb(objectSize > 1024); <END> } reportPayload.setDatabasesName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; }</code><technical_language>constant</technical_language>

Target:
private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, CosmosDiagnostics cosmosDiagnostics, int statusCode, Integer objectSize, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setRegionsContacted(BridgeInternal.getRegionsContacted(cosmosDiagnostics).toString()); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); if (objectSize != null) { reportPayload.setGreaterThan1Kb(objectSize > ClientTelemetry.ONE_KB_TO_BYTES); } reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; }
Source:
<code>public UpdateTransaction newUpdateTransaction(PartitionUpdate update, WriteContext ctx, int nowInSec) { if (!hasIndexes()) return UpdateTransaction.NO_OP; ArrayList<Index.Indexer> idxrs = new ArrayList<>(); for (Index i : indexes.values()) { <START> Index.Indexer idxr = i.indexerFor(update.partitionKey(), update.columns(), nowInSec, ctx, IndexTransaction.Type.UPDATE); if (idxr != null && isIndexWritable(i)) <END> { idxrs.add(idxr); } } if (idxrs.size() == 0) return UpdateTransaction.NO_OP; else return new WriteTimeTransaction(idxrs.toArray(new Index.Indexer[idxrs.size()])); }</code><technical_language>check if index is writable creating indexer: suggestion if (!isIndexWritable(i)) continue; Index.Indexer idxr = i.indexerFor(update.partitionKey(), update.columns(), nowInSec, ctx, IndexTransaction.Type.UPDATE); if (idxr != null) applies other usages of isIndexWritable in IndexGCTransaction#commit() CleanupGCTransaction#commit(). Alternatively, transform set SIM#writableIndexes a Map<String, Index>, iterate values this instead of SIM#indexes values in places. need isIndexWritable method</technical_language>

Target:
public UpdateTransaction newUpdateTransaction(PartitionUpdate update, WriteContext ctx, int nowInSec) { if (!hasIndexes()) return UpdateTransaction.NO_OP; ArrayList<Index.Indexer> idxrs = new ArrayList<>(); for (Index i : writableIndexes.values()) { Index.Indexer idxr = i.indexerFor(update.partitionKey(), update.columns(), nowInSec, ctx, IndexTransaction.Type.UPDATE); if (idxr != null) idxrs.add(idxr); } if (idxrs.size() == 0) return UpdateTransaction.NO_OP; else return new WriteTimeTransaction(idxrs.toArray(new Index.Indexer[idxrs.size()])); }
Source:
<code>public void updateFailedLoginCount(UserDTO userToUpdate) throws UserRetrievalException { userDAO.updateFailedLoginCount(userToUpdate.getSubjectName(), userToUpdate.getFailedLoginCount()); String maxLoginsStr = env.getProperty("authMaximumLoginAttempts"); int maxLogins = Integer.parseInt(maxLoginsStr); <START> if (userToUpdate.getFailedLoginCount() == maxLogins) { <END> userToUpdate.setAccountLocked(true); try { userDAO.updateAccountLockedStatus(userToUpdate.getSubjectName(), userToUpdate.isAccountLocked()); sendAccountLockedEmail(userToUpdate); } catch (Exception ex) { LOGGER.error("Unable to set account " + userToUpdate.getSubjectName() + " as locked.", ex); } } }</code><technical_language>I unlikely, if happened failed login count jumped maxLogins value, lock account, would, right? this comparison >= add a separate if this block send email == comparison is true</technical_language>

Target:
public void updateFailedLoginCount(UserDTO userToUpdate) throws UserRetrievalException { userDAO.updateFailedLoginCount(userToUpdate.getSubjectName(), userToUpdate.getFailedLoginCount()); String maxLoginsStr = env.getProperty("authMaximumLoginAttempts"); int maxLogins = Integer.parseInt(maxLoginsStr); if (userToUpdate.getFailedLoginCount() >= maxLogins) { userToUpdate.setAccountLocked(true); try { userDAO.updateAccountLockedStatus(userToUpdate.getSubjectName(), userToUpdate.isAccountLocked()); if (userToUpdate.getFailedLoginCount() == maxLogins) { sendAccountLockedEmail(userToUpdate); } } catch (Exception ex) { LOGGER.error("Unable to set account " + userToUpdate.getSubjectName() + " as locked.", ex); } } }
Source:
<code>public SingleConsole getAvailableConsole(ConsoleProperties baseConsoleProperties) { ConsoleEntry consoleEntry = null; try { consoleEntry = consoleQueue.poll(getMaxWaitingMilliSecond(), TimeUnit.MILLISECONDS); if (consoleEntry == null) { throw processException("no console entry available"); } synchronized (this) { consoleEntry.releaseSocket(); ConsoleCommunicationSetting consoleCommunicationSetting = ConsoleCommunicationSetting.asDefault(); if (config.getInactiveClientTimeOut() > 0) { consoleCommunicationSetting.setInactiveClientTimeOut(config.getInactiveClientTimeOut()); } SingleConsole singleConsole = new SingleConsole(config.getCurrentIP(), consoleEntry.getPort(), <START> consoleCommunicationSetting, baseConsoleProperties, config.getCsvSeparator()); <END> getConsoleInUse().add(singleConsole); return singleConsole; } } catch (Exception e) { if (consoleEntry != null) { consoleQueue.add(consoleEntry); } throw processException("no console entry available"); } }</code><technical_language>instead of set csv separator in singleconsole contructure.. set separate setter. singleConsole.setCsvSeparator(String csvSeparator)</technical_language>

Target:
public SingleConsole getAvailableConsole(ConsoleProperties baseConsoleProperties) { ConsoleEntry consoleEntry = null; try { consoleEntry = consoleQueue.poll(getMaxWaitingMilliSecond(), TimeUnit.MILLISECONDS); if (consoleEntry == null) { throw processException("no console entry available"); } synchronized (this) { consoleEntry.releaseSocket(); ConsoleCommunicationSetting consoleCommunicationSetting = ConsoleCommunicationSetting.asDefault(); if (config.getInactiveClientTimeOut() > 0) { consoleCommunicationSetting.setInactiveClientTimeOut(config.getInactiveClientTimeOut()); } SingleConsole singleConsole = new SingleConsole(config.getCurrentIP(), consoleEntry.getPort(), consoleCommunicationSetting, baseConsoleProperties); getConsoleInUse().add(singleConsole); singleConsole.setCsvSeparator(config.getCsvSeparator()); return singleConsole; } } catch (Exception e) { if (consoleEntry != null) { consoleQueue.add(consoleEntry); } throw processException("no console entry available"); } }
Source:
<code>public Optional<SchemaIncompatibility> validate(final List<String> jsonPath, final Schema schema) { if (schema instanceof ObjectSchema) { final ObjectSchema objectSchema = (ObjectSchema) schema; if (!objectSchema.getPatternProperties().isEmpty()) { <START> return Optional.of(new ForbiddenAttributeIncompatibility(jsonPathString(jsonPath), this.ATTRIBUTE)); <END> } } return Optional.empty(); }</code><technical_language>Usually, static variables accessed instance class</technical_language>

Target:
public Optional<SchemaIncompatibility> validate(final List<String> jsonPath, final Schema schema) { if (schema instanceof ObjectSchema) { final ObjectSchema objectSchema = (ObjectSchema) schema; if (!objectSchema.getPatternProperties().isEmpty()) { return Optional.of(new ForbiddenAttributeIncompatibility(jsonPathString(jsonPath), PatternPropertiesConstraint.ATTRIBUTE)); } } return Optional.empty(); }
Source:
<code>private CollectionSet getCollectionSet(MonitoredService service, Map<String, Number> entries, String rrdBaseName) { <START> String ifLabel = ""; <END> Map<String, String> ifInfo = new HashMap<>(); if (m_ifLabelDao != null) { ifLabel = m_ifLabelDao.getIfLabel(service.getNodeId(), InetAddressUtils.addr(service.getIpAddr())); if (ifLabel != null) { ifInfo.putAll(m_ifLabelDao.getInterfaceInfoFromIfLabel(service.getNodeId(), ifLabel)); } } LatencyCollectionResource latencyResource = new LatencyCollectionResource(service.getSvcName(), service.getIpAddr(), service.getNodeLocation(), ifLabel, ifInfo); for (final Entry<String, Number> entry : entries.entrySet()) { final String ds = entry.getKey(); final Number value = entry.getValue() != null ? entry.getValue() : Double.NaN; LatencyCollectionAttributeType latencyType = new LatencyCollectionAttributeType(rrdBaseName, ds); latencyResource.addAttribute(new LatencyCollectionAttribute(latencyResource, latencyType, ds, value.doubleValue())); } SingleResourceCollectionSet collectionSet = new SingleResourceCollectionSet(latencyResource, new Date()); collectionSet.setStatus(CollectionStatus.SUCCEEDED); return collectionSet; }</code><technical_language>This right place for this. collecting interface info for a latency collection set here</technical_language>

Target:
private CollectionSet getCollectionSet(MonitoredService service, Map<String, Number> entries, String rrdBaseName) { LatencyCollectionResource latencyResource = new LatencyCollectionResource(service.getSvcName(), service.getIpAddr(), service.getNodeLocation()); for (final Entry<String, Number> entry : entries.entrySet()) { final String ds = entry.getKey(); final Number value = entry.getValue() != null ? entry.getValue() : Double.NaN; LatencyCollectionAttributeType latencyType = new LatencyCollectionAttributeType(rrdBaseName, ds); latencyResource.addAttribute(new LatencyCollectionAttribute(latencyResource, latencyType, ds, value.doubleValue())); } SingleResourceCollectionSet collectionSet = new SingleResourceCollectionSet(latencyResource, new Date()); collectionSet.setStatus(CollectionStatus.SUCCEEDED); return collectionSet; }
Source:
<code>private void setupDirectories(PanStampBindingSettings cfg) { File xmlDir = new File(cfg.xmlDir); if (xmlDir.exists() && xmlDir.isDirectory() && xmlDir.canRead()) { File devFile = new File(xmlDir, "devices.xml"); if (devFile.exists() && devFile.canRead() && devFile.isFile()) { network.setDeviceLibrary(new CompoundDeviceLibrary( new FileLibrary(xmlDir), new ClassLoaderLibrary())); logger.info("Configured XML directory to {}", cfg.xmlDir); } else { logger.error( <START> "Devices file in XML directory can not be read", <END> cfg.xmlDir); } } else { logger.error("XML directory can not be read", cfg.xmlDir); } }</code><technical_language>Change "Devices" "devices.xml" user specifically file name read</technical_language>

Target:
private void setupDirectories(PanStampBindingSettings cfg) { File xmlDir = new File(cfg.xmlDir); if (xmlDir.exists() && xmlDir.isDirectory() && xmlDir.canRead()) { File devFile = new File(xmlDir, "devices.xml"); if (devFile.exists() && devFile.canRead() && devFile.isFile()) { network.setDeviceLibrary(new CompoundDeviceLibrary(new FileLibrary(xmlDir), new ClassLoaderLibrary())); logger.info("Configured XML directory to {}", cfg.xmlDir); } else { logger.error("devices.xml in XML directory can not be read", cfg.xmlDir); } } else { logger.error("XML directory can not be read", cfg.xmlDir); } }
Source:
<code>public static DsRdata parse(final String value) { final Matcher matcher = RDATA_PATTERN.matcher(value); if (!matcher.matches()) { throw new AttributeParseException("Invalid syntax", value); } final int keytag = Integer.parseInt(matcher.group(1)); final int algorithm = Integer.parseInt(matcher.group(2)); final int digestType = Integer.parseInt(matcher.group(3)); final String digestAsHex = StringUtils.deleteWhitespace(matcher.group(4)); if (keytag < 0 || keytag > 65535) { throw new AttributeParseException("Invalid keytag: " + keytag, value); } if (algorithm < 0 || algorithm > 255) { throw new AttributeParseException("Invalid algorithm: " + algorithm, value); } if (digestType < 0 || digestType > 255) { throw new AttributeParseException("Invalid digest type: " + digestType, value); } try { if (!DsRdataDigestType.validateLength(digestType, digestAsHex)) { throw new AttributeParseException("Digest format is invalid for digest type " + digestType + ": ", digestAsHex); } } catch (AttributeParseException e) { throw e; } catch (IllegalArgumentException e) { return new DsRdata(keytag, algorithm, digestType, digestAsHex); <START> } <END> return new DsRdata(keytag, algorithm, digestType, digestAsHex); }</code><technical_language>catching exception throwing again? I earlier argue for a check of 'unknown' types put a check ones</technical_language>

Target:
public static DsRdata parse(final String value) { final Matcher matcher = RDATA_PATTERN.matcher(value); if (!matcher.matches()) { throw new AttributeParseException("Invalid syntax", value); } final int keytag = Integer.parseInt(matcher.group(1)); final int algorithm = Integer.parseInt(matcher.group(2)); final int digestType = Integer.parseInt(matcher.group(3)); final String digestAsHex = StringUtils.deleteWhitespace(matcher.group(4)); if (keytag < 0 || keytag > 65535) { throw new AttributeParseException("Invalid keytag: " + keytag, value); } if (algorithm < 0 || algorithm > 255) { throw new AttributeParseException("Invalid algorithm: " + algorithm, value); } if (digestType < 0 || digestType > 255) { throw new AttributeParseException("Invalid digest type: " + digestType, value); } if(!DsRdataDigestType.validateLengthForKnownTypes(digestType, digestAsHex)) { throw new AttributeParseException("Digest format is invalid for digest type " + digestType + ": ", digestAsHex); } return new DsRdata(keytag, algorithm, digestType, digestAsHex); }
Source:
<code>public static final byte[] hexStringToByteArray(String s) throws DecoderException { <START> return new Hex().decode(s.getBytes()); <END> }</code><technical_language>I tend decodeHex(char[]), charset sensitive this be, however, <127 ASCII used</technical_language>

Target:
public static final byte[] hexStringToByteArray(String s) throws DecoderException { return Hex.decodeHex(s.toCharArray()); }
Source:
<code>public synchronized void runInBackground() { Preconditions.checkState(daemon == null); daemon = new Thread(this); daemon.setDaemon(true); daemon.setName("BackgroundSweeper"); daemon.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("Shutting down persistent lock manager"); try { persistentLockManager.shutdown(); log.info("Shutdown complete!"); } catch (Exception e) { <START> log.error("Exception while shutting down", e); <END> } })); }</code><technical_language>Okay. I inform people a consequence of this backup lock released properly - if problems out lock, release manually. Also, safe log WARN? I if established procedures for users (and do in docs) suffice</technical_language>

Target:
public synchronized void runInBackground() { Preconditions.checkState(daemon == null); daemon = new Thread(this); daemon.setDaemon(true); daemon.setName("BackgroundSweeper"); daemon.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("Shutting down persistent lock manager"); try { persistentLockManager.shutdown(); log.info("Shutdown complete!"); } catch (Exception e) { log.warn("An exception occurred while shutting down. This means that we had the backup lock out when" + "the shutdown was triggered, but failed to release it. If this is the case, sweep or backup" + "may fail to take out the lock in future. If this happens consistently, " + "consult the following documentation on how to release the dead lock: " + "<LINK_0>", e); } })); }
Source:
<code>public void testTooManyFetchFailureWhileSuccessFinishing() throws Exception { MockEventHandler eventHandler = new MockEventHandler(); TaskAttemptImpl taImpl = createTaskAttemptImpl(eventHandler); TaskId reducetaskId = MRBuilderUtils.newTaskId(taImpl.getID().getTaskId() .getJobId(), 1, TaskType.REDUCE); TaskAttemptId reduceTAId = MRBuilderUtils.newTaskAttemptId(reducetaskId, 0); taImpl.handle(new TaskAttemptEvent(taImpl.getID(), TaskAttemptEventType.TA_DONE)); assertEquals("Task attempt's internal state is not " + "SUCCESS_FINISHING_CONTAINER", taImpl.getInternalState(), <START> TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER); <END> taImpl.handle(new TaskAttemptTooManyFetchFailureEvent(taImpl.getID(), reduceTAId, "Host")); assertEquals("Task attempt is not in FAILED state", taImpl.getState(), TaskAttemptState.FAILED); assertFalse("InternalError occurred", eventHandler.internalError); }</code><technical_language>order of arguments is correct. be: assertEquals("Task attempt's internal state is " + "SUCCESS_FINISHING_CONTAINER", TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, taImpl.getInternalState());</technical_language>

Target:
public void testTooManyFetchFailureWhileSuccessFinishing() throws Exception { MockEventHandler eventHandler = new MockEventHandler(); TaskAttemptImpl taImpl = createTaskAttemptImpl(eventHandler); TaskId reducetaskId = MRBuilderUtils.newTaskId(taImpl.getID().getTaskId() .getJobId(), 1, TaskType.REDUCE); TaskAttemptId reduceTAId = MRBuilderUtils.newTaskAttemptId(reducetaskId, 0); taImpl.handle(new TaskAttemptEvent(taImpl.getID(), TaskAttemptEventType.TA_DONE)); assertEquals("Task attempt's internal state is not " + "SUCCESS_FINISHING_CONTAINER", TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, taImpl.getInternalState()); taImpl.handle(new TaskAttemptTooManyFetchFailureEvent(taImpl.getID(), reduceTAId, "Host")); assertEquals("Task attempt is not in FAILED state", TaskAttemptState.FAILED, taImpl.getState()); assertFalse("InternalError occurred", eventHandler.internalError); }
Source:
<code>public void close() { if (context != null) { MDC.clear(); if (backup != null) { MDC.setContextMap(backup); backup = null; } <START> } <END> }</code><technical_language>This clear MDC if initially empty. IOW keys values set executor's thread cleared, if outer context (when calling current() apply()) null empty. Consider this: java MDC.clear(); TransferableMdc mdc = TransferableMdc.current(); executor.submit(() -> { try (@SuppressWarnings("unused") Mdc mdcTmp = mdc.apply()) { MDC.put("transferred", "value"); } logger.info("'{}' == value", MDC.get("transferred")); // logs 'value' == value, log " == value" }); I in this case MDC cleared: empty before, non-empty afterwards? Removing if (context != null) check fix this. side-effects checking context here? related: conditional in apply() spans correct statements. backup set null-check performed foreach loop</technical_language>

Target:
public void close() throws IllegalStateException { if (backup == null) { throw new IllegalStateException(getClass().getSimpleName() + " must not be reused and can not be closed more than once"); } MDC.setContextMap(backup); backup = null; }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; Optional<CaseLabelTree> defaultLabel = getDefaultLabel(switchStatementTree); <START> if (defaultLabel.isPresent() && !defaultIsLastCase(switchStatementTree)) { <END> reportIssue(defaultLabel.get(), "Move this default to the end of the switch."); } }</code><technical_language>Provide defaultLabel argument of defaultIsLastCase, check if label equals() default tree, check for keyword matching</technical_language>

Target:
public void visitNode(Tree tree) { SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; getDefaultLabelAtWrongPosition(switchStatementTree).ifPresent(defaultLabel -> reportIssue(defaultLabel, "Move this default to the end of the switch.")); }
Source:
<code>public void testGetProcessBuilder() throws IOException { String[] command = {"printenv"}; Map<String, String> env = new HashMap<>(); String key = "heron-shell-utils-test-env-key"; String value = "heron-shell-utils-test-env-value"; env.put(key, value); ProcessBuilder pb = ShellUtils.getProcessBuilder(false, command, new File("."), env); Process p = pb.start(); try { p.waitFor(2, TimeUnit.SECONDS); <START> } catch (InterruptedException e) { <END> LOG.log(Level.SEVERE, "Wait interrupted", e); } Assert.assertTrue(p.getInputStream().available() > 0); String output = ShellUtils.inputstreamToString(p.getInputStream()); String entry = String.format("%s=%s", key, value); Assert.assertTrue(output.contains(entry)); }</code><technical_language>declare this in throws clause handle it, trigger a test failure</technical_language>

Target:
public void testGetProcessBuilder() throws IOException, InterruptedException { String[] command = {"printenv"}; Map<String, String> env = new HashMap<>(); String key = "heron-shell-utils-test-env-key"; String value = "heron-shell-utils-test-env-value"; env.put(key, value); ProcessBuilder pb = ShellUtils.getProcessBuilder(false, command, new File("."), env); Process p = pb.start(); p.waitFor(2, TimeUnit.SECONDS); Assert.assertTrue(p.getInputStream().available() > 0); String output = ShellUtils.inputstreamToString(p.getInputStream()); String entry = String.format("%s=%s", key, value); Assert.assertTrue(output.contains(entry)); }
Source:
<code>protected void before(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(this); Map<String, Object> session = ActionContext.getContext().getSession(); if (session == null && autoCreateSession) { session = new SessionMap<>(ServletActionContext.getRequest()); ActionContext.getContext().withSession(session); } if ( session != null) { lock(session, invocation); } String key = getKey(invocation); <START> Map<String, Object> app = ActionContext.getContext().getApplication(); <END> final ValueStack stack = ActionContext.getContext().getValueStack(); LOG.debug("scope interceptor before"); if (application != null) for (String string : application) { Object attribute = app.get(key + string); if (attribute != null) { LOG.debug("Application scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } if (ActionContext.getContext().getParameters().get(sessionReset).isDefined()) { return; } if (reset) { return; } if (session == null) { LOG.debug("No HttpSession created... Cannot set session scoped variables"); return; } if (this.session != null && (!"start".equals(type))) { for (String string : this.session) { Object attribute = session.get(key + string); if (attribute != null) { LOG.debug("Session scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } } }</code><technical_language>Similar note for local variable app renamed application in other methods. be: Map<String, Object> application = ActionContext.getContext().getApplication(); changing existing references application this.application (like in beforeResult())</technical_language>

Target:
protected void before(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(this); Map<String, Object> session = ActionContext.getContext().getSession(); if (session == null && autoCreateSession) { session = new SessionMap<>(ServletActionContext.getRequest()); ActionContext.getContext().withSession(session); } if ( session != null) { lock(session, invocation); } String key = getKey(invocation); Map<String, Object> application = ActionContext.getContext().getApplication(); final ValueStack stack = ActionContext.getContext().getValueStack(); LOG.debug("scope interceptor before"); if (this.application != null) for (String string : this.application) { Object attribute = application.get(key + string); if (attribute != null) { LOG.debug("Application scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } if (ActionContext.getContext().getParameters().get(sessionReset).isDefined()) { return; } if (reset) { return; } if (session == null) { LOG.debug("No HttpSession created... Cannot set session scoped variables"); return; } if (this.session != null && (!"start".equals(type))) { for (String string : this.session) { Object attribute = session.get(key + string); if (attribute != null) { LOG.debug("Session scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } } }
Source:
<code>private void guardedRun() throws Exception { while (true) { try { for (final byte[] messageBody : stream.messageIterable()) { if (messageBody == null) { log.info("Received null message"); <START> } <END> if (shouldStop.getCount() == 0 || messageBody == null) { break; } log.info("Received incoming message. Size=" + messageBody.length); consumeOneWithRetry(messageBody); parkPaused(); if (shouldStop.getCount() == 0) { break; } } break; } catch (ConsumerTimeoutException cte) { log.info("ConsumerTimeoutException while waiting for data from Kafka. Will retry."); if (shouldStop.getCount() == 0) { break; } parkPaused(); if (shouldStop.getCount() == 0) { break; } continue; } } }</code><technical_language>rogue log statement</technical_language>

Target:
private void guardedRun() throws Exception { while (true) { try { for (final byte[] messageBody : stream.messageIterable()) { if (shouldStop.getCount() == 0 || messageBody == null) { break; } consumeOneWithRetry(messageBody); parkPaused(); if (shouldStop.getCount() == 0) { break; } } break; } catch (ConsumerTimeoutException cte) { log.info("ConsumerTimeoutException while waiting for data from Kafka. Will retry."); if (shouldStop.getCount() == 0) { break; } parkPaused(); if (shouldStop.getCount() == 0) { break; } continue; } } }
Source:
<code>private void setRadix(int radix) { if (radix > Character.MAX_RADIX) { throw new IllegalArgumentException("radix == " + radix); } <START> if (this.radix != radix) { <END> integerPattern = null; this.radix = radix; } }</code><technical_language>Is this end of added? mark it</technical_language>

Target:
private void setRadix(int radix) { if (radix > Character.MAX_RADIX) { throw new IllegalArgumentException("radix == " + radix); } END Android-added: Complain loudly if a bogus radix is being set. if (this.radix != radix) { integerPattern = null; this.radix = radix; } }
Source:
<code>public Layout build() { this.pageFirstButton = new ToolStripButton("<< Latest Jobs"); this.pageFirstButton.disable(); this.pageFirstButton.addStyleName("navPreviousPaginationButton"); this.pageFirstButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.firstPage(); } }); <START> this.pagePreviousButton = new ToolStripButton("< Later Jobs"); <END> this.pagePreviousButton.disable(); this.pagePreviousButton.addStyleName("navPreviousPaginationButton"); this.pagePreviousButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.previousPage(); } }); this.pageNextButton = new ToolStripButton("Older Jobs >"); this.pageNextButton.disable(); this.pageNextButton.addStyleName("navNextPaginationButton"); this.pageNextButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.nextPage(); } }); this.pageLastButton = new ToolStripButton("Oldest Jobs >>"); this.pageLastButton.disable(); this.pageLastButton.addStyleName("navNextPaginationButton"); this.pageLastButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.lastPage(); } }); return buildLayout(); }</code><technical_language>I "later jobs" is a clear label. again, I of optimal label. "Later jobs" jobs handled later. "More Jobs", long, "Newer Jobs"</technical_language>

Target:
public Layout build() { this.pageFirstButton = new ToolStripButton("<< Newest Jobs"); this.pageFirstButton.disable(); this.pageFirstButton.addStyleName("navPreviousPaginationButton"); this.pageFirstButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.firstPage(); } }); this.pagePreviousButton = new ToolStripButton("< Newer Jobs"); this.pagePreviousButton.disable(); this.pagePreviousButton.addStyleName("navPreviousPaginationButton"); this.pagePreviousButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.previousPage(); } }); this.pageNextButton = new ToolStripButton("Older Jobs >"); this.pageNextButton.disable(); this.pageNextButton.addStyleName("navNextPaginationButton"); this.pageNextButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.nextPage(); } }); this.pageLastButton = new ToolStripButton("Oldest Jobs >>"); this.pageLastButton.disable(); this.pageLastButton.addStyleName("navNextPaginationButton"); this.pageLastButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.lastPage(); } }); return buildLayout(); }
Source:
<code><START> public static String getRuntimeCount(long l) { <END> if (l / 1000 / 1000 > 0) { return l /1000 / 1000 + "ms"; } else if (l / 1000 > 0) { return l / 1000 + "us"; }else { return l + "ns"; } }</code><technical_language>this change ended unnecessary</technical_language>

Target:
public String getRuntimeCount(long l) { if (l / 1000 / 1000 > 0) { return l /1000 / 1000 + "ms"; } else if (l / 1000 > 0) { return l / 1000 + "us"; }else { return l + "ns"; } }
Source:
<code>public Writer setCharacterStream(long pos) throws SQLException { try { if (isDebugEnabled()) { debugCodeCall("setCharacterStream(" + pos + ");"); } checkClosed(); if (pos != 1) { throw DbException.getInvalidValueException("pos", pos); } if (value.getPrecision() != 0) { throw DbException.getInvalidValueException("length", value.getPrecision()); } final PipedInputStream in = new PipedInputStream(); final Task task = new Task() { @Override public void call() { <START> value = conn.createClob(IOUtils.getReader(in), -1); <END> } }; PipedOutputStream out = new PipedOutputStream(in) { @Override public void close() throws IOException { super.close(); try { task.get(); } catch (Exception e) { throw DbException.convertToIOException(e); } } }; task.execute(); return IOUtils.getBufferedWriter(out); } catch (Exception e) { throw logAndConvert(e); } }</code><technical_language>synthetic method here</technical_language>

Target:
public Writer setCharacterStream(long pos) throws SQLException { try { if (isDebugEnabled()) { debugCodeCall("setCharacterStream(" + pos + ");"); } checkClosed(); if (pos != 1) { throw DbException.getInvalidValueException("pos", pos); } if (value.getPrecision() != 0) { throw DbException.getInvalidValueException("length", value.getPrecision()); } final JdbcConnection c = conn; final PipedInputStream in = new PipedInputStream(); final Task task = new Task() { @Override public void call() { value = c.createClob(IOUtils.getReader(in), -1); } }; PipedOutputStream out = new PipedOutputStream(in) { @Override public void close() throws IOException { super.close(); try { task.get(); } catch (Exception e) { throw DbException.convertToIOException(e); } } }; task.execute(); return IOUtils.getBufferedWriter(out); } catch (Exception e) { throw logAndConvert(e); } }
Source:
<code><START> public void removeType(@Nonnull JDefinedClassOrInterface type, boolean permanent) { <END> if (!this.declaredTypes.contains(type)) { throw new RuntimeException("type does not exist"); } if (permanent) { removeItemWithName(type); } declaredTypes.remove(type); }</code><technical_language>I understand adding that. In general, adding API AST Framework is carefully discussed before. do in experimentation, is guarantee merged end</technical_language>

Target:
public void removeType(@Nonnull JDefinedClassOrInterface type, boolean permanent) { if (!this.declaredTypes.contains(type)) { throw new AssertionError("type does not exist"); } if (permanent) { removeItemWithName(type); } declaredTypes.remove(type); }
Source:
<code>private History mergeOldAndNewHistory(File cacheFile, History histNew, Repository repo) throws HistoryException { History histOld; History history = null; try { histOld = readCache(cacheFile); List<HistoryEntry> listOld = histOld.getHistoryEntries(); if (!listOld.isEmpty()) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); List<HistoryEntry> listNew = histNew.getHistoryEntries(); ListIterator li = listNew.listIterator(listNew.size()); while (li.hasPrevious()) { listOld.add(0, (HistoryEntry) li.previous()); } history = new History(listOld); if (env.isTagsEnabled() && repo.hasFileBasedTags()) { for (HistoryEntry ent : history.getHistoryEntries()) { ent.setTags(null); } repo.assignTagsInHistory(history); } } } catch (IOException ex) { <START> LOGGER.log(Level.SEVERE, "Cannot open history cache file " + cacheFile.getPath()); <END> } return history; }</code><technical_language>logger templates instead of string concatenation</technical_language>

Target:
private History mergeOldAndNewHistory(File cacheFile, History histNew, Repository repo) throws HistoryException { History histOld; History history = null; try { histOld = readCache(cacheFile); List<HistoryEntry> listOld = histOld.getHistoryEntries(); if (!listOld.isEmpty()) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); List<HistoryEntry> listNew = histNew.getHistoryEntries(); ListIterator li = listNew.listIterator(listNew.size()); while (li.hasPrevious()) { listOld.add(0, (HistoryEntry) li.previous()); } history = new History(listOld); if (env.isTagsEnabled() && repo.hasFileBasedTags()) { for (HistoryEntry ent : history.getHistoryEntries()) { ent.setTags(null); } repo.assignTagsInHistory(history); } } } catch (IOException ex) { LOGGER.log(Level.SEVERE, String.format("Cannot open history cache file %s", cacheFile.getPath()), ex); } return history; }
Source:
<code>public void noUpstreamCancelOnCasualChainClose() { AtomicBoolean parentUpstreamCancelled = new AtomicBoolean(false); Flowable.range(1, 10) <START> .doOnCancel(new Action() { <END> @Override public void run() throws Throwable { parentUpstreamCancelled.set(true); } }) .publish(new Function<Flowable<Integer>, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Flowable<Integer> v) throws Exception { return v; } }) .test() .awaitDone(1, TimeUnit.SECONDS); assertFalse("Unnecessary upstream .cancel() call in FlowablePublishMulticast", parentUpstreamCancelled.get()); }</code><technical_language>lambdas in tests now</technical_language>

Target:
public void noUpstreamCancelOnCasualChainClose() { AtomicBoolean parentUpstreamCancelled = new AtomicBoolean(false); Flowable.range(1, 10) .doOnCancel(() -> parentUpstreamCancelled.set(true)) .publish(Functions.identity()) .test() .awaitDone(1, TimeUnit.SECONDS); assertFalse("Unnecessary upstream .cancel() call in FlowablePublishMulticast", parentUpstreamCancelled.get()); }
Source:
<code>public void testOpportunistic() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); <START> String id = "container_01_01"; <END> ContainerId mockContainerId = mock(ContainerId.class); when(mockContainerId.toString()).thenReturn(id); cGroupsMemoryResourceHandler.bootstrap(conf); ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class); when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC); Container container = mock(Container.class); when(container.getContainerId()).thenReturn(mockContainerId); when(container.getContainerTokenIdentifier()).thenReturn(tokenId); when(container.getResource()).thenReturn(Resource.newInstance(1024, 2)); cGroupsMemoryResourceHandler.preStart(container); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES, "0M"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, "100"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES, "1024M"); }</code><technical_language>move this right cgroupMemResourceHandler.prestart() similarly</technical_language>

Target:
public void testOpportunistic() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); cGroupsMemoryResourceHandler.bootstrap(conf); ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class); when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC); Container container = mock(Container.class); String id = "container_01_01"; ContainerId mockContainerId = mock(ContainerId.class); when(mockContainerId.toString()).thenReturn(id); when(container.getContainerId()).thenReturn(mockContainerId); when(container.getContainerTokenIdentifier()).thenReturn(tokenId); when(container.getResource()).thenReturn(Resource.newInstance(1024, 2)); cGroupsMemoryResourceHandler.preStart(container); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES, "0M"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, "100"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES, "1024M"); }
Source:
<code>public SQLSessionContext createSQLSessionContext() throws StandardException { <START> return new SQLSessionContextImpl(getDataDictionary().getDatabaseDescriptor(dbName, getTransactionCompile()), <END> getInitialDefaultSchemaDescriptor(), getSessionUserId(), defaultRoles, groupuserlist); }</code><technical_language>cache DatabaseDescriptor in initialize() method similarly do SchemaDescriptor, throw StandardExceptions place</technical_language>

Target:
public SQLSessionContext createSQLSessionContext() { return new SQLSessionContextImpl(databaseDescriptor, getInitialDefaultSchemaDescriptor(), getSessionUserId(), defaultRoles, groupuserlist); }
Source:
<code>public String moveEntity(@CommandParam("The world in which the entity is formed") String worldName, @CommandParam("Id of the entity to be moved") int id) { for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getKey().getTitle().equalsIgnoreCase(worldName)) { if (entityManager.moveToPool(id, entry.getValue())) { return "Entity " + id + " moved to " + entry.getKey().getTitle() + "world"; } else { <START> return id + "could not be moved"; <END> } } } return worldName + " does not exist"; }</code><technical_language>consistent, return "Entity " + id + "could moved"; Also, remove trailing "world" add else</technical_language>

Target:
public String moveEntity(@CommandParam("The world in which the entity is formed") String worldName, @CommandParam("Id of the entity to be moved") int id) { for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getKey().getTitle().equalsIgnoreCase(worldName)) { if (entityManager.moveToPool(id, entry.getValue())) { return "Entity " + id + " moved to " + entry.getKey().getTitle() + "world"; } else { return "Entity" + id + "could not be moved"; } } } return worldName + " does not exist"; }
Source:
<code>public boolean isFinished() { try { return gzipStream.available() == 0; } catch (IOException e) { <START> throw new CitrusRuntimeException("Failed to check gzip intput stream availability", e); <END> } }</code><technical_language>Typo *intput*</technical_language>

Target:
public boolean isFinished() { try { return gzipStream.available() == 0; } catch (IOException e) { throw new CitrusRuntimeException("Failed to check gzip input stream availability", e); } }
Source:
<code>public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); <START> version = PROD_LINK_PREVIEW_VERSION; <END> }</code><technical_language>remove version variable equal constant</technical_language>

Target:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); }
Source:
<code>private static boolean isQualityGateNameAvailable(Context context, String qualityGateName) throws SQLException { return context.prepareSelect( <START> "SELECT COUNT(*) FROM quality_gates WHERE name = '" + qualityGateName + "'") <END> .get( row -> row.getInt(1) == 0); }</code><technical_language>Minor, COUNT(id), in general faster</technical_language>

Target:
private static boolean isQualityGateNameAvailable(Context context, String qualityGateName) throws SQLException { return context.prepareSelect( "SELECT COUNT(id) FROM quality_gates WHERE name = '" + qualityGateName + "'") .get( row -> row.getInt(1) == 0); }
Source:
<code>Stream<ExecutionPath> addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); PSet<Symbol> newTrackSymbols = newTrackedSymbols(edge); <START> SameConstraints newSameConstaints = new SameConstraints(sameConstraints, newTrackSymbols, domains); <END> Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, filterRedundantObjectDomain(learnedConstraints)); flowBuilder.addAll(lcFlow); boolean endOfPath = visitedAllParents(edge) || shouldTerminate(learnedConstraints); if (endOfPath) { flowBuilder.addAll(flowForNullableMethodParameters(edge.parent)); } List<JavaFileScannerContext.Location> currentFlow = flowBuilder.build(); Set<List<JavaFileScannerContext.Location>> yieldsFlows = flowFromYields(edge); return yieldsFlows.stream() .map(yieldFlow -> ImmutableList.<JavaFileScannerContext.Location>builder().addAll(currentFlow).addAll(yieldFlow).build()) .map(f -> new ExecutionPath(edge, visited.add(edge), newTrackSymbols, newSameConstaints, f, endOfPath)); }</code><technical_language>Typo in variable name. test if is change in trackedSymbols create instance if necessary. case symbols changed</technical_language>

Target:
Stream<ExecutionPath> addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); PSet<Symbol> newTrackSymbols = newTrackedSymbols(edge); SameConstraints newSameConstraints = newTrackSymbols == trackedSymbols ? sameConstraints : new SameConstraints(sameConstraints, newTrackSymbols); Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, filterRedundantObjectDomain(learnedConstraints)); flowBuilder.addAll(lcFlow); boolean endOfPath = visitedAllParents(edge) || shouldTerminate(learnedConstraints); if (endOfPath) { flowBuilder.addAll(flowForNullableMethodParameters(edge.parent)); } List<JavaFileScannerContext.Location> currentFlow = flowBuilder.build(); Set<List<JavaFileScannerContext.Location>> yieldsFlows = flowFromYields(edge); return yieldsFlows.stream() .map(yieldFlow -> ImmutableList.<JavaFileScannerContext.Location>builder().addAll(currentFlow).addAll(yieldFlow).build()) .map(f -> new ExecutionPath(edge, visited.add(edge), newTrackSymbols, newSameConstraints, f, endOfPath)); }
Source:
<code>public String toString() { <START> return "TtyDev [portName=" + this.portName + ", interfaceNumber=" + this.interfaceNumber + "]"; <END> }</code><technical_language>NPE if interface number is null</technical_language>

Target:
public String toString() { String number = this.interfaceNumber != null ? this.interfaceNumber.toString() : "null"; return "TtyDev [portName=" + this.portName + ", interfaceNumber=" + number + "]"; }
Source:
<code>private static String getParamDisplayString( List<org.parosproxy.paros.core.scanner.NameValuePair> list, int type) { StringBuilder sb = new StringBuilder(); list.stream() .sorted() .filter(entry -> entry.getType() == type) .forEach( entry -> { String name = entry.getName(); if (name != null) { if (sb.length() > 0) { sb.append(','); } if (name.length() > 40) { name = name.substring(0, 40); } sb.append(name); } <END> }); <START> String result = ""; if (sb.length() > 0) { result = sb.insert(0, '(').append(')').toString(); } return result; }</code><technical_language>If done a ternary intermediate declare/storage is necessary. a huge difference, simpler shorter... suggestion return sb.length() > 0 ? sb.insert(0, '(').append(')').toString() : "";</technical_language>

Target:
private static String getParamDisplayString( List<org.parosproxy.paros.core.scanner.NameValuePair> list, int type) { StringBuilder sb = new StringBuilder(); list.stream() .sorted() .filter(entry -> entry.getType() == type) .forEach( entry -> { String name = entry.getName(); if (name != null) { if (sb.length() > 0) { sb.append(','); } if (name.length() > 40) { name = name.substring(0, 40) + "..."; } sb.append(name); } }); return sb.length() > 0 ? sb.insert(0, '(').append(')').toString() : ""; }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = null; <START> boolean countered = false; <END> UUID targetId = this.getTargetPointer().getFirst(game, source); if (targetId != null) { controller = game.getPlayer(game.getControllerId(targetId)); } if (targetId != null && game.getStack().counter(targetId, source.getSourceId(), game)) { countered = true; } if (controller != null) { Effect effect = new DrawCardTargetEffect(new StaticValue(1), false); effect.setTargetPointer(new FixedTarget(controller.getId())); effect.setText("That player draws a card"); DelayedTriggeredAbility ability = new AtTheBeginOfNextUpkeepDelayedTriggeredAbility(effect); game.addDelayedTriggeredAbility(ability, source); } return countered; }</code><technical_language>purpose of this</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Player chosenPlayer = null; UUID targetId = this.getTargetPointer().getFirst(game, source); if (targetId == null) { TargetPlayer target = new TargetPlayer(1, 1, true); controller.chooseTarget(outcome, target, source, game); chosenPlayer = game.getPlayer(target.getFirstTarget()); } if (targetId != null) { chosenPlayer = game.getPlayer(game.getControllerId(targetId)); } if (chosenPlayer != null) { Effect effect = new DrawCardTargetEffect(1); effect.setTargetPointer(new FixedTarget(chosenPlayer.getId())); effect.setText("That player draws a card"); DelayedTriggeredAbility ability = new AtTheBeginOfNextUpkeepDelayedTriggeredAbility(effect); game.addDelayedTriggeredAbility(ability, source); } return true; }