auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setSeverUnitTestMode(ServerContextInformation contextInformation) { if (Boolean.parseBoolean(System.getenv("UNIT_TEST"))) { setUnitTestEnabled(true); contextInformation.setServerUnitTestModeEnabled(true); log.info("Synapse unit testing enabled"); String requestPort = System.getenv("UNIT_TEST_PORT"); int unitTestingAgentPort = -1; try { if (requestPort != null && !requestPort.isEmpty()) { unitTestingAgentPort = Integer.parseInt(requestPort); } else { throw new IOException("Starting TCP port can not be empty or null"); } } catch (NumberFormatException e) { log.error("Given port is not in valid format", e); <START> } catch (IOException e) { <END> log.error("Given port can not be empty or null", e); } if (unitTestingAgentPort > 1023) { UnitTestingExecutor testExecutor = UnitTestingExecutor.getExecuteInstance(); testExecutor.setServerPort(unitTestingAgentPort); testExecutor.setSynapseConfiguration(this.synapseConfig); testExecutor.start(); } else { log.error("Input a TCP port higher than 1023 to start the unit testing framework"); } } }</code><technical_language>Do need catch this exception continue logic . continue it</technical_language>

Target:
private void setSeverUnitTestMode(ServerContextInformation contextInformation) { if (Boolean.parseBoolean(System.getProperty("synapseTest"))) { setUnitTestEnabled(true); contextInformation.setServerUnitTestModeEnabled(true); log.info("Synapse unit testing server enabled"); UnitTestingExecutor testExecutor = UnitTestingExecutor.getExecuteInstance(); testExecutor.setSynapseConfiguration(this.synapseConfig); testExecutor.start(); } }
Source:
<code>public boolean reloadPageCompletion(PagePosition position) throws Exception { <START> if (pageStore != null && !pageStore.checkPageFileExists((int)position.getPageNr())) { <END> return false; } if (pageStore != null && pageStore.getCurrentPage() != null && pageStore.getCurrentPage().getPageId() == position.getPageNr()) { pageStore.forceAnotherPage(); } PageCursorInfo info = new PageCursorInfo(position.getPageNr(), position.getMessageNr(), null); info.setCompleteInfo(position); synchronized (consumedPages) { consumedPages.put(Long.valueOf(position.getPageNr()), info); } return true; }</code><technical_language>pageStore is final.. null</technical_language>

Target:
public boolean reloadPageCompletion(PagePosition position) throws Exception { if (!pageStore.checkPageFileExists((int)position.getPageNr())) { return false; } if (pageStore.getCurrentPage() != null && pageStore.getCurrentPage().getPageId() == position.getPageNr()) { pageStore.forceAnotherPage(); } PageCursorInfo info = new PageCursorInfo(position.getPageNr(), position.getMessageNr(), null); info.setCompleteInfo(position); synchronized (consumedPages) { consumedPages.put(Long.valueOf(position.getPageNr()), info); } return true; }
Source:
<code>public static synchronized void startUp() throws InterruptedException, IOException { RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); <START> String transport = System.getProperty("XD_TRANSPORT"); <END> if (application == null) { application = new SingleNodeApplication().run("--transport", StringUtils.hasText(transport) ? transport : "local", "--analytics", "redis"); integrationTestSupport = new SingleNodeIntegrationTestSupport(application); integrationTestSupport.addModuleRegistry(new ArchiveModuleRegistry("classpath:/spring-xd/xd/modules")); Bootstrap bootstrap = new Bootstrap(new String[] { "--port", randomConfigSupport.getAdminServerPort() }); shell = bootstrap.getJLineShellComponent(); } if (!shell.isRunning()) { shell.start(); } }</code><technical_language>This feels wrong: 1. set in stone (like before) 2. allow selecting a transport selected a prop, defaults coded places: in SingleNodeApplication</technical_language>

Target:
public static synchronized void startUp() throws InterruptedException, IOException { RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport(); if (application == null) { application = new SingleNodeApplication().run("--transport", "local", "--analytics", "redis"); integrationTestSupport = new SingleNodeIntegrationTestSupport(application); integrationTestSupport.addModuleRegistry(new ArchiveModuleRegistry("classpath:/spring-xd/xd/modules")); Bootstrap bootstrap = new Bootstrap(new String[] { "--port", randomConfigSupport.getAdminServerPort() }); shell = bootstrap.getJLineShellComponent(); } if (!shell.isRunning()) { shell.start(); } }
Source:
<code>public void start(ComponentContext context) { if (Framework.isTestModeSet()) { return; } for (Directory dir : getDirectories()) { try { dir.getSession().close(); } catch (Exception e) { <START> log.error(String.format("Could not open session for directory %s. Error message: %s", dir.getName(), <END> e.getMessage())); } } if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } }</code><technical_language>remove Error message log message give logger exception</technical_language>

Target:
public void start(ComponentContext context) { if (Framework.isTestModeSet()) { return; } for (Directory dir : getDirectories()) { try { dir.getSession().close(); } catch (Exception e) { log.error(e); } } if (TransactionHelper.isTransactionActiveOrMarkedRollback()) { TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); } }
Source:
<code>public String build() { <START> StringBuilder redirect = new StringBuilder("redirect:"); <END> if (destination != null) { redirect.append(destination); } else { if (path != null) { redirect.append(path); } if (query != null) { redirect.append("?"); redirect.append(query); } if (!parameters.isEmpty()) { if (query == null) { redirect.append("?"); } else { redirect.append("&"); } boolean isFirst = true; for (Entry<String, Object> param : parameters.entrySet()) { if (!isFirst) { redirect.append("&"); } redirect.append(param.getKey()); if (param.getValue() != null) { redirect.append("="); try { String encodedValue = URLEncoder.encode(param.getValue().toString(), "UTF-8"); redirect.append(encodedValue); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } isFirst = false; } } } return redirect.toString(); }</code><technical_language>please UriBuilder</technical_language>

Target:
public String build() { UriBuilder uri = null; if (destination != null) { uri = UriBuilder.fromUri(destination); } else { uri = UriBuilder.fromPath(""); if (path != null) { uri.path(path); } if (query != null) { uri.replaceQuery(query); } if (!parameters.isEmpty()) { for (Entry<String, Object> param : parameters.entrySet()) { uri.queryParam(param.getKey(), param.getValue() != null ? param.getValue() : ""); } } } return "redirect:" + uri.toString(); }
Source:
<code>public Networks list() { Networks networks; if (isFiltered()) { <START> networks = mapCollection(getBackendCollection(VdcQueryType.GetAllNetworksByUserId, new GetAllNetworkQueryParamenters())); <END> } else { networks = mapCollection(getBackendCollection(queryType, getQueryParameters())); } for (Network network : networks.getNetworks()) { network.setDisplay(null); } return networks; }</code><technical_language>extra query needed here? filtering happen original one</technical_language>

Target:
public Networks list() { Networks networks = mapCollection(getBackendCollection(queryType, getQueryParameters())); for (Network network : networks.getNetworks()) { network.setDisplay(null); } return networks; }
Source:
<code>public String serverInfoToJSON(String serverId, String siteUrl, String secureSiteUrl) { Gson gson = new Gson(); JsonObject object = new JsonObject(); object.addProperty("server_id", serverId); object.addProperty("site_url", siteUrl); object.addProperty("secure_site_url", secureSiteUrl); <START> object.addProperty("server_version", CurrentGoCDVersion.getInstance().fullVersion()); <END> return gson.toJson(object); }</code><technical_language>modifying message body v2 of ServerInfoRequestProcessor</technical_language>

Target:
public String serverInfoToJSON(String serverId, String siteUrl, String secureSiteUrl) { Gson gson = new Gson(); JsonObject object = new JsonObject(); object.addProperty("server_id", serverId); object.addProperty("site_url", siteUrl); object.addProperty("secure_site_url", secureSiteUrl); return gson.toJson(object); }
Source:
<code>public GitHubSCMSource(String repoOwnerInternal, String repositoryInternal, String rawUrl, String configurableByScan) { this.configurableByScan = configurableByScan; <START> if(StringUtils.equals("raw", configurableByScan)) { <END> this.rawUrl = rawUrl; this.repoOwner = ""; this.repository = ""; }else{ this.rawUrl = ""; this.repoOwner = repoOwnerInternal; this.repository = repositoryInternal; } pullRequestMetadataCache = new ConcurrentHashMap<>(); pullRequestContributorCache = new ConcurrentHashMap<>(); this.traits = new ArrayList<>(); }</code><technical_language>get rid of configurableByScan entirely? suggestion if(StringUtils.isNotBlank(rawUrl)) {</technical_language>

Target:
public GitHubSCMSource(String repoOwnerInternal, String repositoryInternal, String rawUrl, String configurableByScan) { this.configurableByScan = configurableByScan; if(StringUtils.equals("raw", configurableByScan)) { this.rawUrl = rawUrl; this.repoOwner = null; this.repository = null; }else{ this.rawUrl = null; this.repoOwner = repoOwnerInternal; this.repository = repositoryInternal; } pullRequestMetadataCache = new ConcurrentHashMap<>(); pullRequestContributorCache = new ConcurrentHashMap<>(); this.traits = new ArrayList<>(); }
Source:
<code>public boolean cancel(boolean mayInterruptIfRunning) { <START> if (hasListeners.compareAndSet(false, true)) { <END> refreshListeners.put(this, true); } return super.cancel(mayInterruptIfRunning); }</code><technical_language>I code do ensure this future removed list a refresh if canceled. I this achieve result in a clearer way: boolean result = super.cancel(mayInterruptIfRunning); if (result) { refreshListeners.remove(this); } return result; In particular, if successfully canceled, set(null) call afterRefresh is a no-op</technical_language>

Target:
public boolean cancel(boolean mayInterruptIfRunning) { boolean result = super.cancel(mayInterruptIfRunning); if (result) { notDoneNrtFutures.remove(this); } return result; }
Source:
<code>private void compareSnapshotFiles( Set<String> firstSnapshotFileNames, Set<String> secondSnapshotFileNames, FileSystemAbstraction fileSystem ) { Set<String> firstSnapshotIndexesSegments = firstSnapshotFileNames.stream() <START> .filter( this::segmentsFilePredicate ) <END> .collect( Collectors.toSet() ); Set<String> secondSnapshotIndexesSegments = secondSnapshotFileNames.stream() .filter( this::segmentsFilePredicate ) .collect( Collectors.toSet() ); assertThat( format( "Should have %d modified index segment files. Snapshot segment files are: %s", NUMBER_OF_INDEXES, firstSnapshotIndexesSegments ), firstSnapshotIndexesSegments, hasSize( NUMBER_OF_INDEXES ) ); for ( String fileName : firstSnapshotIndexesSegments ) { assertFalse( "Snapshot segments fileset should not have files from another snapshot set." + describeFileSets( firstSnapshotIndexesSegments, secondSnapshotIndexesSegments ), secondSnapshotIndexesSegments.contains( fileName ) ); String path = FilenameUtils.getFullPath( fileName ); assertTrue( "Snapshot should contain files for index in path: " + path + "." + describeFileSets( firstSnapshotIndexesSegments, secondSnapshotIndexesSegments ), secondSnapshotIndexesSegments.stream().anyMatch( name -> name.startsWith( path ) ) ); assertTrue( format( "Snapshot segment file '%s' should exist.", fileName ), fileSystem.fileExists( new File( fileName ) ) ); } }</code><technical_language>filter moved getFileNames instead. other implications this for rest of test though</technical_language>

Target:
private void compareSnapshotFiles( Set<String> firstSnapshotFileNames, Set<String> secondSnapshotFileNames, FileSystemAbstraction fileSystem ) { assertThat( format( "Should have %d modified index segment files. Snapshot segment files are: %s", NUMBER_OF_INDEXES, firstSnapshotFileNames ), firstSnapshotFileNames, hasSize( NUMBER_OF_INDEXES ) ); for ( String fileName : firstSnapshotFileNames ) { assertFalse( "Snapshot segments fileset should not have files from another snapshot set." + describeFileSets( firstSnapshotFileNames, secondSnapshotFileNames ), secondSnapshotFileNames.contains( fileName ) ); String path = FilenameUtils.getFullPath( fileName ); assertTrue( "Snapshot should contain files for index in path: " + path + "." + describeFileSets( firstSnapshotFileNames, secondSnapshotFileNames ), secondSnapshotFileNames.stream().anyMatch( name -> name.startsWith( path ) ) ); assertTrue( format( "Snapshot segment file '%s' should exist.", fileName ), fileSystem.fileExists( new File( fileName ) ) ); } }
Source:
<code>private void decorateRepositoryGroup(RepositoryTreeNode<?> node, IDecoration decoration) { RepositoryCache cache = org.eclipse.egit.core.Activator.getDefault() .getRepositoryCache(); RepositoryGroup group = ((RepositoryGroupNode) node).getGroup(); boolean markGroupDirty = false; for <START> (String repoDir <END> : group.getRepositoryDirectories()) { Repository repo = cache.getRepository(new File(repoDir)); if (repo != null && RepositoryUtil.hasChanges(repo)) { markGroupDirty = true; break; } } if (markGroupDirty) { decoration.addPrefix(HAS_CHANGES_PREFIX); } else { ensureCorrectLabelCaching(decoration); } }</code><technical_language>File</technical_language>

Target:
private void decorateRepositoryGroup(RepositoryTreeNode<?> node, IDecoration decoration) { RepositoryCache cache = org.eclipse.egit.core.Activator.getDefault() .getRepositoryCache(); RepositoryGroup group = ((RepositoryGroupNode) node).getGroup(); boolean markGroupDirty = false; for (File repoDir : group.getRepositoryDirectories()) { Repository repo = cache.getRepository(repoDir); if (repo != null && RepositoryUtil.hasChanges(repo)) { markGroupDirty = true; break; } } if (markGroupDirty) { decoration.addPrefix(HAS_CHANGES_PREFIX); } else { ensureCorrectLabelCaching(decoration); } }
Source:
<code>public void testThatFilterDoesntRemoveStorageDomainFromList() { List<StorageDomain> filteredDomains = filterStorageDomain(false); <START> assertEquals(filteredDomains, Arrays.asList(storageDomain)); <END> }</code><technical_language>This assumes collections type. safe side, surround collection (e.g., new ArrayList<>)</technical_language>

Target:
public void testThatFilterDoesntRemoveStorageDomainFromList() { List<StorageDomain> filteredDomains = new ArrayList<>(filterStorageDomain(false)); assertEquals(filteredDomains, Arrays.asList(storageDomain)); }
Source:
<code>public SelectQuery( @JsonProperty("dataSource") DataSource dataSource, @JsonProperty("intervals") QuerySegmentSpec querySegmentSpec, @JsonProperty("descending") boolean descending, @JsonProperty("filter") DimFilter dimFilter, @JsonProperty("granularity") Granularity granularity, @JsonProperty("dimensions") List<DimensionSpec> dimensions, @JsonProperty("metrics") List<String> metrics, @JsonProperty("virtualColumns") VirtualColumns virtualColumns, @JsonProperty("pagingSpec") PagingSpec pagingSpec, @JsonProperty("context") Map<String, Object> context ) { <START> super(dataSource, querySegmentSpec, descending, context, granularity == null ? Granularities.ALL : granularity); <END> this.dimFilter = dimFilter; this.dimensions = dimensions; this.virtualColumns = VirtualColumns.nullToEmpty(virtualColumns); this.metrics = metrics; this.pagingSpec = pagingSpec; Preconditions.checkNotNull(pagingSpec, "must specify a pagingSpec"); Preconditions.checkArgument(checkPagingSpec(pagingSpec, descending), "invalid pagingSpec"); }</code><technical_language>I suggest extract method Granularities.nullToAll()</technical_language>

Target:
public SelectQuery( @JsonProperty("dataSource") DataSource dataSource, @JsonProperty("intervals") QuerySegmentSpec querySegmentSpec, @JsonProperty("descending") boolean descending, @JsonProperty("filter") DimFilter dimFilter, @JsonProperty("granularity") Granularity granularity, @JsonProperty("dimensions") List<DimensionSpec> dimensions, @JsonProperty("metrics") List<String> metrics, @JsonProperty("virtualColumns") VirtualColumns virtualColumns, @JsonProperty("pagingSpec") PagingSpec pagingSpec, @JsonProperty("context") Map<String, Object> context ) { super(dataSource, querySegmentSpec, descending, context, Granularities.nullToAll(granularity)); this.dimFilter = dimFilter; this.dimensions = dimensions; this.virtualColumns = VirtualColumns.nullToEmpty(virtualColumns); this.metrics = metrics; this.pagingSpec = pagingSpec; Preconditions.checkNotNull(pagingSpec, "must specify a pagingSpec"); Preconditions.checkArgument(checkPagingSpec(pagingSpec, descending), "invalid pagingSpec"); }
Source:
<code>private void ensureOrderTypeIsSet(Order order, OrderContext orderContext) { Order previousOrder = order.getPreviousOrder(); <START> if (order.getOrderType() == null) { <END> OrderType orderType = null; if (orderContext != null) { orderType = orderContext.getOrderType(); } if (orderType == null) { orderType = getOrderTypeByConcept(order.getConcept()); } if (orderType == null && order instanceof DrugOrder) { orderType = Context.getOrderService().getOrderTypeByUuid(OrderType.DRUG_ORDER_TYPE_UUID); } if (orderType == null && order instanceof TestOrder) { orderType = Context.getOrderService().getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID); } if (orderType == null) { throw new OrderEntryException("Order.type.cannot.determine"); } if (previousOrder != null && !orderType.equals(previousOrder.getOrderType())) { throw new OrderEntryException("Order.type.does.not.match"); } order.setOrderType(orderType); } }</code><technical_language>@Nuwantha simplify this. turn this a guard clause java if (order.getOrderType() != null) { return; } Order previousOrder = order.getPreviousOrder(); ... this remove level of nesting in this method signal reader ok if orderType is set, do here, return</technical_language>

Target:
private void ensureOrderTypeIsSet(Order order, OrderContext orderContext) { if (order.getOrderType() != null) { return; } OrderType orderType = null; if (orderContext != null) { orderType = orderContext.getOrderType(); } if (orderType == null) { orderType = getOrderTypeByConcept(order.getConcept()); } if (orderType == null && order instanceof DrugOrder) { orderType = Context.getOrderService().getOrderTypeByUuid(OrderType.DRUG_ORDER_TYPE_UUID); } if (orderType == null && order instanceof TestOrder) { orderType = Context.getOrderService().getOrderTypeByUuid(OrderType.TEST_ORDER_TYPE_UUID); } if (orderType == null) { throw new OrderEntryException("Order.type.cannot.determine"); } Order previousOrder = order.getPreviousOrder(); if (previousOrder != null && !orderType.equals(previousOrder.getOrderType())) { throw new OrderEntryException("Order.type.does.not.match"); } order.setOrderType(orderType); }
Source:
<code>public DescribeAlarmsResult describeAlarms(String awsRegion) { final DefaultAWSCredentialsProviderChain credentialsProviderChain = new DefaultAWSCredentialsProviderChain(); final AWSStaticCredentialsProvider credentialProvider = new AWSStaticCredentialsProvider(credentialsProviderChain.getCredentials()); return AmazonCloudWatchClientBuilder .standard() <START> .withCredentials(credentialProvider) <END> .withRegion(awsRegion) .build() .describeAlarms(); }</code><technical_language>skip setting .withCredentials() all? dont need set crendentialsProvider default mechanisms automatically</technical_language>

Target:
public DescribeAlarmsResult describeAlarms(String awsRegion) { return AmazonCloudWatchClientBuilder .standard() .withRegion(awsRegion) .build() .describeAlarms(); }
Source:
<code>public static CallExpression call(FunctionManager functionManager, String name, Type returnType, List<RowExpression> arguments) { FunctionHandle functionHandle = functionManager.lookupFunction(name, fromTypes(arguments.stream().map(RowExpression::getType).collect(toImmutableList()))); <START> return new CallExpression(name, functionHandle, returnType, arguments); <END> }</code><technical_language>this delegate call functions above. - also, name a bit confusing displayName. @rongrong provide suggestion</technical_language>

Target:
public static CallExpression call(FunctionManager functionManager, String name, Type returnType, List<RowExpression> arguments) { FunctionHandle functionHandle = functionManager.lookupFunction(name, fromTypes(arguments.stream().map(RowExpression::getType).collect(toImmutableList()))); return call(name, functionHandle, returnType, arguments); }
Source:
<code>} catch (UnsatisfiedLinkError e) { tempOpenCvLoaded = false; <START> System.out.println("OpenCV native library failed to load " + e.toString()); <END> }</code><technical_language>Leftover debug line - edit leftover, logger is available. Suggested saving error string display creating exception a lines down</technical_language>

Target:
} catch (UnsatisfiedLinkError e) { tempOpenCvLoaded = false; exception = e; }
Source:
<code>public BertMaskedLMMasker(Random r, double maskProb, double maskTokenProb, double randomTokenProb){ Preconditions.checkArgument(maskProb > 0 && maskProb < 1, "Probability must be beteen 0 and 1, got %s", maskProb); this.r = r; this.maskProb = maskProb; this.maskTokenProb = maskTokenProb; this.randomTokenProb = randomTokenProb; <START> } <END></code><technical_language>check 0 <= maskTokenProb + randomTokenProb <= 1</technical_language>

Target:
public BertMaskedLMMasker(Random r, double maskProb, double maskTokenProb, double randomTokenProb){ Preconditions.checkArgument(maskProb > 0 && maskProb < 1, "Probability must be beteen 0 and 1, got %s", maskProb); Preconditions.checkState(maskTokenProb >=0 && maskTokenProb <= 1.0, "Mask token probability must be between 0 and 1, got %s", maskTokenProb); Preconditions.checkState(randomTokenProb >=0 && randomTokenProb <= 1.0, "Random token probability must be between 0 and 1, got %s", randomTokenProb); Preconditions.checkState(maskTokenProb + randomTokenProb <= 1.0, "Sum of maskTokenProb (%s) and randomTokenProb (%s) must be <= 1.0, got sum is %s", maskTokenProb, randomTokenProb, (maskTokenProb + randomTokenProb)); this.r = r; this.maskProb = maskProb; this.maskTokenProb = maskTokenProb; this.randomTokenProb = randomTokenProb; }
Source:
<code>public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader) throws IOException { <START> if (FileMode.SYMLINK.equals(mode)) { <END> final TarArchiveEntry entry = new TarArchiveEntry( path, TarConstants.LF_SYMLINK); entry.setLinkName(new String( loader.getCachedBytes(100), "UTF-8")); out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (path.endsWith("/") != FileMode.TREE.equals(mode)) { throw new IllegalArgumentException( "TarFormat.putEntry: path " + path + " does not match mode " + mode); } final TarArchiveEntry entry = new TarArchiveEntry(path); if (FileMode.TREE.equals(mode)) { out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (FileMode.REGULAR_FILE.equals(mode)) { } else if (FileMode.EXECUTABLE_FILE.equals(mode)) { entry.setMode(mode.getBits()); } else { throw new IllegalArgumentException( "TarFormat.putEntry: Unsupported mode " + mode); } entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); }</code><technical_language>change == .equals? Do expect mode null</technical_language>

Target:
public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader) throws IOException { if (mode == FileMode.SYMLINK) { final TarArchiveEntry entry = new TarArchiveEntry( path, TarConstants.LF_SYMLINK); entry.setLinkName(new String( loader.getCachedBytes(100), "UTF-8")); out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (path.endsWith("/") && mode != FileMode.TREE) throw new IllegalArgumentException(MessageFormat.format( ArchiveText.get().pathDoesNotMatchMode, path, mode)); if (!path.endsWith("/") && mode == FileMode.TREE) path = path + "/"; final TarArchiveEntry entry = new TarArchiveEntry(path); if (mode == FileMode.TREE) { out.putArchiveEntry(entry); out.closeArchiveEntry(); return; } if (mode == FileMode.REGULAR_FILE) { } else if (mode == FileMode.EXECUTABLE_FILE) { entry.setMode(mode.getBits()); } else { throw new IllegalArgumentException(MessageFormat.format( ArchiveText.get().unsupportedMode, mode)); } entry.setSize(loader.getSize()); out.putArchiveEntry(entry); loader.copyTo(out); out.closeArchiveEntry(); }
Source:
<code>public void onTerminate() { <START> disposable.dispose(); <END> super.onTerminate(); }</code><technical_language>private Disposable disposable = null add a null check here, sure</technical_language>

Target:
public void onTerminate() { if (disposable != null) { disposable.dispose(); } super.onTerminate(); }
Source:
<code>public static <T extends Annotation> T findAnnotation(Class<?> clazz, Class<T> annotationClass) { T ann = clazz.getAnnotation(annotationClass); if (ann == null && clazz != Object.class) { <START> ann = clazz.getAnnotation(annotationClass); <END> if (ann == null) { ann = clazz.getPackage().getAnnotation(annotationClass); } if (ann == null && clazz != Object.class) { ann = findAnnotation(clazz.getSuperclass(), annotationClass); } } return ann; }</code><technical_language>replaced while if I correct this method below: java public static <T extends Annotation> T findAnnotation(Class<?> clazz, Class<T> annotationClass) { T ann = null; if (clazz != null) { ann = clazz.getAnnotation(annotationClass); if (ann == null) { ann = clazz.getPackage().getAnnotation(annotationClass); } if (ann == null) { ann = findAnnotation(clazz.getSuperclass(), annotationClass); } } return ann; }</technical_language>

Target:
public static <T extends Annotation> T findAnnotation(Class<?> clazz, Class<T> annotationClass) { T ann = clazz.getAnnotation(annotationClass); while (ann == null && clazz != null) { ann = clazz.getAnnotation(annotationClass); if (ann == null) { ann = clazz.getPackage().getAnnotation(annotationClass); } if (ann == null) { clazz = clazz.getSuperclass(); if (clazz != null) { ann = clazz.getAnnotation(annotationClass); } } } return ann; }
Source:
<code>public void testStopStartConsensus() throws Exception { Atomix atomix1 = startAtomix(1, Arrays.asList(1), Profile.CONSENSUS).get(30, TimeUnit.SECONDS); atomix1.stop().get(30, TimeUnit.SECONDS); try { atomix1.start().get(30, TimeUnit.SECONDS); <START> fail("Expected CompletionException"); <END> } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IllegalStateException); assertEquals("Atomix instance shutdown", ex.getCause().getMessage()); } }</code><technical_language>Message is incorrect</technical_language>

Target:
public void testStopStartConsensus() throws Exception { Atomix atomix1 = startAtomix(1, Arrays.asList(1), Profile.CONSENSUS).get(30, TimeUnit.SECONDS); atomix1.stop().get(30, TimeUnit.SECONDS); try { atomix1.start().get(30, TimeUnit.SECONDS); fail("Expected ExecutionException"); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof IllegalStateException); assertEquals("Atomix instance shutdown", ex.getCause().getMessage()); } }
Source:
<code>public static NewParam createOrganizationParameter(NewAction action) { return action.createParam(PARAM_ORGANIZATION) .setDescription("Key of organization, used when group name is set") .setExampleValue("my-org") <START> .setSince("6.2") <END> .setInternal(true); }</code><technical_language>this line in builder method IMO context sensitive</technical_language>

Target:
public static NewParam createOrganizationParameter(NewAction action) { return action.createParam(PARAM_ORGANIZATION) .setDescription("Key of organization, used when group name is set") .setExampleValue("my-org") .setInternal(true); }
Source:
<code>public String generateUnifiedResourceName(String namespace, String libraryIdentifier, String subNamespace, String identifier) { <START> String urn = namespace + ':' + libraryIdentifier + '-' + subNamespace + "-id" + identifier; <END> return SCHEME + ':' + urn + getCheckDigit(urn); }</code><technical_language>id is part of identifier. For example testing urn:nbn:de:bsz:14-qucosa-22579 results in wrong urn:nbn:de:bsz:14-qucosa-id225798. Correct urn:nbn:de:bsz:14-qucosa-225799. I provide some more examples if need them</technical_language>

Target:
public String generateUnifiedResourceName(String namespace, String libraryIdentifier, String subNamespace, String identifier) { String urn = namespace + ':' + libraryIdentifier + '-' + subNamespace + "-" + identifier; return SCHEME + ':' + urn + getCheckDigit(urn); }
Source:
<code>public void initializeUI(UIBuilder builder) throws Exception { Project project = Projects.getSelectedProject(projectFactory, builder.getUIContext()); if (project != null) { MetadataFacet facet = project.getFacet(MetadataFacet.class); Coordinate c = facet.getOutputDependency().getCoordinate(); <START> named.setDefaultValue(AddonId.from(c.getGroupId() + ":" + c.getArtifactId(), c.getVersion()) <END> .toCoordinates()); } named.setCompleter(new UICompleter<String>() { @Override public Iterable<String> getCompletionProposals(UIContext context, InputComponent<?, String> input, String value) { Set<String> items = new TreeSet<String>(); Set<Addon> addons = furnace.getAddonRegistry().getAddons(); for (Addon addon : addons) { items.add(addon.getId().getName()); } return items; } }); named.addValidator(new UIValidator() { @Override public void validate(UIValidationContext context) { String coordinate = (String) context.getCurrentInputComponent().getValue(); try { AddonId addonId = CoordinateUtils.resolveCoordinate(coordinate, Versions.getSpecificationVersionFor(this.getClass()), resolver); Set<Addon> addons = furnace.getAddonRegistry().getAddons(); boolean match = false; for (Addon addon : addons) { if (addon.getId().getName().equals(addonId.getName())) { match = true; break; } } if (!match) { context.addValidationError(context.getCurrentInputComponent(), "\"" + coordinate + "\" does not refer to any installed Addon coordinate"); } } catch (IllegalArgumentException e) { context.addValidationError(context.getCurrentInputComponent(), "\"" + coordinate + "\" is not a valid Addon coordinate"); } } }); builder.add(named); }</code><technical_language>This right. current project addon project</technical_language>

Target:
public void initializeUI(UIBuilder builder) throws Exception { named.setCompleter(new UICompleter<String>() { @Override public Iterable<String> getCompletionProposals(UIContext context, InputComponent<?, String> input, String value) { Set<String> items = new TreeSet<String>(); Set<Addon> addons = furnace.getAddonRegistry().getAddons(); for (Addon addon : addons) { items.add(addon.getId().getName()); } return items; } }); named.addValidator(new UIValidator() { @Override public void validate(UIValidationContext context) { String coordinate = (String) context.getCurrentInputComponent().getValue(); try { AddonId addonId = CoordinateUtils.resolveCoordinate(coordinate, Versions.getSpecificationVersionFor(this.getClass()), resolver); Set<Addon> addons = furnace.getAddonRegistry().getAddons(); boolean match = false; for (Addon addon : addons) { if (addon.getId().getName().equals(addonId.getName())) { match = true; break; } } if (!match) { context.addValidationError(context.getCurrentInputComponent(), "\"" + coordinate + "\" does not refer to any installed Addon coordinate"); } } catch (IllegalArgumentException e) { context.addValidationError(context.getCurrentInputComponent(), "\"" + coordinate + "\" is not a valid Addon coordinate"); } } }); builder.add(named); }
Source:
<code>private static Point lineIntersection(Point a, Point b, Point p, Point q) { double a1 = b.getY() - a.getY(); double b1 = a.getX() - b.getX(); double c1 = a1 * a.getX() + b1 * a.getY(); double a2 = q.getY() - p.getY(); double b2 = p.getX() - q.getX(); double c2 = a2 * p.getX() + b2 * p.getY(); <START> double determinate = a1 * b2 - a2 * b1; <END> double x = (b2 * c1 - b1 * c2) / determinate; double y = (a1 * c2 - a2 * c1) / determinate; return new Point(x, y); }</code><technical_language>determinant</technical_language>

Target:
private static Point lineIntersection(Point a, Point b, Point p, Point q) { double a1 = b.getY() - a.getY(); double b1 = a.getX() - b.getX(); double c1 = a1 * a.getX() + b1 * a.getY(); double a2 = q.getY() - p.getY(); double b2 = p.getX() - q.getX(); double c2 = a2 * p.getX() + b2 * p.getY(); double determinant = a1 * b2 - a2 * b1; double x = (b2 * c1 - b1 * c2) / determinant; double y = (a1 * c2 - a2 * c1) / determinant; return new Point(x, y); }
Source:
<code>private Map<String, Object> processUserList(String query, int start, int limit, boolean includeAnonymous, boolean includeDefault) { Map<String, Object> results = new UsersListTemplate("", 0, query, start, limit, includeAnonymous, includeDefault) { <START> UserAPI userAPI = APILocator.getUserAPI(); <END> @Override public int getUserCount() { try { return new Long(userAPI.getCountUsersByNameOrEmailOrUserID(this.filter, this.includeAnonymous, this.includeDefault)).intValue(); } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); return 0; } } @Override public List<User> getUsers() { try { int page = (start / limit) + 1; int pageSize = limit; return userAPI.getUsersByNameOrEmailOrUserID(filter, page, pageSize, this.includeAnonymous, this.includeDefault); } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); return new ArrayList<User>(); } } }.perform(); return results; }</code><technical_language>move a class attribute</technical_language>

Target:
private Map<String, Object> processUserList(String query, int start, int limit, boolean includeAnonymous, boolean includeDefault) { Map<String, Object> results = new UsersListTemplate("", 0, query, start, limit, includeAnonymous, includeDefault) { @Override public int getUserCount() { try { return toInt(userAPI.getCountUsersByNameOrEmailOrUserID(this.filter, this.includeAnonymous, this.includeDefault), 0); } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); return 0; } } @Override public List<User> getUsers() { try { int page = (start / limit) + 1; int pageSize = limit; return userAPI.getUsersByNameOrEmailOrUserID(filter, page, pageSize, this.includeAnonymous, this.includeDefault); } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); return new ArrayList<User>(); } } }.perform(); return results; }
Source:
<code>public void parse(String[] args, SnipeData v) { String handle = args[0].toLowerCase(); Matcher performersMatch = PERFORMER.matcher(handle); if (performersMatch.matches()) { placeMethod = stringToMethod(performersMatch.group(1)); if (placeMethod == PerformerType.NONE) { <START> throw new IllegalArgumentException("Unknown placement method '" + performersMatch.group(1) + "'"); <END> } replaceMethod = stringToMethod(performersMatch.group(2)); usePhysics = !performersMatch.group(3).equals("p"); parameters(Arrays.copyOfRange(args, 1, args.length), v); } else { parameters(args, v); } v.getVoxelMessage().performerData(placeMethod, replaceMethod, usePhysics); }</code><technical_language>this get returned user feedback? I caught I assume ends in server log</technical_language>

Target:
public void parse(String[] args, SnipeData v) { String handle = args[0].toLowerCase(); Matcher performersMatch = PERFORMER.matcher(handle); if (performersMatch.matches()) { this.placeMethod = stringToMethod(performersMatch.group(1)); if (this.placeMethod == PerformerType.NONE) { throw new IllegalArgumentException("Unknown placement method '" + performersMatch.group(1) + "'"); } this.replaceMethod = stringToMethod(performersMatch.group(2)); this.usePhysics = !performersMatch.group(3).equals("p"); parameters(Arrays.copyOfRange(args, 1, args.length), v); } else { parameters(args, v); } v.getVoxelMessage().performerData(this.placeMethod, this.replaceMethod, this.usePhysics); }
Source:
<code>public void addMpathwayDataToSession(HttpServletRequest request, WAPIResultWrapper wrappedResult, String mpathwaysTermId) { try{ M_log.debug("Mapth Wrapped Result: " + wrappedResult.toJson().toString()); ArrayList<String> mPathwayData = new ArrayList<String>(); JSONArray mPathJsonArray; JSONObject result = new JSONObject(wrappedResult.toJson()); mPathJsonArray = result.getJSONObject("Result").getJSONObject("getInstrClassListResponse").getJSONArray("InstructedClass"); M_log.debug("mPathJsonArray: " + mPathJsonArray); for(int i = 0; i < mPathJsonArray.length(); i++){ JSONObject childJSONObject = mPathJsonArray.getJSONObject(i); <START> if(childJSONObject.get("InstructorRole").equals("Primary Instructor") || <END> childJSONObject.get("InstructorRole").equals("Secondary Instructor") || childJSONObject.get("InstructorRole").equals("Faculty grader") || childJSONObject.get("InstructorRole").equals("Graduate Student Instructor")){ M_log.debug("Class Number: " + childJSONObject.get("ClassNumber")); mPathwayData.add(mpathwaysTermId + childJSONObject.get("ClassNumber").toString()); } } for(String course : mPathwayData){ M_log.debug("Course: " + course); } HttpSession session = request.getSession(true); session.setAttribute(M_PATH_DATA,mPathwayData); } catch(JSONException e){ M_log.error(e.getMessage()); return; } }</code><technical_language>put choices in a list hash loop value</technical_language>

Target:
public void addMpathwayDataToSession(HttpServletRequest request, WAPIResultWrapper wrappedResult, String mpathwaysTermId) { try{ M_log.debug("Mapth Wrapped Result: " + wrappedResult.toJson().toString()); ArrayList<String> mPathwayData = new ArrayList<String>(); JSONArray mPathJsonArray; JSONObject result = new JSONObject(wrappedResult.toJson()); mPathJsonArray = result.getJSONObject("Result").getJSONObject("getInstrClassListResponse").getJSONArray("InstructedClass"); M_log.debug("mPathJsonArray: " + mPathJsonArray); for(int i = 0; i < mPathJsonArray.length(); i++){ JSONObject childJSONObject = mPathJsonArray.getJSONObject(i); if(allowedRoles.contains(childJSONObject.get("InstructorRole"))){ M_log.debug("Class Number: " + childJSONObject.get("ClassNumber")); mPathwayData.add(mpathwaysTermId + childJSONObject.get("ClassNumber").toString()); } } if(M_log.isDebugEnabled()){ for(String course : mPathwayData){ M_log.debug("Course: " + course); } } HttpSession session = request.getSession(true); session.setAttribute(M_PATH_DATA,mPathwayData); } catch(JSONException e){ M_log.error(e.getMessage()); return; } }
Source:
<code><START> public String toString() { <END> return String.format("%s %s %s %s -> %s (± %s)", paramKey, group, name, implementation, getScoreFormatted(), getScoreErrorPct()); }</code><technical_language>nice careful class, I style :) :+1:</technical_language>

Target:
public String toString() { return String.format("%s %s %s %s -> %s (± %s)", paramKey, target, operation, implementation, getScoreFormatted(), getScoreErrorPct()); }
Source:
<code>public IFile createBookmarksFile() throws CoreException { TmfExperimentFolder experimentFolder = getProject().getExperimentsFolder(); IFolder <START> res = getResource(); <END> if (experimentFolder != null) { res = experimentFolder.getResource(); } return createBookmarksFile(res, ITmfEventsEditorConstants.EXPERIMENT_EDITOR_INPUT_TYPE); }</code><technical_language>if experiment folder do exist, create bookmark file anyway</technical_language>

Target:
public IFile createBookmarksFile() throws CoreException { TmfExperimentFolder experimentFolder = getProject().getExperimentsFolder(); if (experimentFolder == null) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TmfProject_ExperimentFolderNotExists)); } return createBookmarksFile(experimentFolder.getResource(), ITmfEventsEditorConstants.EXPERIMENT_EDITOR_INPUT_TYPE); }
Source:
<code><START> public static boolean isOpenCvLoaded() { <END> return OPEN_CV_LOADED; }</code><technical_language>I this needs continue throw exception. is incompatible</technical_language>

Target:
public static boolean isOpenCvLoaded() throws UnsatisfiedLinkError { if (!openCvLoaded) { if (exception != null) { throw exception; } else { throw new UnsatisfiedLinkError("OpenCV native library failed to load"); } } return openCvLoaded; }
Source:
<code>private String keyCodeToString(GameKeyEvent event){ int code = event.getKeyCode(); switch(code){ case KeyEvent.VK_UP: <START> return "UP"; <END> case KeyEvent.VK_DOWN: return "DOWN"; case KeyEvent.VK_RIGHT: return "RIGHT"; case KeyEvent.VK_LEFT: return "LEFT"; default: return "undefined"; } }</code><technical_language>returns in-line cases for conciseness. eg. case KeyEvent.VK_UP: return UP/LEFT/etc. static final variables</technical_language>

Target:
private String keyCodeToString(GameKeyEvent event){ int code = event.getKeyCode(); switch(code){ case KeyEvent.VK_UP: return TestCase.UP; case KeyEvent.VK_DOWN: return TestCase.DOWN; case KeyEvent.VK_RIGHT: return TestCase.RIGHT; case KeyEvent.VK_LEFT: return TestCase.LEFT; default: return "undefined"; } }
Source:
<code>public void removeEntries(List<BibEntry> bibEntries) { StringBuilder query = new StringBuilder() .append("DELETE FROM ") .append(escape("ENTRY")) .append(" WHERE ") .append(escape("SHARED_ID")) .append(" IN ("); for (int i = 0; i < bibEntries.size() - 1; i++) { <START> query.append("?, "); <END> } query.append("?)"); try (PreparedStatement preparedStatement = connection.prepareStatement(query.toString())) { for (int j = 0; j < bibEntries.size(); j++) { preparedStatement.setInt(j + 1, bibEntries.get(j).getSharedBibEntryData().getSharedID()); } preparedStatement.executeUpdate(); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } }</code><technical_language>I "?, ".repeat(bibEntries.size())</technical_language>

Target:
public void removeEntries(List<BibEntry> bibEntries) { Objects.requireNonNull(bibEntries); if (bibEntries.isEmpty()) { return; } StringBuilder query = new StringBuilder() .append("DELETE FROM ") .append(escape("ENTRY")) .append(" WHERE ") .append(escape("SHARED_ID")) .append(" IN ("); query.append("?, ".repeat(bibEntries.size() - 1)); query.append("?)"); try (PreparedStatement preparedStatement = connection.prepareStatement(query.toString())) { for (int j = 0; j < bibEntries.size(); j++) { preparedStatement.setInt(j + 1, bibEntries.get(j).getSharedBibEntryData().getSharedID()); } preparedStatement.executeUpdate(); } catch (SQLException e) { LOGGER.error("SQL Error: ", e); } }
Source:
<code>protected void populateGlobalProperties() { String externalAddress = getExternalAddress(); String externalIP = getExternalIp(externalAddress); globalPropertiesMap.put("internalIp", cheDockerIp); globalPropertiesMap.put("externalAddress", externalAddress); globalPropertiesMap.put("externalIP", externalIP); globalPropertiesMap.put("workspaceId", getWorkspaceId()); <START> globalPropertiesMap.put("workspaceIdWithoutPrefix", getWorkspaceId().replaceFirst("workspace","")); <END> globalPropertiesMap.put("machineName", getMachineName()); globalPropertiesMap.put("wildcardNipDomain", getWildcardNipDomain(externalAddress)); globalPropertiesMap.put("wildcardXipDomain", getWildcardXipDomain(externalAddress)); globalPropertiesMap.put("chePort", chePort); globalPropertiesMap.put("isDevMachine", getIsDevMachine()); }</code><technical_language>move "workspace" a class constant</technical_language>

Target:
protected void populateGlobalProperties() { String externalAddress = getExternalAddress(); String externalIP = getExternalIp(externalAddress); globalPropertiesMap.put("internalIp", cheDockerIp); globalPropertiesMap.put("externalAddress", externalAddress); globalPropertiesMap.put("externalIP", externalIP); globalPropertiesMap.put("workspaceId", getWorkspaceId()); globalPropertiesMap.put("workspaceIdWithoutPrefix", getWorkspaceId().replaceFirst(CHE_WORKSPACE_ID_PREFIX,"")); globalPropertiesMap.put("machineName", getMachineName()); globalPropertiesMap.put("wildcardNipDomain", getWildcardNipDomain(externalAddress)); globalPropertiesMap.put("wildcardXipDomain", getWildcardXipDomain(externalAddress)); globalPropertiesMap.put("chePort", chePort); globalPropertiesMap.put(IS_DEV_MACHINE_MACRO, getIsDevMachine()); }
Source:
<code>public WeightedDoubleReservoirSample(int maxSamples) { <START> checkArgument(maxSamples > 0, "Maximum number of reservoir samples must be positive"); <END> checkArgument(maxSamples <= MAX_SAMPLES_LIMIT, "Maximum number of reservoir samples is capped"); this.size = 0; this.samples = new double[maxSamples]; this.weights = new double[maxSamples]; checkArguments(); }</code><technical_language>Update error messages remove size = 0 match UnweightedDoubleReservoirSample - Remove redundant checkArguments call checkArgument(maxSamples > 0, "Maximum number of samples positive"); checkArgument(maxSamples <= MAX_SAMPLES_LIMIT, "Maximum number of samples exceed " + MAX_SAMPLES_LIMIT); this.samples = new double[maxSamples]; this.weights = new double[maxSamples];</technical_language>

Target:
public WeightedDoubleReservoirSample(int maxSamples) { checkArgument(maxSamples > 0, format("Maximum number of samples must be positive: %s", maxSamples)); checkArgument( maxSamples <= MAX_SAMPLES_LIMIT, format("Maximum number of samples must not exceed limit: %s %s", maxSamples, MAX_SAMPLES_LIMIT)); this.samples = new double[maxSamples]; this.weights = new double[maxSamples]; }
Source:
<code>@Override public void draw(Canvas canvas) { if (!animating) { super.draw(canvas); } else { float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; if (normalized >= 1f) { animating = false; placeholder = null; super.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } <START> int partialAlpha = (int) (ALPHA * normalized); <END> setAlpha(partialAlpha); super.draw(canvas); setAlpha(ALPHA); } } if (debugging) { drawDebugIndicator(canvas); } }</code><technical_language>This right. stomp passed setAlpha revert image 0xFF. a reason instance var mutable</technical_language>

Target:
@Override public void draw(Canvas canvas) { if (!animating) { super.draw(canvas); } else { float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; if (normalized >= 1f) { animating = false; placeholder = null; super.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } int partialAlpha = (int) (alpha * normalized); setAlpha(partialAlpha); super.draw(canvas); setAlpha(alpha); } } if (debugging) { drawDebugIndicator(canvas); } }
Source:
<code><START> public void process() { <END> enchants.forEach((e) -> enchantments.put(Enchantment.fromId(e.id), e.lvl)); }</code><technical_language>is @Override here</technical_language>

Target:
public void process() { enchants.forEach(e -> enchantments.put(Enchantment.fromId(e.id), e.lvl)); }