auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void createQuestionsWithResponses() { questionsWithResponses = new ArrayList<>(); int qnIndx = 1; for (FeedbackQuestionAttributes questionAttributes : bundle.getSortedQuestions()) { int numOfResponseBoxes = questionAttributes.numberOfEntitiesToGiveFeedbackTo; int maxResponsesPossible = bundle.recipientList.get(questionAttributes.getId()).size(); if (numOfResponseBoxes == Const.MAX_POSSIBLE_RECIPIENTS || numOfResponseBoxes > maxResponsesPossible) { numOfResponseBoxes = maxResponsesPossible; } FeedbackSubmissionEditQuestion question = createQuestion(questionAttributes, qnIndx); List<FeedbackSubmissionEditResponse> responses = createResponses(questionAttributes, qnIndx, numOfResponseBoxes); boolean isInstructorCommentsOnResponsesAllowed = questionAttributes.getQuestionDetails().isInstructorCommentsOnResponsesAllowed(); boolean isFeedbackParticipantCommentsOnResponsesAllowed = questionAttributes.getQuestionDetails().isFeedbackParticipantCommentsOnResponsesAllowed(); questionsWithResponses.add(new StudentFeedbackSubmissionEditQuestionsWithResponses( question, responses, numOfResponseBoxes, maxResponsesPossible, isInstructorCommentsOnResponsesAllowed, isFeedbackParticipantCommentsOnResponsesAllowed)); qnIndx++; } }

Target:
private void createQuestionsWithResponses() { questionsWithResponses = new ArrayList<>(); int qnIndx = 1; for (FeedbackQuestionAttributes questionAttributes : bundle.getSortedQuestions()) { int numOfResponseBoxes = questionAttributes.numberOfEntitiesToGiveFeedbackTo; int maxResponsesPossible = bundle.recipientList.get(questionAttributes.getId()).size(); if (numOfResponseBoxes == Const.MAX_POSSIBLE_RECIPIENTS || numOfResponseBoxes > maxResponsesPossible) { numOfResponseBoxes = maxResponsesPossible; } FeedbackSubmissionEditQuestion question = createQuestion(questionAttributes, qnIndx); List<FeedbackSubmissionEditResponse> responses = createResponses(questionAttributes, qnIndx, numOfResponseBoxes); boolean isFeedbackParticipantCommentsOnResponsesAllowed = questionAttributes.getQuestionDetails().isFeedbackParticipantCommentsOnResponsesAllowed(); questionsWithResponses.add(new StudentFeedbackSubmissionEditQuestionsWithResponses( question, responses, numOfResponseBoxes, maxResponsesPossible, isFeedbackParticipantCommentsOnResponsesAllowed)); qnIndx++; } }
Source:
public void init() { ITEMS = new ArrayList<>(Arrays.asList("first", "middle", "last")); dataProvider = DataProvider.ofCollection(ITEMS); dataController = new DataControllerStub(); dataView = new ListDataViewImpl(dataController); }

Target:
public void init() { items = new ArrayList<>(Arrays.asList("first", "middle", "last")); dataProvider = DataProvider.ofCollection(items); dataController = new DataControllerStub(); dataView = new ListDataViewImpl(dataController); }
Source:
public synchronized void removed(IExtension[] extensions) { theAdapterManager.flushLookup(); for (IExtension extension : extensions) { for (List<IAdapterFactory> list : theAdapterManager.getFactories().values()) { for (Iterator<IAdapterFactory> it2 = (list).iterator(); it2.hasNext();) { IAdapterFactory factory = it2.next(); if (!(factory instanceof AdapterFactoryProxy)) continue; if (((AdapterFactoryProxy) factory).originatesFrom(extension)) { it2.remove(); } } } } }

Target:
public synchronized void removed(IExtension[] extensions) { theAdapterManager.flushLookup(); for (IExtension extension : extensions) { for (List<IAdapterFactory> adapterFactories : theAdapterManager.getFactories().values()) { for (Iterator<IAdapterFactory> it2 = (adapterFactories).iterator(); it2.hasNext();) { IAdapterFactory factory = it2.next(); if (!(factory instanceof AdapterFactoryProxy)) continue; if (((AdapterFactoryProxy) factory).originatesFrom(extension)) { it2.remove(); } } } } }
Source:
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws Exception { InputStream is = null; try { is = new FileInputStream(keyStore); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(is, keyStorePassword.toCharArray()); is.close(); return ks; } finally { if (is != null) { is.close(); } } }

Target:
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws Exception { InputStream is = null; try { is = new FileInputStream(keyStore); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(is, keyStorePassword.toCharArray()); return ks; } finally { if (is != null) { is.close(); } } }
Source:
private Metacard transformGeoEntryToMetacard(GeoEntry geoEntry) { if (!GeoCodingConstants.CITY_FEATURE_CODES.contains(geoEntry.getFeatureCode())) { return null; } Metacard metacard = new MetacardImpl(geoNamesMetacardType); String id = uuidGenerator.generateUuid(); metacard.setAttribute( new AttributeImpl( Core.TITLE, geoEntry.getName() + ", " + geoEntry.getCountryCode() + "(" + id.substring(0, 4) + ")")); metacard.setAttribute(new AttributeImpl(Core.DESCRIPTION, geoEntry.getAlternateNames())); metacard.setAttribute(new AttributeImpl(Location.COUNTRY_CODE, geoEntry.getCountryCode())); metacard.setAttribute(new AttributeImpl(Core.ID, id)); metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.FEATURE_CODE_ATTRIBUTE_NAME, geoEntry.getFeatureCode())); metacard.setAttribute( new AttributeImpl(GeoEntryAttributes.POPULATION_ATTRIBUTE_NAME, geoEntry.getPopulation())); Double latitude = geoEntry.getLatitude(); Double longitude = geoEntry.getLongitude(); if (latitude != null && longitude != null) { Coordinate coordinate = new Coordinate(longitude, latitude); Geometry geometry = new GeometryFactory().createPoint(coordinate); String wkt = WKT_WRITER_THREAD_LOCAL.get().write(geometry); metacard.setAttribute(new AttributeImpl(Core.LOCATION, wkt)); } metacard.setAttribute( new AttributeImpl( Core.METACARD_TAGS, Arrays.asList(GAZETTEER_METACARD_TAG, GeoCodingConstants.GEONAMES_TAG))); return metacard; }

Target:
private Metacard transformGeoEntryToMetacard(GeoEntry geoEntry) { if (!GeoCodingConstants.CITY_FEATURE_CODES.contains(geoEntry.getFeatureCode())) { return null; } Metacard metacard = new MetacardImpl(geoNamesMetacardType); String id = uuidGenerator.generateUuid(); metacard.setAttribute( new AttributeImpl( Core.TITLE, String.format( TITLE_FORMAT, geoEntry.getName(), geoEntry.getCountryCode(), id.substring(0, 4)))); metacard.setAttribute(new AttributeImpl(Core.DESCRIPTION, geoEntry.getAlternateNames())); metacard.setAttribute(new AttributeImpl(Location.COUNTRY_CODE, geoEntry.getCountryCode())); metacard.setAttribute(new AttributeImpl(Core.ID, id)); metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.FEATURE_CODE_ATTRIBUTE_NAME, geoEntry.getFeatureCode())); metacard.setAttribute( new AttributeImpl(GeoEntryAttributes.POPULATION_ATTRIBUTE_NAME, geoEntry.getPopulation())); Double latitude = geoEntry.getLatitude(); Double longitude = geoEntry.getLongitude(); if (latitude != null && longitude != null) { Coordinate coordinate = new Coordinate(longitude, latitude); Geometry geometry = new GeometryFactory().createPoint(coordinate); String wkt = WKT_WRITER_THREAD_LOCAL.get().write(geometry); metacard.setAttribute(new AttributeImpl(Core.LOCATION, wkt)); } metacard.setAttribute( new AttributeImpl( Core.METACARD_TAGS, Arrays.asList(GAZETTEER_METACARD_TAG, GeoCodingConstants.GEONAMES_TAG))); return metacard; }
Source:
public void expandPanels() { if (isElementPresent("collapse-panels-button")) { clickCollapseExpandButtonAndWaitForPanelsToExpand(); waitForPanelsToExpand(); } }

Target:
public void expandPanels() { if (isElementPresent("collapse-panels-button")) { clickCollapseExpandButtonAndWaitForPanelsToExpand(); } }
Source:
public void shouldShowListWhenFoundPatientsByQuery() { when(patientDAO.getAllPatients()).thenReturn(patientList); syncedPatientsPresenter.setQuery("TEST"); syncedPatientsPresenter.updateLocalPatientsList(); verify(view).updateListVisibility(true); }

Target:
public void shouldShowListWhenFoundPatientsByQuery() { final String query = "given_name_3"; when(patientDAO.getAllPatients()).thenReturn(Observable.just(patientList)); syncedPatientsPresenter.setQuery(query); syncedPatientsPresenter.updateLocalPatientsList(); verify(view).updateListVisibility(true); verify(view).updateAdapter(Collections.singletonList(patientList.get(2))); }
Source:
void submit() { view.submit(versionRecordManager.getCurrentPath()); versionRecordManager.restoreToCurrentVersion(); concurrentUpdateSessionInfo = null; }

Target:
void submit() { view.submit(versionRecordManager.getCurrentPath()); concurrentUpdateSessionInfo = null; }
Source:
public TTransport getTransport(final TTransport trans) { TSocket tSocket = null; if (trans instanceof TSocket) { tSocket = (TSocket) trans; } else if (trans instanceof TSaslServerTransport) { TSaslServerTransport saslTrans = (TSaslServerTransport) trans; tSocket = (TSocket)(saslTrans.getUnderlyingTransport()); } String remoteHost = tSocket != null ? tSocket.getSocket().getInetAddress().getCanonicalHostName() : null; if (remoteHost != null && isHostFromTrustedDomain(remoteHost, trustedDomain)) { LOG.info("No authentication performed because the connecting host " + remoteHost + " is " + "from the trusted domain " + trustedDomain); return noAuthFactory.getTransport(trans); } else { return otherFactory.getTransport(trans); } }

Target:
public TTransport getTransport(final TTransport trans) { TSocket tSocket = null; if (trans instanceof TSocket) { tSocket = (TSocket) trans; } else if (trans instanceof TSaslServerTransport) { TSaslServerTransport saslTrans = (TSaslServerTransport) trans; tSocket = (TSocket)(saslTrans.getUnderlyingTransport()); } String remoteHost = tSocket != null ? tSocket.getSocket().getInetAddress().getCanonicalHostName() : null; if (remoteHost != null && isHostFromTrustedDomain(remoteHost, trustedDomain)) { LOG.info("No authentication performed because the connecting host " + remoteHost + " is " + "from the trusted domain " + trustedDomain); return noAuthFactory.getTransport(trans); } return otherFactory.getTransport(trans); }
Source:
public static Boolean getBriefcaseTrackingConsentProperty() { return Boolean.valueOf( Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_TRACKING_CONSENT_PROPERTY, Boolean.FALSE.toString()) ); }

Target:
public static boolean getBriefcaseTrackingConsentProperty() { return Boolean.valueOf( Preference.APPLICATION_SCOPED.get(BriefcasePreferences.BRIEFCASE_TRACKING_CONSENT_PROPERTY, Boolean.FALSE.toString()) ).booleanValue(); }
Source:
public BuildResult build( final Project project ) { return oldBehaviour(project); }

Target:
public BuildResult build( final Project project ) { try { cache.invalidateCache( project ); Builder builder = cache.assertBuilder( project ); final BuildResults results = builder.build( ); BuildMessage infoMsg = new BuildMessage( ); infoMsg.setLevel( Level.INFO ); infoMsg.setText( buildResultMessage( project, results ).toString( ) ); results.addBuildMessage( 0, infoMsg ); return new BuildResult( builder, results ); } catch ( Exception e ) { logger.error( e.getMessage( ), e ); return new BuildResult( null, buildExceptionResults( e, project.getPom( ).getGav( ) ) ); } }
Source:
private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (Configuration.getGlobalConfiguration().get(AZURE_TEST_SERVICE_VERSIONS) == null) { return SecretServiceVersion.getLatest().equals(serviceVersion); } return true; }

Target:
private static boolean shouldServiceVersionBeTested(SecretServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return SecretServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion -> serviceVersion.toString().equals(configuredServiceVersion.trim())); }
Source:
private InterpreterResult runWithOutput(String code, InterpreterOutput out) { this.out.setInterpreterOutput(out); PrintStream oldOut = System.out; PrintStream newOut = (out != null) ? new PrintStream(out) : null; System.setOut(newOut); InterpreterResult res = interpreter.eval(code); System.setOut(oldOut); return res; }

Target:
private InterpreterResult runWithOutput(String code, InterpreterOutput out) { this.out.setInterpreterOutput(out); PrintStream oldOut = System.out; PrintStream newOut = (out != null) ? new PrintStream(out) : null; try { System.setOut(newOut); return interpreter.eval(code); } finally { System.setOut(oldOut); } }
Source:
public static String genOutputStringForTest(String filePath, int line, String classification, String msg) { return filePath + ":" + line + ": " + classification + ": " + msg; }

Target:
public static String genOutputStringForTest(String filePath, int line, String classification, String msg) { return new ViolationMessage(filePath, line, 0, classification, msg).toString(); }
Source:
public void reportIssue(JavaCheck javaCheck, Tree syntaxNode, String message, List<Location> secondary, @Nullable Integer cost) { throwIfCrossFileScanner(javaCheck); List<List<Location>> flows = secondary.stream().map(Collections::singletonList).collect(Collectors.toList()); reportIssueWithFlow(javaCheck, syntaxNode, message, flows, cost); }

Target:
public void reportIssue(JavaCheck javaCheck, Tree syntaxNode, String message, List<Location> secondary, @Nullable Integer cost) { List<List<Location>> flows = secondary.stream().map(Collections::singletonList).collect(Collectors.toList()); reportIssueWithFlow(javaCheck, syntaxNode, message, flows, cost); }
Source:
if (s2 == null) return -1; CacheTopology t1 = s1.getCacheTopology(); CacheTopology t2 = s2.getCacheTopology(); int topologyId = ((Integer)t1.getTopologyId()).compareTo(t2.getTopologyId()); if (topologyId != 0) return topologyId; String rt1 = t1.getCurrentCH().getRoutingTableAsString(); String rt2 = t2.getCurrentCH().getRoutingTableAsString(); return rt1.compareTo(rt2); }; private static final Log log = LogFactory.getLog(PreferAvailabilityStrategy.class); private final EventLogManager eventLogManager; private final PersistentUUIDManager persistentUUIDManager; private final boolean resolveConflictsOnMerge; public PreferAvailabilityStrategy(EventLogManager eventLogManager, PersistentUUIDManager persistentUUIDManager, boolean resolveConflictsOnMerge) { this.eventLogManager = eventLogManager; this.persistentUUIDManager = persistentUUIDManager; this.resolveConflictsOnMerge = resolveConflictsOnMerge; }

Target:
if (s2 == null) return -1; CacheTopology t1 = s1.getCacheTopology(); CacheTopology t2 = s2.getCacheTopology(); int topologyId = ((Integer)t1.getTopologyId()).compareTo(t2.getTopologyId()); if (topologyId != 0) return topologyId; int rebalanceId = ((Integer)t1.getRebalanceId()).compareTo(t2.getRebalanceId()); if (rebalanceId != 0) return topologyId; List<Address> m1 = t1.getMembers(); List<Address> m2 = t2.getMembers(); if (m1.size() == m2.size()) { int compareAddress = m1.get(0).compareTo(m2.get(0)); if (compareAddress == 0) return ((Integer)t1.hashCode()).compareTo(t2.hashCode()); }
Source:
public int getLineIndex(int y) { checkWidget(); y -= topMargin; if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); int lineIndex = (y + getVerticalScrollOffset()) / lineHeight; int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount - 1, lineIndex)); return lineIndex; } if (y == topIndexY) return topIndex; int line = topIndex; if (y < topIndexY) { while (y < topIndexY && line > 0) { y += renderer.getCachedLineHeight(--line); } } else { int lineCount = content.getLineCount(); int lineHeight = renderer.getLineHeight(line); while (y - lineHeight >= topIndexY && line < lineCount - 1) { y -= lineHeight; lineHeight = renderer.getCachedLineHeight(++line); } } return line; }

Target:
public int getLineIndex(int y) { checkWidget(); y -= topMargin; if (isFixedLineHeight()) { int lineHeight = renderer.getLineHeight(); int lineIndex = (y + getVerticalScrollOffset()) / lineHeight; int lineCount = content.getLineCount(); lineIndex = Math.max(0, Math.min(lineCount - 1, lineIndex)); return lineIndex; } if (y == topIndexY) return topIndex; int line = topIndex; if (y < topIndexY) { while (y < topIndexY && line > 0) { y += renderer.getLineHeight(--line); } } else { int lineCount = content.getLineCount(); int lineHeight = renderer.getLineHeight(line); while (y - lineHeight >= topIndexY && line < lineCount - 1) { y -= lineHeight; lineHeight = renderer.getLineHeight(++line); } } return line; }
Source:
public Object caseEnumeration(Enumeration enumeration) { org.eclipse.uml2.uml.Package package_ = enumeration .getNearestPackage(); if (package_ != null) { EEnum eEnum = EcoreFactory.eINSTANCE.createEEnum(); elementToEModelElementMap.put(enumeration, eEnum); EPackage ePackage = (EPackage) doSwitch(package_); ePackage.getEClassifiers().add(eEnum); setName(eEnum, enumeration); if (options != null && OPTION__PROCESS .equals(options.get(OPTION__NULLABLE_ENUM_ATTRIBUTES))) { EDataType enumType = EcoreFactory.eINSTANCE.createEDataType(); enumToDataType.put(eEnum, enumType); ePackage.getEClassifiers().add(enumType); enumType.setName(eEnum.getName()+"_Optional"); UML2Util.getEAnnotation( enumType, UMLUtil.UML2_UML_PACKAGE_2_0_NS_URI, true).getReferences().add(enumeration); enumType.setInstanceTypeName(Enumerator.class.getName()); ExtendedMetaData.INSTANCE.setBaseType(enumType, eEnum); } defaultCase(enumeration); return eEnum; } return super.caseEnumeration(enumeration); }

Target:
public Object caseEnumeration(Enumeration enumeration) { org.eclipse.uml2.uml.Package package_ = enumeration .getNearestPackage(); if (package_ != null) { EEnum eEnum = EcoreFactory.eINSTANCE.createEEnum(); elementToEModelElementMap.put(enumeration, eEnum); EPackage ePackage = (EPackage) doSwitch(package_); ePackage.getEClassifiers().add(eEnum); setName(eEnum, enumeration); if (options != null && OPTION__PROCESS .equals(options.get(OPTION__NULLABLE_ENUM_ATTRIBUTES))) { EDataType enumType = EcoreFactory.eINSTANCE.createEDataType(); enumToDataType.put(eEnum, enumType); ePackage.getEClassifiers().add(enumType); enumType.setName(eEnum.getName()+"_Optional"); enumType.setInstanceTypeName(Enumerator.class.getName()); ExtendedMetaData.INSTANCE.setBaseType(enumType, eEnum); } defaultCase(enumeration); return eEnum; } return super.caseEnumeration(enumeration); }
Source:
public void optionsChanged(OptionsParam optionsParam) { this.restartServer(); }

Target:
public void optionsChanged(OptionsParam optionsParam) { if (!currentConfigLocalAddress.equals(this.getCallbackParam() .getLocalAddress()) || currentConfigPort != this.getCallbackParam().getPort()) { int port = actualPort; if (currentConfigPort != this.getCallbackParam().getPort()) { port = this.getCallbackParam().getPort(); } this.restartServer(port); currentConfigLocalAddress = this.getCallbackParam() .getLocalAddress(); currentConfigPort = this.getCallbackParam().getPort(); } }
Source:
public static CloudBigtableScanConfiguration BuildExportConfig(ExportOptions opts) { ValueProvider<ReadRowsRequest> request = new RequestWithScanValueProvider( opts.getBigtableStartRow(), opts.getBigtableStopRow(), opts.getBigtableMaxVersions(), opts.getBigtableFilter()); CloudBigtableScanConfiguration.Builder configBuilder = new CloudBigtableScanConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()) .withRequest(request); if (opts.getBigtableAppProfileId() != null) { configBuilder.withAppProfileId(opts.getBigtableAppProfileId()); } return configBuilder.build(); }

Target:
public static CloudBigtableScanConfiguration BuildExportConfig(ExportOptions opts) { ValueProvider<ReadRowsRequest> request = new RequestValueProvider( opts.getBigtableStartRow(), opts.getBigtableStopRow(), opts.getBigtableMaxVersions(), opts.getBigtableFilter()); CloudBigtableScanConfiguration.Builder configBuilder = new CloudBigtableScanConfiguration.Builder() .withProjectId(opts.getBigtableProject()) .withInstanceId(opts.getBigtableInstanceId()) .withTableId(opts.getBigtableTableId()) .withAppProfileId(opts.getBigtableAppProfileId()) .withRequest(request); return configBuilder.build(); }
Source:
private double toDouble(BigFraction fraction) { double d = fraction.doubleValue(); if (Double.isInfinite(d) || Double.isNaN(d)) { throw new RuntimeException("Encountered a value which can not be represented as a double value"); } if (fraction.subtract(new BigFraction(d)).abs().compareTo(new BigFraction(Math.ulp(d))) > 0) { throw new RuntimeException("Encountered a value with sufficient precision"); } return d; }

Target:
private double toDouble(BigFraction fraction) { double d = fraction.doubleValue(); if (Double.isInfinite(d) || Double.isNaN(d)) { throw new RuntimeException("Encountered a value which can not be represented as a double"); } if (fraction.subtract(new BigFraction(d)).abs().compareTo(new BigFraction(Math.ulp(d))) > 0) { throw new RuntimeException("Encountered a value with insufficient precision"); } return d; }
Source:
public void tearDown() { HotRodClientTestingUtil.killServers(hotRodServer); HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager); }

Target:
public void tearDown() { HotRodClientTestingUtil.killServers(hotRodServer); HotRodClientTestingUtil.killRemoteCacheManager(remoteCacheManager); TestingUtil.killCacheManagers(cacheManager); }
Source:
private static Future<Response> addElementToBatch( CoalescingBatchingEventHandler<Request, Response> handler, Request request, boolean endBatch) { TestBatchElement element = ImmutableTestBatchElement.of(request); handler.onEvent(element, new Random().nextLong(), endBatch); return element.result(); }

Target:
private static Future<Response> addElementToBatch( CoalescingBatchingEventHandler<Request, Response> handler, Request request, boolean endBatch) { TestBatchElement element = ImmutableTestBatchElement.of(request); handler.onEvent(element, COUNTER.getAndIncrement(), endBatch); return element.result(); }
Source:
public void shouldContainNumericConstantsForMessageTypes() throws Exception { assertEquals(HEARTBEAT_TYPE, getField(constants, "MSG_HEARTBEAT")); }

Target:
public void shouldContainNumericConstantsForMessageTypes() throws Exception { assertEquals(HEARTBEAT_TYPE, getField(constants, "HEARTBEAT_MESSAGE")); }
Source:
public boolean isSupporting(Capabilities capabilities) { return BrowserType.EDGE.equals(capabilities.getBrowserName()) || capabilities.getCapability("chromeOptions") != null || capabilities.getCapability("goog:chromeOptions") != null; }

Target:
public boolean isSupporting(Capabilities capabilities) { return BrowserType.EDGE.equals(capabilities.getBrowserName()); }
Source:
public void close(boolean needWait) { try { if (needWait && !currentWatchers.isEmpty()) { LOG.debug("Waiting '{}ms' before closing all log watchers.", WAIT_TIMEOUT * 2); Thread.sleep(WAIT_TIMEOUT * 2); } else { LOG.debug("Just close it now!"); } } catch (InterruptedException e) { LOG.error("Interrupted waiting for the logs. This should not happen.", e); } finally { currentWatchers.forEach(LogWatch::close); currentWatchers.clear(); } }

Target:
public void close(boolean needWait) { try { if (needWait && !currentContainerWatchers.isEmpty()) { int waitBeforeClose = WAIT_TIMEOUT * 2; LOG.debug( "Waiting '{}ms' before closing all log watchers for workspace '{}'.", waitBeforeClose, workspaceId); Thread.sleep(waitBeforeClose); } } catch (InterruptedException e) { LOG.error( "Interrupted while waiting before closing the log watch for workspace '{}'.", workspaceId, e); } finally { LOG.debug("Closing all log watchers for '{}'", workspaceId); currentContainerWatchers.forEach((k, v) -> v.close()); currentContainerWatchers.clear(); } }
Source:
private void updateMemoryUsage(boolean useRevocableMemory) { if (useRevocableMemory) { if (!spillEnabled) { throw new IllegalStateException("Revocable memory requested when spill to disk is not enabled"); } localRevocableMemoryContext.setBytes(pageIndex.getEstimatedSize().toBytes()); } else { if (!localUserMemoryContext.trySetBytes(pageIndex.getEstimatedSize().toBytes())) { pageIndex.compact(); localUserMemoryContext.setBytes(pageIndex.getEstimatedSize().toBytes()); } } }

Target:
private void updateMemoryUsage(boolean useRevocableMemory) { if (useRevocableMemory) { if (!spillEnabled) { throw new IllegalStateException("Revocable memory requested when spill to disk is not enabled"); } pagesIndexRevocableMemoryContext.setBytes(pageIndex.getEstimatedSize().toBytes()); } else { if (!pagesIndexUserMemoryContext.trySetBytes(pageIndex.getEstimatedSize().toBytes())) { pageIndex.compact(); pagesIndexUserMemoryContext.setBytes(pageIndex.getEstimatedSize().toBytes()); } } }
Source:
public JRDataSource getDataSource(String testId) { if (plots == null) { plots = createTaskPlots(); } if (plots.size() == 0) { return null; } String testIdParent = getParentId(testId); if (plots.containsKey(testId)){ plots.get(testId).getMetricPlotDTOs().addAll(plots.get(testIdParent).getMetricPlotDTOs()); return new JRBeanCollectionDataSource(Collections.singleton(plots.get(testId))); } else return new JRBeanCollectionDataSource(Collections.singleton(plots.get(testIdParent))); }

Target:
public JRDataSource getDataSource(String testId) { sessionId = getSessionIdProvider().getSessionId(); String testIdParent = getParentId(testId); if (plots == null) { plots = createTaskPlots(); } if (plots.size() == 0) { return null; } MetricPlotDTOs result = new MetricPlotDTOs(); if (plots.containsKey(testId)) { if (plots.get(testId).getMetricPlotDTOs() != null) { plots.get(testId).sortingByMetricName(); result.getMetricPlotDTOs().addAll(plots.get(testId).getMetricPlotDTOs()); } } if (plots.containsKey(testIdParent)) { if (plots.get(testIdParent).getMetricPlotDTOs() != null) { plots.get(testIdParent).sortingByMetricName(); result.getMetricPlotDTOs().addAll(plots.get(testIdParent).getMetricPlotDTOs()); } } return new JRBeanCollectionDataSource(Collections.singleton(result)); }
Source:
public static void main(String... args) throws Exception { if (args.length > 0 && args[0].equals("-extract")) { extract(args); return; } ClassLoader cl = EmbeddedLauncher.class.getClassLoader(); Enumeration<URL> manifests = cl.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL murl = manifests.nextElement(); Manifest m = new Manifest(murl.openStream()); String runpath = m.getMainAttributes() .getValue(EMBEDDED_RUNPATH); if (runpath != null) { try (ModifiableURLClassLoader ml = new ModifiableURLClassLoader(cl)) { for (String path : runpath.split("\\s*,\\s*")) { URL url = toFileURL(cl.getResource(path)); ml.addURL(url); } Class<?> embeddedLauncher = ml.loadClass("aQute.launcher.pre.EmbeddedLauncher"); embeddedLauncher.getField("MANIFEST") .set(null, m); Class<?> launcher = ml.loadClass("aQute.launcher.Launcher"); MethodHandle mh = MethodHandles.publicLookup() .findStatic(launcher, "main", MethodType.methodType(void.class, String[].class)); try { mh.invoke(args); } catch (Error | Exception e) { throw e; } catch (Throwable e) { throw new InvocationTargetException(e); } } } } }

Target:
public static void main(String... args) throws Throwable { boolean isVerbose = isTrace(); if (args.length > 0 && args[0].equals("-extract")) { if (isVerbose) log("running in extraction mode"); extract(args); return; } findAndExecute(isVerbose, "main", void.class, args); }
Source:
public Response getCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId) { HelixZkClient zkClient = getHelixZkClient(); if (!ZKUtil.isClusterSetup(clusterId, zkClient)) { return notFound(); } ConfigAccessor configAccessor = getConfigAccessor(); CustomizedStateAggregationConfig customizedStateAggregationConfig = configAccessor.getCustomizedStateAggregationConfig(clusterId); if (customizedStateAggregationConfig != null) { return JSONRepresentation(customizedStateAggregationConfig.getRecord()); } return notFound(); }

Target:
public Response getCustomizedStateAggregationConfig(@PathParam("clusterId") String clusterId) { if (!doesClusterExist(clusterId)) { return notFound(String.format("Cluster %s does not exist", clusterId)); } ConfigAccessor configAccessor = getConfigAccessor(); CustomizedStateAggregationConfig customizedStateAggregationConfig = configAccessor.getCustomizedStateAggregationConfig(clusterId); if (customizedStateAggregationConfig != null) { return JSONRepresentation(customizedStateAggregationConfig.getRecord()); } return notFound(); }
Source:
private RemoteCacheManager createExecClient() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super.createHotRodClientConfigurationBuilder(servers.get(0).getPort()); clientBuilder.marshaller(new UTF8StringMarshaller()); clientBuilder.protocolVersion(getProtocolVersion()); return new InternalRemoteCacheManager(clientBuilder.build()); }

Target:
private RemoteCacheManager createExecClient() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super.createHotRodClientConfigurationBuilder(servers.get(0).getPort()); clientBuilder.marshaller(new UTF8StringMarshaller()); clientBuilder.version(getProtocolVersion()); return new InternalRemoteCacheManager(clientBuilder.build()); }
Source:
private void discoverHueBridges() { List<BridgeJsonParameters> bridgeList = getBridgeList(); if (bridgeList != null) { for (BridgeJsonParameters bridge : bridgeList) { if (bridge.getId() != null && bridge.getInternalipaddress() != null) { if (isHueBridge(bridge.getInternalipaddress()) && bridge.getId().substring(6, 10).equals("fffe")) { ThingUID uid = new ThingUID(THING_TYPE_BRIDGE, bridge.getId().substring(0, 6) + bridge.getId().substring(10)); if (uid != null) { Map<String, Object> properties = new HashMap<>(2); properties.put(HOST, bridge.getInternalipaddress()); properties.put(SERIAL_NUMBER, bridge.getId().replace("fffe", "")); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties) .withLabel("Philips hue (" + bridge.getInternalipaddress() + ")") .withRepresentationProperty(SERIAL_NUMBER).build(); thingDiscovered(result); } } } } } }

Target:
private void discoverHueBridges() { for (BridgeJsonParameters bridge : getBridgeList()) { if (isReachableAndValidHueBridge(bridge)) { String host = bridge.getInternalIpAddress(); String serialNumber = bridge.getId().substring(0, 6) + bridge.getId().substring(10); ThingUID uid = new ThingUID(THING_TYPE_BRIDGE, serialNumber); DiscoveryResult result = DiscoveryResultBuilder.create(uid) .withProperties(buildProperties(host, serialNumber)) .withLabel(LABEL_PATTERN.replace("IP", host)).withRepresentationProperty(SERIAL_NUMBER).build(); thingDiscovered(result); } } }
Source:
public boolean performOk() { setColorsAndFontsTheme(getSelectedColorsAndFontsTheme()); ITheme theme = getSelectedTheme(); if (theme != null) { engine.setTheme(getSelectedTheme(), true); } boolean themeChanged = theme != null && !theme.equals(currentTheme); boolean colorsAndFontsThemeChanged = !PlatformUI.getWorkbench().getThemeManager() .getCurrentTheme().getId().equals(currentColorsAndFontsTheme.getId()); if (themeChanged || colorsAndFontsThemeChanged) { MessageDialog.openWarning(getShell(), WorkbenchMessages.ThemeChangeWarningTitle, WorkbenchMessages.ThemeChangeWarningText); } IPreferenceStore apiStore = PrefUtil.getAPIPreferenceStore(); apiStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, enableAnimations.getSelection()); apiStore.setValue(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, useColoredLabels.getSelection()); ((PreferencePageEnhancer) Tweaklets.get(PreferencePageEnhancer.KEY)).performOK(); return super.performOk(); }

Target:
public boolean performOk() { ITheme theme = getSelectedTheme(); if (theme != null) { engine.setTheme(getSelectedTheme(), true); } boolean themeChanged = theme != null && !theme.equals(currentTheme); boolean colorsAndFontsThemeChanged = !PlatformUI.getWorkbench().getThemeManager() .getCurrentTheme().getId().equals(currentColorsAndFontsTheme.getId()); if (themeChanged || colorsAndFontsThemeChanged) { MessageDialog.openWarning(getShell(), WorkbenchMessages.ThemeChangeWarningTitle, WorkbenchMessages.ThemeChangeWarningText); } IPreferenceStore apiStore = PrefUtil.getAPIPreferenceStore(); apiStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, enableAnimations.getSelection()); apiStore.setValue(IWorkbenchPreferenceConstants.USE_COLORED_LABELS, useColoredLabels.getSelection()); ((PreferencePageEnhancer) Tweaklets.get(PreferencePageEnhancer.KEY)).performOK(); return super.performOk(); }
Source:
public TableSpecJson buildTableJson(TableSpec tableSpec) { TableSpecJson tableSpecJson = new TableSpecJson(); tableSpecJson.id = tableSpec.getId(); tableSpecJson.tableProviderFactory = tableSpec.getTableProviderFactory(); tableSpecJson.config = tableSpec.getConfig(); return tableSpecJson; }

Target:
private TableSpecJson buildTableJson(TableSpec tableSpec) { TableSpecJson tableSpecJson = new TableSpecJson(); tableSpecJson.id = tableSpec.getId(); tableSpecJson.tableProviderFactory = tableSpec.getTableProviderFactoryClassName(); tableSpecJson.config = tableSpec.getConfig(); return tableSpecJson; }
Source:
public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (args.length == 0) { new FormValidator().show(); } else { List<String> paths = new ArrayList<>(); boolean failFast = false; for (String arg : args) { if (arg.equals("--failFast") || arg.equals("--fail-fast")) { failFast = true; } else { paths.add(arg); } } new FormValidator().validateAndExitWithErrorCode( paths.toArray(new String[paths.size()]), failFast); } } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }

Target:
public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); if (args.length == 0) { new FormValidator().show(); } else { List<String> paths = new ArrayList<>(); boolean failFast = false; for (String arg : args) { if (arg.equals("--failFast") || arg.equals("--fail-fast")) { failFast = true; } else { paths.add(arg); } } new FormValidator().validateAndExitWithErrorCode( paths, failFast); } } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
Source:
public ListTabbedPage(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); waitWithTimeout().until(ExpectedConditions.visibilityOf(selectedTab)); tablesElements.forEach(table -> { tables.add(new DataTable(table, table.getAttribute("id"))); }); setSelectedTable(); }

Target:
public ListTabbedPage(WebDriver driver) { super(driver); PageFactory.initElements(driver, this); tabs = driver.findElements(By.xpath(" waitWithTimeout().until(ExpectedConditions.visibilityOf(selectedTab)); tablesElements.forEach(table -> { tables.add(new DataTable(table)); }); setSelectedTable(getTabNumber()); }
Source:
public PagedFlux<QueueMessageItem> receiveMessage() { try { return receiveMessagesWithOptionalTimeout(1, null, null, Context.NONE); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } }

Target:
public Mono<QueueMessageItem> receiveMessage() { try { return receiveMessagesWithOptionalTimeout(1, null, null, Context.NONE) .single(); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
public int crawlNewDockerfiles(int number) { int crawledDockerfilesCount = 0; try { while (crawledDockerfilesCount < number) { List<Dockerfile> newDockerfiles = crawlerInstance.crawlDockerfiles(); crawledDockerfilesCount += newDockerfiles.size(); synchronized (crawledDockerfiles) { crawledDockerfiles.addAll(newDockerfiles); } for (Dockerfile dockerfile : newDockerfiles) { String filePath = dockerfile.getRepoName() + "." + dockerfile.getPath(); filePath = filePath.replace("/", "."); filePath = System.getProperty("user.home") + "/Dockerfiles/" + filePath; BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); writer.write(dockerfile.getRepoName() + "\n"); writer.write(dockerfile.getPath() + "\n"); writer.write(dockerfile.getContent()); writer.close(); } } } catch (IOException e) { LOGGER.error("Failed to write dockerfile to the file system", e); } return crawledDockerfilesCount; }

Target:
public int crawlNewDockerfiles(int number) { int crawledDockerfilesCount = 0; try { while (crawledDockerfilesCount < number) { List<Dockerfile> newDockerfiles = crawlerInstance.crawlDockerfiles(); crawledDockerfilesCount += newDockerfiles.size(); synchronized (crawledDockerfiles) { crawledDockerfiles.addAll(newDockerfiles); } if (!localCopyPath.isEmpty()) { for (Dockerfile dockerfile : newDockerfiles) { String filePath = dockerfile.getRepoName() + "." + dockerfile.getPath(); filePath = filePath.replace("/", "."); filePath = localCopyPath + filePath; BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); writer.write(dockerfile.getRepoName() + "\n"); writer.write(dockerfile.getPath() + "\n"); writer.write(dockerfile.getContent()); writer.close(); } } } } catch (IOException e) { LOGGER.error("Failed to write dockerfile to the file system", e); } return crawledDockerfilesCount; }
Source:
public Log getLog(String type) { return logs.get(type); }

Target:
public List<LogEntry> getLog(String type) { WebDriverLog log = (WebDriverLog) logs.get(type); return (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries()); }
Source:
public JwtProxyProvisioner( SignatureKeyManager signatureKeyManager, JwtProxyConfigBuilderFactory jwtProxyConfigBuilderFactory, @Named("che.server.secure_exposer.jwtproxy.image") String jwtProxyImage, @Named("che.server.secure_exposer.jwtproxy.memory_limit") String memoryLimitBytes, @Assisted RuntimeIdentity identity) { this.signatureKeyManager = signatureKeyManager; this.jwtProxyImage = jwtProxyImage; this.proxyConfigBuilder = jwtProxyConfigBuilderFactory.create(identity.getWorkspaceId()); this.identity = identity; this.serviceName = generate(SERVER_PREFIX, SERVER_UNIQUE_PART_SIZE) + "-jwtproxy"; this.availablePort = FIRST_AVAILABLE_PORT; long memoryLimitLong = Size.parseSizeToMegabytes(memoryLimitBytes) * MEGABYTES_TO_BYTES_DEVIDER; this.attributes = ImmutableMap.of( MEMORY_LIMIT_ATTRIBUTE, Long.toString(memoryLimitLong), MEMORY_REQUEST_ATTRIBUTE, Long.toString(memoryLimitLong)); }

Target:
public JwtProxyProvisioner( SignatureKeyManager signatureKeyManager, JwtProxyConfigBuilderFactory jwtProxyConfigBuilderFactory, @Named("che.server.secure_exposer.jwtproxy.image") String jwtProxyImage, @Named("che.server.secure_exposer.jwtproxy.memory_limit") String memoryLimitBytes, @Assisted RuntimeIdentity identity) { this.signatureKeyManager = signatureKeyManager; this.jwtProxyImage = jwtProxyImage; this.proxyConfigBuilder = jwtProxyConfigBuilderFactory.create(identity.getWorkspaceId()); this.identity = identity; this.serviceName = generate(SERVER_PREFIX, SERVER_UNIQUE_PART_SIZE) + "-jwtproxy"; this.availablePort = FIRST_AVAILABLE_PORT; long memoryLimitLong = Size.parseSizeToMegabytes(memoryLimitBytes) * MEGABYTES_TO_BYTES_DIVIDER; this.attributes = ImmutableMap.of( MEMORY_LIMIT_ATTRIBUTE, Long.toString(memoryLimitLong), MEMORY_REQUEST_ATTRIBUTE, Long.toString(memoryLimitLong)); }
Source:
public void attachView(@NonNull final ViewInterface view) { super.attachView(view); view.setUsername(username); view.setEditProfileMenuButtonVisible(isViewingOwnProfile); view.showLoadingIndicator(); observeOnView(userProfileInteractor.observeAccount()).subscribe(new Observer<Account>() { @Override public void onData(@NonNull Account account) { if (account.requiresParentalConsent() || account.getAccountPrivacy() == Account.Privacy.PRIVATE) { view.showLimitedHeader(isViewingOwnProfile); } else { String languageName = null; if (!account.getLanguageProficiencies().isEmpty()) { try { languageName = LocaleUtils.getLanguageNameFromCode(account.getLanguageProficiencies().get(0).getCode()); } catch (InvalidLocaleException e) { logger.error(e, true); } } String countryName = null; if (!TextUtils.isEmpty(account.getCountry())) { try { countryName = LocaleUtils.getCountryNameFromCode(account.getCountry()); } catch (InvalidLocaleException e) { logger.error(e, true); } } view.showFullHeader(languageName, countryName); } if (isViewingOwnProfile && account.requiresParentalConsent()) { view.showParentalConsentRequiredContent(); } else if (isViewingOwnProfile && TextUtils.isEmpty(account.getBio()) && account.getAccountPrivacy() != Account.Privacy.ALL_USERS) { view.showIncompleteContent(); } else if (account.getAccountPrivacy() != Account.Privacy.PRIVATE) { if (TextUtils.isEmpty(account.getBio())) { view.showNoAboutMeContent(); } else { view.showAboutMeContent(account.getBio()); } } else { view.showNoContent(); } } @Override public void onError(@NonNull Throwable error) { view.showError(error); } }); observeOnView(userProfileInteractor.observeProfilePhoto()).subscribe(new Observer<UserProfileInteractor.ImageResource>() { @Override public void onData(@NonNull UserProfileInteractor.ImageResource data) { view.setPhotoUri(data); } @Override public void onError(@NonNull Throwable error) { } }); }

Target:
public void attachView(@NonNull final ViewInterface view) { super.attachView(view); view.setName(userProfileInteractor.getUsername()); view.setEditProfileMenuButtonVisible(userProfileInteractor.isViewingOwnProfile()); view.showLoading(); observeOnView(userProfileInteractor.observeProfile()).subscribe(new Observer<UserProfileViewModel>() { @Override public void onData(@NonNull UserProfileViewModel account) { view.showProfile(account); } @Override public void onError(@NonNull Throwable error) { view.showError(error); } }); observeOnView(userProfileInteractor.observeProfileImage()).subscribe(new Observer<UserProfileImageViewModel>() { @Override public void onData(@NonNull UserProfileImageViewModel data) { view.setPhotoImage(data); } @Override public void onError(@NonNull Throwable error) { } }); }
Source:
private static TestWithParameters createTestWithParameters( TestClass testClass, String pattern, int index, Object[] parameters) { String finalPattern = pattern; Pattern indexMatcherPattern = Pattern.compile("(\\{)index([^\\}]*\\})"); Matcher matcher = indexMatcherPattern.matcher(pattern); if (matcher.find()) { String idxPattern = matcher.group(1) + 0 + matcher.group(2); finalPattern = pattern.replace(matcher.group(), MessageFormat.format(idxPattern, index)); } String name = MessageFormat.format(finalPattern, parameters); return new TestWithParameters("[" + name + "]", testClass, Arrays.asList(parameters)); }

Target:
private static TestWithParameters createTestWithParameters( TestClass testClass, String pattern, int index, Object[] parameters) { String finalPattern = pattern; Matcher matcher = INDEX_MATCHER_PATTERN.matcher(pattern); while (matcher.find()) { String idxPattern = matcher.group(1) + "0" + matcher.group(2); finalPattern = finalPattern.replace(matcher.group(), MessageFormat.format(idxPattern, index)); } String name = MessageFormat.format(finalPattern, parameters); return new TestWithParameters("[" + name + "]", testClass, Arrays.asList(parameters)); }
Source:
public boolean isValid(ChangeRequestValidationContext context) { ChangeRequest crToTest = null; if (context.getChangeRequest() != null && context.getChangeRequest().getId() != null) { try { crToTest = context.getChangeRequestDAO().get(context.getChangeRequest().getId()); } catch (EntityRetrievalException e) { return true; } } else { getMessages().add(getErrorMessage("changeRequest.developer.notActive")); crToTest = context.getChangeRequest(); } DeveloperDTO devDTO; try { devDTO = context.getDeveloperDAO().getById(crToTest.getDeveloper().getDeveloperId()); } catch (Exception e) { return true; } if (!devDTO.getStatus().getStatus().getStatusName().equals(DeveloperStatusType.Active.toString())) { getMessages().add(getErrorMessage("changeRequest.developer.notActive")); return false; } return true; }

Target:
public boolean isValid(ChangeRequestValidationContext context) { ChangeRequest crToTest = null; if (context.getChangeRequest() != null && context.getChangeRequest().getId() != null) { try { crToTest = context.getChangeRequestDAO().get(context.getChangeRequest().getId()); } catch (EntityRetrievalException e) { return true; } } else { crToTest = context.getChangeRequest(); } DeveloperDTO devDTO; try { devDTO = context.getDeveloperDAO().getById(crToTest.getDeveloper().getDeveloperId()); } catch (Exception e) { return true; } if (!devDTO.getStatus().getStatus().getStatusName().equals(DeveloperStatusType.Active.toString())) { getMessages().add(getErrorMessage("changeRequest.developer.notActive")); return false; } return true; }
Source:
GammaIntegerCodec(final BitInputStream coreBlockInputStream, final BitOutputStream coreBlockOutputStream, final int offset) { super(coreBlockInputStream, coreBlockOutputStream); this.offset = offset; }

Target:
public GammaIntegerCodec(final BitInputStream coreBlockInputStream, final BitOutputStream coreBlockOutputStream, final int offset) { super(coreBlockInputStream, coreBlockOutputStream); this.offset = offset; }
Source:
protected void executeDue() { if (executorsSemaphore.availablePermits() <= 0) { return; } Instant now = clock.now(); List<Execution> dueExecutions = taskRepository.getDue(now, pollingLimit); int pickedExecutionCount = 0; int availableExecutorCount = executorsSemaphore.availablePermits(); lastPollAcquiredAllAvailableExecutors = false; LOG.trace("Found taskinstances due for execution", dueExecutions.size()); for (Execution e : dueExecutions) { if (schedulerState.isShuttingDown()) { LOG.info("Scheduler has been shutdown. Skipping due executions.", dueExecutions.size() - pickedExecutionCount); return; } final Optional<Execution> pickedExecution; try { pickedExecution = aquireExecutorAndPickExecution(e); } catch (NoAvailableExecutors ex) { LOG.debug("No available executors. Skipping due executions.", dueExecutions.size() - pickedExecutionCount); lastPollAcquiredAllAvailableExecutors = true; return; } if (pickedExecution.isPresent()) { CompletableFuture .runAsync(new ExecuteTask(pickedExecution.get()), executorService) .thenRun(() -> releaseExecutor(pickedExecution.get())); } else { LOG.debug("Execution picked by another scheduler. Continuing to next due execution."); } pickedExecutionCount++; } lastPollAcquiredAllAvailableExecutors = pickedExecutionCount >= availableExecutorCount; }

Target:
protected void executeDue() { if (executorsSemaphore.availablePermits() <= 0) { return; } Instant now = clock.now(); List<Execution> dueExecutions = taskRepository.getDue(now, pollingLimit); int pickedExecutionCount = 0; lastPollAcquiredAllAvailableExecutors = false; LOG.trace("Found taskinstances due for execution", dueExecutions.size()); for (Execution e : dueExecutions) { if (schedulerState.isShuttingDown()) { LOG.info("Scheduler has been shutdown. Skipping due executions.", dueExecutions.size() - pickedExecutionCount); return; } final Optional<Execution> pickedExecution; try { pickedExecution = aquireExecutorAndPickExecution(e); } catch (NoAvailableExecutors ex) { LOG.debug("No available executors. Skipping due executions.", dueExecutions.size() - pickedExecutionCount); lastPollAcquiredAllAvailableExecutors = true; return; } if (pickedExecution.isPresent()) { CompletableFuture .runAsync(new ExecuteTask(pickedExecution.get()), executorService) .thenRun(() -> releaseExecutor(pickedExecution.get())); } else { LOG.debug("Execution picked by another scheduler. Continuing to next due execution."); } pickedExecutionCount++; } }