auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void enterText(String columnHeading, int rowNum, String text) { if (!text.equals(cleanAscii(text))) { throw new IllegalArgumentException("text contains non-ASCII characters"); } WebElement cell = getCell(columnHeading, rowNum); Action action = new Actions(getDriver()) .click(cell) .sendKeys(Keys.DELETE) .sendKeys(text) .sendKeys(Keys.ENTER) .build(); for (int retries = 0; retries < 3 && !text.equals(getText(columnHeading, rowNum)); retries++) { <START> action.perform(); <END> } }</code><technical_language>This emit a useful error exceeded retry limit</technical_language>

Target:
public void enterText(String columnHeading, int rowNum, String text) { if (LimsUtils.isStringEmptyOrNull(text)) { clearField(columnHeading, rowNum, text); return; } if (!text.equals(cleanAscii(text))) { throw new IllegalArgumentException("text contains non-ASCII characters"); } WebElement cell = getCell(columnHeading, rowNum); cancelEditing(); if (!cell.getAttribute("class").contains("current")) { cell.click(); cell = getCell(columnHeading, rowNum); if (!cell.getAttribute("class").contains("current")) { throw new IllegalStateException("Cell still not selected after clicking"); } } new Actions(getDriver()).sendKeys(Keys.ENTER).build().perform(); waitUntil(presenceOfElementLocated(activeCellEditorSelector)); WebElement cellEditor = getDriver().findElement(activeCellEditorSelector); cellEditor.clear(); waitUntil(textToBe(activeCellEditorSelector, "")); safeInput(activeCellEditorSelector, text); cellEditor.sendKeys(Keys.ENTER); waitUntil(invisibilityOf(cellEditor)); }
Source:
<code>private List<TransactionalStrategyState> getStrategyForMacAllocation() { List<TransactionalStrategyState> states = new ArrayList<>(); if (usingCompensationState.shouldUseCompensation()) { states.add(usingCompensationState); } boolean shouldUseTxDecorator = TransactionSupport.current() != null; if (shouldUseTxDecorator) { states.add(usingTxDecoratorState); } if (states.isEmpty()) { states.add(nontransactionalState); } log.debug("Using as allocation strategies", <START> Arrays.toString(states.toArray())); <END> return states; }</code><technical_language>create array out of existing List Arrays.toString, Arrays.toString is AbstractCollection.toString (that is called if pass states List itself)? If a good reason for Arrays.toString plsease extract a private method</technical_language>

Target:
private List<TransactionalStrategyState> getStrategyForMacAllocation() { List<TransactionalStrategyState> states = new ArrayList<>(); if (usingCompensationState.shouldUseCompensation()) { states.add(usingCompensationState); } boolean shouldUseTxDecorator = TransactionSupport.current() != null; if (shouldUseTxDecorator) { states.add(usingTxDecoratorState); } if (states.isEmpty()) { states.add(nontransactionalState); } log.debug("Using as allocation strategies", states); return states; }
Source:
<code>public void testDescribe() { vpc = vpcClient.createVpc(TEST_REGION, VPC_CIDR); assertNotNull(vpc, "Failed to create VPC to test attachments"); tagger.applyToResources(ImmutableMap.of("Name", simpleName), ImmutableList.of(vpc.id())); final FluentIterable<RouteTable> routeTables = routeTableApi.describeRouteTables(TEST_REGION); assertNotNull(routeTables, "Failed to return list of RouteTables"); boolean foundVpc = false; <START> for (RouteTable rt : routeTables) { <END> if (vpc.id().equals(rt.vpcId())) { foundVpc = true; assertEquals(rt.associationSet().size(), 1, "Route for test VPC has wrong number of associations, should be 1: " + rt.associationSet()); assertTrue(rt.associationSet().get(0).main(), "Association for route " + rt.id() + "should be 'main'"); assertEquals(rt.routeSet().size(), 1, "Wrong number of routes in default route table for VPC " + vpc.id()); final String defaultCidr = rt.routeSet().get(0).destinationCidrBlock(); assertEquals(defaultCidr, vpc.cidrBlock(), "Route in default route table does not match CIDR of VPC, " + defaultCidr + " should be " + vpc.cidrBlock()); break; } } assertTrue(foundVpc, "Could not find VPC " + vpc.id() + " in described route tables"); }</code><technical_language>More idiomatic: java Optional<RouteTable> vpcRT = Iterables.tryFind(routeTables, new Predicate<RouteTable>() { @Override public boolean apply(RouteTable input) { return vpc.id().equals(input.vpcId()); } }); assertTrue(vpcRT.isPresent(), "..."); // other assertions</technical_language>

Target:
public void testDescribe() { vpc = vpcClient.createVpc(TEST_REGION, VPC_CIDR); assertNotNull(vpc, "Failed to create VPC to test attachments"); tagger.applyToResources(ImmutableMap.of("Name", simpleName), ImmutableList.of(vpc.id())); final FluentIterable<RouteTable> routeTables = routeTableApi.describeRouteTables(TEST_REGION); assertNotNull(routeTables, "Failed to return list of RouteTables"); Optional<RouteTable> vpcRT = Iterables.tryFind(routeTables, new Predicate<RouteTable>() { @Override public boolean apply(RouteTable input) { return vpc.id().equals(input.vpcId()); } }); assertTrue(vpcRT.isPresent(), "Could not find VPC " + vpc.id() + " in described route tables"); RouteTable rt = vpcRT.get(); assertEquals(rt.associationSet().size(), 1, "Route for test VPC has wrong number of associations, should be 1: " + rt.associationSet()); assertTrue(rt.associationSet().get(0).main(), "Association for route " + rt.id() + "should be 'main'"); assertEquals(rt.routeSet().size(), 1, "Wrong number of routes in default route table for VPC " + vpc.id()); final String defaultCidr = rt.routeSet().get(0).destinationCidrBlock(); assertEquals(defaultCidr, vpc.cidrBlock(), "Route in default route table does not match CIDR of VPC, " + defaultCidr + " should be " + vpc.cidrBlock()); }
Source:
<code>public LongDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage.getEncoding()); content = new long[dictionaryPage.getDictionarySize()]; LongPlainValuesReader longReader = new LongPlainValuesReader(); <START> final ByteBufferInputStream in = ByteBufferInputStream.wrap(ByteBuffer.wrap(dictionaryPage.getSlice().getBytes())); <END> longReader.initFromPage(dictionaryPage.getDictionarySize(), in); for (int i = 0; i < content.length; i++) { content[i] = longReader.readLong(); } }</code><technical_language>ditto about: - removing final variable - var args call</technical_language>

Target:
public LongDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage.getEncoding()); content = new long[dictionaryPage.getDictionarySize()]; LongPlainValuesReader longReader = new LongPlainValuesReader(); ByteBuffer byteBuffer = ByteBuffer.wrap(dictionaryPage.getSlice().getBytes()); ByteBufferInputStream inputStream = ByteBufferInputStream.wrap(ImmutableList.of(byteBuffer)); longReader.initFromPage(dictionaryPage.getDictionarySize(), inputStream); for (int i = 0; i < content.length; i++) { content[i] = longReader.readLong(); } }
Source:
<code>private Response handleAuthResponse(String chargeId, AuthoriseStatus authoriseStatus) { if (authoriseStatus.equals(AuthoriseStatus.SUBMITTED)) { logger.info("Charge {}: authorisation was deferred.", chargeId); return badRequestResponse("This transaction was deferred."); } if (isAuthorisationDeclined(authoriseStatus)) { <START> logger.info("Charge {}: authorisation was declined.", chargeId); <END> return badRequestResponse("This transaction was declined."); } return ResponseUtil.successResponseWithEntity(ImmutableMap.of("status", authoriseStatus.getMappedChargeStatus().toString())); }</code><technical_language>log a more detailed message authorisation declined status of charge changed a result</technical_language>

Target:
private Response handleAuthResponse(String chargeId, AuthoriseStatus authoriseStatus) { if (authoriseStatus.equals(AuthoriseStatus.SUBMITTED)) { logger.info("Charge {}: authorisation was deferred.", chargeId); return badRequestResponse("This transaction was deferred."); } if (isAuthorisationDeclined(authoriseStatus)) { return badRequestResponse("This transaction was declined."); } return ResponseUtil.successResponseWithEntity(ImmutableMap.of("status", authoriseStatus.getMappedChargeStatus().toString())); }
Source:
<code>private void internalWriteRow(List<Object> values, Sheet sheet, int rowNr) { final org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNr); AtomicInteger counter = new AtomicInteger(0); values .stream() .forEach( record -> { int index = counter.getAndIncrement(); if (record != null) { <START> String stringValue = record.toString().trim(); <END> if (!stringValue.isEmpty()) { final Cell cell = row.createCell(index); cell.setCellValue(stringValue); } } }); }</code><technical_language>I ExcelWriter modify values including trimming</technical_language>

Target:
private void internalWriteRow(List<Object> values, Sheet sheet, int rowNr) { final org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNr); AtomicInteger counter = new AtomicInteger(0); values .stream() .forEach( record -> { int index = counter.getAndIncrement(); if (record != null) { String stringValue = record.toString(); if (!stringValue.isEmpty()) { final Cell cell = row.createCell(index); cell.setCellValue(stringValue); } } }); }
Source:
<code>public void loadModels() { if (loadingModels || mModels.getLoaded()) { return; } loadingModels = true; new Exception().printStackTrace(); new Thread(new Runnable() { <START> @Override <END> public void run() { Timber.v("Loading models"); mModels.load(loadColumn("models")); Timber.v("Models loaded"); } }).start(); }</code><technical_language>a FutureTask instead of a raw Thread wait loop getModels()? Also, verbose a lambda instead of Runnable</technical_language>

Target:
public void loadModels() { if (futureLoadingModel != null) { return; } futureLoadingModel = new FutureTask( () -> mModels.load(loadColumn("models")) ); new Thread(futureLoadingModel).start(); }
Source:
<code>public NoSuchStepExecutionException(long id) { <START> super("Could not find step execution with id '" + id + "'"); <END> }</code><technical_language>I is need for quotes id, is numeric contain, say, spaces</technical_language>

Target:
public NoSuchStepExecutionException(long id) { super("Could not find step execution with id " + id); }
Source:
<code>public PagedFlux<BlockItem> listBlocks(BlockListType listType, LeaseAccessConditions leaseAccessConditions) { return new PagedFlux<>( <START> () -> postProcessResponse(this.azureBlobStorage.blockBlobs().getBlockListWithRestResponseAsync( <END> null, null, listType, snapshot, null, null, null, leaseAccessConditions, Context.NONE)) .map(response -> new PagedResponseBase<>( response.request(), response.statusCode(), response.headers(), Stream.concat( response.value().committedBlocks().stream() .map(committedBlock -> new BlockItem(committedBlock, true)), response.value().uncommittedBlocks().stream() .map(uncommittedBlock -> new BlockItem(uncommittedBlock, false))) .collect(Collectors.toList()), null , response.deserializedHeaders())), (marker) -> null); }</code><technical_language>is complex understand. please a helper method</technical_language>

Target:
public Mono<Response<BlockList>> listBlocks(BlockListType listType, LeaseAccessConditions leaseAccessConditions) { return postProcessResponse(this.azureBlobStorage.blockBlobs().getBlockListWithRestResponseAsync( null, null, listType, snapshot, null, null, null, leaseAccessConditions, Context.NONE)) .map(response -> new SimpleResponse<>(response, response.value())); }
Source:
<code>public Profile getProfileByTicket(String ticketId, String... attributesToReturn) throws ProfileException { MultiValueMap<String, String> params = createBaseParams(); HttpUtils.addValue(PARAM_TICKET_ID, ticketId, params); HttpUtils.addValues(PARAM_ATTRIBUTE_TO_RETURN, attributesToReturn, params); String url = getAbsoluteUrl(BASE_URL_PROFILE + URL_PROFILE_GET_BY_TICKET); url = addQueryParams(url, params, false); <START> return doGetForObject(url, Profile.class); <END> }</code><technical_language>I get rid of try catch, want return null profile. Instead, if status is FOUND, error code is TICKET, throw exception</technical_language>

Target:
public Profile getProfileByTicket(String ticketId, String... attributesToReturn) throws ProfileException { MultiValueMap<String, String> params = createBaseParams(); HttpUtils.addValue(PARAM_TICKET_ID, ticketId, params); HttpUtils.addValues(PARAM_ATTRIBUTE_TO_RETURN, attributesToReturn, params); String url = getAbsoluteUrl(BASE_URL_PROFILE + URL_PROFILE_GET_BY_TICKET); url = addQueryParams(url, params, false); try { return doGetForObject(url, Profile.class); } catch (ProfileRestServiceException e) { if(e.getStatus() == HttpStatus.NOT_FOUND) { return null; } else { throw e; } } }
Source:
<code>public static Tocd readObjectClassDefinition(String pid) throws IOException, Exception, XMLStreamException, FactoryConfigurationError { Tocd ocd = null; StringBuilder sbMetatypeXmlName = new StringBuilder(); sbMetatypeXmlName.append("OSGI-INF/metatype/").append(pid).append(".xml"); String metatypeXmlName = sbMetatypeXmlName.toString(); String metatypeXml = IOUtil.readResource(metatypeXmlName); if (metatypeXml != null) { Tmetadata metaData = unmarshalXml(metatypeXml, Tmetadata.class); <START> if (metaData.getOCD() != null && metaData.getOCD().size() > 0) { <END> ocd = (Tocd) metaData.getOCD().get(0); } else { logger.warn("Cannot find OCD for component with pid: {}", pid); } } return ocd; }</code><technical_language>!isEmpty()</technical_language>

Target:
public static Tocd readObjectClassDefinition(String pid) throws IOException, Exception, XMLStreamException, FactoryConfigurationError { Tocd ocd = null; StringBuilder sbMetatypeXmlName = new StringBuilder(); sbMetatypeXmlName.append("OSGI-INF/metatype/").append(pid).append(".xml"); String metatypeXmlName = sbMetatypeXmlName.toString(); String metatypeXml = IOUtil.readResource(metatypeXmlName); if (metatypeXml != null) { Tmetadata metaData = unmarshal(metatypeXml, Tmetadata.class); if (metaData.getOCD() != null && !metaData.getOCD().isEmpty()) { ocd = (Tocd) metaData.getOCD().get(0); } else { logger.warn("Cannot find OCD for component with pid: {}", pid); } } return ocd; }
Source:
<code>private InetAddress getRandomIPv4Address(final IpPrefix prefix) throws UnknownHostException { <START> byte[] bytes = prefix.getAddress().getAddress(); bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF); return InetAddress.getByAddress(bytes); <END> }</code><technical_language>Technically this works if prefix length is 24, address of prefix (or prefix range for random values). prefix callback a more problematic. I guess do like: final int prefixMask = prefixLengthToV4NetmaskIntHTH(prefix.getPrefixLength()); final int address = inet4AddressToIntHTH(prefix.getAddress()); final int randomAddr = (address & prefixMask) | (Random.nextInt() & ~prefixMask); final byte[] randomAddrBytes = ByteBuffer.allocate(4).putInt(randomAddr).array(); for (int i = 3; i >= prefix.getPrefixLength() / 8; i--) { final byte randomByte = randomAddrBytes[i]; if (randomByte == 0 || randomByte == 1 || randomByte == 0xff) { randomAddrBytes[i] = DOUG_ADAMS; } } return InetAddress.getByAddress(randomAddrBytes); randomize byte if prefixLength <= 24, complete</technical_language>

Target:
private InetAddress getRandomIPv4Address(final IpPrefix prefix) throws UnknownHostException { if (prefix.getPrefixLength() != DEFAULT_PREFIX_LENGTH) { throw new IllegalArgumentException("Unexpected prefix length: " + prefix); } byte[] bytes = prefix.getAddress().getAddress(); bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF); return InetAddress.getByAddress(bytes); }
Source:
<code>public MemberId bestUpstreamDatabase() throws UpstreamDatabaseSelectionException { MemberId result = null; for ( UpstreamDatabaseSelectionStrategy strategy : strategies ) { log.debug( "Trying selection strategy [%s]", strategy.toString() ); try { Optional<MemberId> foundMemberByStrategy = strategy.upstreamDatabase(); if ( foundMemberByStrategy.isPresent() ) { <START> result = foundMemberByStrategy.get(); <END> break; } } catch ( NoSuchElementException ex ) { } } if ( result == null ) { throw new UpstreamDatabaseSelectionException( "Could not find an upstream database with which to connect." ); } log.debug( "Selected upstream database [%s]", result ); return result; }</code><technical_language>more natural a stream().filter(Optional::isPresent).map(Optional::get).findFirst() call</technical_language>

Target:
public MemberId bestUpstreamDatabase() throws UpstreamDatabaseSelectionException { MemberId result = null; for ( UpstreamDatabaseSelectionStrategy strategy : strategies ) { log.debug( "Trying selection strategy [%s]", strategy.toString() ); try { if ( strategy.upstreamDatabase().isPresent() ) { result = strategy.upstreamDatabase().get(); break; } } catch ( NoSuchElementException ex ) { } } if ( result == null ) { throw new UpstreamDatabaseSelectionException( "Could not find an upstream database with which to connect." ); } log.debug( "Selected upstream database [%s]", result ); return result; }
Source:
<code>public String getEmbedMapWikiCode(){ String mapID = mapFrame.getAttribute("data-mapid"); String r = "<imap map-id='"+mapID+"'/>"; <START> return r; <END> }</code><technical_language>I combine lines return "<imap map-id='"+mapID+"'/>";</technical_language>

Target:
public String getEmbedMapWikiCode() { return "<imap map-id='" + mapFrame.getAttribute("data-mapid") + "'/>"; }
Source:
<code>public void testGetValidTraceTypes() { for (Class<? extends ITmfTrace> traceType : fModule.getValidTraceTypes()) { assertTrue(fModule.appliesToTraceType(traceType)); <START> } <END> }</code><technical_language>is a good test, complete, this test method a list of trace types applies traces of list returned module vice-versa. test returned valid trace types valid, need test valid-returned-trace-types included in list of KnownApplicableTraceTypes KnowsApplicableTraceTypes included in valid-returned-trace-types</technical_language>

Target:
public void testGetValidTraceTypes() { TraceTypeHelper traceTypeHelper = TmfTraceType.getInstance().getTraceType(VALID_TRACE_TYPE); int traceTypeCount = 0; for (Class<? extends ITmfTrace> traceType : fModule.getValidTraceTypes()) { assertTrue(fModule.appliesToTraceType(traceType)); assertEquals(traceTypeHelper.getTraceClass(), traceType); traceTypeCount++; } assertEquals(1, traceTypeCount); }
Source:
<code>static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { <START> return Mono.error(e); <END> } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }</code><technical_language>this return Flux.error(e)</technical_language>

Target:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Flux.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }
Source:
<code>public ExtensionProxy activate(String extensionName) { ExtensionEntry entry = loadedEntries.get(extensionName); if (entry == null) { throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found", extensionName)); } if (entry.enabled) { <START> entry.extension.getContext().put( <END> TRACE_LOG_CONTEXT_KEY, LogFactory.getLog( String.format( "%1$s.%2$s.%3$s", getTraceLog(), entry.extension.getContext().get(Base.ContextKeys.EXTENSION_NAME), entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ) ) ); try { ExtMap output = entry.extension.invoke( new ExtMap().mput( Base.InvokeKeys.COMMAND, Base.InvokeCommands.INITIALIZE ) ); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.name, ex.getMessage() ) ); if (log.isDebugEnabled()) { log.debug(ex.toString(), ex); } throw new RuntimeException(ex); } synchronized (globalContext) { globalContext.<List<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add( new ExtMap().mput( Base.ExtensionRecord.INSTANCE_NAME, entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ).mput( Base.ExtensionRecord.PROVIDES, entry.extension.getContext().get(Base.ContextKeys.PROVIDES) ).mput( Base.ExtensionRecord.EXTENSION, entry.extension.getExtension() ).mput( Base.ExtensionRecord.CONTEXT, entry.extension.getContext() ) ); } entry.activated = true; dumpConfig(entry.extension); setChanged(); notifyObservers(); } return entry != null ? entry.extension : null; }</code><technical_language>this load</technical_language>

Target:
public ExtensionProxy activate(String extensionName) { return activate(extensionName, false); }
Source:
<code>public void swipeFromPointToPoint(int startX, int startY, int endX, int endY, int duration, int waitAfter) { startX = (int)((startX / 100f) * appNativeWidth); startY = (int)(((startY / 100f) * appNativeHeight) + taskbarNativeHeight); endX = (int)((endX / 100f) * appNativeWidth); endY = (int)(((endY / 100f) * appNativeHeight) + taskbarNativeHeight); if (mobileDriver.getContext() != "NATIVE_APP") { mobileDriver.context("NATIVE_APP"); } try { mobileDriver.swipe(startX, startY, endX, endY, duration); <START> } catch (Exception e) <END> try { Thread.sleep(waitAfter); } catch (Exception e) if (mobileDriver.getContext() != "WEBVIEW_1") { mobileDriver.context("WEBVIEW_1"); } }</code><technical_language>Please a more specific Exception try block is catching. Also, please throw exception log exception in catch block</technical_language>

Target:
public void swipeFromPointToPoint(int startX, int startY, int endX, int endY, int duration, int waitAfter) { String methodName = "swipeFromPointToPoint"; startX = (int)((startX / 100f) * appNativeWidth); startY = (int)(((startY / 100f) * appNativeHeight) + taskbarNativeHeight); endX = (int)((endX / 100f) * appNativeWidth); endY = (int)(((endY / 100f) * appNativeHeight) + taskbarNativeHeight); switchToContext(CONTEXT_NATIVE_APP, methodName); mobileDriver.swipe(startX, startY, endX, endY, duration); waitForFinish(waitAfter, methodName); switchToContext(CONTEXT_WEBVIEW_1, methodName); }
Source:
<code>public void setNamedParameters(Map<String, Object> params) { <START> if (params != null) params.forEach(this.namedParameters::put); <END> }</code><technical_language>Is forEach putAll? I suppose need care of case params null. if (params == null) { namedParameters.clear(); } else { namedParameters.putAll(params); }</technical_language>

Target:
public void setNamedParameters(Map<String, Object> params) { if (params == null) { namedParameters.clear(); } else { namedParameters.putAll(params); } }
Source:
<code>public boolean supports(final JEEContext context) { val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); <START> val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); <END> return StringUtils.isNotBlank(token) && StringUtils.isNotBlank(clientId); }</code><technical_language>If token is blank need check/fetch client-id. Return false immediately, marginally performance</technical_language>

Target:
public boolean supports(final JEEContext context) { val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); if (StringUtils.isBlank(token)) { return false; } val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); return StringUtils.isNotBlank(clientId); }
Source:
<code>public Properties getProperties() { List<Element> elements = getElements( "*" ); Properties result = new Properties(); for ( Element e : elements ) { Node value = e.getFirstChild(); result.setProperty( e.getNodeName(), (value == null ? "" : e.getFirstChild().getNodeValue() ) ); } for ( String key : result.stringPropertyNames() ) { <START> if ( result.getProperty( key ).startsWith( "${" ) ) <END> { result.setProperty( key, getValue( result, key ) ); } } return result; }</code><technical_language>Try: String = getPomView().resolveExpressions(result.getProperty(key)); //resolves maven expressions</technical_language>

Target:
public Properties getProperties() { List<Element> elements = getElements( "*" ); Properties result = new Properties(); for ( Element e : elements ) { Node value = e.getFirstChild(); result.setProperty( e.getNodeName(), (value == null ? "" : getPomView().resolveExpressions( e.getFirstChild().getNodeValue() ) ) ); } return result; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { <START> wasExternal = savedInstanceState.getBoolean(WAS_EXTERNAL_KEY); <END> loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); } if (finishIfNotRoot()) { return; } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); sessionNavigator = new SessionNavigator(this); formAndDataSyncer = new FormAndDataSyncer(this); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); }</code><technical_language>If set wasExternal remove processFromExternalLaunch</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); } if (finishIfNotRoot()) { return; } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); sessionNavigator = new SessionNavigator(this); formAndDataSyncer = new FormAndDataSyncer(this); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); }
Source:
<code>public void setSourceContainers(ISourceContainer[] containers) { synchronized (this) { List<ISourceContainer> list = Arrays.asList(containers); ISourceContainer[] old = getSourceContainers(); for (ISourceContainer <START> o : <END> old) { if (!list.contains(o)) { o.dispose(); } } fSourceContainers = containers; for (ISourceContainer container : containers) { container.init(this); } } fResolvedElements = null; ISourceLookupParticipant[] participants = getParticipants(); for (ISourceLookupParticipant participant : participants) { participant.sourceContainersChanged(this); } }</code><technical_language>rename container</technical_language>

Target:
public void setSourceContainers(ISourceContainer[] containers) { synchronized (this) { List<ISourceContainer> list = Arrays.asList(containers); ISourceContainer[] old = getSourceContainers(); for (ISourceContainer container : old) { if (!list.contains(container)) { container.dispose(); } } fSourceContainers = containers; for (ISourceContainer container : containers) { container.init(this); } } fResolvedElements = null; ISourceLookupParticipant[] participants = getParticipants(); for (ISourceLookupParticipant participant : participants) { participant.sourceContainersChanged(this); } }
Source:
<code>public void undo() { <START> if (fbType instanceof BasicFBType) { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); } <END> }</code><technical_language>this shows algorithm list moved base fb. change alg type work for siimple fbs</technical_language>

Target:
public void undo() { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); }
Source:
<code><START> public TopologyInfo getTopologyInfoWithOpts(String id, GetInfoOptions options) throws NotAliveException, AuthorizationException, <END> TException { return nimbus.getTopologyInfoWithOpts(id, options); }</code><technical_language>NotAliveException, AuthorizationException removed</technical_language>

Target:
public TopologyInfo getTopologyInfoWithOpts(String id, GetInfoOptions options) throws TException { return nimbus.getTopologyInfoWithOpts(id, options); }
Source:
<code>public void testUnassignServer() { FirewallPolicy result = firewallPolicyApi().unassignServerIp(currentFirewallPolicy.id(), currentServer.ips().get(0).id()); assertNotNull(result); <START> assertEquals(result.id(), currentFirewallPolicy.id()); <END> }</code><technical_language>verify unassigned ip is longer there</technical_language>

Target:
public void testUnassignServer() { FirewallPolicy result = firewallPolicyApi().unassignServerIp(currentFirewallPolicy.id(), currentServer.ips().get(0).id()); assertNotNull(result); assertEquals(result.serverIps().size(), 0); }
Source:
<code>public void addGeneratedProfiles(String expId, String folderPath, String inputFileName, String metaData, String grVersion, String uploader, boolean isPrivate) throws SQLException, IOException { Experiment e = expMethods.getExperiment(expId); if (e == null) { throw new IOException(expId + " does not exist."); } Genome g = genMethods.getGenomeRelease(grVersion); if (g == null) { throw new IOException("Invalid Genome Release! " + grVersion + " does not exist"); } File profileFolder = new File(folderPath); if (!profileFolder.exists()) { throw new IOException("There are no profiles in this folder!"); } for (File f : profileFolder.listFiles()) { if (!f.getName().equals(inputFileName)) { String checkSumMD5; long fileSize; try (FileInputStream is = new FileInputStream(f)) { checkSumMD5 = DigestUtils.md5Hex(is); } fileSize = f.length(); fileMethods.addGeneratedFile(e.getID(), FileTuple.PROFILE, f.getPath(), inputFileName, metaData, uploader, isPrivate, grVersion, checkSumMD5, fileSize); } } <START> } <END></code><technical_language>do fileMethods.addGeneratedFile(e.getID(), FileTuple.PROFILE, f.getPath(), inputFileName, metaData, uploader, isPrivate, grVersion, checkSumMD5, f.length()); unnecessary declaration initialization</technical_language>

Target:
public void addGeneratedProfiles(String expId, String folderPath, String inputFileName, String metaData, String grVersion, String uploader, boolean isPrivate) throws SQLException, IOException { Experiment e = expMethods.getExperiment(expId); if (e == null) { throw new IOException(expId + " does not exist."); } Genome g = genMethods.getGenomeRelease(grVersion); if (g == null) { throw new IOException("Invalid Genome Release! " + grVersion + " does not exist"); } File profileFolder = new File(folderPath); if (!profileFolder.exists()) { throw new IOException("There are no profiles in this folder!"); } for (File f : profileFolder.listFiles()) { if (!f.getName().equals(inputFileName)) { String checkSumMD5; try (FileInputStream is = new FileInputStream(f)) { checkSumMD5 = DigestUtils.md5Hex(is); } fileMethods.addGeneratedFile(e.getID(), FileTuple.PROFILE, f.getPath(), inputFileName, metaData, uploader, isPrivate, grVersion, checkSumMD5, f.length()); } } }
Source:
<code>public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters, CommandContext commandContext) { try { Constructor<CommandBase<? extends VdcActionParametersBase>> constructor = <START> commandContext != null ? findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass(), commandContext.getClass()) : <END> findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass()); CommandBase<P> cmd = (CommandBase<P>) constructor.newInstance(new Object[] { parameters }); Injector.injectMembers(cmd); return cmd; } catch (InvocationTargetException ex) { log.error("Error in invocating CTOR of command " + action.name() + ". Exception is ", ex); return null; } catch (Exception ex) { log.error("An exception has occured while trying to create a command object for command " + action.name(), ex); return null; } }</code><technical_language>mind reversing condition ? (commandContex == null ? ... : ..</technical_language>

Target:
public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters, CommandContext commandContext) { try { CommandBase<P> result = null; if (commandContext == null) { result = (CommandBase<P>)findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass()).newInstance(parameters); } else { result = (CommandBase<P>) findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass(), commandContext.getClass()).newInstance(parameters, commandContext); } Injector.injectMembers(result); return result; } catch (InvocationTargetException ex) { log.error("Error in invocating CTOR of command " + action.name() + ". Exception is ", ex); return null; } catch (Exception ex) { log.error("An exception has occured while trying to create a command object for command " + action.name(), ex); return null; } }
Source:
<code>protected void onCancelled() { super.onCancelled(); if(wasKeyLoggedIn) { <START> CommCareApplication._().getSession().startLogout(); <END> } }</code><technical_language>Leaving a note for this. datapull task "login" ops more seating a user DB "logging in", this equivalent. evaluate</technical_language>

Target:
protected void onCancelled() { super.onCancelled(); if(wasKeyLoggedIn) { try { CommCareApplication._().getSession().startLogout(); } catch (SessionUnavailableException e) { } } }
Source:
<code>public View getView(Context context) { view = LayoutInflater.from(context).inflate(getViewResource(), null); BrickViewProvider.setAlphaOnView(view, alphaValue); final Brick instance = this; int checkboxVisibility = View.GONE; boolean enabled = true; boolean isChecked = false; if (checkbox != null) { checkboxVisibility = checkbox.getVisibility(); enabled = checkbox.isEnabled(); isChecked = checkbox.isChecked(); } checkbox = view.findViewById(R.id.brick_checkbox); checkbox.setChecked(isChecked); checkbox.setVisibility(checkboxVisibility); checkbox.setEnabled(enabled); checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { <START> adapter.handleCheck(instance, ((CheckBox) view).isChecked()); <END> } }); return view; }</code><technical_language>BrickBaseType.this instead of creating a local variable</technical_language>

Target:
public View getView(Context context) { view = LayoutInflater.from(context).inflate(getViewResource(), null); BrickViewProvider.setAlphaOnView(view, alphaValue); int checkboxVisibility = View.GONE; boolean enabled = true; boolean isChecked = false; if (checkbox != null) { checkboxVisibility = checkbox.getVisibility(); enabled = checkbox.isEnabled(); isChecked = checkbox.isChecked(); } checkbox = view.findViewById(R.id.brick_checkbox); checkbox.setChecked(isChecked); checkbox.setVisibility(checkboxVisibility); checkbox.setEnabled(enabled); checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adapter.handleCheck(BrickBaseType.this, ((CheckBox) view).isChecked()); } }); return view; }
Source:
<code>public void mercury_navigation_navigationElementsAnonymousUser() { init(); topBar.openNavigation(); Assertion.assertTrue(navigation.isUserAvatarVisible()); Assertion.assertFalse(navigation.isUserProfileLinkVisible()); <START> Assertion.assertFalse(navigation.isLogoutLinkVisible()); <END> }</code><technical_language>check if sign in | register visible? :)</technical_language>

Target:
public void mercury_navigation_navigationElementsAnonymousUser() { init(); topBar.openNavigation(); Assertion.assertTrue(navigation.isUserAvatarVisible()); Assertion.assertFalse(navigation.isUserProfileLinkVisible()); Assertion.assertFalse(navigation.isLogoutLinkVisible()); Assertion.assertEquals(navigation.getNavigationHeaderText(), "Sign In | Register"); }
Source:
<code>private boolean isDelete(Conflict conflict) { <START> return StringUtils.equalsIgnoreCase(conflict.getOperationKind().toString(), "delete"); <END> }</code><technical_language>suggestion return OperationKind.DELETE == conflict.getOperationKind());</technical_language>

Target:
private boolean isDelete(Conflict conflict) { return OperationKind.DELETE == conflict.getOperationKind(); }
Source:
<code>public Number nextValue(EmbeddedCacheManager cacheManager, NextValueRequest request) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager ); String counterName = ( IdSourceKeyMetadata.IdSourceType.SEQUENCE.equals( request.getKey().getMetadata().getType() ) ) ? request.getKey().getTable() : request.getKey().getColumnValue(); if ( !counterManager.isDefined( counterName ) ) { boolean definedByCurrentThread = counterManager.defineCounter( counterName, CounterConfiguration.builder( CounterType.UNBOUNDED_STRONG ) .initialValue( request.getInitialValue() ) .storage( Storage.VOLATILE ) .build() ); if ( definedByCurrentThread ) { <START> return new Long( request.getInitialValue() ); <END> } } StrongCounter strongCounter = counterManager.getStrongCounter( counterName ); try { return strongCounter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { throw new HibernateException( "Interrupting Operation " + e.getMessage(), e ); } }</code><technical_language>Long.valueOf(...)</technical_language>

Target:
public Number nextValue(EmbeddedCacheManager cacheManager, NextValueRequest request) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager ); String counterName = ( IdSourceKeyMetadata.IdSourceType.SEQUENCE.equals( request.getKey().getMetadata().getType() ) ) ? request.getKey().getTable() : request.getKey().getColumnValue(); if ( !counterManager.isDefined( counterName ) ) { boolean definedByCurrentThread = counterManager.defineCounter( counterName, CounterConfiguration.builder( CounterType.UNBOUNDED_STRONG ) .initialValue( request.getInitialValue() ) .storage( Storage.VOLATILE ) .build() ); if ( definedByCurrentThread ) { return Long.valueOf( request.getInitialValue() ); } } StrongCounter strongCounter = counterManager.getStrongCounter( counterName ); try { return strongCounter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { String message = "Exception while incrementing the sequence " + counterName ; log.error( message ); throw new HibernateException( message + " : " + e.getMessage(), e ); } }
Source:
<code>public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); <START> final ProducerRecord<String,byte[]> record = new ProducerRecord<>(topic, module.marshal(message)); <END> while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); break; } catch (ExecutionException e) { LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic, e); } } } }</code><technical_language>suggestion final ProducerRecord<String, byte[]> record = new ProducerRecord<>(topic, module.marshal(message));</technical_language>

Target:
public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); final ProducerRecord<String, String> record = new ProducerRecord<>(topic, module.marshal(message)); while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic); } } } }
Source:
<code>public void testTryLockWithTimeoutAfterLockWithSmallTimeout() throws Throwable { assertTrue(await(lock.tryLock())); CompletableFuture<Boolean> tryLock = lock.tryLock(1, TimeUnit.NANOSECONDS); <START> TimeUnit.NANOSECONDS.sleep(1); <END> await(lock.unlock()); assertFalse(await(tryLock)); }</code><technical_language>suggestion do assertFalse(await(tryLock)); await(lock.unlock()); later, other delays</technical_language>

Target:
public void testTryLockWithTimeoutAfterLockWithSmallTimeout() throws Throwable { assertTrue(await(lock.tryLock())); assertFalse(await(lock.tryLock(1, TimeUnit.NANOSECONDS))); }
Source:
<code>public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for of block size at address {}, using options: {}", blockId, blockSize, address, options); <START> if (!address.getContainerHost().equals("")) { <END> String containerName = address.getContainerHost(); LOG.debug("Worker is in a container. Replace host with container host {}", address.getHost(), containerName); address.setHost(containerName); } return BlockOutStream.create(mContext, blockId, blockSize, address, options); }</code><technical_language>this redundant translation avoided change in NetworkAddressUtils</technical_language>

Target:
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for of block size at address {}, using options: {}", blockId, blockSize, address, options); return BlockOutStream.create(mContext, blockId, blockSize, address, options); }
Source:
<code>public static void beforeAll() throws Exception { com.cloudant.client.api.Replication r = account.replication(); <START> r.source(CloudantClientHelper.getReplicationSourceUrl("animaldb")); <END> r.createTarget(true); r.target(dbResource.getDbURIWithUserInfo()); r.trigger(); }</code><technical_language>a bit tidier static imports</technical_language>

Target:
public static void beforeAll() throws Exception { com.cloudant.client.api.Replication r = account.replication(); r.source(getReplicationSourceUrl("animaldb")); r.createTarget(true); r.target(dbResource.getDbURIWithUserInfo()); r.trigger(); }
Source:
<code>public static URL[] getURLs(String value, Bundle definingBundle) { if (value == null) { <START> return null; <END> } StringTokenizer tokens = new StringTokenizer(value, ","); List<URL> array = new ArrayList<>(10); while (tokens.hasMoreTokens()) { array.add(getUrl(tokens.nextToken().trim(), definingBundle)); } return (URL[]) array.toArray(new URL[array.size()]); }</code><technical_language>returning null is bad, returng null instead of array/collection is worse</technical_language>

Target:
private static List<URL> getURLs(String value, Bundle definingBundle) { if (value == null) { return Collections.emptyList(); } StringTokenizer tokens = new StringTokenizer(value, ","); List<URL> array = new ArrayList<>(10); while (tokens.hasMoreTokens()) { Optional<URL> urlToken = getUrl(tokens.nextToken().trim(), definingBundle); if (urlToken.isPresent()) { array.add(urlToken.get()); } } return array; }
Source:
<code>public void delVirtualPortMapping(UUID hostIdentifier, UUID portId) throws StateAccessException, SerializationException { String virtualMappingPath = paths.getHostVrnPortMappingPath(hostIdentifier, portId); List<Op> ops = new ArrayList<>(); if (zk.exists(virtualMappingPath)) { ops.add(zk.getDeleteOp(virtualMappingPath)); PortConfig port = portZkManager.get(portId); if <START> (port.getHostId().equals(hostIdentifier)) <END> { ops.add(getMapUpdatePortOp(port, portId, null, null)); } zk.multi(ops); } }</code><technical_language>I guess port is null here, "hostId"? if is null, this is a NPE</technical_language>

Target:
public void delVirtualPortMapping(UUID hostIdentifier, UUID portId) throws StateAccessException, SerializationException { String virtualMappingPath = paths.getHostVrnPortMappingPath(hostIdentifier, portId); List<Op> ops = new ArrayList<>(); if (zk.exists(virtualMappingPath)) { ops.add(zk.getDeleteOp(virtualMappingPath)); PortConfig port = portZkManager.get(portId); if (port.getHostId() != null && port.getHostId().equals(hostIdentifier)) { ops.add(getMapUpdatePortOp(port, portId, null, null)); } zk.multi(ops); } }
Source:
<code>public void createCartInStore(){ <START> StoreFixtures.withStore(client(), store -> { <END> final CartDraft cartDraft = CartDraft.of(EUR).withCountry(DE); final Cart cart = client().executeBlocking(CartInStoreCreateCommand.of(store.getKey(), cartDraft)); assertThat(cart).isNotNull(); assertThat(cart.getStore()).isNotNull(); assertThat(cart.getStore().getKey()).isEqualTo(store.getKey()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }</code><technical_language>nice a static import - more consistent other code</technical_language>

Target:
public void createCartInStore(){ withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withCountry(DE); final Cart cart = client().executeBlocking(CartInStoreCreateCommand.of(store.getKey(), cartDraft)); assertThat(cart).isNotNull(); assertThat(cart.getStore()).isNotNull(); assertThat(cart.getStore().getKey()).isEqualTo(store.getKey()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }
Source:
<code>public float getBlockLocalityIndex(String host) { <START> return (float) getBlocksLocalityWeightInternal(host, e -> e.weight) <END> / (float) uniqueBlocksTotalWeight; }</code><technical_language>method reference here: getBlocksLocalityWeightInternal(host, HostAndWeight::getWeight)</technical_language>

Target:
public float getBlockLocalityIndex(String host) { if (uniqueBlocksTotalWeight == 0) { return 0.0f; } else { return (float) getBlocksLocalityWeightInternal(host, HostAndWeight::getWeight) / (float) uniqueBlocksTotalWeight; } }
Source:
<code>public void testNonExistentAuthority() { File file = buildPath(mContext.getFilesDir(), "file.test"); try { FileProvider.getUriForFile(mContext, "com.example.nonexistent", file); fail("Expected exception for non-existent authority"); } catch (IllegalArgumentException e) { <START> } <END> }</code><technical_language>Assert message contains some of expect</technical_language>

Target:
public void testNonExistentAuthority() { File file = buildPath(mContext.getFilesDir(), "file.test"); try { FileProvider.getUriForFile(mContext, "example.nonexistent", file); fail("Expected exception for non-existent authority"); } catch (IllegalArgumentException e) { assertEquals("Couldn't find meta-data for provider with authority example.nonexistent", e.getMessage()); } }
Source:
<code>public void testErrorForwarding() throws Exception { new Context() {{ runTest(() -> { final Exception testException = new Exception("test Exeption"); <START> testingLeaderRetrievalDriver.getFatalErrorHandler().onFatalError(testException); <END> assertThat(testingListener.getError().getMessage(), containsString(testException.getMessage())); }); }}; }</code><technical_language>I expose onFatalError testingLeaderRetrievalDriver assuming this is a testing implementation</technical_language>

Target:
public void testErrorForwarding() throws Exception { new Context() {{ runTest(() -> { final Exception testException = new Exception("test exception"); testingLeaderRetrievalDriver.onFatalError(testException); testingListener.waitForError(timeout); assertThat(testingListener.getError(), FlinkMatchers.containsCause(testException)); }); }}; }