auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>double silhouetteCoefficient(JavaRDD<Vector> evalData) { <START> Map<Integer, List<double[]>> clusteredPointsMap = <END> 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; }</code><technical_language>Hm, concerned this. entire data set fit in memory in driver then</technical_language>

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:
<code>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 { <START> root.accept(new IPreferenceNodeVisitor() { <END> @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; }</code><technical_language>Lambda preferred nowadays</technical_language>

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:
<code><START> protected boolean acquireSerialDevice() { <END> 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; }</code><technical_language>Return serial device, instead of boolean</technical_language>

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:
<code>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>(); <START> if(mVariants == null) { <END> mVariants = new JSONArray(); } }</code><technical_language>mVariants null here</technical_language>

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:
<code>public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .subscriptionKey(new TextAnalyticsSubscriptionKeyCredential("{subscription_key}")) <START> .endpoint("{endpoint}") <END> .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) { } }</code><technical_language>change {endpoint}? is more clear string change</technical_language>

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:
<code>public EvictionConfig setSize(int size) { this.sizeConfigured = true; <START> this.size = checkNotNegative(size, <END> "size must be positive number!"); return this; }</code><technical_language>update message "size negative"</technical_language>

Target:
public EvictionConfig setSize(int size) { this.sizeConfigured = true; this.size = checkNotNegative(size, "size cannot be a negative number!"); return this; }
Source:
<code>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 { <START> logger.debug("Registering new service at port {}", description.serviceType, <END> 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); } }</code><technical_language>remove this log message duplicates in mdnsClient</technical_language>

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:
<code>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)); <START> } <END></code><technical_language>custom text ("and blocked this turn if able") instead default MustBeBlockedByAtLeastOneTargetEffect</technical_language>

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:
<code>public Response<BlockBlobItem> uploadWithResponse(BlockBlobSimpleUploadOptions options, Duration timeout, Context context) { <START> Objects.requireNonNull(options); <END> Mono<Response<BlockBlobItem>> upload = client.uploadWithResponse(options, context); try { return blockWithOptionalTimeout(upload, timeout); } catch (UncheckedIOException e) { throw logger.logExceptionAsError(e); } }</code><technical_language>this StorageImplUtils</technical_language>

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:
<code>public Long getCount() { <START> return countResults; <END> }</code><technical_language>Field constructor parameters renamed well</technical_language>

Target:
public Long getCount() { return count; }
Source:
<code>private static boolean checkSettingFeatureGesToTrue(CallExpression callExpression) { if (callExpression.arguments().size() == 2) { <START> RegularArgument first = (RegularArgument) callExpression.arguments().get(0); <END> 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; }</code><technical_language>This cast is unsafe, unpacking expression</technical_language>

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:
<code>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())); <START> return list(context, criteriaQuery, true, MetadataValue.class, -1, -1); <END> }</code><technical_language>param false. original query cacheable</technical_language>

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:
<code>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; <START> Long latestCreated = timelineLogs.get(0).createdDate; <END> for (int i = 0; i < timelineLogs.size(); i++) { if (timelineLogs.get(i).createdDate > latestCreated) { index = i; } } return timelineLogs.get(index); }</code><technical_language>final !!! ;)</technical_language>

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:
<code><START> public static final String transformExpression(String toTransform) <END> { return new ExpressionTemplate(toTransform).getValue(); }</code><technical_language>Lets remove final for</technical_language>

Target:
public static String transformExpression(String toTransform) { return new ExpressionTemplate(toTransform).getValue(); }
Source:
<code>public Object getNegotiatedProperty(final String propName) { assertComplete(); if (Sasl.BOUND_SERVER_NAME.equals(propName)) { return boundServerName; } <START> return null; <END> }</code><technical_language>super.getNegotiatedProperty(propName) returned instead of null</technical_language>

Target:
public Object getNegotiatedProperty(final String propName) { assertComplete(); if (Sasl.BOUND_SERVER_NAME.equals(propName)) { return boundServerName; } return super.getNegotiatedProperty(propName); }
Source:
<code>static void closeQuietly(InputStream is) { <START> try { <END> if (is != null) { is.close(); } } catch (IOException ignored) { } }</code><technical_language>Nit: if (is == null) return; instead</technical_language>

Target:
static void closeQuietly(InputStream is) { if (is == null) { return; } try { is.close(); } catch (IOException ignored) { } }
Source:
<code>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; } <START> }).get(0); <END> } catch (WrappedException e) { throw(MessagingException) e.getCause(); } }</code><technical_language>point making a list of a singleton result value. return actual result (which a Long I reckon)</technical_language>

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:
<code>public void close() throws IOException { <START> flush(); <END> }</code><technical_language>channel closed, avoid resources leak</technical_language>

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:
<code>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) { <START> throw new ParquetDecodingException("totalValueCount == 0"); <END> } consume(); }</code><technical_language>I change error message provide of totalValueCount (and change equality)</technical_language>

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:
<code>private void checkPartitions() { if (document == null) { return; } final List<IOConsolePartition> knownInputPartitions = new <START> ArrayList<>(inputPartitions); <END> 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()); }</code><technical_language>unguarded access inputPartitions org.eclipse.ui.internal.console.IOConsolePartitioner.QueueProcessingJob.runInUIThread(IProgressMonitor), is accessed lock partitions</technical_language>

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:
<code>public void initialize(URI uri, Configuration configuration) <START> throws IOException <END> { this.dataTier.initialize(uri, configuration); }</code><technical_language>original line. open is critical inject input streams</technical_language>

Target:
public void initialize(URI uri, Configuration configuration) throws IOException { dataTier.initialize(uri, configuration); }
Source:
<code>public synchronized void writeJSON(String outputDirectory, boolean bForceWrite) { logger.entering(new Object[] { outputDirectory, bForceWrite }); long currentTime = System.currentTimeMillis(); <START> if (!bForceWrite && currentTime - previousTime < ONE_MINUTE) { <END> return; } previousTime = currentTime; parseCompletedTest(); generateReports(outputDirectory); logger.exiting(); }</code><technical_language>this needs parenthesis control order of operations? is hard read</technical_language>

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:
<code>public synchronized Void notifyFailedTask(final String taskId) { final TaskStats taskStats = taskStatsMap.removeTask(taskId); <START> taskAddressInfoMap.remove(taskId); <END> proxyToTaskMap.remove(taskId); appTaskListMap.removeTask(taskId); final Thread t = new Thread(new RecoveryStartRunnable(taskStats)); t.start(); return null; }</code><technical_language>need lock</technical_language>

Target:
public synchronized Void notifyFailedTask(final String taskId) { final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); singleThreadExecutor.submit(new RecoveryStartRunnable(taskId)); return null; }
Source:
<code>PentahoWebPackage findWebPackage( String name, String version ) { <START> synchronized ( this.pentahoWebPackageBundles ) { <END> Collection<PentahoWebPackageBundleImpl> bundles = this.pentahoWebPackageBundles.values(); for ( PentahoWebPackageBundleImpl bundle : bundles ) { PentahoWebPackage webPackage = bundle.findWebPackage( name, version ); if ( webPackage != null ) { return webPackage; } } } return null; }</code><technical_language>Some kind of ReaderWriter lock, addBundle, more efficient, reading</technical_language>

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:
<code>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() ); <START> if ( offset < BANNER_HEIGHT_OFFSET_TOLERANCE ) <END> { return AppLovinAdSize.BANNER; } } return null; }</code><technical_language>this (and rest of comparisons) <= instead? This exclude outer ranges [40,60]</technical_language>

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:
<code>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()) { <START> MetaStoreListenerNotifier.notifyTxnEvent(listeners, EventType.OPEN_TXN, <END> new OpenTxnEvent(txnIds, this), null, null); } return response; }</code><technical_language>original notify() method if 2 parameters null. Also, add implementation for same</technical_language>

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:
<code>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; <START> Boolean dataSourceNotAnalyzed = (dataSourceDBStatus == DrawableDbBuildStatusEnum.UNKNOWN); <END> 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); } }</code><technical_language>this condition check for DEFAULT || UNKOWN? ingest completes, if files mime type, set DEFAULT</technical_language>

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:
<code>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(); <START> try { <END> 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); } } }</code><technical_language>TestUtils.assertFutureThrows()</technical_language>

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:
<code>public static IIngredient getOrb (String name) { <START> if (!RegistrarBloodMagic.BLOOD_ORBS.getKeys().contains(transformName(name))) { <END> 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; }</code><technical_language>suggestion if (!RegistrarBloodMagic.BLOOD_ORBS.containsKey(transformName(name))) {</technical_language>

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:
<code>public SPageMapping create(final String key, final Long pageId, final List<String> authorizationRules) throws SObjectCreationException { SPageMapping pageMapping = null; try { pageMapping = get(key); <START> } catch (final SObjectNotFoundException e) { <END> 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())); }</code><technical_language>create exception for nothing: Instead of get -> exception -> catch -> create change get extract submethod do throw exception do get -> if null -> create</technical_language>

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:
<code>protected Object doReceive() { AbstractFileInfo<F> file = poll(); if (file != null) { String remotePath = remotePath(file); if (this.deleteRemoteFiles) { <START> this.remoteFileTemplate.remove(remotePath); <END> } 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; }</code><technical_language>H-m. stream remote file afterward if remove here</technical_language>

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:
<code>protected boolean validateNoActiveUploadsDownloads() { for <START> (DiskImage diskImage : diskImageDao.getAllForStorageDomain(getStorageDomainId())) <END> { 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; }</code><technical_language>I storage domain's disks is heavy operation in storage domain deactivation verification. get image uploads - GetAllFromImageUploads then, in case image uploads, fetch relevant image upload disks disk ID check storage domain</technical_language>

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:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ["); sb.append(this.getName()); <START> sb.append("], Granted Authorities: ["); <END> sb.append(collectAuthorities(this.getAuthorities())); sb.append("], User Attributes: ["); sb.append(collectAttributes(this.attributes.entrySet())); sb.append("]"); return sb.toString(); }</code><technical_language>I this simpler as: java sb.append("], GrantedAuthorities: "); sb.append(getAuthorities()) sb.append(", User Attributes: "); sb.append(getAttributes()); return sb.toString();</technical_language>

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:
<code>protected String getSelectedDropdownOptionText(WebElement dropdown) { Select select = new Select(dropdown); <START> this.waitForPageToLoad(); <END> return select.getFirstSelectedOption().getText(); }</code><technical_language>is overkill this method if waiting for specific item load</technical_language>

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(); } }
Source:
<code>private CacheTopology getCacheTopology(int requestTopologyId, Address destination, boolean isReqForTransactions) throws InterruptedException { CacheTopology cacheTopology = stateConsumer.getCacheTopology(); int currentTopologyId = cacheTopology != null ? cacheTopology.getTopologyId() : -1; if (requestTopologyId < currentTopologyId) { if (isReqForTransactions) log.debugf("Transactions were requested by node %s with topology %d, older than the local topology (%d)", destination, requestTopologyId, currentTopologyId); else log.debugf("Segments were requested by node %s with topology %d, older than the local topology (%d)", destination, requestTopologyId, currentTopologyId); } else if (requestTopologyId > currentTopologyId) { if (trace) { log.tracef("%s were requested by node %s with topology %d, greater than the local " + "topology (%d). Waiting for topology %d to be installed locally.", isReqForTransactions ? "Transactions" : "Segments", destination, requestTopologyId, currentTopologyId, requestTopologyId); } try { stateTransferLock.waitForTopology(requestTopologyId, timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { <START> throw new CacheException("Failed waiting for topology " + requestTopologyId, e); <END> } cacheTopology = stateConsumer.getCacheTopology(); } return cacheTopology; }</code><technical_language>Please add a log message return o.i.u.c.TimeouException, waitForTopology/topologyFuture is called</technical_language>

Target:
private CacheTopology getCacheTopology(int requestTopologyId, Address destination, boolean isReqForTransactions) throws InterruptedException { CacheTopology cacheTopology = stateConsumer.getCacheTopology(); int currentTopologyId = cacheTopology != null ? cacheTopology.getTopologyId() : -1; if (requestTopologyId < currentTopologyId) { if (isReqForTransactions) log.debugf("Transactions were requested by node %s with topology %d, older than the local topology (%d)", destination, requestTopologyId, currentTopologyId); else log.debugf("Segments were requested by node %s with topology %d, older than the local topology (%d)", destination, requestTopologyId, currentTopologyId); } else if (requestTopologyId > currentTopologyId) { if (trace) { log.tracef("%s were requested by node %s with topology %d, greater than the local " + "topology (%d). Waiting for topology %d to be installed locally.", isReqForTransactions ? "Transactions" : "Segments", destination, requestTopologyId, currentTopologyId, requestTopologyId); } try { stateTransferLock.waitForTopology(requestTopologyId, timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { throw log.failedWaitingForTopology(requestTopologyId); } cacheTopology = stateConsumer.getCacheTopology(); } return cacheTopology; }
Source:
<code>private void createStreamInputReaders() throws CTFException { for (CTFStream stream : fTrace.getStreams()) { Set<CTFStreamInput> streamInputs = stream.getStreamInputs(); for (CTFStreamInput streamInput : streamInputs) { <START> fStreamInputReaders.add(new CTFStreamInputReader(NonNullUtils.checkNotNull(streamInput))); <END> } } fEventCountPerTraceFile = new long[fStreamInputReaders.size()]; }</code><technical_language>static import</technical_language>

Target:
private void createStreamInputReaders() throws CTFException { for (CTFStream stream : fTrace.getStreams()) { Set<CTFStreamInput> streamInputs = stream.getStreamInputs(); for (CTFStreamInput streamInput : streamInputs) { fStreamInputReaders.add(new CTFStreamInputReader(checkNotNull(streamInput))); } } fEventCountPerTraceFile = new long[fStreamInputReaders.size()]; }
Source:
<code>private static boolean isLegacyImplementationPresent() { try { <START> Thread.currentThread().getContextClassLoader().loadClass("org.kie.pmml.pmml_4_2.PMML4ExecutionHelper"); <END> return true; } catch (NoClassDefFoundError | ClassNotFoundException e) { return false; } }</code><technical_language>Is reason attempting load class thread context class loader? wrong, wondering if a plain Class.forName() enough in this case</technical_language>

Target:
private static boolean isLegacyImplementationPresent() { try { Class.forName("org.kie.pmml.pmml_4_2.PMML4ExecutionHelper"); return true; } catch (NoClassDefFoundError | ClassNotFoundException e) { return false; } }
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } final MacPoolValidator validator = new MacPoolValidator(null, getMacPool()); <START> return validate(validator.defaultPoolFlagIsNotSet()) && validate(validator.hasUniqueName()); END> }</code><technical_language>do intend improve</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } final MacPoolValidator validator = new MacPoolValidator(getMacPoolEntity()); return validate(validator.defaultPoolFlagIsNotSet()) && validate(validator.hasUniqueName()); }
Source:
<code>public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { <START> if (installableConnectors.isEmpty()) { <END> throw new IllegalArgumentException(); } try { SubMonitor monitor = SubMonitor.convert(progressMonitor, org.jboss.tools.project.examples.Messages.preparingUninstall, 100); try { final IInstallableUnit[] ius = computeInstallableUnits(monitor.newChild(50)); checkCancelled(monitor); final UninstallOperation uninstallOperation = resolveUninstall(monitor.newChild(50), ius, repositoryLocations.toArray(new URI[0])); checkCancelled(monitor); final RemediationOperation[] rops = new RemediationOperation[1]; rops[0] = null; if (uninstallOperation != null && uninstallOperation.getResolutionResult().getSeverity() == IStatus.ERROR) { rops[0] = new RemediationOperation(ProvisioningUI.getDefaultUI() .getSession(), uninstallOperation.getProfileChangeRequest()); rops[0].resolveModal(monitor.newChild(500)); } checkCancelled(monitor); Display.getDefault().asyncExec(new Runnable() { public void run() { provisioningUI.openUninstallWizard(Arrays.asList(ius), uninstallOperation, null); } }); } finally { monitor.done(); } } catch (OperationCanceledException e) { throw new InterruptedException(); } catch (Exception e) { throw new InvocationTargetException(e); } }</code><technical_language>throw exception here, return gracefully</technical_language>

Target:
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { if (installableConnectors.isEmpty()) { throw null; } try { SubMonitor monitor = SubMonitor.convert(progressMonitor, org.jboss.tools.project.examples.Messages.preparingUninstall, 100); try { final IInstallableUnit[] ius = computeInstallableUnits(monitor.newChild(50)); checkCancelled(monitor); final UninstallOperation uninstallOperation = resolveUninstall(monitor.newChild(50), ius, repositoryLocations.toArray(new URI[0])); checkCancelled(monitor); final RemediationOperation[] rops = new RemediationOperation[1]; rops[0] = null; if (uninstallOperation != null && uninstallOperation.getResolutionResult().getSeverity() == IStatus.ERROR) { rops[0] = new RemediationOperation(ProvisioningUI.getDefaultUI() .getSession(), uninstallOperation.getProfileChangeRequest()); rops[0].resolveModal(monitor.newChild(500)); } checkCancelled(monitor); Display.getDefault().asyncExec(new Runnable() { public void run() { provisioningUI.openUninstallWizard(Arrays.asList(ius), uninstallOperation, null); } }); } finally { monitor.done(); } } catch (OperationCanceledException e) { throw new InterruptedException(); } catch (Exception e) { throw new InvocationTargetException(e); } }