auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response clearAllParagraphOutput(@PathParam("noteId") String noteId) throws IOException { LOG.info("clear all paragraph output of note {}", noteId); if (!noteId.isEmpty()) { Note note = notebook.getNote(noteId); if (note == null) { return new JsonResponse(Status.NOT_FOUND, "note not found.").build(); } <START> note.clearAllParagraphOutput(); <END> } return new JsonResponse(Status.OK, "").build(); }</code><technical_language>I enforce note authorization values here, for example owner/write privileges a call rest api</technical_language>

Target:
public Response clearAllParagraphOutput(@PathParam("noteId") String noteId) throws IOException { LOG.info("clear all paragraph output of note {}", noteId); checkIfUserCanWrite(noteId, "Insufficient privileges you cannot clear this note"); Note note = notebook.getNote(noteId); checkIfNoteIsNotNull(note); note.clearAllParagraphOutput(); return new JsonResponse(Status.OK, "").build(); }
Source:
<code>private String subdomainToLower(String url, EditText mHostUrlInput) { if(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) { if(url.indexOf("/", 8) != -1) <START> url = url.substring(0, url.indexOf("/", 8)).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); <END> else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } else { if(url.indexOf("/") != -1) url = url.substring(0, url.indexOf("/")).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } return url; }</code><technical_language>Please, wrap lines 120 characters read in Github in a glance, horizontal scrollbar</technical_language>

Target:
private String subdomainToLower(String url, EditText mHostUrlInput) { if(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) { if(url.indexOf("/", 8) != -1) url = url.substring(0, url.indexOf("/", 8)).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } else { if(url.indexOf("/") != -1) url = url.substring(0, url.indexOf("/")).toLowerCase() + url.substring(url.indexOf("/"), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } return url; }
Source:
<code>public List<Event> removeEventBeforeSignificant(final List<Event> events){ final Optional<Event> significantEvent = getFirstSignificantEvent(events); if (!significantEvent.isPresent()) { return events; } final List<Event> filteredEvents = new ArrayList<>(); for(final Event event:events){ if(event.getStartTimestamp() < significantEvent.get().getStartTimestamp()){ <START> if (event.getType() == Event.Type.LIGHTS_OUT) { <END> final Long timeDiff = significantEvent.get().getStartTimestamp() - event.getStartTimestamp(); if (timeDiff < FILTER_NON_SIGNIFICANT_EVENT_IN_MILLIS) filteredEvents.add(event); } continue; } filteredEvents.add(event); } return filteredEvents; }</code><technical_language>suggest reversing check: if(Event.Type.LIGHTS_OUT.equals(event.getType()) if getType() is null for reason, a NPE</technical_language>

Target:
public List<Event> removeEventBeforeSignificant(final List<Event> events){ final Optional<Event> significantEvent = getFirstSignificantEvent(events); if (!significantEvent.isPresent()) { return events; } final List<Event> filteredEvents = Lists.newArrayList(); for(final Event event:events){ if(event.getStartTimestamp() < significantEvent.get().getStartTimestamp()){ if (Event.Type.LIGHTS_OUT.equals(event.getType())) { final Long timeDiff = significantEvent.get().getStartTimestamp() - event.getStartTimestamp(); if (timeDiff < FILTER_NON_SIGNIFICANT_EVENT_IN_MILLIS) filteredEvents.add(event); } continue; } filteredEvents.add(event); } return filteredEvents; }
Source:
<code>public void run() { if (dTreeViewer != null && dTreeViewer.getControl() != null && !dTreeViewer.getControl().isDisposed()) { for (Object itemtoExpand : toExpand) { <START> DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); <END> dTreeViewer.setExpandedState(itemtoExpand, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); } for (Object itemToCollapse : toCollapse) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemToCollapse, false); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); } for (Object itemToRefresh : toRefreshInViewer) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); dTreeViewer.refresh(itemToRefresh, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); } DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); dTreeViewer.update(objectsToUpdateInViewer, null); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); } }</code><technical_language>Unrelated this work, a typo "COL[L]APSE" I noticed before</technical_language>

Target:
public void run() { if (dTreeViewer != null && dTreeViewer.getControl() != null && !dTreeViewer.getControl().isDisposed()) { for (Object itemtoExpand : toExpand) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemtoExpand, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); } for (Object itemToCollapse : toCollapse) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemToCollapse, false); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); } for (Object itemToRefresh : toRefreshInViewer) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); dTreeViewer.refresh(itemToRefresh, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); } DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); dTreeViewer.update(objectsToUpdateInViewer, null); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); } }
Source:
<code>public void setUp() throws Exception { super.setUp(); collectionPath = Paths.get("src/test/resources/sample_docs/Iso19115"); collection = new Iso19115Collection(collectionPath); <START> Path segment = Paths.get("src/test/resources/sample_docs/Iso19115/output.json"); <END> segmentPaths.add(segment); segmentDocCounts.put(segment, 1); totalSegments = 1; totalDocs = 1; expected.put("12957", Map.of("id", "12957", "title", "Test title", "abstract", "Test abstract")); }</code><technical_language>I want lowercase i consistent else in directory</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); collectionPath = Paths.get("src/test/resources/sample_docs/iso19115"); collection = new Iso19115Collection(collectionPath); Path segment = Paths.get("src/test/resources/sample_docs/iso19115/output.json"); segmentPaths.add(segment); segmentDocCounts.put(segment, 2); totalSegments = 1; totalDocs = 2; expected.put("12957", Map.of("id", "12957", "title", "Test title", "abstract", "Test abstract")); expected.put("13007", Map.of("id", "13007", "title","Test title 2", "abstract", "Test abstract 2")); }
Source:
<code>public SyncthingRunnable(Context context, Command command) { ((SyncthingApp) context.getApplicationContext()).component().inject(this); mContext = context; mSyncthingBinary = Constants.getSyncthingBinary(mContext); mLogFile = Constants.getLogFile(mContext); <START> Log.v(TAG, "SyncthingRunnable: syncthing-core option restartOnWakeup = " + Boolean.toString(mPreferences.getBoolean("restartOnWakeup", false))); <END> mUseRoot = mPreferences.getBoolean(Constants.PREF_USE_ROOT, false) && Shell.SU.available(); switch (command) { case generate: mCommand = new String[]{ mSyncthingBinary.getPath(), "-generate", mContext.getFilesDir().toString(), "-logflags=0" }; break; case main: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-no-browser", "-logflags=0" }; break; case reset: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-reset", "-logflags=0" }; break; default: throw new InvalidParameterException("Unknown command option"); } }</code><technical_language>This a random place wedge this in. a place</technical_language>

Target:
public SyncthingRunnable(Context context, Command command) { ((SyncthingApp) context.getApplicationContext()).component().inject(this); mContext = context; mSyncthingBinary = Constants.getSyncthingBinary(mContext); mLogFile = Constants.getLogFile(mContext); mUseRoot = mPreferences.getBoolean(Constants.PREF_USE_ROOT, false) && Shell.SU.available(); switch (command) { case generate: mCommand = new String[]{ mSyncthingBinary.getPath(), "-generate", mContext.getFilesDir().toString(), "-logflags=0" }; break; case main: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-no-browser", "-logflags=0" }; break; case reset: mCommand = new String[]{ mSyncthingBinary.getPath(), "-home", mContext.getFilesDir().toString(), "-reset", "-logflags=0" }; break; default: throw new InvalidParameterException("Unknown command option"); } }
Source:
<code>public static void main(String[] args) { CliWrapper cliWrapper = new CliWrapper(); CommandLine commandLine = null; try { commandLine = cliWrapper.parse(args); } catch (ParseException e) { printUsage(cliWrapper); System.out.println(e.getMessage()); System.exit(1); } ConfigurationHolder.initFromFile(commandLine.getOptionValue(CliOption.CONF.getCommandLineParam())); Configuration configuration = ConfigurationHolder.instance(); configuration.updateWithCliOptions(commandLine); <START> ConnectorType connectorType = ConnectorType.valueOf(configuration.getProperty(GeneralOption.CONNECTOR_TYPE)); <END> ConnectorFacade facade = ConnectorFacadeFactory.INSTANCE.build(connectorType); try { facade.supports(ConfigurationHolder.instance()); } catch (GerritException | GeneralOptionNotSupportedException e) { System.out.println(e.getMessage()); System.exit(1); } new Engine(facade).run(); }</code><technical_language>This IllegalArgException NPE is handled</technical_language>

Target:
public static void main(String[] args) { CliWrapper cliWrapper = new CliWrapper(); CommandLine commandLine = null; try { commandLine = cliWrapper.parse(args); } catch (ParseException e) { printUsage(cliWrapper); System.err.println(e.getMessage()); System.exit(1); } ConfigurationHolder.initFromFile(commandLine.getOptionValue(CliOption.CONF.getCommandLineParam())); Configuration configuration = ConfigurationHolder.instance(); configuration.updateWithCliOptions(commandLine); ConnectorFacade facade = getConnectorFacade(configuration); new Engine(facade).run(); }
Source:
<code>public XMLizable asTyped() { <START> if (this.xmlizable != null) { return this.xmlizable; } <END> try { Class<?> childTypeClass = typeMapper.getJavaType(xsiType); if (childTypeClass == null) { this.xmlizable = this; return this.xmlizable; } this.xmlizable = (XMLizable)childTypeClass.newInstance(); this.xmlizable.load(createInputStream(), typeMapper); } catch (PullParserException e) { this.xmlizable = this; } catch (IOException e) { this.xmlizable = this; } catch (ConnectionException e) { this.xmlizable = this; } catch (InstantiationException e) { this.xmlizable = this; } catch (IllegalAccessException e) { this.xmlizable = this; } return this.xmlizable; }</code><technical_language>This is threadsafe</technical_language>

Target:
public XMLizable asTyped() { return this.xmlizable; }
Source:
<code>static void fixConfigGroupServiceNames() { Map<Long, ConfigGroup> configGroupMap = collectConfigGroupsWithoutServiceName(); if (MapUtils.isEmpty(configGroupMap)) return; Clusters clusters = injector.getInstance(Clusters.class); for (Map.Entry<Long, ConfigGroup> configGroupEntry : configGroupMap.entrySet()) { ConfigGroup configGroup = configGroupEntry.getValue(); try { Cluster cluster = clusters.getCluster(configGroup.getClusterName()); Map<String, Service> serviceMap = cluster.getServices(); if (serviceMap.containsKey(configGroup.getTag())) { LOG.info("Setting service name of config group with id to {}", configGroup.getName(), configGroupEntry.getKey(), configGroup.getTag()); configGroup.setServiceName(configGroup.getTag()); <START> } <END> } catch (AmbariException e) { } } }</code><technical_language>Please consider creating else case for logging</technical_language>

Target:
static void fixConfigGroupServiceNames() { Map<Long, ConfigGroup> configGroupMap = collectConfigGroupsWithoutServiceName(); if (MapUtils.isEmpty(configGroupMap)) return; Clusters clusters = injector.getInstance(Clusters.class); for (Map.Entry<Long, ConfigGroup> configGroupEntry : configGroupMap.entrySet()) { ConfigGroup configGroup = configGroupEntry.getValue(); try { Cluster cluster = clusters.getCluster(configGroup.getClusterName()); Map<String, Service> serviceMap = cluster.getServices(); if (serviceMap.containsKey(configGroup.getTag())) { LOG.info("Setting service name of config group with id to {}", configGroup.getName(), configGroupEntry.getKey(), configGroup.getTag()); configGroup.setServiceName(configGroup.getTag()); } else { LOG.info("Config group with id contains a tag which is not a service name in the cluster {}", configGroup.getName(), configGroupEntry.getKey(), configGroup.getTag(), cluster.getClusterName()); } } catch (AmbariException e) { } } }
Source:
<code>public ResourceCollection get(List<ResourceIdentifier> resources) { List<Package> packages = newArrayList(); <START> List<EntityType> entityTypes = newArrayList(); <END> resources.forEach( resource -> { switch (resource.getType()) { case PACKAGE: packages.add(getPackage(resource.getId())); break; case ENTITY_TYPE: case ENTITY_TYPE_ABSTRACT: entityTypes.add(getEntityType(resource.getId())); break; default: throw new UnexpectedEnumException(resource.getType()); } }); return ResourceCollection.of(packages, entityTypes); }</code><technical_language>new ArrayList<>();</technical_language>

Target:
public ResourceCollection get(List<ResourceIdentifier> resources) { List<Package> packages = new ArrayList<>(); List<EntityType> entityTypes = new ArrayList<>(); resources.forEach( resource -> { switch (resource.getType()) { case PACKAGE: packages.add(getPackage(resource.getId())); break; case ENTITY_TYPE: case ENTITY_TYPE_ABSTRACT: entityTypes.add(getEntityType(resource.getId())); break; default: throw new UnexpectedEnumException(resource.getType()); } }); return ResourceCollection.of(packages, entityTypes); }
Source:
<code>private FilenameFilter getNativeIndexFileFilter( boolean inverse ) { return ( dir, name ) -> { File file = new File( dir, name ); <START> return !outsideWorld.fileSystem().isDirectory(file) || ((!file.toPath().getParent().equals(baseSchemaIndexPath) || !name.equals("lucene")) && <END> (file.toPath().getNameCount() - baseSchemaIndexPath.getNameCount() != 3 || !name.startsWith("lucene-"))); }; }</code><technical_language>This class facing compilation problems i this condition is readable in current state</technical_language>

Target:
private FilenameFilter getNativeIndexFileFilter( boolean inverse ) { return ( dir, name ) -> { File file = new File( dir, name ); if ( outsideWorld.fileSystem().isDirectory( file ) ) { return true; } if ( name.equals( FailureStorage.DEFAULT_FAILURE_FILE_NAME ) ) { return false; } Path path = file.toPath(); int nameCount = path.getNameCount(); boolean isLuceneFilePart1 = nameCount >= 3 && path.getName( nameCount - 3 ).toString().startsWith( "lucene-" ); boolean isLuceneFilePart2 = nameCount >= 4 && path.getName( nameCount - 4 ).toString().equals( "lucene" ); boolean isLuceneFile = isLuceneFilePart1 || isLuceneFilePart2; return inverse == isLuceneFile; }; }
Source:
<code>private void cloneOrUpdate() throws RepositoryException { synchronized (mutex) { try { LOGGER.info("Begin fetching process of " + this); boolean lockFileExists = this.lockFile.exists(); if (!lockFileExists) { LOGGER.info("Creating lock file for " + this); try { this.lockFile.getParentFile().mkdirs(); <START> this.lockFile.createNewFile(); <END> } catch (IOException e) { throw new RepositoryException("Couldn't create lock file " + this.lockFile.getAbsolutePath()); } } FileOutputStream lockFileStream = new FileOutputStream(lockFile, true); try { java.nio.channels.FileLock lock = lockFileStream.getChannel().lock(); cloneOrUpdateWithLock(lock); } finally { lockFileStream.close(); } } catch (IOException e) { throw new RepositoryException("An unknown error occurred", e); } } }</code><technical_language>This (i.e. persistent lock management) is responsibility of GitRepository. create another class</technical_language>

Target:
private void cloneOrUpdate() throws RepositoryException { final boolean folderExists = this.localFolder.exists(); if (!folderExists) { LOGGER.info("Creating local folder for " + this); if (!this.localFolder.mkdirs()) { throw new RepositoryException("Couldn't create local folder for " + this); } } Git gitRepository = null; try { if (!folderExists) { LOGGER.info("Cloning " + this); gitRepository = Git.cloneRepository().setURI(this.repositoryUri.toString()) .setDirectory(this.localFolder) .setBranch(this.branch).call(); } else { LOGGER.info("Opening " + this); gitRepository = Git.open(localFolder); LOGGER.info("Pulling new commits from " + this); gitRepository.pull().call(); } } catch (RepositoryNotFoundException | GitAPIException e) { throw new RepositoryException( String.format("Folder '%s' is no git-repository", this.localFolder.getAbsolutePath()), e); } catch (IOException e) { throw new RepositoryException("An unknown error occurred", e); } finally { if (gitRepository != null) { gitRepository.close(); } } }
Source:
<code>Set<String> getWritablePartitions() { <START> Set<String> healthWritablePartitions = new HashSet<>(); <END> for (Map.Entry<String, Set<String>> entry : partitionToInstances.entrySet()) { if (partitionStates.get(entry.getKey()).equals(PartitionState.READ_WRITE)) { boolean up = true; for (String instance : entry.getValue()) { if (!getUpInstances().contains(instance)) { up = false; break; } } if (up) { healthWritablePartitions.add(entry.getKey()); } } } return healthWritablePartitions; }</code><technical_language>healthyWritablePartitions</technical_language>

Target:
Set<String> getWritablePartitions() { Set<String> healthyWritablePartitions = new HashSet<>(); for (Map.Entry<String, Set<String>> entry : partitionToInstances.entrySet()) { if (partitionToPartitionStates.get(entry.getKey()).equals(PartitionState.READ_WRITE)) { boolean up = true; for (String instance : entry.getValue()) { if (!getUpInstances().contains(instance)) { up = false; break; } } if (up) { healthyWritablePartitions.add(entry.getKey()); } } } return healthyWritablePartitions; }
Source:
<code>public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { if (!isReachable()) { return MessageResponse.UNREACHABLE; } User user = getUser(this); boolean afk = false; if (user != null) { if (user.isIgnoreMsg() && !(sender instanceof Console)) { <START> if (sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { END> return MessageResponse.MESSAGES_IGNORED; } } afk = user.isAfk(); if (sender instanceof IUser && user.isIgnoredPlayer((IUser) sender)) { return MessageResponse.SENDER_IGNORED; } } sendMessage(tl("msgFormat", sender.getDisplayName(), tl("me"), message)); if (ess.getSettings().isLastMessageReplyRecipient()) { long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; if (getReplyRecipient() == null || !getReplyRecipient().isReachable() || System.currentTimeMillis() - this.lastMessageMs > timeout) { setReplyRecipient(sender); } } else { setReplyRecipient(sender); } this.lastMessageMs = System.currentTimeMillis(); return afk ? MessageResponse.SUCCESS_BUT_AFK : MessageResponse.SUCCESS; }</code><technical_language>I for sender simultaneously a Console IUser time, previous !(sender instanceof Console) check is redundant</technical_language>

Target:
public MessageResponse onReceiveMessage(IMessageRecipient sender, String message) { if (!isReachable()) { return MessageResponse.UNREACHABLE; } User user = getUser(this); boolean afk = false; if (user != null) { if (user.isIgnoreMsg() && sender instanceof IUser && !((IUser) sender).isAuthorized("essentials.msgtoggle.bypass")) { return MessageResponse.MESSAGES_IGNORED; } afk = user.isAfk(); if (sender instanceof IUser && user.isIgnoredPlayer((IUser) sender)) { return MessageResponse.SENDER_IGNORED; } } sendMessage(tl("msgFormat", sender.getDisplayName(), tl("me"), message)); if (ess.getSettings().isLastMessageReplyRecipient()) { long timeout = ess.getSettings().getLastMessageReplyRecipientTimeout() * 1000; if (getReplyRecipient() == null || !getReplyRecipient().isReachable() || System.currentTimeMillis() - this.lastMessageMs > timeout) { setReplyRecipient(sender); } } else { setReplyRecipient(sender); } this.lastMessageMs = System.currentTimeMillis(); return afk ? MessageResponse.SUCCESS_BUT_AFK : MessageResponse.SUCCESS; }
Source:
<code>private GroupedExecutionProperties processChildren(PlanNode node) { boolean anyUseful = false; <START> OptionalInt totalLifespansOptional = OptionalInt.empty(); <END> boolean allRecoveryEligible = true; ImmutableList.Builder<PlanNodeId> capableTableScanNodesBuilder = ImmutableList.builder(); for (PlanNode source : node.getSources()) { GroupedExecutionProperties properties = source.accept(this, null); if (!properties.isCurrentNodeCapable()) { return GroupedExecutionProperties.notCapable(); } anyUseful |= properties.isSubTreeUseful(); allRecoveryEligible &= properties.isRecoveryEligible(); if (!totalLifespansOptional.isPresent()) { totalLifespansOptional = OptionalInt.of(properties.totalLifespans); } else { checkState(totalLifespansOptional.getAsInt() == properties.totalLifespans, format("Mismatched number of lifespans among children nodes. Expected: %s, actual: %s", totalLifespansOptional.getAsInt(), properties.totalLifespans)); } capableTableScanNodesBuilder.addAll(properties.capableTableScanNodes); } int totalLifespans = totalLifespansOptional.getAsInt(); List<PlanNodeId> capableTableScanNodes = capableTableScanNodesBuilder.build(); if (capableTableScanNodes.size() * totalLifespans > getMaxBucketsForGroupedExecution(session)) { return GroupedExecutionProperties.notCapable(); } return new GroupedExecutionProperties(true, anyUseful, capableTableScanNodes, totalLifespans, allRecoveryEligible); }</code><technical_language>wow, totalLifespans totalLifespans.getAsInt() time is</technical_language>

Target:
private GroupedExecutionProperties processChildren(PlanNode node) { boolean anyUseful = false; OptionalInt totalLifespans = OptionalInt.empty(); boolean allRecoveryEligible = true; ImmutableList.Builder<PlanNodeId> capableTableScanNodes = ImmutableList.builder(); for (PlanNode source : node.getSources()) { GroupedExecutionProperties properties = source.accept(this, null); if (!properties.isCurrentNodeCapable()) { return GroupedExecutionProperties.notCapable(); } anyUseful |= properties.isSubTreeUseful(); allRecoveryEligible &= properties.isRecoveryEligible(); if (!totalLifespans.isPresent()) { totalLifespans = OptionalInt.of(properties.totalLifespans); } else { checkState(totalLifespans.getAsInt() == properties.totalLifespans, format("Mismatched number of lifespans among children nodes. Expected: %s, actual: %s", totalLifespans.getAsInt(), properties.totalLifespans)); } capableTableScanNodes.addAll(properties.capableTableScanNodes); } return new GroupedExecutionProperties(true, anyUseful, capableTableScanNodes.build(), totalLifespans.getAsInt(), allRecoveryEligible); }
Source:
<code>private Iterable<SegmentWithOvershadowedStatus> findAuthorizedSegmentWithOvershadowedStatus( HttpServletRequest req, Stream<DataSegment> metadataSegments ) { <START> final Collection<DataSegment> overshadowedSegments = Optional <END> .ofNullable(metadataSegmentManager.getOvershadowedSegments()) .orElse(Collections.emptyList()); final Stream<SegmentWithOvershadowedStatus> segmentsWithOvershadowedStatus = metadataSegments .map(segment -> new SegmentWithOvershadowedStatus( segment, overshadowedSegments.contains(segment) )); final Function<SegmentWithOvershadowedStatus, Iterable<ResourceAction>> raGenerator = segment -> Collections .singletonList(AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSegment().getDataSource())); final Iterable<SegmentWithOvershadowedStatus> authorizedSegments = AuthorizationUtils.filterAuthorizedResources( req, segmentsWithOvershadowedStatus::iterator, raGenerator, authorizerMapper ); return authorizedSegments; }</code><technical_language>this a Set, please. on, overshadowedSegments.contains(segment), scary if overshadowed is kind of Collection other a Set (or short List). way, clearer this a Set<SegmentId> Set<DataSegment></technical_language>

Target:
private Iterable<SegmentWithOvershadowedStatus> findAuthorizedSegmentWithOvershadowedStatus( HttpServletRequest req, Stream<DataSegment> metadataSegments ) { final Set<SegmentId> overshadowedSegments = Optional .ofNullable(metadataSegmentManager.getOvershadowedSegments()) .orElse(Collections.emptySet()); final Stream<SegmentWithOvershadowedStatus> segmentsWithOvershadowedStatus = metadataSegments .map(segment -> new SegmentWithOvershadowedStatus( segment, overshadowedSegments.contains(segment.getId()) )); final Function<SegmentWithOvershadowedStatus, Iterable<ResourceAction>> raGenerator = segment -> Collections .singletonList(AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSegment().getDataSource())); final Iterable<SegmentWithOvershadowedStatus> authorizedSegments = AuthorizationUtils.filterAuthorizedResources( req, segmentsWithOvershadowedStatus::iterator, raGenerator, authorizerMapper ); return authorizedSegments; }
Source:
<code>public void testGeneralPoolHasNoReservation() { int reservePool = 10; int generalPool = 12; <START> ImmutableMap<String, Map<String, Long>> queries = ImmutableMap.<String, Map<String, Long>>builder() <END> .put("q_1", ImmutableMap.of("n1", 0L, "n2", 0L, "n3", 0L, "n4", 0L, "n5", 0L)) .put("q_r", ImmutableMap.of("n1", 6L, "n2", 6L, "n3", 6L, "n4", 6L, "n5", 6L)) .build(); assertEquals( lowMemoryKiller.chooseQueryToKill( LowMemoryKillerTestingUtils.toQueryMemoryInfoList("q_r", queries), toNodeMemoryInfoList(reservePool, generalPool, "q_r", queries)), Optional.empty()); }</code><technical_language>Declare map</technical_language>

Target:
public void testGeneralPoolHasNoReservation() { int reservePool = 10; int generalPool = 12; Map<String, Map<String, Long>> queries = ImmutableMap.<String, Map<String, Long>>builder() .put("q_1", ImmutableMap.of("n1", 0L, "n2", 0L, "n3", 0L, "n4", 0L, "n5", 0L)) .put("q_r", ImmutableMap.of("n1", 6L, "n2", 6L, "n3", 6L, "n4", 6L, "n5", 6L)) .build(); assertEquals( lowMemoryKiller.chooseQueryToKill( toQueryMemoryInfoList("q_r", queries), toNodeMemoryInfoList(reservePool, generalPool, "q_r", queries)), Optional.empty()); }
Source:
<code>public void notifyAboutChanges(@NonNull Changes changes) { if (changesBus != null) { changesBus.onNext(changes); } else { <START> loggi.d("Changes was occurred, but changesBus is null. " + changes); <END> } }</code><technical_language>This log shown pretty often.</technical_language>

Target:
public void notifyAboutChanges(@NonNull Changes changes) { if (changesBus != null) { changesBus.onNext(changes); } }
Source:
<code>private static String getPathFromCtfTestTrace(@NonNull CtfTestTrace testTrace) { CtfTmfTrace ctftrace = CtfTmfTestTraceUtils.getTrace(testTrace); String path = ctftrace.getPath(); <START> if (path == null) { throw new NullPointerException("Path shouldn't be null"); } <END> ctftrace.dispose(); return path; }</code><technical_language>Objects.requireNonNull</technical_language>

Target:
private static String getPathFromCtfTestTrace(@NonNull CtfTestTrace testTrace) { CtfTmfTrace ctftrace = CtfTmfTestTraceUtils.getTrace(testTrace); String path = Objects.requireNonNull(ctftrace.getPath()); ctftrace.dispose(); return path; }
Source:
<code>public T open() { if (streamName != null) { streamID = CorfuRuntime.getStreamID(streamName); } <START> if (needOrderedUUIDs) { <END> setArguments(runtime.getGuidGenerator()); } try { if (options.contains(ObjectOpenOptions.NO_CACHE)) { return CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); } else { ObjectsView.ObjectID<T> oid = new ObjectsView.ObjectID(streamID, type); return (T) runtime.getObjectsView().objectCache.computeIfAbsent(oid, x -> { try { T result = CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); ISerializer objectSerializer = ((CorfuCompileProxy) ((ICorfuSMR) result). getCorfuSMRProxy()) .getSerializer(); if (serializer != objectSerializer) { log.warn("open: Attempt to open an existing object with a different serializer {}. " + "Object opened with original serializer {}.", serializer.getClass().getSimpleName(), oid, objectSerializer.getClass().getSimpleName()); } return result; } catch (Exception ex) { throw new UnrecoverableCorfuError(ex); } } ); } } catch (Exception ex) { log.error("Runtime instrumentation no longer supported and no compiled class found" + " for {}", type); throw new UnrecoverableCorfuError(ex); } }</code><technical_language>This instrumented a higher layer. object view need uuid ordered not, needs a uuid</technical_language>

Target:
public T open() { if (streamName != null) { streamID = CorfuRuntime.getStreamID(streamName); } try { if (options.contains(ObjectOpenOptions.NO_CACHE)) { return CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); } else { ObjectsView.ObjectID<T> oid = new ObjectsView.ObjectID(streamID, type); return (T) runtime.getObjectsView().objectCache.computeIfAbsent(oid, x -> { try { T result = CorfuCompileWrapperBuilder.getWrapper(type, runtime, streamID, arguments, serializer); ISerializer objectSerializer = ((CorfuCompileProxy) ((ICorfuSMR) result). getCorfuSMRProxy()) .getSerializer(); if (serializer != objectSerializer) { log.warn("open: Attempt to open an existing object with a different serializer {}. " + "Object opened with original serializer {}.", serializer.getClass().getSimpleName(), oid, objectSerializer.getClass().getSimpleName()); } return result; } catch (Exception ex) { throw new UnrecoverableCorfuError(ex); } } ); } } catch (Exception ex) { log.error("Runtime instrumentation no longer supported and no compiled class found" + " for {}", type); throw new UnrecoverableCorfuError(ex); } }
Source:
<code>public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (obj instanceof Number) { Number num = (Number) obj; double value = num.doubleValue() * fFactor; double abs = Math.abs(value); if (abs >= 1) { if (abs >= PETA) { return toAppendTo.append(FORMAT.format(value / PETA)).append(' ').append(PETA_PREFIX); } if (abs >= TERA) { return toAppendTo.append(FORMAT.format(value / TERA)).append(' ').append(TERA_PREFIX); } if (abs >= GIGA) { return toAppendTo.append(FORMAT.format(value / GIGA)).append(' ').append(GIGA_PREFIX); } if (abs >= MEGA) { return toAppendTo.append(FORMAT.format(value / MEGA)).append(' ').append(MEGA_PREFIX); } if (abs >= KILO) { return toAppendTo.append(FORMAT.format(value / <START> (KILO))).append(' <END> ').append(KILO_PREFIX); } return toAppendTo.append(FORMAT.format(value)); } if (abs < PICO) { return toAppendTo.append(FORMAT.format(value)); } if (abs < NANO) { return toAppendTo.append(FORMAT.format(value * (TERA))).append(' ').append(PICO_PREFIX); } if (abs < MICRO) { return toAppendTo.append(FORMAT.format(value * (GIGA))).append(' ').append(NANO_PREFIX); } if (abs < MILLI) { return toAppendTo.append(FORMAT.format(value * (MEGA))).append(' ').append(MICRO_PREFIX); } return toAppendTo.append(FORMAT.format(value * (KILO))).append(' ').append(MILLI_PREFIX); } throw new IllegalArgumentException("Cannot format given Object as a Number"); }</code><technical_language>This () others don't</technical_language>

Target:
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (obj instanceof Number) { Number num = (Number) obj; double value = num.doubleValue() * fFactor; double abs = Math.abs(value); if (abs >= 1) { if (abs >= PETA) { return toAppendTo.append(FORMAT.format(value / PETA)).append(' ').append(PETA_PREFIX); } if (abs >= TERA) { return toAppendTo.append(FORMAT.format(value / TERA)).append(' ').append(TERA_PREFIX); } if (abs >= GIGA) { return toAppendTo.append(FORMAT.format(value / GIGA)).append(' ').append(GIGA_PREFIX); } if (abs >= MEGA) { return toAppendTo.append(FORMAT.format(value / MEGA)).append(' ').append(MEGA_PREFIX); } if (abs >= KILO) { return toAppendTo.append(FORMAT.format(value / KILO)).append(' ').append(KILO_PREFIX); } return toAppendTo.append(FORMAT.format(value)); } if (abs < PICO) { return toAppendTo.append(FORMAT.format(value)); } if (abs < NANO) { return toAppendTo.append(FORMAT.format(value * TERA)).append(' ').append(PICO_PREFIX); } if (abs < MICRO) { return toAppendTo.append(FORMAT.format(value * GIGA)).append(' ').append(NANO_PREFIX); } if (abs < MILLI) { return toAppendTo.append(FORMAT.format(value * MEGA)).append(' ').append(MICRO_PREFIX); } return toAppendTo.append(FORMAT.format(value * KILO)).append(' ').append(MILLI_PREFIX); } throw new IllegalArgumentException("Cannot format given Object as a Number: " + obj); }
Source:
<code>public KafkaMessageListenerContainer container() { Assert.isTrue(!ObjectUtils.isEmpty(properties.getTopics()) || !ObjectUtils.isEmpty(properties.getPartitions()), <START> "Either a list of topics OR a topic=<comma separated partitions> must be provided"); <END> Configuration zookeeperConfiguration = new ZookeeperConfiguration(zookeeperConnect()); ConnectionFactory kafkaConnectionFactory = new DefaultConnectionFactory(zookeeperConfiguration); Partition[] partitions = getPartitions(); KafkaMessageListenerContainer container = ObjectUtils.isEmpty(partitions) ? new KafkaMessageListenerContainer(kafkaConnectionFactory, properties.getTopics()) : new KafkaMessageListenerContainer(kafkaConnectionFactory, partitions); container.setOffsetManager(kafkaNativeOffsetManager(kafkaConnectionFactory)); return container; }</code><technical_language>Assert validation in KafkaConfigurationProperties. other side this message reflect topics/partitions reality</technical_language>

Target:
public KafkaMessageListenerContainer container() { Partition[] partitions = getPartitions(); KafkaMessageListenerContainer container = ObjectUtils.isEmpty(partitions) ? new KafkaMessageListenerContainer(kafkaConnectionFactory(), properties.getTopics()) : new KafkaMessageListenerContainer(kafkaConnectionFactory(), partitions); if(properties.getConcurrency() > partitions.length) { logger.warn(String.format("%s : %d", "Max concurrency is reduced to", partitions.length)); } container.setConcurrency(Math.min(properties.getConcurrency(), partitions.length)); container.setMaxFetch(properties.getMaxFetch()); container.setStopTimeout(properties.getStopTimeout()); container.setQueueSize(properties.getQueueSize()); container.setOffsetManager(kafkaNativeOffsetManager(kafkaConnectionFactory())); return container; }
Source:
<code>public long countProjectsByFilter(final Map<ProgramFilters, Object> filters) throws MiddlewareException { try { final Criteria criteria = this.getSession().createCriteria(Project.class); for (Map.Entry<ProgramFilters, Object> entry : filters.entrySet()) { final ProgramFilters filter = entry.getKey(); final Object value = entry.getValue(); criteria.add(Restrictions.eq(filter.getStatement(), value)); } return criteria.list().size(); <START> } catch (HibernateException e) { <END> throw new MiddlewareException("Error in countProjectsByFilter(): " + e.getMessage(), e); } }</code><technical_language>Apply code cleanup (eg. append final applicable variables, parameters) ProjectDao.java</technical_language>

Target:
public long countProjectsByFilter(final Map<ProgramFilters, Object> filters) throws MiddlewareException { try { final Criteria criteria = this.getSession().createCriteria(Project.class); for (final Map.Entry<ProgramFilters, Object> entry : filters.entrySet()) { final ProgramFilters filter = entry.getKey(); final Object value = entry.getValue(); criteria.add(Restrictions.eq(filter.getStatement(), value)); } return criteria.list().size(); } catch (final HibernateException e) { throw new MiddlewareException("Error in countProjectsByFilter(): " + e.getMessage(), e); } }
Source:
<code>public void install() { BundleContext ctx = runtime.getBundleContext(); ctx.addBundleListener(this); Bundle[] bundles = ctx.getBundles(); int mask = Bundle.STARTING | Bundle.ACTIVE; for (Bundle bundle : bundles) { String name = bundle.getSymbolicName(); runtime.bundles.put(name, bundle); int state = bundle.getState(); log.debug("Install bundle: {}", () -> name, () -> bundleStateAsString(state)); if ((state & mask) != 0) { if (OSGiRuntimeService.getComponentsList(bundle) != null) { log.trace("Install bundle: component list: {}", name, OSGiRuntimeService.getComponentsList(bundle)); try { runtime.createContext(bundle); } catch (RuntimeException e) { log.warn("Failed to load components for bundle: " + name, e); } } else { <START> log.trace("Install bundle: has no components", name); <END> } } else { log.debug("Install bundle: is not STARTING or ACTIVE, so no context was created", name); } } }</code><technical_language>debug</technical_language>

Target:
public void install() { BundleContext ctx = runtime.getBundleContext(); ctx.addBundleListener(this); Bundle[] bundles = ctx.getBundles(); int mask = Bundle.STARTING | Bundle.ACTIVE; for (Bundle bundle : bundles) { String name = bundle.getSymbolicName(); runtime.bundles.put(name, bundle); int state = bundle.getState(); log.debug("Install bundle: {}", () -> name, () -> bundleStateAsString(state)); if ((state & mask) != 0) { if (OSGiRuntimeService.getComponentsList(bundle) != null) { log.debug("Install bundle: component list: {}", name, OSGiRuntimeService.getComponentsList(bundle)); try { runtime.createContext(bundle); } catch (RuntimeException e) { log.warn("Failed to load components for bundle: " + name, e); } } else { log.debug("Install bundle: has no components", name); } } else { log.debug("Install bundle: is not STARTING or ACTIVE, so no context was created", name); } } }
Source:
<code>public void testDataDeletionCallback() throws Exception { _zkList.forEach(zk -> { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { for (String zkRealm : zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } } } ); Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { _metadataStoreDirectory.getMetadataStoreRealm(namespace, "anyKey"); return false; } catch (IllegalStateException e) { if (!e.getMessage().equals("Failed to get metadata store realm: Namespace " + namespace + " contains either empty or invalid routing data!")) { return false; } } catch (IllegalArgumentException iae) { if (!iae.getMessage().equals("Provided path is not a valid Zookeeper path: anyKey")) { <START> return false; <END> } } } return true; }, TestHelper.WAIT_DURATION)); }</code><technical_language>meaning of block line 343 is "ensure IllegalStateException is raised message is 'Failed get...'". Is this block ensuring a IllegalArgumentException is raised? this test case is testing</technical_language>

Target:
public void testDataDeletionCallback() throws Exception { _zkList.forEach(zk -> { ZkClient zkClient = ZK_SERVER_MAP.get(zk).getZkClient(); if (zkClient.exists(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { for (String zkRealm : zkClient .getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH)) { zkClient.delete(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + zkRealm); } } } ); Assert.assertTrue(TestHelper.verify(() -> { for (String namespace : _routingZkAddrMap.keySet()) { try { _metadataStoreDirectory.getMetadataStoreRealm(namespace, TEST_SHARDING_KEYS_1.get(0)); return false; } catch (IllegalStateException e) { if (!e.getMessage().equals("Failed to get metadata store realm: Namespace " + namespace + " contains either empty or invalid routing data!")) { throw e; } } } return true; }, TestHelper.WAIT_DURATION)); }
Source:
<code>public ResponseEntity<?> deleteProject(@PathVariable Long projectId) { <START> ProjectEntity project = new ProjectEntity(); <END> project.setId(projectId); projectService.delete(project); return ResponseEntity.noContent().build(); }</code><technical_language>extract this service method deleteProjectById(id)</technical_language>

Target:
public ResponseEntity<?> deleteProject(@PathVariable Long projectId) { projectService.delete(projectId); return ResponseEntity.noContent().build(); }
Source:
<code>private void open() throws IOException { if (remoteFilename == null) return; commBuf.clear(); if (readonly) commBuf.put("OPENW ".getBytes(Sage.BYTE_CHARSET)); else <START> commBuf.put("WRITEOPENW ".getBytes(Sage.BYTE_CHARSET)); <END> commBuf.put(remoteFilename.getBytes(StandardCharsets.UTF_16BE)); commBuf.put("\r\n".getBytes(Sage.BYTE_CHARSET)); commBuf.flip(); socket.write(commBuf); commBuf.clear(); String response = IOUtils.readLineBytes(socket, commBuf, TIMEOUT, null); if (!"OK".equals(response)) { disconnect(); throw new java.io.IOException("Error opening remote file of:" + response); } }</code><technical_language>issue usage of WRITEOPENW in RemoteSageFile class</technical_language>

Target:
private void open() throws IOException { if (remoteFilename == null) return; commBuf.clear(); if (readonly) { commBuf.put("OPENW ".getBytes(Sage.BYTE_CHARSET)); commBuf.put(remoteFilename.getBytes(StandardCharsets.UTF_16BE)); } else { commBuf.put("WRITEOPENW ".getBytes(Sage.BYTE_CHARSET)); commBuf.put(remoteFilename.getBytes(StandardCharsets.UTF_16BE)); commBuf.put((" " + Integer.toString(uploadId)).getBytes(Sage.BYTE_CHARSET)); } commBuf.put("\r\n".getBytes(Sage.BYTE_CHARSET)); commBuf.flip(); socket.write(commBuf); commBuf.clear(); String response = IOUtils.readLineBytes(socket, commBuf, TIMEOUT, null); if (!"OK".equals(response)) { disconnect(); throw new java.io.IOException("Error opening remote file of:" + response); } }
Source:
<code>protected final int readVarInt() throws IOException { long retvalue = 0; boolean is_negative = false; int b; done: for (;;) { if ((b = read()) < 0) throwUnexpectedEOFException(); if ((b & 0x40) != 0) { is_negative = true; } retvalue = (b & 0x3F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; throwVarIntOverflowException(); } if (is_negative) { retvalue = -retvalue; } int retValueAsInt = (int) retvalue; <START> if(retvalue != ((long)retValueAsInt)) { <END> throwVarIntOverflowException(); } return retValueAsInt; }</code><technical_language>style in rest of this file, add a space "if": s/if(/if (/ for similar if statements</technical_language>

Target:
protected final int readVarInt() throws IOException { return readVarInt(read()); }
Source:
<code>public void start() { if (log.isDebugEnabled()) log.debug("Starting poll for (using {})", new Object[] {entity, this}); if (running) { throw new IllegalStateException(String.format("Attempt to start poller %s of entity %s when already running", this, entity)); } running = true; for (final Callable<?> oneOffJob : oneOffJobs) { BasicTask<?> task = new BasicTask(oneOffJob); oneOffTasks.add(((EntityInternal)entity).getExecutionContext().submit(task)); } for (final PollJob<V> pollJob : pollJobs) { final String scheduleName = pollJob.handler.getDescription(); if (pollJob.pollPeriod.compareTo(Duration.ZERO) > 0) { Callable<Task<?>> pollingTaskFactory = new Callable<Task<?>>() { public Task<?> call() { <START> DynamicSequentialTask<V> task = new DynamicSequentialTask<V>(MutableMap.of("displayName", scheduleName, "entity", entity), <END> new Callable<V>() { public V call() { pollJob.wrappedJob.run(); return null; } } ); BrooklynTasks.setTransient(task); return task; } }; ScheduledTask task = new ScheduledTask(MutableMap.of("period", pollJob.pollPeriod), pollingTaskFactory); tasks.add((ScheduledTask)Entities.submit(entity, task)); } else { if (log.isDebugEnabled()) log.debug("Activating poll (but leaving off, as period {}) for (using {})", new Object[] {pollJob.pollPeriod, entity, this}); } } }</code><technical_language>Hm, strange generics (which changed this). returning null is more DynamicSequentTask<Void>. wrappedJob changed a callable a Runnable. strong feelings changing this now</technical_language>

Target:
public void start() { if (log.isDebugEnabled()) log.debug("Starting poll for (using {})", new Object[] {entity, this}); if (running) { throw new IllegalStateException(String.format("Attempt to start poller %s of entity %s when already running", this, entity)); } running = true; for (final Callable<?> oneOffJob : oneOffJobs) { BasicTask<?> task = new BasicTask(oneOffJob); oneOffTasks.add(((EntityInternal)entity).getExecutionContext().submit(task)); } for (final PollJob<V> pollJob : pollJobs) { final String scheduleName = pollJob.handler.getDescription(); if (pollJob.pollPeriod.compareTo(Duration.ZERO) > 0) { Callable<Task<?>> pollingTaskFactory = new Callable<Task<?>>() { public Task<?> call() { DynamicSequentialTask<Void> task = new DynamicSequentialTask<Void>(MutableMap.of("displayName", scheduleName, "entity", entity), new Callable<Void>() { public Void call() { pollJob.wrappedJob.run(); return null; } } ); BrooklynTasks.setTransient(task); return task; } }; ScheduledTask task = new ScheduledTask(MutableMap.of("period", pollJob.pollPeriod), pollingTaskFactory); tasks.add((ScheduledTask)Entities.submit(entity, task)); } else { if (log.isDebugEnabled()) log.debug("Activating poll (but leaving off, as period {}) for (using {})", new Object[] {pollJob.pollPeriod, entity, this}); } } }
Source:
<code>public CompletionStage<List<T>> unwrapList(CompletionStage<List<GetResult<T>>> future) { <START> return future.thenApplyAsync(listResultUnwrapper, Utils.SAME_THREAD_EXECUTOR); <END> }</code><technical_language>simple thenApply(...) instead</technical_language>

Target:
public CompletionStage<List<T>> unwrapList(CompletionStage<List<GetResult<T>>> future) { return future.thenApply(listResultUnwrapper); }
Source:
<code>public void testDistCpWithNoLocalWrite() throws Exception { describe("test dictcp job compatibility with option: noLocalWrite"); Path target = distCpDeepDirectoryStructure(localFS, localDir, remoteFS, remoteDir); lsR("Local to update", localFS, localDir); lsR("Remote before update", remoteFS, target); Job job = runDistCp(buildWithStandardOptions( new DistCpOptions.Builder( Collections.singletonList(localDir), target) .withDeleteMissing(true) .withSyncFolder(true) .withCRC(true) .withOverwrite(false) .withNoLocalWrite(true))); <START> assertTrue(job.isSuccessful()); <END> }</code><technical_language>Add a string include in exception text, e.g "job failed"</technical_language>

Target:
public void testDistCpWithNoLocalWrite() throws Exception { describe("test dictcp job compatibility with option: noLocalWrite"); Path target = distCpDeepDirectoryStructure(localFS, localDir, remoteFS, remoteDir); lsR("Local to update", localFS, localDir); lsR("Remote before update", remoteFS, target); Job job = runDistCp(buildWithStandardOptions( new DistCpOptions.Builder( Collections.singletonList(localDir), target) .withDeleteMissing(true) .withSyncFolder(true) .withCRC(true) .withOverwrite(false) .withNoLocalWrite(true))); assertTrue("DistCp job did not complete successfully.", job.isSuccessful()); }