auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>boolean isBlank(final DataType dataType) { final String name = dataType.getName(); <START> return name == null || name.isEmpty(); <END> }</code><technical_language>new [StringUtils](<LINK_0></technical_language>

Target:
boolean isBlank(final DataType dataType) { return isEmpty(dataType.getName()); }
Source:
<code>private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnWildProject(permissionName)) { <START> section.removePermission(permissionName); <END> } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }</code><technical_language>this rule applies special AccessSection.ALL. OK put Owner refs/heads/* for example, this inherits tree giving administrative privileges server. concerned Push refs/meta/config? limit this intersection of Push Administrator</technical_language>

Target:
private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnWildProject(section.getName(), permissionName)) { section.removePermission(permissionName); } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }
Source:
<code>public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); <START> if (installedPatches.size() == 0) { <END> out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }</code><technical_language>suggestion if (installedPatches.isEmpty()) {</technical_language>

Target:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); if (installedPatches.isEmpty()) { out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }
Source:
<code>private void assertDateEquals(String actual, Instant instant, ZoneId timeZone) { String dateStrWithAbbr = getDateStringWithAbbr(instant, timeZone); String dateStrWithOffset = getDateStringWithOffset(instant, timeZone); boolean isExpected = actual.equals(dateStrWithAbbr) || actual.equals(dateStrWithOffset); <START> assertTrue(isExpected); <END> }</code><technical_language>I variable isExpected is necessary</technical_language>

Target:
private void assertDateEquals(String actual, Instant instant, ZoneId timeZone) { String dateStrWithAbbr = getDateStringWithAbbr(instant, timeZone); String dateStrWithOffset = getDateStringWithOffset(instant, timeZone); assertTrue(actual.equals(dateStrWithAbbr) || actual.equals(dateStrWithOffset)); }
Source:
<code>protected void onNext() { AuthType authType = getSelectedAuthType(); if (authType == AuthType.XOAUTH2) { <START> K9.oAuth2TokenStore.authorizeAPI(mAccount.getEmail(), this, <END> new OAuth2TokenProvider.OAuth2TokenProviderAuthCallback() { @Override public void success() { updateAccountSettings(""); AccountSetupCheckSettings.actionCheckSettings( AccountSetupIncoming.this, mAccount, CheckDirection.INCOMING); } @Override public void failure(Exception e) { AccountSetupIncoming.this.failure(e); } }); return; } updateAccountSettings(mPasswordView.getText().toString()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, CheckDirection.INCOMING); }</code><technical_language>this block deserves a method of</technical_language>

Target:
protected void onNext() { AuthType authType = getSelectedAuthType(); if (authType == AuthType.XOAUTH2) { Globals.getOAuth2TokenProvider().authorizeAPI(mAccount.getEmail(), this, new OAuth2TokenProvider.OAuth2TokenProviderAuthCallback() { @Override public void success() { updateAccountSettings(""); AccountSetupCheckSettings.actionCheckSettings( AccountSetupIncoming.this, mAccount, CheckDirection.INCOMING); } @Override public void failure(AuthorizationException e) { AccountSetupIncoming.this.failure(e); } }); return; } updateAccountSettings(mPasswordView.getText().toString()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, CheckDirection.INCOMING); }
Source:
<code><START> public static String toStringWithId(Identifiable<String> obj) { <END> return String.format("[%s][%s]", obj.getGuid(), obj.getName()); }</code><technical_language>check for null referencing</technical_language>

Target:
public static String toStringWithId(Identifiable<String> obj) { Conditions.checkNotNull(obj, "object"); return String.format("[%s][%s]", obj.getGuid(), obj.getName()); }
Source:
<code>private String validate(Details details) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; final boolean shouldCheckLastRcurly = details.shouldCheckLastRcurly; String violation = ""; if (shouldHaveLineBreakBefore(option, details)) { violation = MSG_KEY_LINE_BREAK_BEFORE; } else if (shouldCheckLastRcurly && option != RightCurlyOption.ALONE) { if (rcurly.getLineNo() == nextToken.getLineNo()) { violation = MSG_KEY_LINE_ALONE; } } else if (shouldBeOnSameLine(option, details)) { violation = MSG_KEY_LINE_SAME; } else if (shouldBeAloneOnLine(option, details)) { violation = MSG_KEY_LINE_ALONE; } <START> return violation; <END> }</code><technical_language>Revert changes in SingleSpaceSeparatorCheckTest inputs</technical_language>

Target:
private String validate(Details details) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; final boolean shouldCheckLastRcurly = details.shouldCheckLastRcurly; String violation = ""; if (shouldHaveLineBreakBefore(option, details)) { violation = MSG_KEY_LINE_BREAK_BEFORE; } else if (shouldCheckLastRcurly && option != RightCurlyOption.ALONE) { if (rcurly.getLineNo() == nextToken.getLineNo()) { violation = MSG_KEY_LINE_ALONE; } } else if (shouldBeOnSameLine(option, details)) { violation = MSG_KEY_LINE_SAME; } else if (shouldBeAloneOnLine(option, details)) { violation = MSG_KEY_LINE_ALONE; } else if (shouldStartLine) { final String targetSourceLine = getLines()[rcurly.getLineNo() - 1]; if (!isOnStartOfLine(details, targetSourceLine)) { violation = MSG_KEY_LINE_NEW; } } return violation; }
Source:
<code>private Logger configureLoggers(String name) { final Logger root = loggerContext .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); loggerContext.reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); loggerContext.addListener(propagator); root.setLevel(level); <START> if (advancedLoggers != null && advancedLoggers.size() > 0) { <END> for (Entry<String, DefaultLoggerFactory> entry : advancedLoggers .entrySet()) { Logger logger = loggerContext.getLogger(entry.getKey()); logger.setLevel(entry.getValue().getLevel()); for (AppenderFactory appender : entry.getValue().getAppenders()) { Appender<ILoggingEvent> newAppender = appender.build( loggerContext, name, null); logger.addAppender(newAppender); } } } else { for (Map.Entry<String, Level> entry : loggers.entrySet()) { loggerContext.getLogger(entry.getKey()).setLevel( entry.getValue()); } } return root; }</code><technical_language>this if I define a single advanced logger other loggers affect? configuration yaml level: INFO loggers: "com.example.dw.Thing": DEBUG advancedLoggers: "com.example.app": level: DEBUG appenders: - type: console threshold: Correct if wrong, logic com.example.dw.Thing registered DEBUG</technical_language>

Target:
private Logger configureLoggers(String name) { final Logger root = loggerContext .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); loggerContext.reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); loggerContext.addListener(propagator); root.setLevel(level); for (Map.Entry<String, JsonNode> entry : loggers.entrySet()) { final Logger logger = loggerContext.getLogger(entry.getKey()); final JsonNode jsonNode = entry.getValue(); if (jsonNode.isTextual()) { Level level = Level.valueOf(jsonNode.asText()); logger.setLevel(level); } else if (jsonNode.isObject()) { DefaultLoggerFactory configuration; try { configuration = Jackson.newObjectMapper().treeToValue(jsonNode, DefaultLoggerFactory.class); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Wrong format of logger '" + entry.getKey() + "'", e); } logger.setLevel(configuration.getLevel()); for (AppenderFactory appender : configuration.getAppenders()) { logger.addAppender(appender.build(loggerContext, name, null)); } } else { throw new IllegalArgumentException("Unsupported format of logger '" + entry.getKey() + "'"); } } return root; }
Source:
<code>protected boolean canDoAction() { <START> setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); <END> if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }</code><technical_language>volumeId set in constructor parameters</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }
Source:
<code>private void addStateSystem(@NonNull ITmfStateSystem ss, long parentId) { fetchTreeIsComplete &= ss.waitUntilBuilt(0); long id = ENTRY_ID.getAndIncrement(); StateSystemEntryModel stateSystemEntryModel = new StateSystemEntryModel(id, parentId, ss); entryList.add(stateSystemEntryModel); for (Integer attrib : ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false)) { addSubAttributes(stateSystemEntryModel, ss, attrib); <START> END> } }</code><technical_language>line</technical_language>

Target:
private void addStateSystem(@NonNull ITmfStateSystem ss, long parentId) { fetchTreeIsComplete &= ss.waitUntilBuilt(0); long id = ENTRY_ID.getAndIncrement(); StateSystemEntryModel stateSystemEntryModel = new StateSystemEntryModel(id, parentId, ss); ssToId.put(ss, id); for (Integer attrib : ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false)) { addSubAttributes(stateSystemEntryModel, ss, attrib); } entryList.add(stateSystemEntryModel); }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if (className == null || classTree.symbol().isAbstract() || superType == null || !(superType.is("java.io.InputStream") || superType.is("java.io.FilterInputStream"))) { return; } Optional<MethodTree> readByteIntInt = findMethod(classTree, READ_BYTES_INT_INT); <START> Optional<MethodTree> readInt = findMethod(classTree, READ_INT); <END> if (!readByteIntInt.isPresent()) { String message = readInt.filter(readIntTree -> readIntTree.block().body().isEmpty()) .map(readIntTree -> "Provide an empty override of \"read(byte[],int,int)\" for this class as well.") .orElse("Provide an override of \"read(byte[],int,int)\" for this class."); reportIssue(className, message); } }</code><technical_language>tiny optim, this method resulting variable called if</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if (className == null || classTree.symbol().isAbstract() || superType == null || !(superType.is("java.io.InputStream") || superType.is("java.io.FilterInputStream"))) { return; } Optional<MethodTree> readByteIntInt = findMethod(classTree, READ_BYTES_INT_INT); if (!readByteIntInt.isPresent()) { String message = findMethod(classTree, READ_INT) .filter(readIntTree -> readIntTree.block().body().isEmpty()) .map(readIntTree -> "Provide an empty override of \"read(byte[],int,int)\" for this class as well.") .orElse("Provide an override of \"read(byte[],int,int)\" for this class."); reportIssue(className, message); } }
Source:
<code>public void testConvertProfileGenericDataRequestDto() { ProfileGenericDataRequest reqData1 = this.makeRequest(); Object obj = this.mapper.map(reqData1, ProfileGenericDataRequestDto.class); <START> assertTrue(obj != null && obj instanceof ProfileGenericDataRequestDto); <END> }</code><technical_language>This test test if field values mapped correctly. is important in orika mapping tests, orika fail a field mapped</technical_language>

Target:
public void testConvertProfileGenericDataRequestDto() { ProfileGenericDataRequest profileGenericDateRequest = this.makeRequest(); Object result = this.mapper.map(profileGenericDateRequest, ProfileGenericDataRequestDto.class); assertNotNull("mapping ProfileGenericDataRequest should not return null", result); assertThat("mapping ProfileGenericDataRequest should return correct type", result, instanceOf(ProfileGenericDataRequestDto.class)); final ProfileGenericDataRequestDto profileGenericDataRequestDto = (ProfileGenericDataRequestDto) result; assertEquals("mapped values should be identical", profileGenericDataRequestDto.getBeginDate(), DATE); assertEquals("mapped values should be identical", profileGenericDataRequestDto.getEndDate(), DATE); assertEquals("mapped values should be identical", profileGenericDataRequestDto.getDeviceIdentification(), DEVICE_NAME); final ObisCodeValuesDto obisCodeValuesDto = profileGenericDataRequestDto.getObisCode(); assertEquals("mapped values should be identical", obisCodeValuesDto.getA(), profileGenericDateRequest.getObisCode().getA()); }
Source:
<code>public void define(Context context) { NewController controller = context.createController(CONTROLLER_QUALITY_GATES) .setSince("4.3") .setDescription("Manage quality gates, including conditions and project association."); for (QualityGatesWsAction action : actions) { action.define(controller); } controller.createAction("unset_default") .setDescription("Unset the default quality gate is no more authorized. A quality gate is now required.<br>" + <START> "Previously, this web service unset a quality gate as the default quality gate.<br>" + <END> "Required the 'Administer Quality Gates' permission.") .setSince("4.3") .setDeprecatedSince("7.0") .setPost(true) .setHandler(RemovedWebServiceHandler.INSTANCE) .setResponseExample(RemovedWebServiceHandler.INSTANCE.getResponseExample()) .setChangelog( new Change("7.0", "Unset a quality gate is no more authorized") ); controller.done(); }</code><technical_language>explain this web service</technical_language>

Target:
public void define(Context context) { NewController controller = context.createController(CONTROLLER_QUALITY_GATES) .setSince("4.3") .setDescription("Manage quality gates, including conditions and project association."); for (QualityGatesWsAction action : actions) { action.define(controller); } controller.createAction("unset_default") .setDescription("This webservice is no more available : a default quality gate is mandatory.") .setSince("4.3") .setDeprecatedSince("7.0") .setPost(true) .setHandler(RemovedWebServiceHandler.INSTANCE) .setResponseExample(RemovedWebServiceHandler.INSTANCE.getResponseExample()) .setChangelog( new Change("7.0", "Unset a quality gate is no more authorized") ); controller.done(); }
Source:
<code>ReconnectingChannel( long maxRefreshMs, Factory connectionFactory, ScheduledExecutorService executorService) throws IOException { <START> Preconditions.checkArgument(maxRefreshMs >= 0L, "maxRefreshTime cannot be less than 0."); <END> this.maxRefreshMs = maxRefreshMs; this.factory = connectionFactory; this.delegate = new ChannelWrapper(factory); this.authority = delegate.channel.authority(); this.refreshExecutor = executorService; if (maxRefreshMs > 0) { double randomizedPercentage = 1D - (.05D * Math.random()); long delay = (long) (this.maxRefreshMs * randomizedPercentage); Runnable refreshRunanable = new Runnable() { @Override public void run() { ChannelWrapper oldDelegate = delegate; try { setDelegate(new ChannelWrapper(factory)); } catch (IOException e) { throw new IllegalStateException("Channel cannot create a new delegate", e); } if(oldDelegate != null) { try { oldDelegate.close(); } catch (IOException e) { log.log(Level.INFO, "Could not close a recycled delegate", e); } } } }; refreshExecutor.scheduleAtFixedRate(refreshRunanable, delay, delay, TimeUnit.MILLISECONDS); } }</code><technical_language>maxRefreshTime -> maxRefreshMs</technical_language>

Target:
ReconnectingChannel( long maxRefreshMs, Factory connectionFactory, ScheduledExecutorService executorService) throws IOException { Preconditions.checkArgument(maxRefreshMs >= 0L, "maxRefreshMs cannot be less than 0."); this.maxRefreshMs = maxRefreshMs; this.factory = connectionFactory; this.delegate = new ChannelWrapper(factory); this.authority = delegate.channel.authority(); this.refreshExecutor = executorService; if (maxRefreshMs > 0) { double randomizedPercentage = 1D - (.05D * Math.random()); long delay = (long) (this.maxRefreshMs * randomizedPercentage); Runnable refreshRunanable = new Runnable() { @Override public void run() { ChannelWrapper oldDelegate = delegate; try { setDelegate(new ChannelWrapper(factory)); } catch (IOException e) { throw new IllegalStateException("Channel cannot create a new delegate", e); } if(oldDelegate != null) { try { oldDelegate.close(); } catch (IOException e) { log.log(Level.INFO, "Could not close a recycled delegate", e); } } } }; refreshExecutor.scheduleAtFixedRate(refreshRunanable, delay, delay, TimeUnit.MILLISECONDS); } }
Source:
<code>public boolean isReadable(int size) { <START> return buffer.isReadable(); END> }</code><technical_language>this buffer.isReadable(size)</technical_language>

Target:
public boolean isReadable(int size) { return buffer.isReadable(size); }
Source:
<code>@Test public void iteratorThrowsIOException() throws IOException { File parent = folder.getRoot(); File file = new File(parent, "object-queue"); QueueFile queueFile = new QueueFile.Builder(file).build(); ObjectQueue<Object> queue = ObjectQueue.create(queueFile, new ObjectQueue.Converter<Object>() { @Override public String from(byte[] bytes) throws IOException { throw new IOException(); } @Override public void toStream(Object o, OutputStream bytes) { } }); queue.add(new Object()); Iterator<Object> iterator = queue.iterator(); try { iterator.next(); fail(); } catch (Throwable ioe) { <START> assertThat(ioe).isInstanceOf(IOException.class); <END> } }</code><technical_language>catch IOE? surprised error-prone flag this pattern</technical_language>

Target:
@Test public void iteratorThrowsIOException() throws IOException { File parent = folder.getRoot(); File file = new File(parent, "object-queue"); QueueFile queueFile = new QueueFile.Builder(file).build(); ObjectQueue<Object> queue = ObjectQueue.create(queueFile, new ObjectQueue.Converter<Object>() { @Override public String from(byte[] bytes) throws IOException { throw new IOException(); } @Override public void toStream(Object o, OutputStream bytes) { } }); queue.add(new Object()); Iterator<Object> iterator = queue.iterator(); try { iterator.next(); fail(); } catch (Exception ioe) { assertThat(ioe).isInstanceOf(IOException.class); } }
Source:
<code>public default TraversalSource with(final String key, final Object value) { final Optional<OptionsStrategy> opt = getStrategies().getStrategy(OptionsStrategy.class); final OptionsStrategy strategy = opt.orElse(OptionsStrategy.EMPTY); final OptionsStrategy.Builder builder = OptionsStrategy.build(); strategy.getOptions().forEach(builder::with); builder.with(key, value); <START> return withStrategies(builder.create()); <END> }</code><technical_language>a bit more elegant: java public default TraversalSource with(final String key, final Object value) { final OptionsStrategy.Builder builder = OptionsStrategy.build(); getStrategies().getStrategy(OptionsStrategy.class) .ifPresent(optionsStrategy -> optionsStrategy.getOptions().forEach(builder::with)); builder.with(key, value); return withStrategies(builder.create()); }</technical_language>

Target:
public default TraversalSource with(final String key, final Object value) { final OptionsStrategy.Builder builder = OptionsStrategy.build(); getStrategies().getStrategy(OptionsStrategy.class) .ifPresent(optionsStrategy -> optionsStrategy.getOptions().forEach(builder::with)); builder.with(key, value); return withStrategies(builder.create()); }
Source:
<code><START> private <T> AbstractCatalogItem<T> getAbstractCatalogItem(CatalogItem<T> item) { <END> while (item instanceof CatalogItemDo) item = ((CatalogItemDo<T>)item).itemDto; if (item==null) return null; if (item instanceof AbstractCatalogItem) return (AbstractCatalogItem<T>) item; throw new IllegalStateException("Cannot unwrap catalog item '"+item+"' (type "+item.getClass()+") to restore DTO"); }</code><technical_language>confused terminology here. Is "AbstractCatalogItem" for DTOs (which based extends it). renamed AbstractCatalogItemDto then</technical_language>

Target:
private <T> CatalogItemDtoAbstract<T> getAbstractCatalogItem(CatalogItem<T> item) { while (item instanceof CatalogItemDo) item = ((CatalogItemDo<T>)item).itemDto; if (item==null) return null; if (item instanceof CatalogItemDtoAbstract) return (CatalogItemDtoAbstract<T>) item; throw new IllegalStateException("Cannot unwrap catalog item '"+item+"' (type "+item.getClass()+") to restore DTO"); }
Source:
<code>public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || (off + len) > cbuf.length) { throw new IndexOutOfBoundsException(); } if (!inputBuffer.hasRemaining()) { return -1; } CharBuffer charbuffer = CharBuffer.wrap(cbuf, off, len); CoderResult result = utf8Decoder.decode(inputBuffer, charbuffer, true); if (result.isError()) { result.throwException(); } if (result.isUnderflow()) { if (!inputBuffer.hasRemaining()) { <START> utf8Decoder.flush(charbuffer); <END> } return charbuffer.position() - off; } else { return charbuffer.position() - off; } }</code><technical_language>sure: happen if decode result is underflow, calling flush() fails overflow? If reader final (not flushed) characters</technical_language>

Target:
public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || (off + len) > cbuf.length) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } int countRead = 0; if (hasLeftoverChar) { cbuf[off] = (char) leftoverChar; hasLeftoverChar = false; off++; len--; countRead++; } if (len == 0) { return countRead; } if (!inputBuffer.hasRemaining()) { return -1; } decoder.reset(); if (len == 1) { int charRead = read(); if (charRead == -1) { return countRead == 0 ? -1 : countRead; } cbuf[off] = (char) charRead; return countRead + 1; } CharBuffer charbuffer = CharBuffer.wrap(cbuf, off, len); CoderResult result = decoder.decode(inputBuffer, charbuffer, true); if (result.isError()) { result.throwException(); } if (result.isUnderflow()) { if (!inputBuffer.hasRemaining()) { decoder.flush(charbuffer); } } return countRead + charbuffer.position() - off; }
Source:
<code><START> private void testBlockingChannelInfo(String host, Port port, int maxConnectionsPerPortPlainText, <END> int maxConnectionsPerPortSSL) throws Exception { Properties props = new Properties(); props.put("connectionpool.max.connections.per.port.plain.text", "" + maxConnectionsPerPortPlainText); props.put("connectionpool.max.connections.per.port.ssl", "" + maxConnectionsPerPortSSL); int maxConnectionsPerChannel = (port.getPortType() == PortType.PLAINTEXT) ? maxConnectionsPerPortPlainText : maxConnectionsPerPortSSL; createAndReleaseSingleChannelTest(props, host, port); overSubscriptionTest(props, host, port, maxConnectionsPerChannel, true); overSubscriptionTest(props, host, port, maxConnectionsPerChannel, false); underSubscriptionTest(props, host, port, (maxConnectionsPerChannel / 2)); }</code><technical_language>a suggestion @Test functions in beginning of file more obvious tests w.r.t readability</technical_language>

Target:
private void testBlockingChannelInfo(String host, Port port, int maxConnectionsPerPortPlainText, int maxConnectionsPerPortSSL) throws Exception { Properties props = new Properties(); props.put("connectionpool.max.connections.per.port.plain.text", "" + maxConnectionsPerPortPlainText); props.put("connectionpool.max.connections.per.port.ssl", "" + maxConnectionsPerPortSSL); int maxConnectionsPerHost = (port.getPortType() == PortType.PLAINTEXT) ? maxConnectionsPerPortPlainText : maxConnectionsPerPortSSL; createAndReleaseSingleChannelTest(props, host, port); overSubscriptionTest(props, host, port, maxConnectionsPerHost, true); overSubscriptionTest(props, host, port, maxConnectionsPerHost, false); underSubscriptionTest(props, host, port, (maxConnectionsPerHost / 2)); }
Source:
<code><START> private Mono<Void> createTempFile() { <END> try (InputStream inputStream = createRandomInputStream(options.getSize()); OutputStream outputStream = new FileOutputStream(TEMP_FILE.toString())) { copyStream(inputStream, outputStream); return Mono.empty(); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>want move this a shared helper method for other tests need a temp file random data</technical_language>

Target:
private Mono<Void> createTempFile() { return Mono.fromCallable(() -> { TestDataCreationHelper.writeToFile(TEMP_FILE_PATH, options.getSize(), DEFAULT_BUFFER_SIZE); return 1; }).then(); }
Source:
<code>public TypedOperation selectOperation() { updateBranchCoverageMaybe(); <START> updateWeightsForOperations(); <END> TypedOperation operation = Randomness.randomMemberWeighted(operationSimpleList, methodWeights); incrementInMap(methodSelections, operation); int numSuccessfulInvocations = incrementInMap(methodSuccessfulCalls, operation); maxSuccessfulCalls = Math.max(maxSuccessfulCalls, numSuccessfulInvocations); return operation; }</code><technical_language>is updateWeightsForOperations called step? called in selectOperation, right updateBranchCoverageMaybe effect sometimes. concern efficiency cost of re-computing weights operation. Also, GRT paper says, "At update of coverage, weights recalculated, is reset 0." This implies weights recomputed step. replace updateBranchCoverageMaybe(); updateWeightsForOperations(); stepNum++; if (stepNum % branchCoverageInterval == 0) { updateBranchCoverage(); updateWeightsForOperations(); }</technical_language>

Target:
public TypedOperation selectOperation() { updateBranchCoverageMaybe(); TypedOperation selectedOperation = Randomness.randomMemberWeighted( operationSimpleList, methodWeights, totalWeightOfMethodsUnderTest); CollectionsPlume.incrementMap(methodSelectionCounts, selectedOperation); updateWeight(selectedOperation); return selectedOperation; }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_FILE) { if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); String filePath = ""; try { filePath = UriToFilePath.getPathFromUri(CommCareApplication.instance(), uri); } catch (UriToFilePath.NoDataColumnForUriException e) { filePath = getContext().getFilesDir().getAbsolutePath() + "/temp/" + FileUtil.getFileName(uri.toString()); File file = new File(filePath); try { InputStream fileStream = getContext().getContentResolver().openInputStream(uri); FileUtil.ensureFilePathExists(file); FileUtil.copyFile(fileStream, file); } catch (IOException e1) { e1.printStackTrace(); <START> String failureMessage = e1 instanceof FileNotFoundException ? Localization.get("file.not.exist") : Localization.get("file.copy.failed"); <END> Toast.makeText(getActivity(), failureMessage, Toast.LENGTH_LONG).show(); return; } } validateFile(filePath); } else { Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show(); } } }</code><technical_language>I showing of messages (file.not.exist file.copy.failed) user is confusing helpful. do is set file location for a preference, a message "copying a file failed" "the file exist" pretty confusing, user copy file selected file chooser, idea file exist. I suggest: 1. Showing a more generic more actionable error message user (something Unable resolve chosen file. If issue persists, need delete file targeting re-add file system). 2. Logging exception device logs of issues (if understanding this correctly) wrong anticipated</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_FILE) { if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); String filePath = null; try { filePath = UriToFilePath.getPathFromUri(CommCareApplication.instance(), uri); } catch (UriToFilePath.NoDataColumnForUriException e) { try { filePath = getNewPathFromUri(uri); } catch (IOException ioe) { Logger.exception(LogTypes.TYPE_MAINTENANCE, e); Toast.makeText(getActivity(), Localization.get("file.selection.failed"), Toast.LENGTH_LONG).show(); return; } } validateFile(filePath); } else { Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show(); } } }
Source:
<code>public void setOriginalResponseData(String originalResponseData) { <START> if(originalResponseData!=null && !originalResponseData.equals("") && <END> originalResponseContentType!= null && originalResponseContentType.toLowerCase().indexOf("application/json")!=-1){ try{ JSONObject originalResponseJSON = new JSONObject(originalResponseData); this.originalResponseData = originalResponseJSON.toString(); }catch(Exception e){ e.printStackTrace(); } }else { this.originalResponseData = originalResponseData; } }</code><technical_language>reformat original response data.. this retain database value</technical_language>

Target:
public void setOriginalResponseData(String originalResponseData) { this.originalResponseData = originalResponseData; }
Source:
<code>private static OutputGroupDeterminer constructOutputGroupDeterminer(OptionHolder transportOptionHolder, OptionHolder distributedOptHolder, StreamDefinition streamDefinition, int endpointCount){ OutputGroupDeterminer groupDeterminer = null; if (distributedOptHolder != null){ int partitionCount = endpointCount; String strategy = distributedOptHolder.validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_STRATEGY_KEY); if (strategy.equalsIgnoreCase(DistributedTransport.DISTRIBUTION_STRATEGY_PARTITIONED)){ String partitionKeyField = distributedOptHolder.validateAndGetStaticValue(DistributedTransport.PARTITION_KEY_FIELD_KEY); int partitioningFieldIndex = streamDefinition.getAttributePosition(partitionKeyField); if (distributedOptHolder.isOptionExists(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)){ partitionCount = Integer.parseInt(distributedOptHolder.validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)); } groupDeterminer = new PartitionedGrouping(partitioningFieldIndex, partitionCount); } } if (groupDeterminer == null){ <START> ArrayList<Option> transportOptions = new ArrayList<Option>(transportOptionHolder.getDynamicOptionsKeys().size()); <END> for (String publishGroupDeterminer : transportOptionHolder.getDynamicOptionsKeys()) { transportOptions.add(transportOptionHolder.validateAndGetOption(publishGroupDeterminer)); } if (transportOptions.size() > 0){ groupDeterminer = new DynamicOptionGrouping(transportOptions); } } return groupDeterminer; }</code><technical_language>/s/ArrayList/List</technical_language>

Target:
private static OutputGroupDeterminer constructOutputGroupDeterminer(OptionHolder transportOptionHolder, OptionHolder distributedOptHolder, StreamDefinition streamDefinition, int endpointCount){ OutputGroupDeterminer groupDeterminer = null; if (distributedOptHolder != null){ int partitionCount = endpointCount; String strategy = distributedOptHolder .validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_STRATEGY_KEY); if (strategy.equalsIgnoreCase(DistributedTransport.DISTRIBUTION_STRATEGY_PARTITIONED)){ String partitionKeyField = distributedOptHolder .validateAndGetStaticValue(DistributedTransport.PARTITION_KEY_FIELD_KEY); int partitioningFieldIndex = streamDefinition.getAttributePosition(partitionKeyField); if (distributedOptHolder.isOptionExists(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)){ partitionCount = Integer.parseInt(distributedOptHolder .validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)); } groupDeterminer = new PartitionedGroupDeterminer(partitioningFieldIndex, partitionCount); } } if (groupDeterminer == null){ List<Option> dynamicTransportOptions = new ArrayList<Option>(transportOptionHolder .getDynamicOptionsKeys().size()); transportOptionHolder.getDynamicOptionsKeys(). forEach(option -> dynamicTransportOptions.add(transportOptionHolder.validateAndGetOption(option))); if (dynamicTransportOptions.size() > 0){ groupDeterminer = new DynamicOptionGroupDeterminer(dynamicTransportOptions); } } return groupDeterminer; }
Source:
<code>public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (editionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE) { throw BadRequestException.create("Can't apply a license when applying one is already in progress"); } <START> String licenseParam = request.mandatoryParam(PARAM_LICENSE); <END> License newLicense = License.parse(licenseParam).orElseThrow(() -> BadRequestException.create("The license provided is invalid")); NextState nextState = computeNextState(newLicense); WsUtils.writeProtobuf(buildResponse(nextState), request, response); }</code><technical_language>mind it. "license=" argument fail mandatory param check in request.mandatoryParam explicitly add if (licenseParam.isEmpty()) { throw new IllegalArgumentException(format("The '%s' parameter is missing", PARAM_LICENSE)); } get a "invalid license" in this case. This is super user friendly</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (editionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE) { throw BadRequestException.create("Can't apply a license when applying one is already in progress"); } String licenseParam = request.mandatoryParam(PARAM_LICENSE); if (licenseParam.isEmpty()) { throw new IllegalArgumentException(String.format("The '%s' parameter is empty", PARAM_LICENSE)); } License newLicense = License.parse(licenseParam).orElseThrow(() -> BadRequestException.create("The license provided is invalid")); NextState nextState = computeNextState(newLicense); WsUtils.writeProtobuf(buildResponse(nextState), request, response); }
Source:
<code>public RemoteViewsFactory onGetViewFactory(Intent intent) { <START> return new MessageListRemoteViewFactory(this.getApplicationContext()); <END> }</code><technical_language>this. unnecessary</technical_language>

Target:
public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MessageListRemoteViewFactory(getApplicationContext()); }
Source:
<code>protected void executeQueryCommand() { final List<VdsNetworkInterface> list = getDbFacade().getInterfaceDao() .getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<VdsNetworkInterface>(list.size()); if (!list.isEmpty()) { VdsStatic vdsStatic = getDbFacade().getVdsStaticDao().get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName( getDbFacade().getNetworkDao().getAllForCluster(vdsStatic.getVdsGroupId())); for (final VdsNetworkInterface i : list) { if (i.getBonded() == null || (i.getBonded() != null && i.getBonded()) && LinqUtils.filter(list, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface bond) { return StringUtils.equals(bond.getBondName(), i.getName()); } }).size() > 0) { interfaces.add(i); i.setNetworkImplementationDetails(NetworkUtils.calculateNetworkImplementationDetails(networks, i)); } } } <START> Collections.sort(interfaces, new Comparator<VdsNetworkInterface>() { <END> private boolean isBond(VdsNetworkInterface nic) { return (nic.getBonded() != null && nic.getBonded()); } private String extractBondName(VdsNetworkInterface nic) { if (isBond(nic)) { return nic.getName(); } else { return nic.getBondName(); } } @Override public int compare(VdsNetworkInterface nic1, VdsNetworkInterface nic2) { int compRes = LexoNumericComparator.comp(extractBondName(nic1), extractBondName(nic2)); if (compRes != 0) { if (extractBondName(nic1) == null) { return 1; } if (extractBondName(nic2) == null) { return -1; } return compRes; } if (isBond(nic1) != isBond(nic2)) { return isBond(nic1) ? -1 : 1; } return LexoNumericComparator.comp(nic1.getName(), nic2.getName()); } }); getQueryReturnValue().setReturnValue(interfaces); }</code><technical_language>extend LexoNumericComparator</technical_language>

Target:
protected void executeQueryCommand() { final List<VdsNetworkInterface> list = getDbFacade().getInterfaceDao() .getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<VdsNetworkInterface>(list.size()); if (!list.isEmpty()) { VdsStatic vdsStatic = getDbFacade().getVdsStaticDao().get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName( getDbFacade().getNetworkDao().getAllForCluster(vdsStatic.getVdsGroupId())); for (final VdsNetworkInterface i : list) { if (i.getBonded() == null || (i.getBonded() != null && i.getBonded()) && LinqUtils.filter(list, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface bond) { return StringUtils.equals(bond.getBondName(), i.getName()); } }).size() > 0) { interfaces.add(i); i.setNetworkImplementationDetails(NetworkUtils.calculateNetworkImplementationDetails(networks, i)); } } } Collections.sort(interfaces, new NicComparator()); getQueryReturnValue().setReturnValue(interfaces); }
Source:
<code>public void configUpdated(String configName, boolean downloadApplications) { <START> LOGGER.info("Configuration updated, fetching Commcare schema, {}", configName); <END> if (downloadApplications) { reloadConfig(configName); } else { clearApps(configName); } }</code><technical_language>Move log if log in else</technical_language>

Target:
public void configUpdated(String configName, boolean downloadApplications) { if (downloadApplications) { LOGGER.info("Configuration updated, fetching Commcare schema, {}", configName); reloadConfig(configName); } else { LOGGER.info("Configuration updated, not fetching new Commcare schema, {}", configName); clearApps(configName); } }
Source:
<code>protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) { ExecutionContext ctx = new ExecutionContext(); try { Map<String, String> values = new HashMap<String, String>(); values.put(VdcObjectType.VM.name().toLowerCase(), vm.getName()); values.put(VdcObjectType.VDS.name().toLowerCase(), vm.getRunOnVdsName()); Step step = ExecutionHandler.addSubStep(getExecutionContext(), parentContext.getJob().getStep(StepEnum.EXECUTING), StepEnum.MIGRATE_VM, ExecutionMessageDirector.resolveStepMessage(StepEnum.MIGRATE_VM, values)); ctx.setJob(parentContext.getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for MigrateVmCommand", e); } <START> return dupContext().setExecutionContext(ctx).resetCompensationContext().resetLock(); <END> }</code><technical_language>aaa</technical_language>

Target:
protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) { ExecutionContext ctx = new ExecutionContext(); try { Map<String, String> values = new HashMap<String, String>(); values.put(VdcObjectType.VM.name().toLowerCase(), vm.getName()); values.put(VdcObjectType.VDS.name().toLowerCase(), vm.getRunOnVdsName()); Step step = ExecutionHandler.addSubStep(getExecutionContext(), parentContext.getJob().getStep(StepEnum.EXECUTING), StepEnum.MIGRATE_VM, ExecutionMessageDirector.resolveStepMessage(StepEnum.MIGRATE_VM, values)); ctx.setJob(parentContext.getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for MigrateVmCommand", e); } return dupContext().withExecutionContext(ctx).withoutCompensationContext().withoutLock(); }
Source:
<code>public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, <START> CoreText.AssumeUnchangedOperation_adding, rsrcList.size() + 1); <END> caches.clear(); mappings.clear(); try { for (IResource resource : rsrcList) { assumeValid(resource); progress.worked(1); } progress.setWorkRemaining(caches.size()); for (Map.Entry<Repository, DirCache> e : caches.entrySet()) { final Repository db = e.getKey(); final DirCache editor = e.getValue(); progress.setTaskName(NLS.bind( CoreText.AssumeUnchangedOperation_writingIndex, db .getDirectory())); editor.write(); editor.commit(); progress.worked(1); } } catch (RuntimeException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } catch (IOException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } finally { for (DirCache cache : caches.values()) { cache.unlock(); } caches.clear(); mappings.clear(); } }</code><technical_language>This consume of progress loop. Suggest changing this "rsrcList.size() + caches.size()" removing extra call setWorkRemaining</technical_language>

Target:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, rsrcList.size() * 2); progress.setTaskName(CoreText.AssumeUnchangedOperation_adding); caches.clear(); try { for (IResource resource : rsrcList) { assumeValid(resource); progress.worked(1); } progress.setWorkRemaining(caches.size()); for (Map.Entry<Repository, DirCache> e : caches.entrySet()) { final Repository db = e.getKey(); final DirCache editor = e.getValue(); progress.setTaskName(NLS.bind( CoreText.AssumeUnchangedOperation_writingIndex, db .getDirectory())); editor.write(); editor.commit(); progress.worked(1); } } catch (RuntimeException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } catch (IOException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } finally { for (DirCache cache : caches.values()) { cache.unlock(); } caches.clear(); } }
Source:
<code>private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); <START> DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); <END> dirStream.forEach( path -> txFiles.add( path.toFile() ) ); return txFiles; }</code><technical_language>need close this directory stream</technical_language>

Target:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); dirStream.forEach( path -> txFiles.add( path.toFile() ) ); dirStream.close(); return txFiles; }
Source:
<code>public double[] derivative(Trade trade, RatesProvider provider, List<CurveParameterSize> curveOrder) { CalibrationMeasure<Trade> measure = getMeasure(trade.getClass()); CurveCurrencyParameterSensitivities paramSens = measure.sensitivities(trade, provider); CurveUnitParameterSensitivities unitSens = CurveUnitParameterSensitivities.empty(); for (CurveCurrencyParameterSensitivity ccySens : paramSens.getSensitivities()) { unitSens = unitSens.combinedWith(CurveUnitParameterSensitivity.of(ccySens.getMetadata(), ccySens.getSensitivity())); } double[] result = DoubleArrayMath.EMPTY_DOUBLE_ARRAY; for (CurveParameterSize curveParams : curveOrder) { double[] sens = unitSens.findSensitivity(curveParams.getName()) <START> .map(s -> s.getSensitivity()) <END> .orElse(new double[curveParams.getParameterCount()]); result = Doubles.concat(result, sens); } return result; }</code><technical_language>a method ref here</technical_language>

Target:
public double[] derivative(Trade trade, RatesProvider provider, List<CurveParameterSize> curveOrder) { CurveUnitParameterSensitivities unitSens = extractSensitivities(trade, provider); double[] result = DoubleArrayMath.EMPTY_DOUBLE_ARRAY; for (CurveParameterSize curveParams : curveOrder) { double[] sens = unitSens.findSensitivity(curveParams.getName()) .map(s -> s.getSensitivity()) .orElse(new double[curveParams.getParameterCount()]); result = Doubles.concat(result, sens); } return result; }
Source:
<code>public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) { List<RefactoringParticipant> result= new ArrayList<>(); for (IJavaElement <START> iJavaElement : <END> fDelete) { result.addAll(Arrays.asList(ParticipantManager.loadDeleteParticipants(status, owner, iJavaElement, new DeleteArguments(), natures, shared))); } result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared))); return result.toArray(new RefactoringParticipant[result.size()]); }</code><technical_language>rename javaElement element</technical_language>

Target:
public RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor owner, String[] natures, SharableParticipants shared) { List<RefactoringParticipant> result= new ArrayList<>(); for (IJavaElement javaElement : fDelete) { result.addAll(Arrays.asList(ParticipantManager.loadDeleteParticipants(status, owner, javaElement, new DeleteArguments(), natures, shared))); } result.addAll(Arrays.asList(getResourceModifications().getParticipants(status, owner, natures, shared))); return result.toArray(new RefactoringParticipant[result.size()]); }
Source:
<code>public void validate() { if (sheetName.indexOf(".") != -1) { throw new IllegalStateException("Sheet name cannot contain dots (.)"); } if (file.exists() && !overwriteFile) { <START> throw new IllegalStateException("The file already exits and the columns selected do not match"); <END> } }</code><technical_language>Typo: file EXITS :) I more explicit in message: "The file exists columns selected do match existing records"</technical_language>

Target:
public void validate() { if (sheetName.indexOf(".") != -1) { throw new IllegalStateException("Sheet name cannot contain dots (.)"); } if (file.exists() && !overwriteFileIfExists) { throw new IllegalStateException("The file already exists and the columns selected do not match. Please configure the job to overwrite the existing file."); } }