auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void postInvocationTearDown() { try { CLog.i("Shutting down GCE device %s", getSerialNumber()); if (!(getIDevice() instanceof StubDevice)) { try (InputStreamSource logcatSource = getLogcat()) { clearLogcat(); String name = "device_logcat_teardown_gce"; mTestLogger.testLog(name, LogDataType.LOGCAT, logcatSource); } } if (mGceAvd != null) { if (!GceStatus.SUCCESS.equals(mGceAvd.getStatus())) { getSshBugreport(); } getGceHandler().logSerialOutput(mGceAvd, mTestLogger); getGceHandler().shutdownGce(); } setFastbootEnabled(false); if (getGceHandler() != null) { getGceHandler().cleanUp(); } } finally { super.postInvocationTearDown(); } }

Target:
public void postInvocationTearDown() { try { CLog.i("Shutting down GCE device %s", getSerialNumber()); if (!(getIDevice() instanceof StubDevice)) { try (InputStreamSource logcatSource = getLogcat()) { clearLogcat(); String name = "device_logcat_teardown_gce"; mTestLogger.testLog(name, LogDataType.LOGCAT, logcatSource); } } if (mGceAvd != null) { if (!GceStatus.SUCCESS.equals(mGceAvd.getStatus())) { getSshBugreport(); } getGceHandler().logSerialOutput(mGceAvd, mTestLogger); getGceHandler().attemptShutdownGce(); } setFastbootEnabled(false); if (getGceHandler() != null) { getGceHandler().cleanUp(); } } finally { super.postInvocationTearDown(); } }
Source:
public boolean isModelClass() { String type = classType.toString(); return !type.equals("io.realm.DynamicRealmObject") && (!type.endsWith(".RealmObject") && !type.endsWith("RealmProxy")); }

Target:
public boolean isModelClass() { String type = classType.toString(); return !type.equals("io.realm.DynamicRealmObject") && !type.endsWith(".RealmObject") && !type.endsWith("RealmProxy"); }
Source:
default void setCharge(Location l, int charge) { int capacity = getCapacity(); if (capacity > 0) { charge = NumberUtils.clamp(0, charge, capacity); if (charge != getCharge(l)) { BlockStorage.addBlockInfo(l, "energy-charge", String.valueOf(charge), false); if (getEnergyComponentType() == EnergyNetComponentType.CAPACITOR) { SlimefunUtils.updateCapacitorTexture(l, charge, capacity); } } } }

Target:
default void setCharge(Location l, int charge) { Validate.notNull(l, "Location was null!"); Validate.isTrue(charge >= 0, "You can only set a charge of zero or more!"); int capacity = getCapacity(); if (capacity > 0) { charge = NumberUtils.clamp(0, charge, capacity); if (charge != getCharge(l)) { BlockStorage.addBlockInfo(l, "energy-charge", String.valueOf(charge), false); if (getEnergyComponentType() == EnergyNetComponentType.CAPACITOR) { SlimefunUtils.updateCapacitorTexture(l, charge, capacity); } } } }
Source:
private void startDiscoveryProcess(XBeeDevice device, IDiscoveryListener listener, String id, Set<DiscoveryOptions> options, long timeout) throws XBeeException { if (!device.isOpen()) throw new InterfaceNotOpenException(); finished = false; running = true; try { configureDiscoveryOptions(device, options, timeout, listener); if (timeout == USE_DEVICE_TIMEOUT) { timeout = DEFAULT_TIMEOUT; byte[] value = getParameter(device, NT_COMMAND, DEFAULT_TIMEOUT, "network timeout", listener); if (value != null) { timeout = ByteUtils.byteArrayToLong(value) * 100; logger.debug("{}Using NT value: ms.", toString(), timeout); } } discoverDevicesAPI(device, listener, id, timeout); logger.debug("{}Restoring discovery options.", toString()); setDiscoveryOptions(device, oldNOValue, oldNTValue, listener); } finally { finished = true; running = false; notifyDiscoveryFinished(listener, null); } }

Target:
private void startDiscoveryProcess(XBeeDevice device, IDiscoveryListener listener, String id, Set<DiscoveryOptions> options, long timeout) throws XBeeException { if (!device.isOpen()) throw new InterfaceNotOpenException(); finished = false; running = true; try { configureDiscoveryOptions(device, options, timeout, listener); if (timeout == USE_DEVICE_TIMEOUT) { timeout = DEFAULT_TIMEOUT; byte[] value = getParameter(device, NT_COMMAND, DEFAULT_TIMEOUT, "network timeout", listener); if (value != null) { timeout = ByteUtils.byteArrayToLong(value) * 100; logger.debug("{}Using NT value: ms.", toString(), timeout); } } discoverDevicesAPI(device, listener, id, timeout); if (device.getXBeeProtocol() == XBeeProtocol.DIGI_MESH) { logger.debug("{}Waiting 3 seconds before restoring values (DigiMesh related issue).", toString()); try { Thread.sleep(3000); } catch (InterruptedException e) } } finally { finished = true; running = false; logger.debug("{}Restoring discovery options.", toString()); setDiscoveryOptions(device, oldNOValue, oldNTValue, listener); notifyDiscoveryFinished(listener, null); } }
Source:
public LocalDate calculateFixingFromMaturity(LocalDate maturityDate) { ArgChecker.notNull(maturityDate, "maturityDate"); LocalDate effectiveBusinessDay = maturityDateCalendar().nextOrSame(maturityDate); LocalDate fixingDate = effectiveBusinessDay; while (maturityDateOffset.adjust(fixingDate).isAfter(effectiveBusinessDay) || fixingCalendar.isHoliday(fixingDate)) { fixingDate = fixingDate.minusDays(1); } return fixingDate; }

Target:
public LocalDate calculateFixingFromMaturity(LocalDate maturityDate) { ArgChecker.notNull(maturityDate, "maturityDate"); LocalDate maturityBusinessDay = maturityDateCalendar().nextOrSame(maturityDate); LocalDate fixingDate = maturityBusinessDay; while (calculateMaturityFromFixing(fixingDate).isAfter(maturityBusinessDay)) { fixingDate = fixingDate.minusDays(1); } return fixingDate; }
Source:
String getNumberWithLeadingZeroesAsString(final Integer number, final GermplasmNameSetting setting) { final StringBuilder sb = new StringBuilder(); final String numberString = number.toString(); final Integer numOfDigits = setting.getNumOfDigits(); if (numOfDigits != null && numOfDigits > 0) { final int numOfZerosNeeded = numOfDigits - numberString.length(); if (numOfZerosNeeded > 0) { for (int i = 0; i < numOfZerosNeeded; i++) { sb.append("0"); } } } sb.append(number); return sb.toString(); }

Target:
String getNumberWithLeadingZeroesAsString(final Integer number, final GermplasmNameSetting setting) { final Integer numOfDigits = setting.getNumOfDigits(); if (numOfDigits == null || numOfDigits <= 0) { return number.toString(); } return String.format("%0" + numOfDigits + "d", number); }
Source:
double silhouetteCoefficient(JavaRDD<Vector> evalData) { Map<Integer, List<double[]>> clusteredPointsMap = fetchClusteredPoints(evalData).collectAsMap(); double overallSilhouetteCoefficientForClustering = 0.0; for (Map.Entry<Integer, List<double[]>> entry : clusteredPointsMap.entrySet()) { double silhouetteCoefficientForCluster = 0.0; for (double[] point : entry.getValue()) { double pointIntraClusterDissimilarity = clusterDissimilarityForPoint(point, entry.getValue(), Boolean.TRUE); double pointInterClusterDissimilarity = minInterClusterDissimilarityForPoint(entry.getKey(), point, clusteredPointsMap); silhouetteCoefficientForCluster += calcSilhouetteCoefficient(pointIntraClusterDissimilarity, pointInterClusterDissimilarity); } overallSilhouetteCoefficientForClustering += silhouetteCoefficientForCluster / entry.getValue().size(); } double silhouetteCoefficient = overallSilhouetteCoefficientForClustering / numClusters; log.info("Computed Silhouette Coefficient for clusters: {}", numClusters, silhouetteCoefficient); return silhouetteCoefficient; }

Target:
double silhouetteCoefficient(JavaRDD<Vector> evalData) { JavaRDD<Vector> data = evalData; if (evalData.count() > MAX_SAMPLE_SIZE) { data = evalData.sample(false, (double) MAX_SAMPLE_SIZE / evalData.count()); } Map<Integer, Iterable<double[]>> clusteredPointsMap = fetchClusteredPoints(data).collectAsMap(); double overallSilhouetteCoefficientForClustering = 0.0; for (Map.Entry<Integer, Iterable<double[]>> entry : clusteredPointsMap.entrySet()) { Iterable<double[]> clusteredPoints = entry.getValue(); double silhouetteCoefficientForCluster = 0.0; if (Iterables.size(clusteredPoints) > 1) { for (double[] point : clusteredPoints) { double pointIntraClusterDissimilarity = clusterDissimilarityForPoint(point, clusteredPoints, true); double pointInterClusterDissimilarity = minInterClusterDissimilarityForPoint(entry.getKey(), point, clusteredPointsMap); silhouetteCoefficientForCluster += calcSilhouetteCoefficient(pointIntraClusterDissimilarity, pointInterClusterDissimilarity); } } overallSilhouetteCoefficientForClustering += silhouetteCoefficientForCluster; } double silhouetteCoefficient = overallSilhouetteCoefficientForClustering / data.count(); log.info("Computed Silhouette Coefficient for clusters: {}", numClusters, silhouetteCoefficient); return silhouetteCoefficient; }
Source:
public Collection<? extends ContentType> getMatchingRegexpAssociated(ContentTypeCatalog catalog, String fileName, final int typeMask) { if ((typeMask & IContentType.FILE_PATTERN_SPEC) == 0) { throw new IllegalArgumentException("This method only applies for FILE_REGEXP_SPEC."); } final IEclipsePreferences root = context.getNode(ContentTypeManager.CONTENT_TYPE_PREF_NODE); final Set<ContentType> result = new HashSet<>(3); try { root.accept(new IPreferenceNodeVisitor() { @Override public boolean visit(IEclipsePreferences node) { if (node == root) return true; String[] fileSpecs = ContentTypeSettings.getFileSpecs(node, typeMask); for (String fileSpecification : fileSpecs) if (Pattern.matches(catalog.toRegexp(fileSpecification), fileName)) { ContentType associated = catalog.getContentType(node.name()); if (associated != null) result.add(associated); break; } return false; } }); } catch (BackingStoreException bse) { ContentType.log(ContentMessages.content_errorLoadingSettings, bse); } return result == null ? Collections.EMPTY_SET : result; }

Target:
public Collection<? extends ContentType> getMatchingRegexpAssociated(ContentTypeCatalog catalog, String fileName, final int typeMask) { if ((typeMask & IContentType.FILE_PATTERN_SPEC) == 0) { throw new IllegalArgumentException("This method only applies for FILE_REGEXP_SPEC."); } final IEclipsePreferences root = context.getNode(ContentTypeManager.CONTENT_TYPE_PREF_NODE); final Set<ContentType> result = new HashSet<>(3); try { root.accept(node -> { if (node == root) return true; String[] fileSpecs = ContentTypeSettings.getFileSpecs(node, typeMask); for (String fileSpecification : fileSpecs) if (Pattern.matches(catalog.toRegexp(fileSpecification), fileName)) { ContentType associated = catalog.getContentType(node.name()); if (associated != null) result.add(associated); break; } return false; }); } catch (BackingStoreException bse) { ContentType.log(ContentMessages.content_errorLoadingSettings, bse); } return result == null ? Collections.EMPTY_SET : result; }
Source:
protected boolean acquireSerialDevice() { mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); mSerialDevice = UsbSerialProber.acquire(mUsbManager); if (mSerialDevice != null) { try { mSerialDevice.open(); return true; } catch (IOException e) { Log.e(TAG, "Unable to open USB. ", e); Tracker tracker; tracker = ((Nightscout) getApplicationContext()).getTracker(); tracker.send(new HitBuilders.ExceptionBuilder() .setDescription("Unable to open serial connection") .setFatal(false) .build() ); } } else { Log.d(TAG, "Unable to acquire USB device from manager."); } return false; }

Target:
protected UsbSerialDriver acquireSerialDevice() { UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); UsbSerialDriver serialDevice = UsbSerialProber.acquire(mUsbManager); if (serialDevice != null) { try { serialDevice.open(); return serialDevice; } catch (IOException e) { Log.e(TAG, "Unable to open USB. ", e); Tracker tracker; tracker = ((Nightscout) getApplicationContext()).getTracker(); tracker.send(new HitBuilders.ExceptionBuilder() .setDescription("Unable to open serial connection") .setFatal(false) .build() ); } } else { Log.d(TAG, "Unable to acquire USB device from manager."); } return serialDevice; }
Source:
public DecideMessages(String token, OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { mToken = token; mListener = listener; mUpdatesFromMixpanel = updatesFromMixpanel; mDistinctId = null; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); if(mVariants == null) { mVariants = new JSONArray(); } }

Target:
public DecideMessages(String token, OnNewResultsListener listener, UpdatesFromMixpanel updatesFromMixpanel) { mToken = token; mListener = listener; mUpdatesFromMixpanel = updatesFromMixpanel; mDistinctId = null; mUnseenSurveys = new LinkedList<Survey>(); mUnseenNotifications = new LinkedList<InAppNotification>(); mSurveyIds = new HashSet<Integer>(); mNotificationIds = new HashSet<Integer>(); mVariants = new JSONArray(); }
Source:
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .subscriptionKey(new TextAnalyticsSubscriptionKeyCredential("{subscription_key}")) .endpoint("{endpoint}") .buildAsyncClient(); String text = "The hotel was dark and unclean."; client.analyzeSentiment(text).subscribe( result -> { final TextSentiment documentSentiment = result.getDocumentSentiment(); System.out.printf( "Recognized sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", documentSentiment.getTextSentimentClass(), documentSentiment.getPositiveScore(), documentSentiment.getNeutralScore(), documentSentiment.getNegativeScore()); for (TextSentiment textSentiment : result.getSentenceSentiments()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", textSentiment.getTextSentimentClass(), textSentiment.getPositiveScore(), textSentiment.getNeutralScore(), textSentiment.getNegativeScore()); } }, error -> System.err.println("There was an error analyzing sentiment of the text." + error), () -> System.out.println("Sentiment analyzed.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }

Target:
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .subscriptionKey(new TextAnalyticsApiKeyCredential("{subscription_key}")) .endpoint("{endpoint}") .buildAsyncClient(); String text = "The hotel was dark and unclean."; client.analyzeSentiment(text).subscribe( result -> { final TextSentiment documentSentiment = result.getDocumentSentiment(); System.out.printf( "Recognized sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", documentSentiment.getTextSentimentClass(), documentSentiment.getPositiveScore(), documentSentiment.getNeutralScore(), documentSentiment.getNegativeScore()); for (TextSentiment textSentiment : result.getSentenceSentiments()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", textSentiment.getTextSentimentClass(), textSentiment.getPositiveScore(), textSentiment.getNeutralScore(), textSentiment.getNegativeScore()); } }, error -> System.err.println("There was an error analyzing sentiment of the text." + error), () -> System.out.println("Sentiment analyzed.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }
Source:
public EvictionConfig setSize(int size) { this.sizeConfigured = true; this.size = checkNotNegative(size, "size must be positive number!"); return this; }

Target:
public EvictionConfig setSize(int size) { this.sizeConfigured = true; this.size = checkNotNegative(size, "size cannot be a negative number!"); return this; }
Source:
public void setMDNSClient(MDNSClient client) { this.mdnsClient = client; if (servicesToRegisterQueue.size() > 0) { Runnable runnable = new Runnable() { @Override public void run() { logger.debug("Registering queued services", servicesToRegisterQueue.size()); for (ServiceDescription description : servicesToRegisterQueue) { try { logger.debug("Registering new service at port {}", description.serviceType, description.servicePort); mdnsClient.registerService(description); } catch (IOException e) { logger.error(e.getMessage()); } catch (IllegalStateException e) { logger.debug("Not registering service {}, because service is already deactivated!", description.serviceType); } } servicesToRegisterQueue.clear(); } }; Executors.newSingleThreadExecutor().execute(runnable); } }

Target:
public void setMDNSClient(MDNSClient client) { this.mdnsClient = client; if (servicesToRegisterQueue.size() > 0) { Runnable runnable = new Runnable() { @Override public void run() { logger.debug("Registering queued services", servicesToRegisterQueue.size()); for (ServiceDescription description : servicesToRegisterQueue) { try { mdnsClient.registerService(description); } catch (IOException e) { logger.error(e.getMessage()); } catch (IllegalStateException e) { logger.debug("Not registering service {}, because service is already deactivated!", description.serviceType); } } servicesToRegisterQueue.clear(); } }; Executors.newSingleThreadExecutor().execute(runnable); } }
Source:
public EmergentGrowth(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{G}"); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect(new BoostTargetEffect(5, 5, Duration.EndOfTurn)); this.getSpellAbility().addEffect(new MustBeBlockedByAtLeastOneTargetEffect(Duration.EndOfTurn)); }

Target:
public EmergentGrowth(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{G}"); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect(new BoostTargetEffect(5, 5, Duration.EndOfTurn)); Effect effect = new MustBeBlockedByAtLeastOneTargetEffect(Duration.EndOfTurn); effect.setText("and must be blocked this turn if able"); this.getSpellAbility().addEffect(effect); }
Source:
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout, Context context) { Objects.requireNonNull(options); Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context); try { return blockWithOptionalTimeout(upload, timeout); } catch (UncheckedIOException e) { throw logger.logExceptionAsError(e); } }

Target:
public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", options); Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context); try { return blockWithOptionalTimeout(upload, timeout); } catch (UncheckedIOException e) { throw logger.logExceptionAsError(e); } }
Source:
public Long getCount() { return countResults; }

Target:
public Long getCount() { return count; }
Source:
private static boolean checkSettingFeatureGesToTrue(CallExpression callExpression) { if (callExpression.arguments().size() == 2) { RegularArgument first = (RegularArgument) callExpression.arguments().get(0); RegularArgument second = (RegularArgument) callExpression.arguments().get(1); return first.expression().is(Tree.Kind.NAME) && "feature_external_ges".equals(((NameImpl) first.expression()).name()) && !Expressions.isFalsy(second.expression()); } return false; }

Target:
private static boolean checkSettingFeatureGesToTrue(CallExpression callExpression) { List<Argument> arguments = callExpression.arguments(); if (arguments.size() != 2 || arguments.stream().anyMatch(argument -> !argument.is(Tree.Kind.REGULAR_ARGUMENT))) { return false; } Expression first = ((RegularArgument) arguments.get(0)).expression(); Expression second = ((RegularArgument) arguments.get(1)).expression(); if (!(first instanceof HasSymbol)) { return false; } Symbol symbol = ((HasSymbol) first).symbol(); if (symbol == null) { return false; } return "xml.sax.handler.feature_external_ges".equals(symbol.fullyQualifiedName()) && !Expressions.isFalsy(second); }
Source:
public List<MetadataValue> findByField(Context context, MetadataField metadataField) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, MetadataValue.class); Root<MetadataValue> metadataValueRoot = criteriaQuery.from(MetadataValue.class); Join<MetadataValue, MetadataField> join = metadataValueRoot.join("metadataField"); criteriaQuery.select(metadataValueRoot); criteriaQuery.where(criteriaBuilder.equal(join.get(MetadataField_.id), metadataField.getID())); return list(context, criteriaQuery, true, MetadataValue.class, -1, -1); }

Target:
public List<MetadataValue> findByField(Context context, MetadataField metadataField) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, MetadataValue.class); Root<MetadataValue> metadataValueRoot = criteriaQuery.from(MetadataValue.class); Join<MetadataValue, MetadataField> join = metadataValueRoot.join("metadataField"); criteriaQuery.select(metadataValueRoot); criteriaQuery.where(criteriaBuilder.equal(join.get(MetadataField_.id), metadataField.getID())); return list(context, criteriaQuery, false, MetadataValue.class, -1, -1); }
Source:
private TimelineLog getAlgorithmFromTimelineLog(final Long accountId, final String date) { final DateTime dateTime = DateTimeUtil.ymdStringToDateTime(date); final ImmutableList<TimelineLog> timelineLogs = this.timelineLogDAO.getLogsForUserAndDay(accountId, dateTime, Optional.<Integer>absent()); if (timelineLogs.isEmpty()) { return TimelineLog.createEmpty(); } else if (timelineLogs.size() == 1) { return timelineLogs.get(0); } int index = 0; Long latestCreated = timelineLogs.get(0).createdDate; for (int i = 0; i < timelineLogs.size(); i++) { if (timelineLogs.get(i).createdDate > latestCreated) { index = i; } } return timelineLogs.get(index); }

Target:
private TimelineLog getAlgorithmFromTimelineLog(final Long accountId, final String date) { final DateTime dateTime = DateTimeUtil.ymdStringToDateTime(date); final ImmutableList<TimelineLog> timelineLogs = this.timelineLogDAO.getLogsForUserAndDay(accountId, dateTime, Optional.<Integer>absent()); if (timelineLogs.isEmpty()) { return TimelineLog.createEmpty(); } else if (timelineLogs.size() == 1) { return timelineLogs.get(0); } int index = 0; Long latestCreated = timelineLogs.get(0).createdDate; for (int i = 0; i < timelineLogs.size(); i++) { if (timelineLogs.get(i).createdDate > latestCreated) { index = i; latestCreated = timelineLogs.get(i).createdDate; } } return timelineLogs.get(index); }
Source:
public static final String transformExpression(String toTransform) { return new ExpressionTemplate(toTransform).getValue(); }

Target:
public static String transformExpression(String toTransform) { return new ExpressionTemplate(toTransform).getValue(); }
Source:
public Object getNegotiatedProperty(final String propName) { assertComplete(); if (Sasl.BOUND_SERVER_NAME.equals(propName)) { return boundServerName; } return null; }

Target:
public Object getNegotiatedProperty(final String propName) { assertComplete(); if (Sasl.BOUND_SERVER_NAME.equals(propName)) { return boundServerName; } return super.getNegotiatedProperty(propName); }
Source:
protected void resultClassChecking(Class resultClass, QueryImpl hqlQuery) { HQLQueryPlan queryPlan = hqlQuery.getQueryPlan(); if ( queryPlan == null ) { queryPlan = getFactory().getQueryPlanCache().getHQLQueryPlan( hqlQuery.getQueryString(), false, getLoadQueryInfluencers().getEnabledFilters() ); } if ( queryPlan.getTranslators()[0].isManipulationStatement() ) { throw new IllegalArgumentException( "Update/delete queries cannot be typed" ); } if ( Object[].class.equals( resultClass ) ) { } else if ( Tuple.class.equals( resultClass ) ) { TupleBuilderTransformer tupleTransformer = new TupleBuilderTransformer( hqlQuery ); hqlQuery.setResultTransformer( tupleTransformer ); } else { final Class dynamicInstantiationClass = queryPlan.getDynamicInstantiationResultType(); if ( dynamicInstantiationClass != null ) { if ( ! resultClass.isAssignableFrom( dynamicInstantiationClass ) ) { throw new IllegalArgumentException( "Mismatch in requested result type [" + resultClass.getName() + "] and actual result type [" + dynamicInstantiationClass.getName() + "]" ); } } else if ( queryPlan.getTranslators()[0].getReturnTypes().length == 1 ) { final Type queryResultType = queryPlan.getTranslators()[0].getReturnTypes()[0]; if ( !resultClass.isAssignableFrom( queryResultType.getReturnedClass() ) ) { throw new IllegalArgumentException( "Type specified for TypedQuery [" + resultClass.getName() + "] is incompatible with query return type [" + queryResultType.getReturnedClass() + "]" ); } } else { throw new IllegalArgumentException( "Cannot create TypedQuery for query with more than one return using requested result type [" + resultClass.getName() + "]" ); } } }

Target:
protected void resultClassChecking(Class resultClass, QueryImpl hqlQuery) { HQLQueryPlan queryPlan = hqlQuery.getQueryPlan(); if ( queryPlan.getTranslators()[0].isManipulationStatement() ) { throw new IllegalArgumentException( "Update/delete queries cannot be typed" ); } if ( Object[].class.equals( resultClass ) ) { } else if ( Tuple.class.equals( resultClass ) ) { TupleBuilderTransformer tupleTransformer = new TupleBuilderTransformer( hqlQuery ); hqlQuery.setResultTransformer( tupleTransformer ); } else { final Class dynamicInstantiationClass = queryPlan.getDynamicInstantiationResultType(); if ( dynamicInstantiationClass != null ) { if ( ! resultClass.isAssignableFrom( dynamicInstantiationClass ) ) { throw new IllegalArgumentException( "Mismatch in requested result type [" + resultClass.getName() + "] and actual result type [" + dynamicInstantiationClass.getName() + "]" ); } } else if ( queryPlan.getTranslators()[0].getReturnTypes().length == 1 ) { final Type queryResultType = queryPlan.getTranslators()[0].getReturnTypes()[0]; if ( !resultClass.isAssignableFrom( queryResultType.getReturnedClass() ) ) { throw new IllegalArgumentException( "Type specified for TypedQuery [" + resultClass.getName() + "] is incompatible with query return type [" + queryResultType.getReturnedClass() + "]" ); } } else { throw new IllegalArgumentException( "Cannot create TypedQuery for query with more than one return using requested result type [" + resultClass.getName() + "]" ); } } }
Source:
static void closeQuietly(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException ignored) { } }

Target:
static void closeQuietly(InputStream is) { if (is == null) { return; } try { is.close(); } catch (IOException ignored) { } }
Source:
public String getSmallestMessageUid() throws MessagingException { try { return localStore.database.execute(false, new DbCallback<List<String>>() { @Override public List<String> doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor cursor = null; ArrayList<String> result = new ArrayList<>(); try { open(OPEN_MODE_RO); cursor = db.rawQuery( "SELECT min(uid) " + "FROM messages " + "WHERE empty = 0 AND deleted = 0 AND " + "folder_id = ? ORDER BY date DESC", new String[] { Long.toString(mFolderId) }); while (cursor.moveToNext()) { String uid = cursor.getString(0); result.add(uid); } } catch (MessagingException e) { throw new WrappedException(e); } finally { Utility.closeQuietly(cursor); } return result; } }).get(0); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } }

Target:
public Long getSmallestMessageUid() throws MessagingException { try { return localStore.database.execute(false, new DbCallback<Long>() { @Override public Long doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { Cursor cursor = null; try { open(OPEN_MODE_RO); cursor = db.rawQuery( "SELECT min(uid) " + "FROM messages " + "WHERE empty = 0 AND deleted = 0 AND " + "folder_id = ? ORDER BY date DESC", new String[] { Long.toString(mFolderId) }); if (!cursor.moveToFirst()) { return null; } return cursor.getLong(0); } catch (MessagingException e) { throw new WrappedException(e); } finally { Utility.closeQuietly(cursor); } } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } }
Source:
public void close() throws IOException { flush(); }

Target:
public void close() throws IOException { Closer closer = Closer.create(); try { closer.register(channel); flush(); } catch (Throwable t) { closer.rethrow(t); } finally { closer.close(); } }
Source:
public ColumnReaderImpl(ColumnDescriptor path, PageReader pageReader, PrimitiveConverter converter, ParsedVersion writerVersion) { this.path = checkNotNull(path, "path"); this.pageReader = checkNotNull(pageReader, "pageReader"); this.converter = checkNotNull(converter, "converter"); this.writerVersion = writerVersion; DictionaryPage dictionaryPage = pageReader.readDictionaryPage(); if (dictionaryPage != null) { try { this.dictionary = dictionaryPage.getEncoding().initDictionary(path, dictionaryPage); if (converter.hasDictionarySupport()) { converter.setDictionary(dictionary); } } catch (IOException e) { throw new ParquetDecodingException("could not decode the dictionary for " + path, e); } } else { this.dictionary = null; } this.totalValueCount = pageReader.getTotalValueCount(); if (totalValueCount <= 0) { throw new ParquetDecodingException("totalValueCount == 0"); } consume(); }

Target:
public ColumnReaderImpl(ColumnDescriptor path, PageReader pageReader, PrimitiveConverter converter, ParsedVersion writerVersion) { this.path = checkNotNull(path, "path"); this.pageReader = checkNotNull(pageReader, "pageReader"); this.converter = checkNotNull(converter, "converter"); this.writerVersion = writerVersion; DictionaryPage dictionaryPage = pageReader.readDictionaryPage(); if (dictionaryPage != null) { try { this.dictionary = dictionaryPage.getEncoding().initDictionary(path, dictionaryPage); if (converter.hasDictionarySupport()) { converter.setDictionary(dictionary); } } catch (IOException e) { throw new ParquetDecodingException("could not decode the dictionary for " + path, e); } } else { this.dictionary = null; } this.totalValueCount = pageReader.getTotalValueCount(); if (totalValueCount <= 0) { throw new ParquetDecodingException("totalValueCount '" + totalValueCount + "' <= 0"); } consume(); }
Source:
private void checkPartitions() { if (document == null) { return; } final List<IOConsolePartition> knownInputPartitions = new ArrayList<>(inputPartitions); int offset = 0; for (IOConsolePartition partition : partitions) { Assert.isTrue(offset == partition.getOffset()); Assert.isTrue(partition.getLength() > 0); offset += partition.getLength(); if (isInputPartition(partition) && !partition.isReadOnly()) { Assert.isTrue(knownInputPartitions.remove(partition)); } } Assert.isTrue(offset == document.getLength()); Assert.isTrue(knownInputPartitions.isEmpty()); }

Target:
private void checkPartitions() { if (document == null) { return; } synchronized (partitions) { final List<IOConsolePartition> knownInputPartitions = new ArrayList<>(inputPartitions); int offset = 0; for (IOConsolePartition partition : partitions) { Assert.isTrue(offset == partition.getOffset()); Assert.isTrue(partition.getLength() > 0); offset += partition.getLength(); if (isInputPartition(partition) && !partition.isReadOnly()) { Assert.isTrue(knownInputPartitions.remove(partition)); } } Assert.isTrue(offset == document.getLength()); Assert.isTrue(knownInputPartitions.isEmpty()); } }
Source:
public void initialize(URI uri, Configuration configuration) throws IOException { this.dataTier.initialize(uri, configuration); }

Target:
public void initialize(URI uri, Configuration configuration) throws IOException { dataTier.initialize(uri, configuration); }
Source:
public synchronized void writeJSON(String outputDirectory, boolean bForceWrite) { logger.entering(new Object[] { outputDirectory, bForceWrite }); long currentTime = System.currentTimeMillis(); if (!bForceWrite && currentTime - previousTime < ONE_MINUTE) { return; } previousTime = currentTime; parseCompletedTest(); generateReports(outputDirectory); logger.exiting(); }

Target:
public synchronized void writeJSON(String outputDirectory, boolean bForceWrite) { logger.entering(new Object[] { outputDirectory, bForceWrite }); long currentTime = System.currentTimeMillis(); if (!bForceWrite && (currentTime - previousTime < ONE_MINUTE)) { return; } previousTime = currentTime; parseCompletedTest(); generateReports(outputDirectory); logger.exiting(); }
Source:
public synchronized Void notifyFailedTask(final String taskId) { final TaskStats taskStats = taskStatsMap.removeTask(taskId); taskAddressInfoMap.remove(taskId); proxyToTaskMap.remove(taskId); appTaskListMap.removeTask(taskId); final Thread t = new Thread(new RecoveryStartRunnable(taskStats)); t.start(); return null; }

Target:
public synchronized Void notifyFailedTask(final String taskId) { final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); singleThreadExecutor.submit(new RecoveryStartRunnable(taskId)); return null; }
Source:
PentahoWebPackage findWebPackage( String name, String version ) { synchronized ( this.pentahoWebPackageBundles ) { Collection<PentahoWebPackageBundleImpl> bundles = this.pentahoWebPackageBundles.values(); for ( PentahoWebPackageBundleImpl bundle : bundles ) { PentahoWebPackage webPackage = bundle.findWebPackage( name, version ); if ( webPackage != null ) { return webPackage; } } } return null; }

Target:
PentahoWebPackage findWebPackage( String name, String version ) { this.readLock.lock(); try { Collection<PentahoWebPackageBundleImpl> bundles = this.pentahoWebPackageBundles.values(); for ( PentahoWebPackageBundleImpl bundle : bundles ) { PentahoWebPackage webPackage = bundle.findWebPackage( name, version ); if ( webPackage != null ) { return webPackage; } } } finally { this.readLock.unlock(); } return null; }
Source:
private AppLovinAdSize appLovinAdSizeFromAdMobAdSize(final AdSize adSize) { if ( AdSize.BANNER.equals( adSize ) || AdSize.LARGE_BANNER.equals( adSize ) ) { return AppLovinAdSize.BANNER; } else if ( AdSize.MEDIUM_RECTANGLE.equals( adSize ) ) { return AppLovinAdSize.MREC; } else if ( AdSize.LEADERBOARD.equals( adSize ) ) { return AppLovinAdSize.LEADER; } else { final int offset = Math.abs( BANNER_STANDARD_HEIGHT - adSize.getHeight() ); if ( offset < BANNER_HEIGHT_OFFSET_TOLERANCE ) { return AppLovinAdSize.BANNER; } } return null; }

Target:
private AppLovinAdSize appLovinAdSizeFromAdMobAdSize(final AdSize adSize) { if ( AdSize.BANNER.equals( adSize ) || AdSize.LARGE_BANNER.equals( adSize ) ) { return AppLovinAdSize.BANNER; } else if ( AdSize.MEDIUM_RECTANGLE.equals( adSize ) ) { return AppLovinAdSize.MREC; } else if ( AdSize.LEADERBOARD.equals( adSize ) ) { return AppLovinAdSize.LEADER; } else { final int offset = Math.abs( BANNER_STANDARD_HEIGHT - adSize.getHeight() ); if ( offset <= BANNER_HEIGHT_OFFSET_TOLERANCE ) { return AppLovinAdSize.BANNER; } } return null; }
Source:
public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (txnIds != null && listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyTxnEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds, this), null, null); } return response; }

Target:
public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (txnIds != null && listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds, this)); } return response; }
Source:
protected void updateItem(Optional<DataSource> item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(""); } else { DataSource dataSource = item.orElse(null); String text = (dataSource == null) ? "All" : dataSource.getName() + " (Id: " + dataSource.getId() + ")"; Boolean tooManyFilesInDataSource = dataSourcesTooManyFiles.getOrDefault(dataSource, false); DrawableDbBuildStatusEnum dataSourceDBStatus = (dataSource != null) ? dataSourcesDrawableDBStatus.get(dataSource.getId()) : DrawableDbBuildStatusEnum.UNKNOWN; Boolean dataSourceNotAnalyzed = (dataSourceDBStatus == DrawableDbBuildStatusEnum.UNKNOWN); if (tooManyFilesInDataSource) { text += " - Too many files"; } if (dataSourceNotAnalyzed) { text += " - Not Analyzed"; } if (tooManyFilesInDataSource || dataSourceNotAnalyzed) { setDisable(true); setStyle("-fx-opacity : .5"); } else { setGraphic(null); setStyle("-fx-opacity : 1"); } setText(text); } }

Target:
protected void updateItem(Optional<DataSource> item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(""); } else { DataSource dataSource = item.orElse(null); String dataSourceName; boolean shouldEnable = true; if (dataSource == null) { dataSourceName = "All"; } else { dataSourceName = dataSource.getName() + " (Id: " + dataSource.getId() + ")"; if (dataSourcesDrawableDBStatus.get(dataSource.getId()) == DrawableDbBuildStatusEnum.UNKNOWN) { dataSourceName += " - Not Analyzed"; shouldEnable = false; } } if (shouldEnable) { if (dataSourcesTooManyFiles.getOrDefault(dataSource, false)) { dataSourceName += " - Too Many Files"; shouldEnable = false; } } if (shouldEnable) { setGraphic(null); setStyle("-fx-opacity : 1"); } else { setDisable(true); setStyle("-fx-opacity : .5"); } setText(dataSourceName); } }
Source:
public void testDeleteTopicsPartialResponse() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(body -> body instanceof DeleteTopicsRequest, prepareDeleteTopicsResponse("myTopic", Errors.NONE)); Map<String, KafkaFuture<Void>> values = env.adminClient().deleteTopics(asList("myTopic", "myOtherTopic"), new DeleteTopicsOptions()).values(); values.get("myTopic").get(); try { values.get("myOtherTopic").get(); fail("Expected an exception."); } catch (ExecutionException e) { assertTrue("Expected an ExecutionException wrapping an ApiException, but got " + Utils.stackTrace(e), e.getCause() instanceof ApiException); } } }

Target:
public void testDeleteTopicsPartialResponse() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse(body -> body instanceof DeleteTopicsRequest, prepareDeleteTopicsResponse("myTopic", Errors.NONE)); Map<String, KafkaFuture<Void>> values = env.adminClient().deleteTopics(asList("myTopic", "myOtherTopic"), new DeleteTopicsOptions()).values(); values.get("myTopic").get(); TestUtils.assertFutureThrows(values.get("myOtherTopic"), ApiException.class); } }
Source:
public static IIngredient getOrb (String name) { if (!RegistrarBloodMagic.BLOOD_ORBS.getKeys().contains(transformName(name))) { CraftTweakerAPI.logError("Blood Magic orb doesn't exist: "+name); return null; } BloodOrb orb = RegistrarBloodMagic.BLOOD_ORBS.getValue(transformName(name)); List<ItemStack> orbList = OrbRegistry.getOrbsDownToTier(orb.getTier()); if (orbList.size() == 0) { CraftTweakerAPI.logError("Blood Magic orb tier returned invalid orbs: "+name); return null; } IIngredient suitableOrbs = new MCItemStack(orbList.get(0)); for (ItemStack item : orbList) { suitableOrbs = suitableOrbs.or(new MCItemStack(item)); } return suitableOrbs; }

Target:
public static IIngredient getOrb (String name) { if (!RegistrarBloodMagic.BLOOD_ORBS.containsKey(transformName(name))) { CraftTweakerAPI.logError("Blood Magic orb doesn't exist: "+name); return null; } BloodOrb orb = RegistrarBloodMagic.BLOOD_ORBS.getValue(transformName(name)); List<ItemStack> orbList = OrbRegistry.getOrbsDownToTier(orb.getTier()); if (orbList.size() == 0) { CraftTweakerAPI.logError("Blood Magic orb tier returned invalid orbs: "+name); return null; } IIngredient suitableOrbs = new MCItemStack(orbList.get(0)); for (ItemStack item : orbList) { suitableOrbs = suitableOrbs.or(new MCItemStack(item)); } return suitableOrbs; }
Source:
public static ClusterException decode(StructDecoder<StructDecoder<Void>> decoder) { String exceptionClassName = decoder.string(FQCN_FIELD); String message = decoder.string(MESSAGE_FIELD); StructArrayDecoder<StructDecoder<StructDecoder<Void>>> arrayDecoder = decoder.structs(STACKTRACE_ELEMENTS_FIELD); StackTraceElement[] stackTraceElements = new StackTraceElement[arrayDecoder.length()]; for (int i = 0; i < arrayDecoder.length(); i++) { StructDecoder<?> element = arrayDecoder.next(); stackTraceElements[i] = new StackTraceElement( element.string(DECLARING_CLASS_FIELD), element.string(METHOD_NAME_FIELD), element.string(FILE_NAME_FIELD), element.int32(LINE_NUM_FIELD)); element.end(); } arrayDecoder.end(); Class<?> clazz = null; ClusterException exception; try { clazz = Class.forName(exceptionClassName); } catch (ClassNotFoundException e) { LOGGER.error("Exception type not found", e); } exception = getClusterException(message, clazz); if (exception == null) { exception = new UnknownClusterException(message); } exception.setStackTrace(stackTraceElements); return exception; }

Target:
public static ClusterException decode(StructDecoder<StructDecoder<Void>> decoder) { String exceptionClassName = decoder.string(FQCN_FIELD); String message = decoder.string(MESSAGE_FIELD); StructArrayDecoder<StructDecoder<StructDecoder<Void>>> arrayDecoder = decoder.structs(STACKTRACE_ELEMENTS_FIELD); StackTraceElement[] stackTraceElements = new StackTraceElement[arrayDecoder.length()]; for (int i = 0; i < arrayDecoder.length(); i++) { StructDecoder<?> element = arrayDecoder.next(); stackTraceElements[i] = new StackTraceElement( element.string(DECLARING_CLASS_FIELD), element.string(METHOD_NAME_FIELD), element.string(FILE_NAME_FIELD), element.int32(LINE_NUM_FIELD)); element.end(); } arrayDecoder.end(); Class<? extends ClusterException> clazz = null; ClusterException exception; try { clazz = Class.forName(exceptionClassName).asSubclass(ClusterException.class); } catch (ClassNotFoundException e) { LOGGER.error("Exception type not found", e); } exception = getClusterException(message, clazz); if (exception == null) { exception = new UnknownClusterException(message); } exception.setStackTrace(stackTraceElements); return exception; }
Source:
public SPageMapping create(final String key, final Long pageId, final List<String> authorizationRules) throws SObjectCreationException { SPageMapping pageMapping = null; try { pageMapping = get(key); } catch (final SObjectNotFoundException e) { final SPageMappingImpl entity = new SPageMappingImpl(); entity.setPageId(pageId); entity.setPageAuthorizationRules(authorizationRules); entity.setKey(key); return insert(entity); } catch (final SBonitaReadException e) { throw new SObjectCreationException(String.format("Failed to get page mapping %s", key), e); } throw new SObjectCreationException(String.format("Mapping key %s already exists for page with id %s", key, pageMapping.getPageId())); }

Target:
public SPageMapping create(final String key, final Long pageId, final List<String> authorizationRules) throws SObjectCreationException { SPageMapping pageMapping = null; try { pageMapping = findMapping(key); } catch (final SBonitaReadException e) { throw new SObjectCreationException(String.format("Failed to get page mapping %s", key), e); } if (pageMapping == null) { final SPageMappingImpl entity = new SPageMappingImpl(); entity.setPageId(pageId); entity.setPageAuthorizationRules(authorizationRules); entity.setKey(key); return insert(entity); } throw new SObjectCreationException(String.format("Mapping key %s already exists for page with id %s", key, pageMapping.getPageId())); }
Source:
protected Object doReceive() { AbstractFileInfo<F> file = poll(); if (file != null) { String remotePath = remotePath(file); if (this.deleteRemoteFiles) { this.remoteFileTemplate.remove(remotePath); } Session<?> session = this.remoteFileTemplate.getSesssion(); try { return getMessageBuilderFactory().withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .build(); } catch (IOException e) { return new MessagingException("IOException when retrieving " + remotePath, e); } } return null; }

Target:
protected Object doReceive() { AbstractFileInfo<F> file = poll(); if (file != null) { String remotePath = remotePath(file); Session<?> session = this.remoteFileTemplate.getSesssion(); try { return getMessageBuilderFactory().withPayload(session.readRaw(remotePath)) .setHeader(IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE, session) .setHeader(FileHeaders.REMOTE_DIRECTORY, file.getRemoteDirectory()) .setHeader(FileHeaders.REMOTE_FILE, file.getFilename()) .build(); } catch (IOException e) { return new MessagingException("IOException when retrieving " + remotePath, e); } } return null; }
Source:
protected boolean validateNoActiveUploadsDownloads() { for (DiskImage diskImage : diskImageDao.getAllForStorageDomain(getStorageDomainId())) { ImageTransferPhase imageTransferPhase = diskImage.getImageTransferPhase(); if (imageTransferPhase == null) { continue; } switch (imageTransferPhase) { case TRANSFERRING: case RESUMING: case FINALIZING_SUCCESS: case FINALIZING_FAILURE: return failValidation(EngineMessage.ERROR_CANNOT_DEACTIVATE_STORAGE_DOMAIN_DURING_UPLOAD_OR_DOWNLOAD); } } return true; }

Target:
protected boolean validateNoActiveUploadsDownloads() { for (ImageTransfer transfer : imageTransferDao.getByStorageId(getStorageDomainId())) { ImageTransferPhase imageTransferPhase = transfer.getPhase(); switch (imageTransferPhase) { case TRANSFERRING: case RESUMING: case FINALIZING_SUCCESS: case FINALIZING_FAILURE: return failValidation(EngineMessage.ERROR_CANNOT_DEACTIVATE_STORAGE_DOMAIN_DURING_UPLOAD_OR_DOWNLOAD); } } return true; }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ["); sb.append(this.getName()); sb.append("], Granted Authorities: ["); sb.append(collectAuthorities(this.getAuthorities())); sb.append("], User Attributes: ["); sb.append(collectAttributes(this.attributes.entrySet())); sb.append("]"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ["); sb.append(this.getName()); sb.append("], Granted Authorities: ["); sb.append(getAuthorities()); sb.append("], User Attributes: ["); sb.append(getAttributes()); sb.append("]"); return sb.toString(); }
Source:
protected String getSelectedDropdownOptionText(WebElement dropdown) { Select select = new Select(dropdown); this.waitForPageToLoad(); return select.getFirstSelectedOption().getText(); }

Target:
protected String getSelectedDropdownOptionText(WebElement dropdown) { Select select = new Select(dropdown); try { uiRetryManager.runUntilNoRecognizedException(new RetryableTask("Wait for dropdown text to load") { @Override public void run() { String txt = select.getFirstSelectedOption().getText(); assertNotEquals("", txt); } }, WebDriverException.class, AssertionError.class); return select.getFirstSelectedOption().getText(); } catch (MaximumRetriesExceededException e) { return select.getFirstSelectedOption().getText(); } }