auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void refreshProjectTree(final IProject project) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (viewer == null || viewer.getControl() == null || viewer.getControl().isDisposed()) return; Object firstItem = null; if (viewer instanceof TreeViewer) { if( ((TreeViewer) viewer).getTree().getItemCount() <= 0) { return; } else { firstItem = ((TreeViewer) viewer).getTree().getItem(0).getData(); } } else if (viewer instanceof TableViewer) { if( ((TableViewer) viewer).getTable().getItemCount() <= 0) { viewer.refresh(project); return; } else { firstItem = ((TableViewer) viewer).getTable().getItem(0).getData(); } } IContainer parentContainer = null; boolean isDrilledDown = !(firstItem instanceof IProject); if (!isDrilledDown) { viewer.refresh(project); } else { if (firstItem instanceof IResource) { parentContainer = ((IResource) firstItem).getParent(); } else if (firstItem instanceof TargetSourceContainer) { parentContainer = ((TargetSourceContainer) firstItem).getContainer().getParent(); } else if (firstItem instanceof IMakeTarget) { parentContainer = ((IMakeTarget) firstItem).getContainer(); } if (parentContainer != null && project.equals(parentContainer.getProject())) { viewer.refresh(); } } } }); }

Target:
private void refreshProjectTree(final IProject project) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (viewer == null || viewer.getControl() == null || viewer.getControl().isDisposed()) return; Object firstItem = null; if (viewer instanceof TreeViewer) { if( ((TreeViewer) viewer).getTree().getItemCount() <= 0) { return; } else { firstItem = ((TreeViewer) viewer).getTree().getItem(0).getData(); } } else if (viewer instanceof TableViewer) { if( ((TableViewer) viewer).getTable().getItemCount() <= 0) { viewer.refresh(); return; } else { firstItem = ((TableViewer) viewer).getTable().getItem(0).getData(); } } IContainer parentContainer = null; boolean isDrilledDown = !(firstItem instanceof IProject); if (!isDrilledDown) { viewer.refresh(project); } else { if (firstItem instanceof IResource) { parentContainer = ((IResource) firstItem).getParent(); } else if (firstItem instanceof TargetSourceContainer) { parentContainer = ((TargetSourceContainer) firstItem).getContainer().getParent(); } else if (firstItem instanceof IMakeTarget) { parentContainer = ((IMakeTarget) firstItem).getContainer(); } if (parentContainer != null && project.equals(parentContainer.getProject())) { viewer.refresh(); } } } }); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE_FROM_SEARCH) { int position = 0; finalLanguageList = StringUtil.listToJsonArrayString(app.language().getAppLanguageCodes()); if (!finalLanguageList.equals(initialLanguageList)) { requireActivity().setResult(RESULT_LANG_CHANGED); } if (data != null && data.hasExtra(ACTIVITY_RESULT_LANG_POSITION_DATA)) { position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); } else if (app.language().getAppLanguageCodes().contains(searchLanguageCode)) { position = app.language().getAppLanguageCodes().indexOf(searchLanguageCode); } searchResultsFragment.clearSearchResultsCountCache(); Prefs.setSelectedLanguagePositionInSearch(position); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE_FROM_SEARCH) { int position = 0; String finalLanguageList = StringUtil.listToJsonArrayString(app.language().getAppLanguageCodes()); if (!finalLanguageList.equals(initialLanguageList)) { requireActivity().setResult(RESULT_LANG_CHANGED); } if (data != null && data.hasExtra(ACTIVITY_RESULT_LANG_POSITION_DATA)) { position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); } else if (app.language().getAppLanguageCodes().contains(searchLanguageCode)) { position = app.language().getAppLanguageCodes().indexOf(searchLanguageCode); } searchResultsFragment.clearSearchResultsCountCache(); Prefs.setSelectedLanguagePositionInSearch(position); } }
Source:
public final void run() { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThread", "start", fZoomStartTime, "end", fZoomEndTime).setCategoryAndId(getViewId(), fScopeId).build()) { doRun(); } finally { fDirty.incrementAndGet(); } }

Target:
public final void run() { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThread", "start", fZoomStartTime, "end", fZoomEndTime).setCategoryAndId(getViewId(), fScopeId).build()) { doRun(); } finally { if (fDirty.decrementAndGet() < 0) { Activator.getDefault().logError(DIRTY_UNDERFLOW_ERROR, new Throwable()); } } }
Source:
public static ScalarFunction getFloorExpression(List<Expression> children) throws SQLException { final Expression firstChild = children.get(0); final PDataType firstChildDataType = firstChild.getDataType(); if(firstChildDataType.isCoercibleTo(PDataType.DATE) || firstChildDataType == PDataType.TIMESTAMP) { return new FloorDateExpression(children); } else if(firstChildDataType.isCoercibleTo(PDataType.DECIMAL)) { return new FloorDecimalExpression(children); } else { throw new TypeMismatchException(firstChildDataType, "1"); } }

Target:
public static ScalarFunction getFloorExpression(List<Expression> children) throws SQLException { final Expression firstChild = children.get(0); final PDataType firstChildDataType = firstChild.getDataType(); if(firstChildDataType.isCoercibleTo(PDataType.DATE) || firstChildDataType == PDataType.TIMESTAMP || firstChildDataType == PDataType.UNSIGNED_TIMESTAMP) { return new FloorDateExpression(children); } else if(firstChildDataType.isCoercibleTo(PDataType.DECIMAL)) { return new FloorDecimalExpression(children); } else { throw new TypeMismatchException(firstChildDataType, "1"); } }
Source:
private void displayAppStateMetadata(int stateKey) { TextView metaDataView = (TextView) findViewById(R.id.text_metadata); metaDataView.setText(""); String metadataStr = "Source: Cloud Save" + '\n' + "State Key: " + stateKey; metaDataView.setText(metadataStr); }

Target:
private void displayAppStateMetadata(int stateKey) { TextView metaDataView = (TextView) findViewById(R.id.text_metadata); String metadataStr = "Source: Cloud Save" + '\n' + "State Key: " + stateKey; metaDataView.setText(metadataStr); }
Source:
private void updateBackup() { if (getCurrentStorageItem() != null && getAvailableStorageTypeItems().getSelectedItem() != null) { boolean isStorageDomainUnattached = getDataCenter().getSelectedItem().getId().equals(UnassignedDataCenterId); if (isStorageDomainUnattached) { if (getCurrentStorageItem().getRole().isDataDomain()) { getBackup().setIsAvailable(true); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); return; } else { getBackup().setIsAvailable(false); getBackup().setEntity(false); return; } } if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { getBackup().setIsAvailable(false); getBackup().setEntity(false); return; } else { boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); return; } } getBackup().setIsAvailable(false); getBackup().setEntity(false); return; }

Target:
private void updateBackup() { if (getCurrentStorageItem() != null && getAvailableStorageTypeItems().getSelectedItem() != null) { boolean isStorageDomainUnattached = getDataCenter().getSelectedItem().getId().equals(UnassignedDataCenterId); if (isStorageDomainUnattached) { if (getCurrentStorageItem().getRole().isDataDomain()) { getBackup().setIsAvailable(true); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); } else { getBackup().setIsAvailable(false); getBackup().setEntity(false); } return; } if (getCurrentStorageItem().getRole() == StorageDomainType.ISO || getCurrentStorageItem().getRole() == StorageDomainType.ImportExport) { getBackup().setIsAvailable(false); getBackup().setEntity(false); } else { boolean backupSupported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted( ConfigValues.BackupSupported, getDataCenter().getSelectedItem().getCompatibilityVersion().toString()); getBackup().setIsAvailable(backupSupported); getBackup().setEntity(isNewStorage() ? false : getStorage().isBackup()); } return; } else { getBackup().setIsAvailable(false); getBackup().setEntity(false); } return; }
Source:
public SharkCollisionBehaviour(Displayable me) { super(); this.handler = new OnCollisionPlayerLosesComponent(me, new OnCollisionIncreaseSizeComponent(me, new OnCollisionIncreaseAmmunitionComponent(me, new OnCollisionHighScoreIncrementComponent( new OnCollisionEatenCompomnentLeaf( new DefaultCompomnentLeaf()))))); }

Target:
public SharkCollisionBehaviour(Displayable me) { super(); this.handler = new OnCollisionPlayerLosesComponent(me, new OnCollisionIncreaseSizeComponent(me, new OnCollisionIncreaseAmmunitionComponent(me, new OnCollisionHighScoreIncrementComponent( new OnCollisionEatenComponentLeaf( new DefaultComponentLeaf()))))); }
Source:
private String[][] getAvailableMergeStrategies() { org.eclipse.egit.core.Activator coreActivator = org.eclipse.egit.core.Activator .getDefault(); List<String[]> strategies = new ArrayList<>(); strategies.add(new String[] { UIText.GitPreferenceRoot_defaultMergeStrategyLabel, GitCorePreferences.core_preferredMergeStrategy_Default }); for (MergeStrategyDescriptor strategy : coreActivator .getRegisteredMergeStrategies()) { strategies.add(new String[] { strategy.getLabel(), strategy.getName() }); } return strategies.toArray(new String[0][2]); }

Target:
private String[][] getAvailableMergeStrategies() { org.eclipse.egit.core.Activator coreActivator = org.eclipse.egit.core.Activator .getDefault(); List<String[]> strategies = new ArrayList<>(); strategies.add(new String[] { UIText.GitPreferenceRoot_defaultMergeStrategyLabel, GitCorePreferences.core_preferredMergeStrategy_Default }); for (MergeStrategyDescriptor strategy : coreActivator .getRegisteredMergeStrategies()) { strategies.add(new String[] { strategy.getLabel(), strategy.getName() }); } return strategies.toArray(new String[0][0]); }
Source:
private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } LinkPreviewFunnel linkPreviewFunnel = new LinkPreviewFunnel(app, title); if (app.getReleaseType() == WikipediaApp.RELEASE_PROD || LinkPreviewVersion.getVersion(app) == 0) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); ((PageActivity) getActivity()).displayNewPage(title, historyEntry); linkPreviewFunnel.logNavigate(); } else { LinkPreviewDialog dialog = LinkPreviewDialog.newInstance(title, LinkPreviewVersion.getVersion(app)); dialog.show(getActivity().getSupportFragmentManager(), "link_preview_dialog"); } }

Target:
private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } if (app.getReleaseType() == WikipediaApp.RELEASE_PROD || LinkPreviewVersion.getVersion(app) == 0) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); ((PageActivity) getActivity()).displayNewPage(title, historyEntry); new LinkPreviewFunnel(app, title).logNavigate(); } else { LinkPreviewDialog dialog = LinkPreviewDialog.newInstance(title, LinkPreviewVersion.getVersion(app)); dialog.show(getActivity().getSupportFragmentManager(), "link_preview_dialog"); } }
Source:
public <U> TableElement<U> map(Function<? super T, ? extends U> mapper) { return new CheckConstraint(name, expression, expressionStr); }

Target:
public <U> TableElement<U> map(Function<? super T, ? extends U> mapper) { return new CheckConstraint<>(name, columnName, mapper.apply(expression), expressionStr); }
Source:
public TestSession getNewSession(Map<String, Object> requestedCapability) { LOGGER.entering(); if (totalSessionsStarted >= maxSessionsAllowed || forceShutDown) { return logSessionInfo(); } synchronized (this) { if (totalSessionsStarted >= maxSessionsAllowed || forceShutDown) { return logSessionInfo(); } TestSession session = super.getNewSession(requestedCapability); if (session != null) { totalSessionsStarted++; if (totalSessionsStarted >= maxSessionsAllowed) { startNodeRecycleThread(); } proxyLogger.fine("Beginning session #" + totalSessionsStarted + " (" + session.toString() + ")"); } LOGGER.exiting((session != null) ? session.toString() : null); return session; } }

Target:
public TestSession getNewSession(Map<String, Object> requestedCapability) { LOGGER.entering(); if (totalSessionsStarted >= maxSessionsAllowed || forceShutDown) { return logSessionInfo(); } try { accessLock.lock(); if (totalSessionsStarted >= maxSessionsAllowed || forceShutDown) { return logSessionInfo(); } TestSession session = super.getNewSession(requestedCapability); if (session != null) { totalSessionsStarted++; if (totalSessionsStarted >= maxSessionsAllowed) { startNodeRecycleThread(); } proxyLogger.fine("Beginning session #" + totalSessionsStarted + " (" + session.toString() + ")"); } LOGGER.exiting((session != null) ? session.toString() : null); return session; } finally { accessLock.unlock(); } }
Source:
public int read() throws IOException { if (this.template != null) { if (this.templateIndex < this.template.length()) { return this.template.charAt(this.templateIndex++); } if (this.templateIndex == this.template.length()) { this.template = null; this.templateIndex = 0; } } int data = this.pushbackReader.read(); if (data != '$') { return data; } data = this.pushbackReader.read(); if (data != '{') { this.pushbackReader.unread(data); return '$'; } this.templateBuffer.delete(0, this.templateBuffer.length()); data = this.pushbackReader.read(); while (data != '}') { this.templateBuffer.append((char) data); data = this.pushbackReader.read(); } this.template = this.templateResolver .resolveTemplate(this.templateBuffer.toString()); if (this.template == null) { this.template = "${" + this.templateBuffer.toString() + "}"; } if (this.template.length() == 0) { return read(); } return this.template.charAt(this.templateIndex++); }

Target:
public int read() throws IOException { if (template != null) { if (templateIndex < template.length()) { return template.charAt(this.templateIndex++); } if (templateIndex == template.length()) { template = null; templateIndex = 0; } } int data = pushbackReader.read(); if (data != '$') { return data; } data = pushbackReader.read(); if (data != '{') { pushbackReader.unread(data); return '$'; } templateBuffer.delete(0, templateBuffer.length()); data = pushbackReader.read(); while (data != '}') { templateBuffer.append((char) data); data = pushbackReader.read(); } template = templateResolver .resolveTemplate(templateBuffer.toString()); if (template == null) { template = "${" + templateBuffer.toString() + "}"; } if (template.length() == 0) { return read(); } return template.charAt(templateIndex++); }
Source:
public OauthAuthenticationResult authenticate(HttpRequest httpRequest) { RequestLocation[] locations = this.locations != null ? this.locations : new RequestLocation[]{RequestLocation.HEADER, RequestLocation.BODY}; Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = (HttpServletRequest) httpRequest; } else if (HttpRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = new OauthHttpServletRequest((HttpRequest) httpRequest); } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpRequest.class.getName(), HttpServletRequest.class.getName())); } AuthenticationRequest request; try { request = new ResourceAuthenticationRequest(httpServletRequest, locations); } catch (Exception e) { throw ApiAuthenticationExceptionFactory.newOauthException(OauthAuthenticationException.class, OauthAuthenticationException.INVALID_REQUEST); } AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }

Target:
public OauthAuthenticationResult authenticate(HttpRequest httpRequest) { RequestLocation[] locations = this.locations != null ? this.locations : new RequestLocation[]{RequestLocation.HEADER, RequestLocation.BODY}; Class httpRequestClass = httpRequest.getClass(); if (HttpServletRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = (HttpServletRequest) httpRequest; } else if (HttpRequest.class.isAssignableFrom(httpRequestClass)) { this.httpServletRequest = new OauthHttpServletRequest(httpRequest); } else { throw new IllegalArgumentException(String.format(HTTP_REQUEST_NOT_SUPPORTED_MSG, httpRequest.getClass(), HttpRequest.class.getName(), HttpServletRequest.class.getName())); } AuthenticationRequest request; try { request = new ResourceAuthenticationRequest(httpServletRequest, locations); } catch (Exception e) { throw ApiAuthenticationExceptionFactory.newOauthException(OauthAuthenticationException.class, OauthAuthenticationException.INVALID_REQUEST); } AuthenticationResult result = application.authenticateAccount(request); Assert.isInstanceOf(OauthAuthenticationResult.class, result); return (OauthAuthenticationResult) result; }
Source:
public KafkaFuture<Void> all() { if (removeAll()) { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((memberErrors, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { System.out.println("Remove all active members succeeded, removed " + memberErrors.size() + " members: " + memberErrors.keySet()); result.complete(null); } }); return result; } else { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((memberErrors, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { for (MemberToRemove memberToRemove : memberInfos) { if (maybeCompleteExceptionally(memberErrors, memberToRemove.toMemberIdentity(), result)) { return; } } result.complete(null); } }); return result; } }

Target:
public KafkaFuture<Void> all() { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); this.future.whenComplete((memberErrors, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { if (removeAll()) { for (Map.Entry<MemberIdentity, Errors> entry: memberErrors.entrySet()) { Exception exception = entry.getValue().exception(); if (exception != null) { Throwable ex = new KafkaException("Encounter exception when trying to remove: " + entry.getKey(), exception); result.completeExceptionally(ex); return; } } } else { for (MemberToRemove memberToRemove : memberInfos) { if (maybeCompleteExceptionally(memberErrors, memberToRemove.toMemberIdentity(), result)) { return; } } } result.complete(null); } }); return result; }
Source:
public void write(JsonGenerator jg, DocumentModel document) throws IOException { jg.writeFieldName(NAME); jg.writeStartObject(); Map<String, List<String>> h = (Map<String, List<String>>) document.getContextData(NAME); if (h != null) { for (String field : h.keySet()) { jg.writeObjectField(field, h.get(field)); } } jg.writeEndObject(); }

Target:
public void write(JsonGenerator jg, DocumentModel document) throws IOException { jg.writeFieldName(HIGHLIGHT_CTX_DATA); jg.writeStartObject(); Map<String, List<String>> h = (Map<String, List<String>>) document.getContextData(HIGHLIGHT_CTX_DATA); if (h != null) { for (String field : h.keySet()) { jg.writeObjectField(field, h.get(field)); } } jg.writeEndObject(); }
Source:
private Value getSerializableValue(Object object, Schema schema) { Value value = null; switch (schema.getType()) { case UNION: if (object != null) { int schemaPos = getUnionSchema(object, schema); Schema unionSchema = schema.getTypes().get(schemaPos); value = getSerializableValue(object, unionSchema); } break; case STRING: value = Value.get(object.toString()); break; case BYTES: value = Value.get(((ByteBuffer) object).array()); break; case MAP: Map<Object, Object> newMap = new HashMap<>(); Map<?, ?> fieldMap = (Map<?, ?>) object; for (Object key : fieldMap.keySet()) { newMap.put(key.toString(), getSerializableValue(fieldMap.get(key), schema.getValueType())); } value = Value.get(newMap); break; case ARRAY: List<Object> objectList = new ArrayList<>(); for (Object obj : (List<Object>) object) { objectList.add(getSerializableValue(obj, schema.getElementType())); } value = Value.get(objectList); break; default: value = Value.get(object); break; } return value; }

Target:
private Value getSerializableValue(Object object, Schema schema) { Value value = null; switch (schema.getType()) { case UNION: if (object != null) { int schemaPos = getUnionSchema(object, schema); Schema unionSchema = schema.getTypes().get(schemaPos); value = getSerializableValue(object, unionSchema); } break; case STRING: value = Value.get(object.toString()); break; case BYTES: value = Value.get(((ByteBuffer) object).array()); break; case MAP: Map<Object, Object> newMap = new HashMap<>(); Map<?, ?> fieldMap = (Map<?, ?>) object; for (Map.Entry<?, ?> entry : fieldMap.entrySet()) { newMap.put(entry.getKey().toString(), getSerializableValue(fieldMap.get(entry.getKey()), schema.getValueType())); } value = Value.get(newMap); break; case ARRAY: List<Object> objectList = new ArrayList<>(); for (Object obj : (List<Object>) object) { objectList.add(getSerializableValue(obj, schema.getElementType())); } value = Value.get(objectList); break; default: value = Value.get(object); break; } return value; }
Source:
public void notifyRcsAutoConfigurationReceived(int subId, @NonNull byte[] config, boolean isCompressed) { try { IImsConfig configBinder = getImsConfig(getSlotIndex(subId), ImsFeature.FEATURE_RCS); configBinder.notifyRcsAutoConfigurationReceived(config, isCompressed); } catch (RemoteException e) { Rlog.e(LOG_TAG, "fail to getImsConfig " + e.getMessage()); } }

Target:
public void notifyRcsAutoConfigurationReceived(int subId, @NonNull byte[] config, boolean isCompressed) { try { IImsConfig configBinder = getImsConfig(getSlotIndex(subId), ImsFeature.FEATURE_RCS); if (configBinder == null) { Rlog.e(LOG_TAG, "null result for getImsConfig"); } else { configBinder.notifyRcsAutoConfigurationReceived(config, isCompressed); } } catch (RemoteException e) { Rlog.e(LOG_TAG, "fail to getImsConfig " + e.getMessage()); } }
Source:
public RiseTransitSet getRTS(Alloc alloc) { return new RiseTransitSet(schedule.getSite(), alloc.getObs().getCoords(alloc.getVariant().getSchedule().getMiddlePoint()), alloc.getStart()); }

Target:
public RiseTransitSet getRTS(Alloc alloc) { return new RiseTransitSet(schedule.getSite(), alloc.getObs()::getCoords, alloc.getStart()); }
Source:
private void run() { suspended.compareAndSet(true, false); running.compareAndSet(false, true); outer: while (running.get()) { try { WatchKey watchKey = service.take(); Path dir; synchronized (keys) { dir = keys.get(watchKey); } if (dir == null) { resetAndRemove(watchKey, dir); LOG.debug("Reported directory is not registered - skipping."); continue; } for (List<WatchEvent<?>> watchEvents = watchKey.pollEvents(); !watchEvents.isEmpty(); watchEvents = watchKey.pollEvents()) { if (suspended.get()) { resetAndRemove(watchKey, dir); LOG.debug("File watchers are running in suspended mode - skipping."); continue outer; } for (WatchEvent<?> event : watchEvents) { Kind<?> kind = event.kind(); if (kind == OVERFLOW) { LOG.warn("Detected file system events overflowing"); continue outer; } WatchEvent<Path> ev = cast(event); Path item = ev.context(); Path path = dir.resolve(item).toAbsolutePath(); if (excludePatternsRegistry.isExcluded(path)) { LOG.debug("Path is within exclude list, skipping..."); continue; } handler.handle(path, kind); } } resetAndRemove(watchKey, dir); } catch (InterruptedException e) { running.compareAndSet(true, false); LOG.debug( "Interruption error when running file watcher, most likely caused by stopping it", e); } catch (ClosedWatchServiceException e) { running.compareAndSet(true, false); LOG.debug("Closing watch service while some of keys may be processing", e); } } }

Target:
private void run() { suspended.compareAndSet(true, false); running.compareAndSet(false, true); outer: while (running.get()) { try { WatchKey watchKey = service.take(); Path dir; synchronized (keys) { dir = keys.get(watchKey); } if (dir == null) { resetAndRemove(watchKey, dir); LOG.debug("Reported directory is not registered - skipping."); continue; } List<WatchEvent<?>> watchEvents = watchKey.pollEvents(); while (!watchEvents.isEmpty()) { if (suspended.get()) { resetAndRemove(watchKey, dir); LOG.debug("File watchers are running in suspended mode - skipping."); continue outer; } for (WatchEvent<?> event : watchEvents) { Kind<?> kind = event.kind(); if (kind == OVERFLOW) { LOG.warn("Detected file system events overflowing"); continue outer; } WatchEvent<Path> ev = cast(event); Path item = ev.context(); Path path = dir.resolve(item).toAbsolutePath(); if (excludePatternsRegistry.isExcluded(path)) { LOG.debug("Path is within exclude list, skipping..."); continue; } handler.handle(path, kind); } watchEvents = watchKey.pollEvents(); } resetAndRemove(watchKey, dir); } catch (InterruptedException e) { running.compareAndSet(true, false); LOG.debug( "Interruption error when running file watcher, most likely caused by stopping it", e); } catch (ClosedWatchServiceException e) { running.compareAndSet(true, false); LOG.debug("Closing watch service while some of keys may be processing", e); } } }
Source:
private void renderCommands() { commandTable.removeAllRows(); if (scheme.getItemCount() > 0) { FetchInfo fetchInfo = fetch.get(scheme.getValue(scheme.getSelectedIndex())); for (String commandName : Natives.keys(fetchInfo.commands())) { String command = fetchInfo.command(commandName); if (command.contains("@*:")) { command = command.replace("@*:", "@" + Window.Location.getHostName() + ":"); } CopyableLabel copyLabel = new CopyableLabel(command); copyLabel.setStyleName(Gerrit.RESOURCES.css().downloadBoxCopyLabel()); insertCommand(commandName, copyLabel); } } insertPatch(); insertCommand(null, scheme); }

Target:
private void renderCommands() { commandTable.removeAllRows(); if (scheme.getItemCount() > 0) { FetchInfo fetchInfo = fetch.get(scheme.getValue(scheme.getSelectedIndex())); for (String commandName : Natives.keys(fetchInfo.commands())) { String command = fetchInfo.command(commandName); if (command.contains("@*:")) { command = command.replace("@*:", "@" + Window.Location.getHostName() + ":"); } CopyableLabel copyLabel = new CopyableLabel(command); copyLabel.setStyleName(style.clippy()); insertCommand(commandName, copyLabel); } } insertPatch(); insertCommand(null, scheme); }
Source:
private Set<String> readUsernamesFromFile() { try { Stream<String> lines = Files.lines(source); Set<String> res = new HashSet<>(); lines.forEach(name -> res.add(name.trim())); return res; } catch (IOException e) { e.printStackTrace(); return Collections.emptySet(); } }

Target:
private Set<String> readUsernamesFromFile() { try { return Files.lines(source) .map(String::trim) .collect(Collectors.toSet()); } catch (IOException e) { e.printStackTrace(); return Collections.emptySet(); } }
Source:
public PlannerTestCase() { }

Target:
public PlannerTestCase() { super(); }
Source:
protected Boolean checkIfMainPage() { Global.LOG_ENABLED = false; try { driver.findElement(By.cssSelector("body.mainpage")); } catch (NoSuchElementException e) { Global.LOG_ENABLED = true; return false; } Global.LOG_ENABLED = true; return true; }

Target:
protected Boolean checkIfMainPage() { WebElement body = driver.findElement(By.cssSelector("body")); return (body.getAttribute("class").contains("mainpage")); }
Source:
public void init() { try { eventBus.registerSubscriber(this); currentStatus.compareAndSet(InstanceInfo.InstanceStatus.UNKNOWN, client.getInstanceRemoteStatus()); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }

Target:
public void init() { try { eventBus.registerSubscriber(this); currentStatus = client.getInstanceRemoteStatus(); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }
Source:
private boolean isRootShardingKey(Map<String, List<String>> routingData) { if (routingData.values().size() == 1) { for (List<String> shardingKeys : routingData.values()) { return shardingKeys.size() == 1 && (shardingKeys.get(0).equals(DELIMITER) || shardingKeys.get(0).equals("")); } } return false; }

Target:
private boolean isRootShardingKey(Map<String, List<String>> routingData) { if (routingData.size() == 1) { for (List<String> shardingKeys : routingData.values()) { return shardingKeys.size() == 1 && shardingKeys.get(0).equals(DELIMITER); } } return false; }
Source:
public void branchDelete(BranchDeleteRequest request) throws GitException, UnauthorizedException { String remoteName = null; String branchName = getBranchRef(request.getName()); BranchDeleteCommand branchDeleteCommand = null; if (branchName.startsWith("refs/")) { branchName = parseBranchName(branchName); } else if (branchName.startsWith("refs/remotes/")) { remoteName = parseRemoteName(branchName); String remoteUri; try { remoteUri = nativeGit.createRemoteListCommand() .setRemoteName(remoteName) .execute() .get(0) .getUrl(); } catch (GitException ignored) { remoteUri = remoteName; } if (Util.isSSH(remoteUri)) { branchDeleteCommand = nativeGit.createBranchDeleteCommand(keysManager.writeKeyFile(remoteUri).getAbsolutePath()); } } if (branchDeleteCommand == null) { branchDeleteCommand = nativeGit.createBranchDeleteCommand(); } if (remoteName != null) { branchDeleteCommand.setBranchName(branchName) .setRemote(remoteName) .setDeleteFullyMerged(request.isForce()); executeWithCredentials(branchDeleteCommand, remoteName); } else { branchDeleteCommand.setBranchName(branchName) .setDeleteFullyMerged(request.isForce()); branchDeleteCommand.execute(); } }

Target:
public void branchDelete(BranchDeleteRequest request) throws GitException, UnauthorizedException { String branchName = getBranchRef(request.getName()); String remoteName = null; BranchDeleteCommand branchDeleteCommand = null; if (branchName.startsWith("refs/remotes/")) { remoteName = parseRemoteName(branchName); String remoteUri; try { remoteUri = nativeGit.createRemoteListCommand() .setRemoteName(remoteName) .execute() .get(0) .getUrl(); } catch (GitException ignored) { remoteUri = remoteName; } if (Util.isSSH(remoteUri)) { branchDeleteCommand = nativeGit.createBranchDeleteCommand(keysManager.writeKeyFile(remoteUri).getAbsolutePath()); } } branchName = parseBranchName(branchName); if (branchDeleteCommand == null) { branchDeleteCommand = nativeGit.createBranchDeleteCommand(); } branchDeleteCommand.setBranchName(branchName); branchDeleteCommand.setRemote(remoteName); branchDeleteCommand.setDeleteFullyMerged(request.isForce()); executeWithCredentials(branchDeleteCommand, remoteName); }
Source:
private void glusterHostRemove(Guid sourceClusterId) { boolean forceAction = false; if (getClusterUtils().hasServers(sourceClusterId) && !getClusterUtils().hasVolumeOnServer(getVdsId())) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((getClusterUtils().getUpServer(sourceClusterId)).getId(), getVds().gethost_name(), forceAction)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; return; } } else { setSucceeded(true); } }

Target:
private void glusterHostRemove(Guid sourceClusterId) { if (getClusterUtils().hasServers(sourceClusterId) && !getClusterUtils().hasVolumeOnServer(getVdsId())) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((getClusterUtils().getUpServer(sourceClusterId)).getId(), getVds().gethost_name(), false)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; return; } } }
Source:
public static <T> Map<String, T> safeGetMap(Map map, String key, Class<T> valueType) { Map<?, ?> unchecked = safeGet(map, key, Map.class); if (unchecked == null) { return null; } try { return unchecked .entrySet() .stream() .map(e -> new AbstractMap.SimpleEntry<>(String.class.cast(e.getKey()), e.getValue())) .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), valueType.cast(e.getValue()))) .collect( Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a querySettings Map containing type {}", key, valueType.getName()); } return null; }

Target:
public static <T> Map<String, T> safeGetMap(Map map, String key, Class<T> valueType) { Map<?, ?> unchecked = safeGet(map, key, Map.class); if (unchecked == null) { return Collections.emptyMap(); } try { return unchecked .entrySet() .stream() .map(e -> new AbstractMap.SimpleEntry<>(String.class.cast(e.getKey()), e.getValue())) .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), valueType.cast(e.getValue()))) .collect( Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a querySettings Map containing type {}", key, valueType.getName()); } return Collections.emptyMap(); }
Source:
public void testSimplePlainTextMessage() throws MessagingException { String bodyText = "K-9 Mail rocks :>"; TextBody body = new TextBody(bodyText); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, body); List<Part> outputNonViewableParts = new ArrayList<Part>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts); ViewableExtractedText container = extractTextFromViewables(RuntimeEnvironment.application, outputViewableParts); String expectedText = bodyText; String expectedHtml = "<pre class=\"k9mail\">" + "K-9 Mail rocks :&gt;" + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, container.html); }

Target:
public void testSimplePlainTextMessage() throws MessagingException { TextBody body = new TextBody(BODY_TEXT); MimeMessage message = new MimeMessage(); MimeMessageHelper.setBody(message, body); List<Part> outputNonViewableParts = new ArrayList<Part>(); ArrayList<Viewable> outputViewableParts = new ArrayList<>(); MessageExtractor.findViewablesAndAttachments(message, outputViewableParts, outputNonViewableParts); ViewableExtractedText container = messageViewInfoExtractor.extractTextFromViewables(outputViewableParts); String expectedText = BODY_TEXT; String expectedHtml = "<pre class=\"k9mail\">" + "K-9 Mail rocks :&gt;" + "</pre>"; assertEquals(expectedText, container.text); assertEquals(expectedHtml, getHtmlBodyText(container.html)); }
Source:
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) { return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { clientRequestInterceptor.handle(new GrpcClientRequestAdapter<>(method, headers)); final Span currentClientSpan = clientSpanThreadBinder.getCurrentClientSpan(); super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onClose(Status status, Metadata trailers) { clientSpanThreadBinder.setCurrentSpan(currentClientSpan); clientResponseInterceptor.handle(new GrpcClientResponseAdapter(status)); super.onClose(status, trailers); } }, headers); } }; }

Target:
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) { return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { clientRequestInterceptor.handle(new HttpClientRequestAdapter( new GrpcHttpClientRequest<>(method, headers), new StringServiceNameProvider(clientService), new MethodSpanNameProvider<>(method))); final Span currentClientSpan = clientSpanThreadBinder.getCurrentClientSpan(); super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onClose(Status status, Metadata trailers) { try { clientSpanThreadBinder.setCurrentSpan(currentClientSpan); clientResponseInterceptor.handle(new HttpClientResponseAdapter(new GrpcHttpResponse(status))); super.onClose(status, trailers); } finally { clientSpanThreadBinder.setCurrentSpan(null); } } }, headers); } }; }
Source:
public static void setValidWriteIdList(Configuration conf, TableScanDesc tsDesc) { String dbName = tsDesc.getDatabaseName(); String tableName = tsDesc.getTableName(); if ((dbName != null) && (tableName != null)) { ValidWriteIdList validWriteIdList = getTableValidWriteIdList(conf, AcidUtils.getFullTableName(dbName, tableName)); if (validWriteIdList != null) { setValidWriteIdList(conf, validWriteIdList); } else if (HiveConf.getBoolVar(conf, ConfVars.HIVE_TRANSACTIONAL_TABLE_SCAN, false)) { LOG.error("setValidWriteIdList on table: " + AcidUtils.getFullTableName(dbName, tableName) + " isAcidTable: " + HiveConf.getBoolVar(conf, ConfVars.HIVE_TRANSACTIONAL_TABLE_SCAN, false) + " acidProperty: " + getAcidOperationalProperties(conf) + " couldn't find the ValidWriteId list from ValidTxnWriteIdList: " + conf.get(ValidTxnWriteIdList.VALID_TABLES_WRITEIDS_KEY)); } } }

Target:
public static void setValidWriteIdList(Configuration conf, TableScanDesc tsDesc) { if (tsDesc.isTranscationalTable()) { String dbName = tsDesc.getDatabaseName(); String tableName = tsDesc.getTableName(); ValidWriteIdList validWriteIdList = getTableValidWriteIdList(conf, AcidUtils.getFullTableName(dbName, tableName)); if (validWriteIdList != null) { setValidWriteIdList(conf, validWriteIdList); } else { LOG.error("setValidWriteIdList on table: " + AcidUtils.getFullTableName(dbName, tableName) + " isAcidTable: " + true + " acidProperty: " + getAcidOperationalProperties(conf) + " couldn't find the ValidWriteId list from ValidTxnWriteIdList: " + conf.get(ValidTxnWriteIdList.VALID_TABLES_WRITEIDS_KEY)); throw new IllegalStateException("ACID table: " + AcidUtils.getFullTableName(dbName, tableName) + " is missing from the ValidWriteIdList config: " + conf.get(ValidTxnWriteIdList.VALID_TABLES_WRITEIDS_KEY)); } } }
Source:
public void testNoValues() { Stats s = new Stats(); assertTrue(Double.isNaN(s.var())); assertTrue(Double.isNaN(s.stddev())); s.add(42.3); assertTrue(Double.isNaN(s.var())); assertTrue(Double.isNaN(s.stddev())); }

Target:
public void testNoValues() { Stats s = new Stats(); assertTrue(Double.isNaN(s.var())); assertTrue(Double.isNaN(s.stddev())); assertTrue(Double.isNaN(s.avg())); assertTrue(Double.isNaN(s.min())); assertTrue(Double.isNaN(s.max())); s.add(42.3); assertTrue(Double.isNaN(s.var())); assertTrue(Double.isNaN(s.stddev())); assertEquals(42.3, s.avg(), 1E-6); assertEquals(42.3, s.max(), 1E-6); assertEquals(42.3, s.min(), 1E-6); s.add(42.3); assertEquals(0, s.var(), 1E-6); assertEquals(0, s.stddev(), 1E-6); }
Source:
private static void setStatus(ITmfStateSystemBuilder ss, long status, int curThreadNode, @Nullable Long cpu, long timestamp, long type) { ITmfStateValue value; if (ss.queryOngoingState(curThreadNode).isNull()) { value = ProcessStatus.getStatusFromStatedump(status).getStateValue(); ss.modifyAttribute(timestamp, value.unboxValue(), curThreadNode); if (status == LinuxValues.STATEDUMP_PROCESS_STATUS_WAIT_CPU) { setRunQueue(ss, curThreadNode, cpu, timestamp); } if (type != 0) { int sysallQuark = ss.getQuarkRelativeAndAdd(curThreadNode, Attributes.SYSTEM_CALL); ss.modifyAttribute(timestamp, "", sysallQuark); } } }

Target:
private static void setStatus(ITmfStateSystemBuilder ss, long status, int curThreadNode, @Nullable Long cpu, long timestamp, long type) { ITmfStateValue value; if (ss.queryOngoingState(curThreadNode).isNull()) { value = ProcessStatus.getStatusFromStatedump(status).getStateValue(); ss.modifyAttribute(timestamp, value.unboxValue(), curThreadNode); if (status == LinuxValues.STATEDUMP_PROCESS_STATUS_WAIT_CPU) { setRunQueue(ss, curThreadNode, cpu, timestamp); } } if (type != 0) { int sysallQuark = ss.getQuarkRelativeAndAdd(curThreadNode, Attributes.SYSTEM_CALL); ss.modifyAttribute(timestamp, "", sysallQuark); } }
Source:
private EntryLogAndLockTuple(long ledgerId) { int lockIndex = Math.abs(Long.hashCode(ledgerId) % lockArrayPool.length()); if (lockArrayPool.get(lockIndex) == null) { lockArrayPool.compareAndSet(lockIndex, null, new ReentrantLock()); } ledgerLock = lockArrayPool.get(lockIndex); }

Target:
private EntryLogAndLockTuple(long ledgerId) { int lockIndex = MathUtils.signSafeMod(Long.hashCode(ledgerId), lockArrayPool.length()); if (lockArrayPool.get(lockIndex) == null) { lockArrayPool.compareAndSet(lockIndex, null, new ReentrantLock()); } ledgerLock = lockArrayPool.get(lockIndex); }
Source:
public static <K, V> TypeToken<CorfuTable<K, V>> getMapType() { return new TypeToken<CorfuTable<K, V>>() { }; }

Target:
getMapType() { return new TypeToken<CorfuTable<K, V>>() {}; }
Source:
public static NicType fromValue(String value) { Optional<NicType> nicType = Enums.getIfPresent(NicType.class, value.toUpperCase()); checkArgument(nicType.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(Policy.values()), value); return nicType.get(); }

Target:
public static NicType fromValue(String value) { Optional<NicType> nicType = Enums.getIfPresent(NicType.class, value.toUpperCase()); checkArgument(nicType.isPresent(), "Expected one of %s but was %s", Joiner.on(',').join(NicType.values()), value); return nicType.get(); }
Source:
public void run() { UserFilter userFilter = new UserFilter("", true); UserAccount localUserAccount = userAccountRepository.getUser(userFilter, NetworkStrategy.LocalFirst); userFilter = new UserFilter(localUserAccount.getUserUid(), false); UserAccount updatedUserAccount = userAccountRepository.getUser(userFilter, NetworkStrategy.NetworkFirst); if(updatedUserAccount==null){ notifyError(localUserAccount); return; } if(localUserAccount.getAnnouncement()!=null && !localUserAccount.getAnnouncement().isEmpty() && !localUserAccount.getAnnouncement().equals(updatedUserAccount.getAnnouncement())){ PreferencesState.getInstance().setUserAccept(false); } notifyOnComplete(updatedUserAccount); }

Target:
public void run() { UserAccount updatedUserAccount = null; try { updatedUserAccount = userAccountRepository.getUser(networkStrategy); } catch (Exception e){ notifyError(); } notifyOnComplete(updatedUserAccount); }
Source:
public Monitor(Map conf, final String boltService) { startTimestampPerId = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(60, TimeUnit.MINUTES) .concurrencyLevel(2) .removalListener(new RemovalListener<Object, Long>() { @Override public void onRemoval(RemovalNotification<Object, Long> notification) { if (notification.getCause() != RemovalCause.EXPLICIT) { ExceptionEvent event = new ExceptionEvent("Latency object unexpectedly removed"); event.attribute("removalCause", notification.getCause().name()); event.service(boltService); send(event); } } }) .build(); if (RiemannDiscovery.getInstance().isAWS()) { eventSender = RiemannEventSender.getInstance(); } else { eventSender = new LoggerEventSender(); } customAttributes = extractCustomEventAttributes(conf); }

Target:
public Monitor(Map conf, final String boltService) { startTimestampPerId = createCache(conf, boltService); if (RiemannDiscovery.getInstance().isAWS()) { eventSender = RiemannEventSender.getInstance(); } else { eventSender = new LoggerEventSender(); } customAttributes = extractCustomEventAttributes(conf); }
Source:
public static StandardVariable createStandardVariable() { final StandardVariable stdVariable = new StandardVariable(); stdVariable.setName("variable name " + new Random().nextInt(10000)); stdVariable.setDescription("variable description"); stdVariable.setProperty(new Term(2002, "User", "Database user")); stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned")); stdVariable.setScale(new Term(61220, "DBCV", "Controlled vocabulary from a database")); stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values")); stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class")); stdVariable.setEnumerations(new ArrayList<Enumeration>()); stdVariable.getEnumerations().add(new Enumeration(10001, "HB", "Hybridization nursery", 2)); stdVariable.getEnumerations().add(new Enumeration(10002, "PN", "Pedigree nursery", 3)); stdVariable.setConstraints(new VariableConstraints(100.0, 999.0)); stdVariable.setCropOntologyId("CROP-TEST"); return stdVariable; }

Target:
public static StandardVariable createStandardVariable() { final StandardVariable stdVariable = new StandardVariable(); stdVariable.setName("variable name " + new Random().nextInt(10000)); stdVariable.setDescription("variable description"); stdVariable.setProperty(new Term(2002, "User", "Database user")); stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned")); stdVariable.setScale(new Term(61220, "DBCV", "Controlled vocabulary from a database")); stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values")); stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class")); stdVariable.setEnumerations(new ArrayList<Enumeration>()); stdVariable.getEnumerations().add(new Enumeration(StudyType.N.getId(), StudyType.N.getName(), StudyType.N.getLabel(), 1)); stdVariable.getEnumerations().add(new Enumeration(StudyType.HB.getId(), StudyType.HB.getName(), StudyType.HB.getLabel(), 2)); stdVariable.getEnumerations().add(new Enumeration(StudyType.PN.getId(), StudyType.PN.getName(), StudyType.PN.getLabel(), 3)); stdVariable.setConstraints(new VariableConstraints(100.0, 999.0)); stdVariable.setCropOntologyId("CROP-TEST"); return stdVariable; }
Source:
public String getLongestIndex() { Map<Integer, Integer> lengths = pooledElementViews.stream() .flatMap(element -> element.getIndices().stream()) .collect(Collectors.toMap(Index::getPosition, index -> index.getSequence().length(), Integer::max)); if (lengths.isEmpty()) { return "0"; } return lengths.entrySet().stream() .sorted((a, b) -> { return a.getKey().compareTo(b.getKey()); }) .map(Entry<Integer, Integer>::getValue) .map(length -> length.toString()) .collect(Collectors.joining(",")); }

Target:
public String getLongestIndex() { Map<Integer, Integer> lengths = pooledElementViews.stream() .flatMap(element -> element.getIndices().stream()) .collect(Collectors.toMap(Index::getPosition, index -> index.getSequence().length(), Integer::max)); if (lengths.isEmpty()) { return "0"; } return lengths.entrySet().stream() .sorted((a, b) -> a.getKey().compareTo(b.getKey())) .map(Entry<Integer, Integer>::getValue) .map(length -> length.toString()) .collect(Collectors.joining(",")); }