auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void loadRules(URI uri, List<String> scriptNames, List<String> scripts) throws IOException { FileSystem fs = null; String entryName = uri.toString(); int separator = entryName.indexOf(PATH_JAR_SEPARATOR); if (separator != -1) { fs = FileSystems.newFileSystem(URI.create(entryName.substring(0, separator)), Collections.<String, Object>emptyMap()); entryName = entryName.substring(separator + PATH_JAR_SEPARATOR.length()); } else if (entryName.startsWith(FILE_SCHEME)) { fs = FileSystems.getFileSystem(URI.create(FILE_SCHEME + File.separator)); <START> entryName = entryName.substring(5); <END> } if (fs != null) { try { Path rules = fs.getPath(entryName); Files.walk(rules).filter(f -> f.toString().endsWith(RULE_FILE_EXTENSION)).forEach(f -> { try { scripts.add(new String(Files.readAllBytes(f))); scriptNames.add(f.toString()); } catch (IOException ioe) { log.log(Level.SEVERE, "Failed to load rule file: " + f.toString(), ioe); } }); } finally { if (separator != -1) { fs.close(); } } } }</code><technical_language>please change this FILE_SCHEME.length() (IIRC)</technical_language>

Target:
private static void loadRules(URI uri, List<String> scriptNames, List<String> scripts) throws IOException { FileSystem fs = null; String entryName = uri.toString(); int separator = entryName.indexOf(PATH_JAR_SEPARATOR); if (separator != -1) { fs = FileSystems.newFileSystem(URI.create(entryName.substring(0, separator)), Collections.<String, Object>emptyMap()); entryName = entryName.substring(separator + PATH_JAR_SEPARATOR.length()); } else if (entryName.startsWith(FILE_SCHEME)) { fs = FileSystems.getFileSystem(URI.create(FILE_SCHEME + File.separator)); entryName = entryName.substring(FILE_SCHEME.length()); } if (fs != null) { try { Path rules = fs.getPath(entryName); Files.walk(rules).filter(f -> f.toString().endsWith(RULE_FILE_EXTENSION)).forEach(f -> { try { scripts.add(new String(Files.readAllBytes(f))); scriptNames.add(f.toString()); } catch (IOException ioe) { log.log(Level.SEVERE, "Failed to load rule file: " + f.toString(), ioe); } }); } finally { if (separator != -1) { fs.close(); } } } }
Source:
<code>public static MeasurementUnits bestFitUnits(double[] values, MeasurementUnits originalUnits) { Double average = 0.0; <START> for (int i = 0, sz = values.length; i < sz; i++) { <END> average += (values[i] / sz); } MeasurementNumericValueAndUnits fittedAverage = fit(average, originalUnits); return fittedAverage.getUnits(); }</code><technical_language>values.length instead of sz ? values.length is more readable</technical_language>

Target:
public static MeasurementUnits bestFitUnits(double[] values, MeasurementUnits originalUnits) { Double average = 0.0; for (int i = 0; i < values.length; i++) { average += (values[i] / values.length); } MeasurementNumericValueAndUnits fittedAverage = fit(average, originalUnits); return fittedAverage.getUnits(); }
Source:
<code>protected void getFollowing(Long id) { Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers")); <START> if( ids_only == true ) <END> collectIds(id); else collectUsers(id); }</code><technical_language>java if (ids_only)</technical_language>

Target:
protected void getFollowing(Long id) { Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers")); if( idsOnly ) collectIds(id); else collectUsers(id); }
Source:
<code>public void should_create_error_message_for_file_not_has_size() { ErrorMessageFactory factory = shouldHaveSize(new FakeFile("abc"), 3L); String expectedErrorMessage = format("[Test] %n" + "Expecting file%n" + " <abc>%n" + "to have size:%n" + " <3L>%n" + "but had:%n" + " <0L>"); <START> assertThat(factory.create(new TextDescription("Test"), new StandardRepresentation())).isEqualTo(expectedErrorMessage); <END> }</code><technical_language>extract factory.create(new TextDescription("Test"), new StandardRepresentation()) a variable put in // section</technical_language>

Target:
public void should_create_error_message_for_file_not_has_size() { ErrorMessageFactory factory = shouldHaveSize(new FakeFile("abc"), 3L); String expectedErrorMessage = format("[Test] %n" + "Expecting file%n" + " <abc>%n" + "to have size of:%n" + " 3L bytes%n" + "but had:%n" + " 0L bytes"); String actualErrorMessage = factory.create(new TextDescription("Test"), new StandardRepresentation()); assertThat(actualErrorMessage).isEqualTo(expectedErrorMessage); }
Source:
<code>public static boolean isCssEnabled(){ try{ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); <START> return properties.getString(CSS_ENABLED, BuildConfig.DEBUG ? CommCarePreferences.YES : CommCarePreferences.NO).equals(CommCarePreferences.YES); <END> } catch(NullPointerException e){ return false; } }</code><technical_language>I want Debug this true default, dev apps normal apps default</technical_language>

Target:
public static boolean isCssEnabled(){ return doesPropertyMatch(CSS_ENABLED, CommCarePreferences.NO, CommCarePreferences.YES); }
Source:
<code>public Predicate<EngineVersionDTO> createFilter(EngineCategoryDTO engineCategory, EngineSubCategoryDTO engineSubCategory) { return engineVersion -> { return searchTerm .map(searchTerm -> engineVersion.getVersion().toLowerCase().contains(searchTerm.toLowerCase())) <START> .orElse(true) <END> && ((this.showInstalled.getValue() && isInstalled(engineCategory, engineSubCategory, engineVersion)) || (this.showNotInstalled.getValue() && !isInstalled(engineCategory, engineSubCategory, engineVersion))); }; }</code><technical_language>this formatted differently</technical_language>

Target:
public Predicate<EngineVersionDTO> createFilter(EngineCategoryDTO engineCategory, EngineSubCategoryDTO engineSubCategory) { return engineVersion -> { final boolean containsSearchTerm = searchTerm .map(searchTerm -> engineVersion.getVersion().toLowerCase().contains(searchTerm.toLowerCase())) .orElse(true); final boolean fulfillsShowInstalled = this.showInstalled.getValue() && isInstalled(engineCategory, engineSubCategory, engineVersion); final boolean fulfillsShowNotInstalled = this.showNotInstalled.getValue() && !isInstalled(engineCategory, engineSubCategory, engineVersion); return containsSearchTerm && (fulfillsShowInstalled || fulfillsShowNotInstalled); }; }
Source:
<code>public ProtocolMessageEnum deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { int intValue = jsonParser.getIntValue(); Class<?> enumClass = Preconditions.checkNotNull(javaType, "javaType").getRawClass(); try { <START> return (ProtocolMessageEnum) enumClass.getMethod("forNumber", int.class).invoke(null, intValue); <END> } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { context.reportWrongTokenException(ProtocolMessageEnum.class, JsonToken.VALUE_NUMBER_INT, wrongTokenMessage(context)); throw new AssertionError(); } }</code><technical_language>This moved Deserializer constructor I remember top of head contextual deserializers get cached automatically</technical_language>

Target:
public ProtocolMessageEnum deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { int intValue = jsonParser.getIntValue(); try { return (ProtocolMessageEnum) Preconditions.checkNotNull(forNumberMethod, "forNumberMethod").invoke(null, intValue); } catch (IllegalAccessException | InvocationTargetException e) { context.reportWrongTokenException(ProtocolMessageEnum.class, JsonToken.VALUE_NUMBER_INT, wrongTokenMessage(context)); throw new AssertionError(); } }
Source:
<code>private void assignInstancesToContainers( <START> ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation, <END> Map<String, Integer> parallelismMap, int firstTaskIndex) { ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(parallelismMap); int globalTaskIndex = firstTaskIndex; for (RamRequirement ramRequirement : ramRequirements) { String component = ramRequirement.getComponentName(); int numInstance = parallelismMap.get(component); for (int j = 0; j < numInstance; j++) { Resource instanceResource = this.defaultInstanceResources.cloneWithRam(ramRequirement.getRamRequirement()); int containerId = placeFFDInstance(containers, instanceResource, new InstanceId( component, globalTaskIndex, j)); List<InstanceId> instances = allocation.get(containerId); if (instances == null) { instances = new ArrayList<>(); } instances.add(new InstanceId(component, globalTaskIndex++, j)); allocation.put(containerId, instances); } } }</code><technical_language>I feel stretching of Lists Maps in signature here, passing a mutable list of containers a map of containers instance lists. Instead object encapsulated of that? a PackingPlan object a variant of it? Some container object is able effectively mutate a plan? a Builder takes a packing plan, allows update methods called change internal state, produces a new plan a build() method</technical_language>

Target:
private void assignInstancesToContainers( ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation, Map<String, Integer> parallelismMap, int firstTaskIndex) { ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(parallelismMap); int globalTaskIndex = firstTaskIndex; for (RamRequirement ramRequirement : ramRequirements) { String component = ramRequirement.getComponentName(); int numInstance = parallelismMap.get(component); for (int j = 0; j < numInstance; j++) { Resource instanceResource = this.defaultInstanceResources.cloneWithRam(ramRequirement.getRamRequirement()); int containerId = placeFFDInstance(containers, new PackingPlan.InstancePlan(new InstanceId( component, globalTaskIndex, j), instanceResource)); List<InstanceId> instances = allocation.get(containerId); if (instances == null) { instances = new ArrayList<>(); } instances.add(new InstanceId(component, globalTaskIndex++, j)); allocation.put(containerId, instances); } } }
Source:
<code>private void dumpLongRunningTransaction(IgniteInternalTx tx) { if (cctx.tm().txOwnerDumpRequestsAllowed() && tx.local() && tx.state() == TransactionState.ACTIVE) { Collection<UUID> masterNodeIds = tx.masterNodeIds(); if (masterNodeIds.size() == 1) { UUID nearNodeId = masterNodeIds.iterator().next(); long txOwnerThreadId = tx.threadId(); Ignite ignite = cctx.kernalContext().grid(); ClusterGroup nearNode = ignite.cluster().forNodeId(nearNodeId); if (allNodesSupports(nearNode.nodes(), TRANSACTION_OWNER_THREAD_DUMP_PROVIDING)) { IgniteCompute compute = ignite.compute(ignite.cluster().forNodeId(nearNodeId)); try { compute .callAsync(new FetchActiveTxOwnerTraceClosure(txOwnerThreadId)) .listen(new IgniteInClosure<IgniteFuture<String>>() { @Override public void apply(IgniteFuture<String> strIgniteFut) { String traceDump = null; try { traceDump = strIgniteFut.get(); } catch (Exception e) { <START> U.warn( <END> diagnosticLog, "Could not get thread dump from transaction owner near node: " + e.getMessage() ); } if (traceDump != null) { U.warn( diagnosticLog, String.format( "Dumping the near node thread that started transaction [xidVer=%s]\n%s", tx.xidVersion().toString(), traceDump ) ); } } }); } catch (Exception e) { U.warn(diagnosticLog, "Could not send dump request to transaction owner near node: " + e.getMessage()); } } else { U.warn( diagnosticLog, "Could not send dump request to transaction owner near node: node does not support this feature." ); } } } }</code><technical_language>log exception in this case. U.error(IgniteLogger, String, Throwable) for it</technical_language>

Target:
private void dumpLongRunningTransaction(IgniteInternalTx tx) { if (cctx.tm().txOwnerDumpRequestsAllowed() && tx.local() && tx.state() == TransactionState.ACTIVE) { Collection<UUID> masterNodeIds = tx.masterNodeIds(); if (masterNodeIds.size() == 1) { UUID nearNodeId = masterNodeIds.iterator().next(); long txOwnerThreadId = tx.threadId(); Ignite ignite = cctx.kernalContext().grid(); ClusterGroup nearNode = ignite.cluster().forNodeId(nearNodeId); if (allNodesSupports(nearNode.nodes(), TRANSACTION_OWNER_THREAD_DUMP_PROVIDING)) { IgniteCompute compute = ignite.compute(ignite.cluster().forNodeId(nearNodeId)); try { compute .callAsync(new FetchActiveTxOwnerTraceClosure(txOwnerThreadId)) .listen(new IgniteInClosure<IgniteFuture<String>>() { @Override public void apply(IgniteFuture<String> strIgniteFut) { String traceDump = null; try { traceDump = strIgniteFut.get(); } catch (Exception e) { U.error( diagnosticLog, "Could not get thread dump from transaction owner near node: ", e ); } if (traceDump != null) { U.warn( diagnosticLog, String.format( "Dumping the near node thread that started transaction [xidVer=%s]\n%s", tx.xidVersion().toString(), traceDump ) ); } } }); } catch (Exception e) { U.error(diagnosticLog, "Could not send dump request to transaction owner near node: ", e); } } else { U.warn( diagnosticLog, "Could not send dump request to transaction owner near node: node does not support this feature." ); } } } }
Source:
<code>public List<String> getApplicableCallOwners() { return Arrays.asList( JAVAX_CRYPTO_KEY_GENERATOR, JAVA_SECURITY_KEY_PAIR_GENERATOR, JAVAX_CRYPTO_KEY_AGREEMENT, <START> OWNER_SECURE_RANDOM <END> ); }</code><technical_language>Please add: (1) javax.crypto.Signature (ideally if generate signatures -- i.e., invokes "initSign" methods), (2) javax.crypto.Cipher (ideally if init invoked opmode WRAP_MODE ENCRYPT_MODE), (3) javax.net.ssl.SSLEngine</technical_language>

Target:
public List<String> getApplicableCallOwners() { return Arrays.asList( JAVAX_CRYPTO_KEY_GENERATOR, JAVA_SECURITY_KEY_PAIR_GENERATOR, JAVAX_CRYPTO_KEY_AGREEMENT, OWNER_SECURE_RANDOM, JAVAX_NET_SSL_SSLENGINE, JAVAX_CRYPTO_SIGNATURE, JAVAX_CRYPTO_CIPHER ); }
Source:
<code>public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } CourseSignup entity = courseService.signup(courseId, components, email, message); <START> ResponseBuilderImpl builder = new ResponseBuilderImpl(); <END> builder.status(201); builder.entity(entity); return builder.build(); }</code><technical_language>implementation ResponseBuilder class</technical_language>

Target:
public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } CourseSignup entity = courseService.signup(courseId, components, email, message); ResponseBuilder builder = new ResponseBuilderImpl(); builder.status(201); builder.entity(entity); return builder.build(); }
Source:
<code>public T call() throws Exception { Exception lastException = null; do { try { logger.fine(String.format("%d tries remaining for task %s", triesRemaining, task)); T t = task.call(); logger.fine(String.format("Success with %d tries remaining for task %s", <START> triesRemaining, task)); <END> return t; } catch (RetryException re) { throw re; } catch (InterruptedException e) { throw e; } catch (Exception e) { lastException = e; Thread.sleep(timeToWait); } } while (--triesRemaining > 0); throw new RetryException(String.format("Failed after %d attempts for task %s", totalRetries, task), lastException); }</code><technical_language>I is issue successful attempt consumed of tries. In case log message triesRemaining - 1. arguably field parameter called totalRetries totalTries message is correct while condition --triesRemaining >= 0</technical_language>

Target:
public T call() throws Exception { Exception lastException = null; do { try { logger.fine(String.format("%d tries remaining for task %s", triesRemaining, task)); T t = task.call(); return t; } catch (RetryException re) { throw re; } catch (InterruptedException e) { throw e; } catch (Exception e) { lastException = e; Thread.sleep(timeToWait); } } while (--triesRemaining > 0); throw new RetryException(String.format("Failed after %d attempts for task %s", totalTries, task), lastException); }
Source:
<code>public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); <START> boolean checkForInstructorAccess = logic.getInstructorForGoogleId(courseId, userInfo.getId()) != null; <END> if (userInfo.isInstructor && checkForInstructorAccess) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, userInfo.getId()), logic.getCourse(courseId)); return; } boolean checkForStudentAccess = logic.getStudentForGoogleId(courseId, userInfo.getId()) != null; if (userInfo.isStudent && checkForStudentAccess) { CourseAttributes course = logic.getCourse(courseId); gateKeeper.verifyAccessible(logic.getStudentForGoogleId(courseId, userInfo.id), course); return; } throw new UnauthorizedAccessException("Student or instructor account is required to access this resource."); }</code><technical_language>Consider Const.ParamsNames.ENTITY_TYPE)? do think? I idea of identifying "who are" in server side. is expensive do that. Instead, I prefer client (the frontend) explicitly intent (e.g., requesting resource behalf of student instructor)</technical_language>

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String entityType = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); if (userInfo.isInstructor && Const.EntityType.INSTRUCTOR.equals(entityType)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, userInfo.getId()), logic.getCourse(courseId)); return; } if (userInfo.isStudent && Const.EntityType.STUDENT.equals(entityType)) { CourseAttributes course = logic.getCourse(courseId); gateKeeper.verifyAccessible(logic.getStudentForGoogleId(courseId, userInfo.id), course); return; } throw new UnauthorizedAccessException("Student or instructor account is required to access this resource."); }
Source:
<code>private ResultScanner<Row> streamRows(ReadRowsRequest request) { PooledChannel reservedChannel = channelPool.reserveChannel(); final ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = reservedChannel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); int timeout = retryOptions.getReadPartialRowTimeoutMillis(); int streamingBufferSize = retryOptions.getStreamingBufferSize(); int batchRequestSize = retryOptions.getStreamingBatchSize(); ResponseQueueReader responseQueueReader = new ResponseQueueReader(timeout, streamingBufferSize, batchRequestSize, batchRequestSize, readRowsCall); <START> System.out.println(String.format("Buffer size: %d, Batch size: %d", streamingBufferSize, <END> batchRequestSize)); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner(reservedChannel, responseQueueReader, cancellationToken); clientCallService.asyncServerStreamingCall( readRowsCall, request, createClientCallListener(resultScanner)); if (batchRequestSize > 1) { readRowsCall.request(batchRequestSize - 1); } return resultScanner; }</code><technical_language>log instead of system.out</technical_language>

Target:
private ResultScanner<Row> streamRows(ReadRowsRequest request) { PooledChannel reservedChannel = channelPool.reserveChannel(); final ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = reservedChannel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); int timeout = retryOptions.getReadPartialRowTimeoutMillis(); int streamingBufferSize = retryOptions.getStreamingBufferSize(); int batchRequestSize = retryOptions.getStreamingBatchSize(); ResponseQueueReader responseQueueReader = new ResponseQueueReader(timeout, streamingBufferSize, batchRequestSize, batchRequestSize, readRowsCall); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner(reservedChannel, responseQueueReader, cancellationToken); clientCallService.asyncServerStreamingCall( readRowsCall, request, createClientCallListener(resultScanner)); if (batchRequestSize > 1) { readRowsCall.request(batchRequestSize - 1); } return resultScanner; }
Source:
<code>private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); <START> if (destinationPath == PathManager.getInstance().getRecordingPath("")) { <END> return false; } return !StringUtils.isBlank(name); }</code><technical_language>welcome! noticed wrong error message a consequence of wrong comparison. isNameValid(name) returning true false, if statement enterPressed() executed causing this bug</technical_language>

Target:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); return !destinationPath.equals(PathManager.getInstance().getRecordingPath("")); }
Source:
<code>public CommandWrapper() { <START> command = null; <END> }</code><technical_language>this(null);</technical_language>

Target:
public CommandWrapper() { this(null); }
Source:
<code>public ByAll(By[] bys) { super(bys); checkNotNull(bys); <START> if (bys.length == 0) { <END> throw new IllegalArgumentException("By array should not be empty"); } this.bys = bys; }</code><technical_language>isEmpty()</technical_language>

Target:
public ByAll(By[] bys) { super(bys); checkNotNull(bys); this.bys = Arrays.asList(bys); checkArgument(this.bys.isEmpty(), "By array should not be empty"); }
Source:
<code>RecoveryTestClusterManager(StaticClusterManager staticClusterManager, HelixClusterManager helixClusterManager) { this.staticClusterManager = staticClusterManager; <START> this.helixClusterManager = helixClusterManager; <END> ambryDataNodeToDataNodeMap = new HashMap<>(); ambryDiskToDiskMap = new HashMap<>(); }</code><technical_language>do Objects.requireNonNull() params</technical_language>

Target:
RecoveryTestClusterManager(StaticClusterManager staticClusterManager, HelixClusterManager helixClusterManager) { this.staticClusterManager = Objects.requireNonNull(staticClusterManager); this.helixClusterManager = Objects.requireNonNull(helixClusterManager); ambryDataNodeToDataNodeMap = new HashMap<>(); ambryDiskToDiskMap = new HashMap<>(); }
Source:
<code>public String createAvatarHtml() { StringWriter string = new StringWriter(); HtmlWriter html = new HtmlWriter(string); try { String name = getName(); html.writeStart("span", "class", "ToolUserAvatar", "title", name); { StringBuilder initials = new StringBuilder(); String[] nameParts = name.split("\\s+"); for (int i = 0, length = nameParts.length; i < length; ++ i) { String namePart = nameParts[i]; <START> if (!StringUtils.isBlank(namePart)) { <END> char initial = namePart.charAt(0); if (Character.isLetter(initial)) { initials.append(initial); if (initials.length() >= 2) { break; } } } } html.writeHtml(initials); StorageItem avatar = getAvatar(); if (avatar != null) { html.writeElement("img", "src", ImageEditor.Static.resize(ImageEditor.Static.getDefault(), avatar, null, 100, 100).getPublicUrl()); } else { String email = getEmail(); if (!ObjectUtils.isBlank(email)) { String hash = StringUtils.hex(StringUtils.md5(email.trim().toLowerCase(Locale.ENGLISH))); html.writeElement("img", "src", StringUtils.addQueryParameters( "<LINK_0>" + hash, "s", 100, "d", "blank")); } } } html.writeEnd(); return string.toString(); } catch (IOException error) { throw new IllegalStateException(error); } }</code><technical_language>Instead of checking for blank-ness here, .trim() name line 1052</technical_language>

Target:
public String createAvatarHtml() { StringWriter string = new StringWriter(); HtmlWriter html = new HtmlWriter(string); try { String name = getName(); html.writeStart("span", "class", "ToolUserAvatar", "title", name); { StringBuilder initials = new StringBuilder(); if (StringUtils.isBlank(name)) { initials.append("?"); } else { String[] nameParts = name.trim().split("\\s+"); for (int i = 0, length = nameParts.length; i < length; ++i) { char initial = nameParts[i].charAt(0); if (Character.isLetter(initial)) { initials.append(initial); if (initials.length() >= 2) { break; } } } } html.writeHtml(initials); StorageItem avatar = getAvatar(); if (avatar != null) { html.writeElement("img", "src", ImageEditor.Static.resize(ImageEditor.Static.getDefault(), avatar, null, 100, 100).getPublicUrl()); } else { String email = getEmail(); if (!ObjectUtils.isBlank(email)) { String hash = StringUtils.hex(StringUtils.md5(email.trim().toLowerCase(Locale.ENGLISH))); html.writeElement("img", "src", StringUtils.addQueryParameters( "<LINK_0>" + hash, "s", 100, "d", "blank")); } } } html.writeEnd(); return string.toString(); } catch (IOException error) { throw new IllegalStateException(error); } }
Source:
<code><START> public void addCommonWhereConditions(final Optional<Integer> gid, final StringBuilder builder) { <END> builder.append("WHERE g.deleted = 0 AND g.gpid1 = :femaleParentId "); if(gid.isPresent()) { builder.append("AND g.gid <> :gid "); } }</code><technical_language>access modifier for addCommonWhereConditions private</technical_language>

Target:
private void addCommonWhereConditions(final Optional<Integer> gid, final StringBuilder builder) { builder.append("WHERE g.deleted = 0 AND g.gpid1 = :femaleParentId "); if(gid.isPresent()) { builder.append("AND g.gid <> :gid "); } }
Source:
<code>void insertProperties(final DataObject dataObject) { final DataType existing = findDataTypeByName(dataObject.getClassType()); <START> final DataTypeListItem item = findItem(existing).get(); <END> for (final DataObjectProperty property : dataObject.getProperties()) { final DataType newDataType = createNewDataType(property); item.insertNestedField(newDataType); } }</code><technical_language>add NPE guard: java findItem(existing).ifPresent(item -> { for (final DataObjectProperty property : dataObject.getProperties()) { final DataType newDataType = createNewDataType(property); item.insertNestedField(newDataType); } });</technical_language>

Target:
void insertProperties(final DataObject dataObject) { final Optional<DataType> existing = findDataTypeByName(dataObject.getClassType()); existing.ifPresent(dataType -> { findItem(dataType).ifPresent(item -> { for (final DataObjectProperty property : dataObject.getProperties()) { final DataType newDataType = createNewDataType(property); item.insertNestedField(newDataType); } }); }); }
Source:
<code>protected HttpURLConnection configureRequest(final HttpURLConnection request) { GitHubAccount account = accountProvider.get(); if (Log.isLoggable(TAG, DEBUG)) Log.d(TAG, "Authenticating using " + account); <START> if(account.authToken != null) END> setOAuth2Token(account.authToken); else setCredentials(account.username, account.password); return super.configureRequest(request); }</code><technical_language>I do a !TextUtils.isEmpty(account.authToken) instead safe side</technical_language>

Target:
protected HttpURLConnection configureRequest(final HttpURLConnection request) { GitHubAccount account = accountProvider.get(); if (Log.isLoggable(TAG, DEBUG)) Log.d(TAG, "Authenticating using " + account); if(!TextUtils.isEmpty(account.authToken)) setOAuth2Token(account.authToken); else setCredentials(account.username, account.password); return super.configureRequest(request); }
Source:
<code>public boolean isItemRangeMeetingDisplayed() { <START> WebElement elem = driver.findElement(By.xpath(" END> + "/descendant::div[contains(@class,'item range meeting')]")); return elem.isDisplayed(); }</code><technical_language>page factory</technical_language>

Target:
public boolean isItemRangeMeetingDisplayed() { return itemRangeMeeting.isDisplayed(); }
Source:
<code>private ListenableFuture<Void> deinitInternal() { synchronized (mInitDeinitLock) { switch (mInitState) { case UNINITIALIZED: <START> return Futures.immediateFuture(null); <END> case INITIALIZING: throw new IllegalStateException( "CameraX could not be deinitialized when it is initializing."); case INITIALIZED: mInitState = InternalInitState.DEINITIALIZED; mDeinitInternalFuture = CallbackToFutureAdapter.getFuture( completer -> { ListenableFuture<Void> future = mCameraRepository.deinit(); future.addListener(() -> { if (mCameraExecutor instanceof CameraExecutor) { CameraExecutor executor = (CameraExecutor) mCameraExecutor; executor.deinit(); } completer.set(null); }, mCameraExecutor); return "CameraX deinitInternal"; } ); return mDeinitInternalFuture; case DEINITIALIZED: return mDeinitInternalFuture; default: throw new IllegalStateException( "deinitInternal() should not be possible from state: " + mInitState); } } }</code><technical_language>This change state DEINITIALIZED</technical_language>

Target:
private ListenableFuture<Void> deinitInternal() { synchronized (mInitDeinitLock) { switch (mInitState) { case UNINITIALIZED: mInitState = InternalInitState.DEINITIALIZED; return Futures.immediateFuture(null); case INITIALIZING: throw new IllegalStateException( "CameraX could not be deinitialized when it is initializing."); case INITIALIZED: mInitState = InternalInitState.DEINITIALIZED; mDeinitInternalFuture = CallbackToFutureAdapter.getFuture( completer -> { ListenableFuture<Void> future = mCameraRepository.deinit(); future.addListener(() -> { if (mCameraExecutor instanceof CameraExecutor) { CameraExecutor executor = (CameraExecutor) mCameraExecutor; executor.deinit(); } completer.set(null); }, mCameraExecutor); return "CameraX deinitInternal"; } ); case DEINITIALIZED: break; } } return mDeinitInternalFuture; }
Source:
<code>public void setName(String name) { if(!PodTemplateUtils.validateContainerName(name)) { <START> throw new IllegalArgumentException(String.format("Container Names MUST match RFC 1123 - They can only contain lowercase letters, numbers or dashes. ContainerName-%s",name)); <END> } this.name = name; }</code><technical_language>Fine add FormValidation DescriptorImpl.doCheckName(@QueryParameter String name) users of **Pipeline Syntax** a _proposed_ step configuration is invalid</technical_language>

Target:
public void setName(String name) { this.name = name; }
Source:
<code>public NetworkDispatcher(NetworkManager manager) { super(false); this.manager = manager; this.scm = null; this.side = Side.CLIENT; <START> this.modList = new HashMap<>(); <END> this.handshakeChannel = new EmbeddedChannel(new HandshakeInjector(this), new ChannelRegistrationHandler(), new FMLHandshakeCodec(), new HandshakeMessageHandler<FMLHandshakeClientState>(FMLHandshakeClientState.class)); this.handshakeChannel.attr(FML_DISPATCHER).set(this); this.handshakeChannel.attr(NetworkRegistry.CHANNEL_SOURCE).set(Side.SERVER); this.handshakeChannel.attr(NetworkRegistry.FML_CHANNEL).set("FML|HS"); this.handshakeChannel.attr(IS_LOCAL).set(manager.isLocalChannel()); if (DEBUG_HANDSHAKE) PacketLoggingHandler.register(manager); }</code><technical_language>Collections.emptyMap() for a non-null initial value, making empty HashMaps</technical_language>

Target:
public NetworkDispatcher(NetworkManager manager) { super(false); this.manager = manager; this.scm = null; this.side = Side.CLIENT; this.handshakeChannel = new EmbeddedChannel(new HandshakeInjector(this), new ChannelRegistrationHandler(), new FMLHandshakeCodec(), new HandshakeMessageHandler<FMLHandshakeClientState>(FMLHandshakeClientState.class)); this.handshakeChannel.attr(FML_DISPATCHER).set(this); this.handshakeChannel.attr(NetworkRegistry.CHANNEL_SOURCE).set(Side.SERVER); this.handshakeChannel.attr(NetworkRegistry.FML_CHANNEL).set("FML|HS"); this.handshakeChannel.attr(IS_LOCAL).set(manager.isLocalChannel()); if (DEBUG_HANDSHAKE) PacketLoggingHandler.register(manager); }
Source:
<code>public final void onSensorChanged(SensorEvent sensorEvent) { JsonObject jsonObject = new JsonObject(); if (timestampZeroReferenceNanos <= 0) { timestampZeroReferenceNanos = sensorEvent.timestamp; long uptimeNanos; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { uptimeNanos = SystemClock.elapsedRealtimeNanos(); } else { <START> uptimeNanos = SystemClock.elapsedRealtime() * 100000; END> } long timestampReferenceMillis = System.currentTimeMillis() + ((timestampZeroReferenceNanos - uptimeNanos) / 1000000L); Date timestampReferenceDate = new Date(timestampReferenceMillis); jsonObject.addProperty(TIMESTAMP_DATE_KEY, new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601, Locale.getDefault()) .format(timestampReferenceDate)); } jsonObject.addProperty(TIMESTAMP_IN_SECONDS_KEY, (sensorEvent.timestamp - timestampZeroReferenceNanos) * 1e-9); jsonObject.addProperty(UPTIME_IN_SECONDS_KEY, sensorEvent.timestamp * 1e-9); recordSensorEvent(sensorEvent, jsonObject); writeJsonObjectToFile(jsonObject); }</code><technical_language>/ 1e-6</technical_language>

Target:
public final void onSensorChanged(SensorEvent sensorEvent) { JsonObject jsonObject = new JsonObject(); if (timestampZeroReferenceNanos <= 0) { timestampZeroReferenceNanos = sensorEvent.timestamp; long uptimeNanos; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { uptimeNanos = SystemClock.elapsedRealtimeNanos(); } else { uptimeNanos = (long) (SystemClock.elapsedRealtime() * 1e6); } long timestampReferenceMillis = System.currentTimeMillis() + (long) ((timestampZeroReferenceNanos - uptimeNanos) * 1e-6d); Date timestampReferenceDate = new Date(timestampReferenceMillis); jsonObject.addProperty(TIMESTAMP_DATE_KEY, new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601, Locale.getDefault()) .format(timestampReferenceDate)); } jsonObject.addProperty(TIMESTAMP_IN_SECONDS_KEY, (sensorEvent.timestamp - timestampZeroReferenceNanos) * 1e-9); jsonObject.addProperty(UPTIME_IN_SECONDS_KEY, sensorEvent.timestamp * 1e-9); recordSensorEvent(sensorEvent, jsonObject); writeJsonObjectToFile(jsonObject); }
Source:
<code>private static <T> ClassLoadingStrategy<ClassLoader> chooseClassLoadingStrategy(Class<T> type) { try { final ClassLoadingStrategy<ClassLoader> strategy; if (ClassInjector.UsingLookup.isAvailable() && privateLookupIn != null && lookup != null) { Object privateLookup = privateLookupIn.invoke(null, type, lookup); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } return strategy; } catch (Exception e) { return null; } <START> } <END></code><technical_language>I need catch Exception return null. throw IllegalStateException caller handle exception</technical_language>

Target:
private static <T> ClassLoadingStrategy<ClassLoader> chooseClassLoadingStrategy(Class<T> type) { try { final ClassLoadingStrategy<ClassLoader> strategy; if (ClassInjector.UsingLookup.isAvailable() && PRIVATE_LOOKUP_IN != null && LOOKUP != null) { Object privateLookup = PRIVATE_LOOKUP_IN.invoke(null, type, LOOKUP); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } return strategy; } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); } }
Source:
<code>public String getInstanceID() { <START> context.ensureOpen(); <END> final String instanceName = context.info.getInstanceName(); if (context.instanceId == null) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + instanceName; byte[] iidb = context.zooCache.get(instanceNamePath); if (iidb == null) { throw new RuntimeException( "Instance name " + instanceName + " does not exist in zookeeper. " + "Run \"accumulo org.apache.accumulo.server.util.ListInstances\" to see a list."); } context.instanceId = new String(iidb, UTF_8); } if (context.zooCache.get(Constants.ZROOT + "/" + context.instanceId) == null) { if (instanceName == null) throw new RuntimeException( "Instance id " + context.instanceId + " does not exist in zookeeper"); throw new RuntimeException("Instance id " + context.instanceId + " pointed to by the name " + instanceName + " does not exist in zookeeper"); } return context.instanceId; }</code><technical_language>leave implementation of getInstanceID() in Client context. private members of client context need exposed. This method return context.getInstanceID()</technical_language>

Target:
public String getInstanceID() { return context.getInstanceID(); }
Source:
<code>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final CachedAsset cachedAsset = loadAsset(req.getRequestURI()); if (cachedAsset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (isCachedClientSide(req, cachedAsset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); final Buffer mimeType = mimeTypes.getMimeByExtension(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeType != null) { try { mediaType = MediaType.parse( mimeType.toString() ); if (defaultCharset != null && mediaType.is( MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch ( IllegalArgumentException ignore ) } resp.setContentType( mediaType.type() + "/" + mediaType.subtype() ); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding( mediaType.charset().get().toString() ); } final ServletOutputStream output = resp.getOutputStream(); try { output.write(cachedAsset.getResource()); } finally { output.close(); } <START> } catch (RuntimeException ignored) {ignored.printStackTrace(); <END> resp.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }</code><technical_language>This go</technical_language>

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final CachedAsset cachedAsset = loadAsset(req.getRequestURI()); if (cachedAsset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (isCachedClientSide(req, cachedAsset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); final Buffer mimeTypeOfExtension = mimeTypes.getMimeByExtension(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeTypeOfExtension != null) { try { mediaType = MediaType.parse(mimeTypeOfExtension.toString()); if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch (IllegalArgumentException ignore) } resp.setContentType(mediaType.type() + "/" + mediaType.subtype()); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding(mediaType.charset().get().toString()); } final ServletOutputStream output = resp.getOutputStream(); try { output.write(cachedAsset.getResource()); } finally { output.close(); } } catch (RuntimeException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
<code>public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); <START> return queryEngine.executeQuery(query); <END> }</code><technical_language>Ideally, I this is cache queried for entries. This allow cache for multiple engines (Fili, SQL, etc). I cache key generation logic common well. key derived Query object (rather generated SQL) data freshness key (which query engine surface)</technical_language>

Target:
public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); QueryResult result = null; String cacheKey = null; if (cache != null && !query.isBypassingCache()) { String tableVersion = queryEngine.getTableVersion(query.getTable(), queryEngineTransaction); if (tableVersion != null) { cacheKey = tableVersion + ';' + QueryKeyExtractor.extractKey(query); result = cache.get(cacheKey); } } if (result == null) { result = queryEngine.executeQuery(query, queryEngineTransaction); if (cacheKey != null) { cache.put(cacheKey, result); } } if (entityProjection.getPagination() != null && entityProjection.getPagination().returnPageTotals()) { entityProjection.getPagination().setPageTotals(result.getPageTotals()); } return result.getData(); }
Source:
<code>private synchronized void startZkServer() { lastCommitted = zk.getZxid(); LOG.info("Have quorum of supporters, sids: [{}]; starting up and setting last processed zxid: 0x{}", newLeaderProposal.ackSetsToString(), Long.toHexString(zk.getZxid())); if (QuorumPeerConfig.isReconfigEnabled()) { QuorumVerifier newQV = self.getLastSeenQuorumVerifier(); Long designatedLeader = getDesignatedLeader(newLeaderProposal, zk.getZxid()); self.processReconfig(newQV, designatedLeader, zk.getZxid(), true); if (designatedLeader != self.getId()) { LOG.warn("This leader is not the designated leader, it will be initialized with allowedToCommit = false"); allowedToCommit = false; } } else { <START> LOG.debug("Reconfig feature is disabled, skip designatedLeader calculation and reconfig processing."); <END> } leaderStartTime = Time.currentElapsedTime(); zk.startup(); self.updateElectionVote(getEpoch()); zk.getZKDatabase().setlastProcessedZxid(zk.getZxid()); }</code><technical_language>LOG.debug -> putting LOG.info ? In new test cases, exercising this branch "if QuorumPeerConfig.isReconfigEnabled()" branch</technical_language>

Target:
private synchronized void startZkServer() { lastCommitted = zk.getZxid(); LOG.info("Have quorum of supporters, sids: [{}]; starting up and setting last processed zxid: 0x{}", newLeaderProposal.ackSetsToString(), Long.toHexString(zk.getZxid())); if (self.isReconfigEnabled()) { QuorumVerifier newQV = self.getLastSeenQuorumVerifier(); Long designatedLeader = getDesignatedLeader(newLeaderProposal, zk.getZxid()); self.processReconfig(newQV, designatedLeader, zk.getZxid(), true); if (designatedLeader != self.getId()) { LOG.warn("This leader is not the designated leader, it will be initialized with allowedToCommit = false"); allowedToCommit = false; } } else { LOG.info("Dynamic reconfig feature is disabled, skip designatedLeader calculation and reconfig processing."); } leaderStartTime = Time.currentElapsedTime(); zk.startup(); self.updateElectionVote(getEpoch()); zk.getZKDatabase().setlastProcessedZxid(zk.getZxid()); }
Source:
<code><START> public static void validateRefPattern(String refPattern) <END> throws InvalidNameException { if (refPattern.startsWith(ProjectConfigSection.REGEX_PREFIX)) { if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) { throw new InvalidNameException(); } } else if (refPattern.equals(ProjectConfigSection.ALL)) { } else if (refPattern.endsWith("/*")) { String prefix = refPattern.substring(0, refPattern.length() - 2); if (!Repository.isValidRefName(prefix)) { throw new InvalidNameException(refPattern); } } else if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(refPattern); } }</code><technical_language>style-nit: newline methods is missing</technical_language>

Target:
public static void validateRefPattern(String refPattern) throws InvalidNameException { if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) { if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) { throw new InvalidNameException(refPattern); } } else if (refPattern.equals(RefConfigSection.ALL)) { } else if (refPattern.endsWith("/*")) { String prefix = refPattern.substring(0, refPattern.length() - 2); if (!Repository.isValidRefName(prefix)) { throw new InvalidNameException(refPattern); } } else if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(refPattern); } }
Source:
<code>private boolean isExistingUser(Map<String, String> subject) throws InternalErrorException { if (subject.isEmpty()) { return false; } String login = subject.get("login"); PerunSession sess = getSession(); List<User> usersFromREMS = perunBl.getUsersManagerBl().getUsersByExtSourceTypeAndLogin(sess, ExtSourcesManager.EXTSOURCE_REMS, login); if (usersFromREMS.size() > 0) { return true; } String extSource = subject.get("additionalues_1"); if (extSource == null) { log.error("Failed to get additionalues_1 from subject {}", subject); <START> throw new InternalErrorException("Failed to get additionalues_1 from subject: " + subject); <END> } String[] extSourceSplit = subject.get("additionalues_1").split("\\|", 4); if(extSourceSplit.length != 4) { log.error("Ivalid format of additionalues_1. It should be '{extSourceName}|{extSourceClass}|{eppn}|0'. Actual: {}", extSource); throw new InternalErrorException("Ivalid format of additionalues_1. It should be '{extSourceName}|{extSourceClass}|{eppn}|0', Actual: " + extSource); } String extSourceName = extSourceSplit[0]; String eppn = extSourceSplit[2]; try { perunBl.getUsersManagerBl().getUserByExtSourceNameAndExtLogin(sess, extSourceName, eppn); return true; } catch (ExtSourceNotExistsException | UserExtSourceNotExistsException e) { log.error("Failed to get extSource with name '{}'", extSourceName); } catch (UserNotExistsException e) { return false; } return false; }</code><technical_language>thrown exception is logged perun log file, need log twice</technical_language>

Target:
private boolean isExistingUser(Map<String, String> subject) throws InternalErrorException { if (subject == null || subject.isEmpty()) { throw new InternalErrorException("Subject can not be empty or null: " + subject); } String login = subject.get("login"); if (login == null || login.isEmpty()) { log.error("Failed to get user's login from subject {}"); return false; } PerunSession sess = getSession(); List<User> usersFromREMS = perunBl.getUsersManagerBl().getUsersByExtSourceTypeAndLogin(sess, ExtSourcesManager.EXTSOURCE_REMS, login); if (usersFromREMS.size() > 0) { return true; } List<String> extSources = getAdditionalUESes(subject); if (extSources.isEmpty()) { log.error("Failed to get any additionalues from subject {}", subject); return false; } for (String ues : extSources) { if (existsSubjectWithUes(ues)) { return true; } } return false; }
Source:
<code>private static synchronized void initializeModes() { if (modes != null) { return; } modes = new LinkedHashMap<>(); modes.put(GroupLaunchElement.MODE_INHERIT, new InheritModeGroup()); Set<ILaunchGroup> sortedGroups = new <START> TreeSet<>((a, b) -> a.getLabel().compareTo(b.getLabel())); <END> LaunchConfigurationManager mgr = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); sortedGroups.addAll(Arrays.asList(mgr.getLaunchGroups())); for (ILaunchGroup launchGroup : sortedGroups) { LaunchHistory history = mgr.getLaunchHistory(launchGroup.getIdentifier()); if (history == null) { continue; } String modeName = launchGroup.getMode(); if (!modes.containsKey(modeName)) { modes.put(modeName, launchGroup); } } }</code><technical_language>optimized Comparator.comparing(ILaunchGroup::getLabel)</technical_language>

Target:
private static synchronized void initializeModes() { if (modes != null) { return; } modes = new LinkedHashMap<>(); modes.put(GroupLaunchElement.MODE_INHERIT, new InheritModeGroup()); Set<ILaunchGroup> sortedGroups = new TreeSet<>(Comparator.comparing(ILaunchGroup::getLabel)); LaunchConfigurationManager mgr = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); sortedGroups.addAll(Arrays.asList(mgr.getLaunchGroups())); for (ILaunchGroup launchGroup : sortedGroups) { LaunchHistory history = mgr.getLaunchHistory(launchGroup.getIdentifier()); if (history == null) { continue; } String modeName = launchGroup.getMode(); if (!modes.containsKey(modeName)) { modes.put(modeName, launchGroup); } } }