auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, String> getTraceProperties() <START> { <END> for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return null; }</code><technical_language>{ line</technical_language>

Target:
private Map<String, String> getTraceProperties() { for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }
Source:
<code>public String toString() { return "ServiceDiscoveryEvent{" + "type=" + type + ", groupId='" + groupId + '\'' + ", serviceEndpoint=" + Optional.ofNullable(serviceEndpoint) .map(ServiceEndpoint::id) .orElse(null) + ", serviceEndpoints=" + serviceEndpoints.stream() <START> .map(se -> se.id() + "( " + se.address() + ")") <END> .collect(Collectors.joining(",", "[", "]")) + '}'; }</code><technical_language>in format ID@ADDRESS</technical_language>

Target:
public String toString() { return "ServiceDiscoveryEvent{" + "type=" + type + ", groupId='" + groupId + '\'' + ", serviceEndpoint=" + Optional.ofNullable(serviceEndpoint) .map(ServiceEndpoint::id) .orElse(null) + ", serviceEndpoints=" + serviceEndpoints.stream() .map(se -> se.id() + "@" + se.address()) .collect(Collectors.joining(",", "[", "]")) + '}'; }
Source:
<code>public static void main(String[] args) throws Exception { <START> String in = args[0], out = args[1]; <END> LogSource source = new FileLogSource(new File(in)); try (Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)))) { FlamegraphData data = FlamegraphCollector.readFlamegraph(source); data.writeTo(output); } }</code><technical_language>If people provide commandline arguments nice a message explaining be</technical_language>

Target:
public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.print( "Usage: java com.insightfullogic.honest_profiler.ports.Flamegraph <profile.hpl> <profile.txt>\n" + "\n" + "The output needs to be processed with the tools at <LINK_0> to produce the actual flamegraph\n"); System.exit(1); } String in = args[0], out = args[1]; LogSource source = new FileLogSource(new File(in)); try (Writer output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)))) { FlamegraphData data = FlamegraphCollector.readFlamegraph(source); data.writeTo(output); } }
Source:
<code>public void run() { try { final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); final String taskPath = JOINER.join(config.getTaskPath(), workerId, taskId); cf.delete().guaranteed().forPath(statusPath); cf.delete().guaranteed().forPath(taskPath); } catch (Exception e) { <START> log.warn("Tried to delete a path that didn't exist! Must've gone away already!"); <END> } }</code><technical_language>If deleter for statusPath throws exception, taskPath exists, ok leaving task path garbage in ZK</technical_language>

Target:
public void run() { try { final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); cf.delete().guaranteed().forPath(statusPath); } catch (Exception e) { log.warn("Tried to delete a status path that didn't exist! Must've gone away already?"); } try { final String taskPath = JOINER.join(config.getTaskPath(), workerId, taskId); cf.delete().guaranteed().forPath(taskPath); } catch (Exception e) { log.warn("Tried to delete a task path that didn't exist! Must've gone away already?"); } }
Source:
<code>private void updateVmStatistics() { <START> if (getVdsManager().isTimeToRefreshStatistics()) { <END> dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } }</code><technical_language>shouldnt this vmRefresher.timeToRefresh()</technical_language>

Target:
protected void updateVmStatistics() { if (vdsmVm.getVmStatistics() != null) { dbVm.updateRunTimeStatisticsData(vdsmVm.getVmStatistics(), dbVm); saveStatistics(); saveVmInterfaces(); updateInterfaceStatistics(); updateVmNumaNodeRuntimeInfo(); for (DiskImageDynamic diskImageDynamic : vdsmVm.getVmDynamic().getDisks()) { vmsMonitoring.addDiskImageDynamicToSave(new Pair<>(dbVm.getId(), diskImageDynamic)); } } }
Source:
<code>public double determinant() { if (rows != columns) { throw new IllegalStateException("Can't compute determinant for " + "non-square matrix."); } if (rows == 0) { return 0.0; } else if (rows == 1) { return get(0, 0); } else if (rows == 2) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } else if (rows == 3) { return get(0, 0) * get(1, 1) * get(2, 2) + get(0, 1) * get(1, 2) * get(2, 0) + get(0, 2) * get(1, 0) * get(2, 1) - get(0, 2) * get(1, 1) * get(2, 0) - get(0, 1) * get(1, 0) * get(2, 2) - get(0, 0) * get(1, 2) * get(2, 1); } <START> <END> if (rows < 0) { return determinantByCrout(); } else { return determinantByLUDecomposition(); } }</code><technical_language>Is determinantByCrout disabled default</technical_language>

Target:
public double determinant() { if (rows != columns) { throw new IllegalStateException("Can't compute determinant for " + "non-square matrix."); } if (rows == 0) { return 0.0; } else if (rows == 1) { return get(0, 0); } else if (rows == 2) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } else if (rows == 3) { return get(0, 0) * get(1, 1) * get(2, 2) + get(0, 1) * get(1, 2) * get(2, 0) + get(0, 2) * get(1, 0) * get(2, 1) - get(0, 2) * get(1, 1) * get(2, 0) - get(0, 1) * get(1, 0) * get(2, 2) - get(0, 0) * get(1, 2) * get(2, 1); } Matrix lup[] = decompose(Matrices.LU_DECOMPOSITOR); Matrix u = lup[Matrices.LU_U]; Matrix p = lup[Matrices.LU_P]; double result = u.diagonalProduct(); int permutations[] = new int[p.rows()]; for (int i = 0; i < p.rows(); i++) { for (int j = 0; j < p.columns(); j++) { if (p.get(i, j) > 0.0) { permutations[i] = j; break; } } } int sign = 1; for (int i = 0; i < permutations.length; i++) { for (int j = i + 1; j < permutations.length; j++) { if (permutations[j] < permutations[i]) { sign *= -1; } } } return sign * result; }
Source:
<code>private void printMacroData(String eventName, String name, Map<String, String> parameters, String content, boolean isInline) { StringBuilder parametersBuffer = new StringBuilder(); for (Iterator<Map.Entry<String, String>> paramsIt = parameters.entrySet().iterator(); paramsIt.hasNext();) { Map.Entry<String, String> entry = paramsIt.next(); <START> parametersBuffer.append(entry.getKey()).append(String.valueOf('=')).append(entry.getValue()); <END> if (paramsIt.hasNext()) { parametersBuffer.append(String.valueOf('|')); } } StringBuilder macroBuffer = new StringBuilder(); macroBuffer.append(eventName); macroBuffer.append(isInline ? "Inline" : "Standalone"); macroBuffer.append(" ["); macroBuffer.append(name); macroBuffer.append(String.valueOf(']')); macroBuffer.append(" ["); macroBuffer.append(parametersBuffer); macroBuffer.append(String.valueOf(']')); if (content != null) { macroBuffer.append(" ["); macroBuffer.append(content); macroBuffer.append(String.valueOf(']')); } getPrinter().println(macroBuffer.toString()); }</code><technical_language>This is this Sonar issue is about. point is append(char) instead of append(String), need trough String.valueOf</technical_language>

Target:
private void printMacroData(String eventName, String name, Map<String, String> parameters, String content, boolean isInline) { StringBuilder parametersBuffer = new StringBuilder(); for (Iterator<Map.Entry<String, String>> paramsIt = parameters.entrySet().iterator(); paramsIt.hasNext();) { Map.Entry<String, String> entry = paramsIt.next(); parametersBuffer.append(entry.getKey()).append('=').append(entry.getValue()); if (paramsIt.hasNext()) { parametersBuffer.append('|'); } } StringBuilder macroBuffer = new StringBuilder(); macroBuffer.append(eventName); macroBuffer.append(isInline ? "Inline" : "Standalone"); macroBuffer.append(" ["); macroBuffer.append(name); macroBuffer.append(']'); macroBuffer.append(" ["); macroBuffer.append(parametersBuffer); macroBuffer.append(']'); if (content != null) { macroBuffer.append(" ["); macroBuffer.append(content); macroBuffer.append(']'); } getPrinter().println(macroBuffer.toString()); }
Source:
<code>public void shouldNotFailEmptyChecks() throws Exception { GHCommitPointer commitPtr = mock(GHCommitPointer.class); when(local.getPulls()).thenReturn(ImmutableMap.of(3, localPR)); when(localPR.getHeadSha()).thenReturn("this is not the sha you are looking for"); when(remotePR.getNumber()).thenReturn(3); when(remotePR.getState()).thenReturn(GHIssueState.OPEN); when(remotePR.getHead()).thenReturn(commitPtr); when(trigger.getEvents()).thenReturn(Collections.<GitHubPREvent>emptyList()); final GitHubPRCause cause = toGitHubPRCause(local, tlRule.getListener(), trigger) .apply(remotePR); <START> assertThat(cause, nullValue()); <END> }</code><technical_language>![MAJOR](<LINK_1> Add a message this assertion. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void shouldNotFailEmptyChecks() throws Exception { final GitHubPRCause cause = toGitHubPRCause(local, tlRule.getListener(), trigger) .apply(remotePR); assertThat(cause, nullValue()); }
Source:
<code><START> public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { <END> if (rest != null && rest.isEnableCors()) { response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add( "Access-Control-Allow-Headers", "origin, content-type, accept, authorization" ); response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } }</code><technical_language>I remove throws IOException</technical_language>

Target:
public void filter(ContainerRequestContext request, ContainerResponseContext response) { if (rest != null && rest.isEnableCors()) { response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD"); } }
Source:
<code>public void testParsingLimits() throws Exception { for (Map.Entry<String, Long> e : s_validLimits.entrySet()) { long lim = RetentionPolicyMgr.parseByteLimit(e.getKey()); assertEquals(lim, e.getValue().longValue()); } for (String limStr : s_invalidLimits) { try { long lim = RetentionPolicyMgr.parseByteLimit(limStr); <START> assertNull(limStr); <END> } catch (RetentionLimitException expected) { ; } } }</code><technical_language>get this statement. So, add a fail() statement here</technical_language>

Target:
public void testParsingLimits() throws Exception { for (Map.Entry<String, Long> e : s_validLimits.entrySet()) { long lim = RetentionPolicyMgr.parseByteLimit(e.getKey()); assertEquals(lim, e.getValue().longValue()); } for (String limStr : s_invalidLimits) { try { long lim = RetentionPolicyMgr.parseByteLimit(limStr); fail(); } catch (RetentionLimitException expected) { ; } } }
Source:
<code>protected void notifyAccountUpdateConsumers(Collection<Account> updatedAccounts, boolean isCalledFromListener) { if (updatedAccounts.size() > 0) { logger.info("Received updates for accounts. Received from listener={}. Accounts={}", updatedAccounts.size(), <START> isCalledFromListener, updatedAccounts); <END> if (isCalledFromListener) { accountServiceMetrics.accountUpdatesCapturedByScheduledUpdaterCount.inc(); } for (Consumer<Collection<Account>> accountUpdateConsumer : accountUpdateConsumers) { long startTime = System.currentTimeMillis(); try { accountUpdateConsumer.accept(Collections.unmodifiableCollection(updatedAccounts)); long consumerExecutionTimeInMs = System.currentTimeMillis() - startTime; logger.trace("Consumer={} has been notified for account change, took ms", accountUpdateConsumer, consumerExecutionTimeInMs); accountServiceMetrics.accountUpdateConsumerTimeInMs.update(consumerExecutionTimeInMs); } catch (Exception e) { logger.error("Exception occurred when notifying accountUpdateConsumer={}", accountUpdateConsumer, e); } } } else { logger.debug("HelixAccountService is updated with 0 updated account"); } }</code><technical_language>this updatedAccounts hold account info? If yes, end printing thousands of containers here. print account id (as previous code did) change this DEBUG level</technical_language>

Target:
protected void notifyAccountUpdateConsumers(Collection<Account> updatedAccounts, boolean isCalledFromListener) { if (updatedAccounts.size() > 0) { logger.info("Received updates for accounts. Received from listener={}. Account IDs={}", updatedAccounts.size(), isCalledFromListener, updatedAccounts.stream().map(Account::getId).collect(Collectors.toList())); if (isCalledFromListener) { accountServiceMetrics.accountUpdatesCapturedByScheduledUpdaterCount.inc(); } for (Consumer<Collection<Account>> accountUpdateConsumer : accountUpdateConsumers) { long startTime = System.currentTimeMillis(); try { accountUpdateConsumer.accept(Collections.unmodifiableCollection(updatedAccounts)); long consumerExecutionTimeInMs = System.currentTimeMillis() - startTime; logger.trace("Consumer={} has been notified for account change, took ms", accountUpdateConsumer, consumerExecutionTimeInMs); accountServiceMetrics.accountUpdateConsumerTimeInMs.update(consumerExecutionTimeInMs); } catch (Exception e) { logger.error("Exception occurred when notifying accountUpdateConsumer={}", accountUpdateConsumer, e); } } } else { logger.debug("HelixAccountService is updated with 0 updated account"); } }
Source:
<code>protected void addNewProvidedObjects(List<String> newPortfolio, List<String> previousPortfolio, Set<E> parsedObjects) { List<ProviderChangeListener<E>> snapshot = null; synchronized (listeners) { snapshot = new LinkedList<ProviderChangeListener<E>>(listeners); } for (E parsedObject : parsedObjects) { String uid = getUID(parsedObject); <START> E oldelement = providedObjectsHolder.get(uid); <END> if (oldelement != null && !previousPortfolio.contains(uid)) { logger.warn( String.format("%s with UID \"%s\" already exists! Failed to add a second with the same UID!", parsedObject.getClass().getName(), uid)); continue; } else { newPortfolio.add(uid); providedObjectsHolder.put(uid, parsedObject); for (ProviderChangeListener<E> listener : snapshot) { if (oldelement == null) { listener.added((Provider<E>) this, parsedObject); } else { listener.updated((Provider<E>) this, oldelement, parsedObject); } } } } }</code><technical_language>change name oldElement</technical_language>

Target:
protected void addNewProvidedObjects(List<String> newPortfolio, List<String> previousPortfolio, Set<E> parsedObjects) { List<ProviderChangeListener<E>> snapshot = null; synchronized (listeners) { snapshot = new LinkedList<ProviderChangeListener<E>>(listeners); } for (E parsedObject : parsedObjects) { String uid = getUID(parsedObject); E oldElement = providedObjectsHolder.get(uid); if (oldElement != null && !previousPortfolio.contains(uid)) { logger.warn("{} with UID '{}' already exists! Failed to add a second with the same UID!", parsedObject.getClass().getName(), uid); continue; } else { newPortfolio.add(uid); providedObjectsHolder.put(uid, parsedObject); for (ProviderChangeListener<E> listener : snapshot) { if (oldElement == null) { listener.added((Provider<E>) this, parsedObject); } else { listener.updated((Provider<E>) this, oldElement, parsedObject); } } } } }
Source:
<code>public TokenCredentials extract(WebContext context) throws HttpAction, CredentialsException { final String method = context.getRequestMethod(); <START> if (HTTP_METHOD.GET.name().equals(method) && !supportGetRequest) { <END> throw new CredentialsException("GET requests not supported"); } else if (HTTP_METHOD.POST.name().equals(method) && !supportPostRequest) { throw new CredentialsException("POST requests not supported"); } final String value = context.getRequestParameter(this.parameterName); if (value == null) { return null; } return new TokenCredentials(value, clientName); }</code><technical_language>compare ignoring case</technical_language>

Target:
public TokenCredentials extract(WebContext context) throws HttpAction, CredentialsException { final String method = context.getRequestMethod(); if (HTTP_METHOD.GET.name().equalsIgnoreCase(method) && !supportGetRequest) { throw new CredentialsException("GET requests not supported"); } else if (HTTP_METHOD.POST.name().equalsIgnoreCase(method) && !supportPostRequest) { throw new CredentialsException("POST requests not supported"); } final String value = context.getRequestParameter(this.parameterName); if (value == null) { return null; } return new TokenCredentials(value, clientName); }
Source:
<code>public ScoredCandidates<Item> score( org.atlasapi.media.entity.Item subject, Set<? extends org.atlasapi.media.entity.Item> candidates, ResultDescription desc, EquivToTelescopeResults equivToTelescopeResults ) { EquivToTelescopeComponent scorerComponent = EquivToTelescopeComponent.create(); scorerComponent.setComponentName("Item Year Scorer"); DefaultScoredCandidates.Builder<Item> equivalents = DefaultScoredCandidates.fromSource(YEAR); for (Item candidate : candidates) { Score score = score(subject, candidate); <START> equivalents.addEquivalent(candidate, score); <END> scorerComponent.addComponentResult( candidate.getId(), String.valueOf(score.asDouble()) ); } equivToTelescopeResults.addScorerResult(scorerComponent); return equivalents.build(); }</code><technical_language>I get feeling this called scoredCandidates equivalents! I copied somewhere, saying</technical_language>

Target:
public ScoredCandidates<Item> score( org.atlasapi.media.entity.Item subject, Set<? extends org.atlasapi.media.entity.Item> candidates, ResultDescription desc, EquivToTelescopeResults equivToTelescopeResults ) { EquivToTelescopeComponent scorerComponent = EquivToTelescopeComponent.create(); scorerComponent.setComponentName("Item Year Scorer"); DefaultScoredCandidates.Builder<Item> scoredCandidates = DefaultScoredCandidates.fromSource(YEAR); for (Item candidate : candidates) { Score score = score(subject, candidate); scoredCandidates.addEquivalent(candidate, score); scorerComponent.addComponentResult( candidate.getId(), String.valueOf(score.asDouble()) ); } equivToTelescopeResults.addScorerResult(scorerComponent); return scoredCandidates.build(); }
Source:
<code>private void addRecipientsFromAddresses(final RecipientType recipientType, final Address... addresses) { new RecipientLoader(context, cryptoProvider, addresses) { @Override public void deliverResult(List<Recipient> result) { Recipient[] recipientArray = result.toArray(new Recipient[result.size()]); recipientView.addRecipients(recipientType, recipientArray); stopLoading(); } <START> }.startLoading(); <END> }</code><technical_language>a loader this feels hacky. easy introduce a memory leak this way</technical_language>

Target:
private void addRecipientsFromAddresses(final RecipientType recipientType, final Address... addresses) { new RecipientLoader(context, cryptoProvider, addresses) { @Override public void deliverResult(List<Recipient> result) { Recipient[] recipientArray = result.toArray(new Recipient[result.size()]); recipientMvpView.addRecipients(recipientType, recipientArray); stopLoading(); abandon(); } }.startLoading(); }
Source:
<code>AggregationBuilder bucketsAgg(final QueryFilter filter, final String interval) { DateHistogramInterval dateHistogramInterval = null; if (interval.endsWith("d")) { dateHistogramInterval = DateHistogramInterval .days(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else if (interval.endsWith("h")) { dateHistogramInterval = DateHistogramInterval .hours(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else if (interval.endsWith("m")) { dateHistogramInterval = DateHistogramInterval .hours(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else { throw new IllegalArgumentException("Please set valid interval"); } <START> System.out.println("HERE"); <END> DateHistogramAggregationBuilder agg = AggregationBuilders.dateHistogram(TIME_AGG) .field(START_TIME_FIELD) .dateHistogramInterval(dateHistogramInterval); System.out.println("HERE1" ); return AggregationBuilders.terms(EVENT_TYPE_AGG). field(RESULT_EVENT_TYPE_FIELD) .subAggregation(agg); }</code><technical_language>cleanup</technical_language>

Target:
AggregationBuilder bucketsAgg(final QueryFilter filter, final String interval) { DateHistogramInterval dateHistogramInterval = null; if (interval.endsWith("d")) { dateHistogramInterval = DateHistogramInterval .days(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else if (interval.endsWith("h")) { dateHistogramInterval = DateHistogramInterval .hours(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else if (interval.endsWith("m")) { dateHistogramInterval = DateHistogramInterval .minutes(Integer.valueOf(interval.substring(0, interval.length() - 1))); } else { throw new IllegalArgumentException("Please set valid interval"); } DateHistogramAggregationBuilder agg = AggregationBuilders.dateHistogram(TIME_AGG) .field(START_TIME_FIELD) .dateHistogramInterval(dateHistogramInterval); return AggregationBuilders.terms(EVENT_TYPE_AGG). field(RESULT_EVENT_TYPE_FIELD) .subAggregation(agg); }
Source:
<code>public void validPlatformsAndApiLevels() { <START> final AndroidSdk sdk16 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "19"); <END> }</code><technical_language>variable name is sdk16. confusing</technical_language>

Target:
public void validPlatformsAndApiLevels() { final AndroidSdk sdk19 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "19"); }
Source:
<code>public String getDomainsConfigurationEntry() { <START> StringBuilder configurationEntry = new StringBuilder(""); <END> boolean firstEntry = true; for ( Entry<String,String> currEntry: valuePerDomain.entrySet() ) { if (!firstEntry) { configurationEntry.append(domainSeperator); } else { firstEntry = false; } configurationEntry.append(currEntry.getKey()); if (currEntry.getValue() != null) { configurationEntry.append(valueSeperator).append(currEntry.getValue()); } } return configurationEntry.toString(); }</code><technical_language>empty string in constructor is redundant</technical_language>

Target:
public String getDomainsConfigurationEntry() { StringBuilder configurationEntry = new StringBuilder(); boolean firstEntry = true; for ( Entry<String,String> currEntry: valuePerDomain.entrySet() ) { if (!firstEntry) { configurationEntry.append(domainSeperator); } else { firstEntry = false; } configurationEntry.append(currEntry.getKey()); if (currEntry.getValue() != null) { configurationEntry.append(valueSeperator).append(currEntry.getValue()); } } return configurationEntry.toString(); }
Source:
<code>public void setUp() throws Exception { font = new Font(display, "Arial", 12, SWT.NORMAL); shell = new Shell(display); shell.setSize(600, 400); <START> shell.setLayout(GridLayoutFactory.fillDefaults().create()); <END> shell.setFont(font); shell.open(); }</code><technical_language>Good change... applyTo() create() attaching a control. Change to: GridLayoutFactory.fillDefaults().applyTo(shell)</technical_language>

Target:
public void setUp() throws Exception { font = new Font(display, "Arial", 12, SWT.NORMAL); shell = new Shell(display); shell.setSize(600, 400); GridLayoutFactory.fillDefaults().applyTo(shell); shell.setFont(font); shell.open(); }
Source:
<code>public void testDiscontinuousLocations() throws ExecutionException, InterruptedException { Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); try (ZKConnectionRegistry registry = new ZKConnectionRegistry(conf)) { CompletableFuture<RegionLocations> cf = new CompletableFuture<>(); List<String> znodes = Arrays.asList( new String[] { ZNodePaths.META_ZNODE_PREFIX, ZNodePaths.META_ZNODE_PREFIX + "_003" }); <START> registry.getMetaRegionLocation(cf, znodes); <END> cf.get(); } }</code><technical_language>expose this method write fake znode zk simulate discontinuous meta replicas? I do is difficult do..</technical_language>

Target:
public void testDiscontinuousLocations() throws ExecutionException, InterruptedException, IOException, KeeperException, TimeoutException { Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/" + this.name.getMethodName()); ZooKeeperProtos.MetaRegionServer pbrsr = ZooKeeperProtos.MetaRegionServer.newBuilder() .setServer(ProtobufUtil.toServerName(ServerName.valueOf("example.org,1,1"))) .setRpcVersion(HConstants.RPC_CURRENT_VERSION) .setState(RegionState.State.OPEN.convert()).build(); byte[] data = ProtobufUtil.prependPBMagic(pbrsr.toByteArray()); try (ZKWatcher zkw = new ZKWatcher(conf, this.name.getMethodName(), new Abortable() { @Override public void abort(String why, Throwable e) @Override public boolean isAborted() { return false; } })) { ZKUtil.createSetData(zkw, zkw.getZNodePaths().getZNodeForReplica(0), data); ZKUtil.createSetData(zkw, zkw.getZNodePaths().getZNodeForReplica(3), data); List<String> znodes = zkw.getMetaReplicaNodes(); assertEquals(2, znodes.size()); try (ZKConnectionRegistry registry = new ZKConnectionRegistry(conf)) { CompletableFuture<RegionLocations> cf = registry.getMetaRegionLocations(); RegionLocations locations = cf.get(60, TimeUnit.SECONDS); assertEquals(2, locations.numNonNullElements()); } } }
Source:
<code>public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils) { EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils); instance.setNonSecurePort(this.nonSecurePort); instance.setInstanceId(getDefaultInstanceId(this.env)); <START> instance.setPreferIpAddress(preferIpAddress); <END> if (this.managementPort != this.nonSecurePort && this.managementPort != 0) { if (StringUtils.hasText(this.hostname)) { instance.setHostname(this.hostname); } RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(env, "eureka.instance."); String statusPageUrlPath = relaxedPropertyResolver.getProperty("statusPageUrlPath"); String healthCheckUrlPath = relaxedPropertyResolver.getProperty("healthCheckUrlPath"); if (StringUtils.hasText(statusPageUrlPath)) { instance.setStatusPageUrlPath(statusPageUrlPath); } if (StringUtils.hasText(healthCheckUrlPath)) { instance.setHealthCheckUrlPath(healthCheckUrlPath); } String scheme = instance.getSecurePortEnabled() ? "https" : "http"; instance.setStatusPageUrl(scheme + "://" + instance.getHostname() + ":" + this.managementPort + instance.getStatusPageUrlPath()); instance.setHealthCheckUrl(scheme + "://" + instance.getHostname() + ":" + this.managementPort + instance.getHealthCheckUrlPath()); } return instance; }</code><technical_language>This get automatically set is simply a @ConfigurationProperties bean. other items set business logic performed</technical_language>

Target:
public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils) { RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(env, "eureka.instance."); String hostname = relaxedPropertyResolver.getProperty("hostname"); boolean preferIpAddress = Boolean.parseBoolean(relaxedPropertyResolver.getProperty("preferIpAddress")); EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils); instance.setNonSecurePort(this.nonSecurePort); instance.setInstanceId(getDefaultInstanceId(this.env)); instance.setPreferIpAddress(preferIpAddress); if (this.managementPort != this.nonSecurePort && this.managementPort != 0) { if (StringUtils.hasText(hostname)) { instance.setHostname(hostname); } String statusPageUrlPath = relaxedPropertyResolver.getProperty("statusPageUrlPath"); String healthCheckUrlPath = relaxedPropertyResolver.getProperty("healthCheckUrlPath"); if (StringUtils.hasText(statusPageUrlPath)) { instance.setStatusPageUrlPath(statusPageUrlPath); } if (StringUtils.hasText(healthCheckUrlPath)) { instance.setHealthCheckUrlPath(healthCheckUrlPath); } String scheme = instance.getSecurePortEnabled() ? "https" : "http"; instance.setStatusPageUrl(scheme + "://" + instance.getHostname() + ":" + this.managementPort + instance.getStatusPageUrlPath()); instance.setHealthCheckUrl(scheme + "://" + instance.getHostname() + ":" + this.managementPort + instance.getHealthCheckUrlPath()); } return instance; }
Source:
<code>default String getParam(String paramName, String defaultValue) { Objects.requireNonNull(defaultValue, "defaultValue"); <START> return params().contains(paramName) ? params().get(paramName) : defaultValue; <END> }</code><technical_language>This method is a good idea! I nitpicking, I suggest skip contains() call do a get() if null, return defaultValue? This skip MultiMap call</technical_language>

Target:
default String getParam(String paramName, String defaultValue) { Objects.requireNonNull(defaultValue, "defaultValue"); final String paramValue = params().get(paramName); return paramValue != null ? paramValue : defaultValue; }
Source:
<code><START> public void addExifCache(long objectID) { <END> if (cacheBuildCount == 0) return; hasExifCache.add(objectID); }</code><technical_language>addXXXCache methods synchronized too</technical_language>

Target:
public void addExifCache(long objectID) { synchronized (cacheLock) { if (cacheBuildCount == 0) return; hasExifCache.add(objectID); } }
Source:
<code>public List<PrestoSparkRow> get() throws InterruptedException { List<PrestoSparkRow> rows = null; synchronized (monitor) { while (buffer.isEmpty() && !finished) { monitor.wait(); } if (!buffer.isEmpty()) { rows = buffer.poll(); } if (rows != null) { <START> memoryManager.updateMemoryUsage(-getRetainedSize(rows)); <END> } } return rows; }</code><technical_language>Note memory get cleaned this batch get fully consumed PrestoSparkTaskExecutor#getNextRow. under-count 1 batch of rows. Is this acceptable</technical_language>

Target:
public List<PrestoSparkRow> get() throws InterruptedException { BufferedRows bufferedRows = null; synchronized (monitor) { while (buffer.isEmpty() && !finished) { monitor.wait(); } if (!buffer.isEmpty()) { bufferedRows = buffer.poll(); } if (bufferedRows != null) { memoryManager.updateMemoryUsage(-bufferedRows.getRetainedSizeInBytes()); } } if (bufferedRows == null) { return null; } return bufferedRows.getRows(); }
Source:
<code>private boolean setSealedReplicas(List<String> sealedReplicas) { HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); if (instanceConfig == null) { throw new IllegalStateException( "No instance config found for cluster: \"" + clusterName + "\", instance: \"" + instanceName + "\""); } <START> logger.trace("Setting the list of sealed replicas in InstanceConfig"); <END> instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); return helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }</code><technical_language>do want log list too</technical_language>

Target:
private boolean setSealedReplicas(List<String> sealedReplicas) { HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); if (instanceConfig == null) { throw new IllegalStateException( "No instance config found for cluster: \"" + clusterName + "\", instance: \"" + instanceName + "\""); } logger.trace("Setting InstanceConfig with list of sealed replicas: {}", Arrays.toString(sealedReplicas.toArray())); instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); return helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }
Source:
<code>public void testConstructAccountFromJson() throws Exception { <START> System.out.println(refAccountJson); <END> assertAccountAgainstReference(Account.fromJson(refAccountJson), true, true); }</code><technical_language>need remove this</technical_language>

Target:
public void testConstructAccountFromJson() throws Exception { assertAccountAgainstReference(Account.fromJson(refAccountJson), true, true); }
Source:
<code>private static void checkGreater(final NakadiCursor less, final NakadiCursor greater) { <START> Assert.assertTrue("Cursor " + less + " should be less then " + greater, <END> comparator.compare(less, greater) < 0); Assert.assertTrue("Cursor " + greater + " should be greater then " + less, comparator.compare(greater, less) > 0); }</code><technical_language>s/then/than/</technical_language>

Target:
private static void checkGreater(final NakadiCursor less, final NakadiCursor greater) { Assert.assertTrue("Cursor " + less + " should be less than " + greater, comparator.compare(less, greater) < 0); Assert.assertTrue("Cursor " + greater + " should be greater than " + less, comparator.compare(greater, less) > 0); }
Source:
<code>public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { DataSource pool = (DataSource) req.getServletContext().getAttribute("my-pool"); int tabCount; int spaceCount; List<Vote> recentVotes = new ArrayList<>(); try (Connection conn = pool.getConnection()) { PreparedStatement voteStmt = conn.prepareStatement( "SELECT TOP(5) candidate, time_cast FROM votes ORDER BY time_cast DESC"); ResultSet voteResults = voteStmt.executeQuery(); while (voteResults.next()) { String candidate = voteResults.getString(1); Timestamp timeCast = voteResults.getTimestamp(2); <START> recentVotes.add(new Vote(candidate.trim(), timeCast)); <END> } PreparedStatement voteCountStmt = conn.prepareStatement( "SELECT COUNT(vote_id) FROM votes WHERE candidate=?"); voteCountStmt.setString(1, "TABS"); ResultSet tabResult = voteCountStmt.executeQuery(); tabResult.next(); tabCount = tabResult.getInt(1); voteCountStmt.setString(1, "SPACES"); ResultSet spaceResult = voteCountStmt.executeQuery(); spaceResult.next(); spaceCount = spaceResult.getInt(1); } catch (SQLException ex) { throw new ServletException("Unable to successfully connect to the database. Please check the " + "steps in the README and try again.", ex); } req.setAttribute("tabCount", tabCount); req.setAttribute("spaceCount", spaceCount); req.setAttribute("recentVotes", recentVotes); req.getRequestDispatcher("/index.jsp").forward(req, resp); }</code><technical_language>feel free leave this suggestion - I refactor new Vote(... out a variable</technical_language>

Target:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { DataSource pool = (DataSource) req.getServletContext().getAttribute("my-pool"); int tabCount; int spaceCount; List<Vote> recentVotes = new ArrayList<>(); try (Connection conn = pool.getConnection()) { PreparedStatement voteStmt = conn.prepareStatement( "SELECT TOP(5) candidate, time_cast FROM votes ORDER BY time_cast DESC"); ResultSet voteResults = voteStmt.executeQuery(); while (voteResults.next()) { String candidate = voteResults.getString(1); Timestamp timeCast = voteResults.getTimestamp(2); Vote vote = new Vote(candidate.trim(), timeCast); recentVotes.add(vote); } PreparedStatement voteCountStmt = conn.prepareStatement( "SELECT COUNT(vote_id) FROM votes WHERE candidate=?"); voteCountStmt.setString(1, "TABS"); ResultSet tabResult = voteCountStmt.executeQuery(); tabResult.next(); tabCount = tabResult.getInt(1); voteCountStmt.setString(1, "SPACES"); ResultSet spaceResult = voteCountStmt.executeQuery(); spaceResult.next(); spaceCount = spaceResult.getInt(1); } catch (SQLException ex) { throw new ServletException("Unable to successfully connect to the database. Please check the " + "steps in the README and try again.", ex); } req.setAttribute("tabCount", tabCount); req.setAttribute("spaceCount", spaceCount); req.setAttribute("recentVotes", recentVotes); req.getRequestDispatcher("/index.jsp").forward(req, resp); }
Source:
<code>private boolean reserve(Resource perAllocationResource, FSSchedulerNode node, Container reservedContainer, NodeType type, SchedulerRequestKey schedulerKey) { <START> if (!reservationExceedsThreshold(node, type)) { <END> LOG.info("Making reservation: node=" + node.getNodeName() + " app_id=" + getApplicationId()); if (reservedContainer == null) { reservedContainer = createContainer(node, perAllocationResource, schedulerKey); getMetrics().reserveResource(getUser(), reservedContainer.getResource()); RMContainer rmContainer = super.reserve(node, schedulerKey, null, reservedContainer); node.reserveResource(this, schedulerKey, rmContainer); setReservation(node); } else { RMContainer rmContainer = node.getReservedContainer(); super.reserve(node, schedulerKey, rmContainer, reservedContainer); node.reserveResource(this, schedulerKey, rmContainer); setReservation(node); } return true; } return false; }</code><technical_language>Spurious change</technical_language>

Target:
private boolean reserve(Resource perAllocationResource, FSSchedulerNode node, Container reservedContainer, NodeType type, SchedulerRequestKey schedulerKey) { RMContainer nodeReservedContainer = node.getReservedContainer(); boolean reservableForThisApp = nodeReservedContainer == null || nodeReservedContainer.getApplicationAttemptId() .equals(getApplicationAttemptId()); if (reservableForThisApp &&!reservationExceedsThreshold(node, type)) { LOG.info("Making reservation: node=" + node.getNodeName() + " app_id=" + getApplicationId()); if (reservedContainer == null) { reservedContainer = createContainer(node, perAllocationResource, schedulerKey); getMetrics().reserveResource(getUser(), reservedContainer.getResource()); RMContainer rmContainer = super.reserve(node, schedulerKey, null, reservedContainer); node.reserveResource(this, schedulerKey, rmContainer); setReservation(node); } else { RMContainer rmContainer = node.getReservedContainer(); super.reserve(node, schedulerKey, rmContainer, reservedContainer); node.reserveResource(this, schedulerKey, rmContainer); setReservation(node); } return true; } return false; }
Source:
<code>@Override public void registerWorldGen(ICubicWorldServer world, GeneratorPipeline pipeline) { ServerCubeCache cubeCache = world.getCubeCache(); GeneratorStage terrain = new GeneratorStage("TERRAIN"); GeneratorStage surface = new GeneratorStage("SURFACE"); GeneratorStage features = new GeneratorStage("FEATURES"); GeneratorStage lighting = new GeneratorStage("LIGHTING"); GeneratorStage population = new GeneratorStage("POPULATION"); pipeline.addStage(terrain, new FlatTerrainProcessor(cubeCache, 5)); <START> pipeline.addStage(surface, new NullProcessor("Surface", cubeCache)); <END> pipeline.addStage(features, new NullProcessor("Features", cubeCache)); pipeline.addStage(lighting, new FirstLightProcessor(lighting, "Lighting", cubeCache, 5)); pipeline.addStage(population, new NullProcessor("Population", cubeCache)); pipeline.addStage(GeneratorStage.LIVE, null); }</code><technical_language>Stages NullProcessor safely removed. I added workaround fact stage processors exist registered</technical_language>

Target:
@Override public void registerWorldGen(ICubicWorldServer world, GeneratorPipeline pipeline) { ServerCubeCache cubeCache = world.getCubeCache(); GeneratorStage terrain = new GeneratorStage("terrain"); pipeline.addStage(terrain, new FlatTerrainProcessor(cubeCache, 5)); pipeline.addStage(GeneratorStage.LIGHTING, new FirstLightProcessor(null, "Lighting", cubeCache, 5)); }
Source:
<code>public Optional<String> getActiveSearchText() { if (stackSearch.topControl == cmpTitle) { return Optional.of(txtSearchTitle.getText()); } else if (stackSearch.topControl == cmpRBNumber) { return Optional.of(txtSearchRBNumber.getText()); } else if (stackSearch.topControl == cmpUsers) { return Optional.of(txtSearchUsers.getText()); } else { <START> return null; <END> } }</code><technical_language>This Optional.empty() null - lose benefits of Optional</technical_language>

Target:
public String getActiveSearchText() { return textSearchBox.getText(); }
Source:
<code>static private boolean rewriteUnionStmt(ParsedUnionStmt stmt) { final AtomicInteger indx = new AtomicInteger(0); final AtomicBoolean updated = new AtomicBoolean(false); stmt.m_children.stream().flatMap(c -> { if(c instanceof ParsedSelectStmt) { <START> final ParsedSelectStmt s = (ParsedSelectStmt) c; <END> if ((new MVQueryRewriter(s)).rewrite()) { updated.set(true); return Stream.of(new Pair<>(indx.getAndIncrement(), s)); } } else if (c instanceof ParsedUnionStmt) { if ((new MVQueryRewriter((ParsedUnionStmt) c)).rewrite()) { updated.set(true); } } else { assert(false); } return null; }).forEach(kv -> { final int i = kv.getFirst(); final ParsedSelectStmt sel = kv.getSecond(); assert (sel.m_tableList.size() == 1); stmt.m_tableList.set(i, sel.m_tableList.get(0)); final Table view = sel.m_tableList.get(0); stmt.m_tableAliasMap.forEach((k, v) -> { if (v.getTableName().equals(view.getMaterializer().getTypeName())) { sel.generateStmtTableScan(view); } }); }); return updated.get(); }</code><technical_language>do need atomic values...is code multi-threaded? spawning new threads planning is want do</technical_language>

Target:
static private boolean rewriteUnionStmt(ParsedUnionStmt stmt) { final AtomicInteger indx = new AtomicInteger(0); final AtomicBoolean updated = new AtomicBoolean(false); stmt.m_children.stream().flatMap(c -> { if (c instanceof ParsedSelectStmt) { final ParsedSelectStmt s = (ParsedSelectStmt) c; if ((new MVQueryRewriter(s)).rewrite()) { updated.set(true); return Stream.of(Pair.of(indx.getAndIncrement(), s)); } } else if (c instanceof ParsedUnionStmt) { if ((new MVQueryRewriter((ParsedUnionStmt) c)).rewrite()) { updated.set(true); } } else { assert(false); } return null; }).forEach(kv -> { final int i = kv.getFirst(); final ParsedSelectStmt sel = kv.getSecond(); assert (sel.m_tableList.size() == 1); stmt.m_tableList.set(i, sel.m_tableList.get(0)); final Table view = sel.m_tableList.get(0); stmt.m_tableAliasMap.forEach((k, v) -> { if (v.getTableName().equals(view.getMaterializer().getTypeName())) { sel.generateStmtTableScan(view); } }); }); return updated.get(); }
Source:
<code>public Object start(IApplicationContext context) throws Exception { long start = System.currentTimeMillis(); processArguments((String[]) context.getArguments().get("application.args")); IProvisioningAgent agent = ServiceHelper.getService(Activator.getBundleContext(), IProvisioningAgent.class); IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); IMetadataRepository repository = manager.loadRepository(uri, new NullProgressMonitor()); RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(new IMetadataRepository[] {repository}); IStatus status = repositoryAnalyzer.analyze(new NullProgressMonitor()); IStatus[] children = status.getChildren(); long time = (System.currentTimeMillis()) - start; if (status.isOK()) System.out.println("Repository Analyzer Finished succesfuly in " + time + " ms."); else System.out.println("Repository Analyzer Finished in " + time + " ms with status with errors."); for (IStatus <START> children1 : <END> children) { if (children1.isOK()) { System.out.print("[OK] "); } else { System.out.print("[Error] "); } System.out.println(children1.getMessage()); if (children1.isMultiStatus() && children1.getChildren() != null && children1.getChildren().length > 0) { IStatus[] subChildren = children1.getChildren(); for (IStatus subChildren1 : subChildren) { System.out.println(" " + subChildren1.getMessage()); } } } return IApplication.EXIT_OK; }</code><technical_language>child</technical_language>

Target:
public Object start(IApplicationContext context) throws Exception { long start = System.currentTimeMillis(); processArguments((String[]) context.getArguments().get("application.args")); IProvisioningAgent agent = ServiceHelper.getService(Activator.getBundleContext(), IProvisioningAgent.class); IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); IMetadataRepository repository = manager.loadRepository(uri, new NullProgressMonitor()); RepositoryAnalyzer repositoryAnalyzer = new RepositoryAnalyzer(new IMetadataRepository[] {repository}); IStatus status = repositoryAnalyzer.analyze(new NullProgressMonitor()); IStatus[] children = status.getChildren(); long time = (System.currentTimeMillis()) - start; if (status.isOK()) System.out.println("Repository Analyzer Finished succesfuly in " + time + " ms."); else System.out.println("Repository Analyzer Finished in " + time + " ms with status with errors."); for (IStatus child : children) { if (child.isOK()) { System.out.print("[OK] "); } else { System.out.print("[Error] "); } System.out.println(child.getMessage()); if (child.isMultiStatus() && child.getChildren() != null && child.getChildren().length > 0) { IStatus[] subChildren = child.getChildren(); for (IStatus subChild : subChildren) { System.out.println(" " + subChild.getMessage()); } } } return IApplication.EXIT_OK; }
Source:
<code>public String findCurrentLeader() { Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); final FullResponseHolder responseHolder; try { responseHolder = go(makeRequest(HttpMethod.GET, leaderRequestPath)); } catch (Exception ex) { throw new ISE(ex, "Couldn't find leader."); } if (responseHolder.getStatus().getCode() == 200) { String leaderUrl = responseHolder.getContent(); try { new URL(leaderUrl); currentKnownLeader.set(leaderUrl); return leaderUrl; } <START> catch (MalformedURLException ex) { <END> } } throw new ISE( "Couldn't find leader, failed response status is [%s] and content [%s].", responseHolder.getStatus().getCode(), responseHolder.getContent() ); }</code><technical_language>log</technical_language>

Target:
public String findCurrentLeader() { Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)); final FullResponseHolder responseHolder; try { responseHolder = go(makeRequest(HttpMethod.GET, leaderRequestPath)); } catch (Exception ex) { throw new ISE(ex, "Couldn't find leader."); } if (responseHolder.getStatus().getCode() == 200) { String leaderUrl = responseHolder.getContent(); try { URL validatedUrl = new URL(leaderUrl); currentKnownLeader.set(leaderUrl); return validatedUrl.toString(); } catch (MalformedURLException ex) { log.error(ex, "Received malformed leader url[%s].", leaderUrl); } } throw new ISE( "Couldn't find leader, failed response status is [%s] and content [%s].", responseHolder.getStatus().getCode(), responseHolder.getContent() ); }
Source:
<code>public ArrayList<cgImage> loadLogImages(int log_id) { init(); ArrayList<cgImage> logImgList = new ArrayList<cgImage>(); Cursor cursor = null; cursor = databaseRO.query( dbTableLogImages, new String[]{"_id", "log_id", "title", "url"}, "log_id = \"" + log_id + "\"", null, null, null, null, "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { final cgImage log_img = new cgImage(); log_img.title = (String)cursor.getString(cursor.getColumnIndex("title")); log_img.url = (String)cursor.getString(cursor.getColumnIndex("url")); <START> if (logImgList != null) { <END> logImgList.add(log_img); } } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return logImgList; }</code><technical_language>nan</technical_language>

Target:
public ArrayList<cgImage> loadLogImages(int log_id) { init(); ArrayList<cgImage> logImgList = new ArrayList<cgImage>(); Cursor cursor = null; cursor = databaseRO.query( dbTableLogImages, new String[]{"_id", "log_id", "title", "url"}, "log_id = \"" + log_id + "\"", null, null, null, null, "100"); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); do { final cgImage log_img = new cgImage(); log_img.title = (String)cursor.getString(cursor.getColumnIndex("title")); log_img.url = (String)cursor.getString(cursor.getColumnIndex("url")); logImgList.add(log_img); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return logImgList; }