auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String getPrettyMessage(LogEvent event) { String payload = event.getPayload(); StringWriter swriter = new StringWriter(estimatePrettySize(payload)); XMLStreamWriter xwriter = new PrettyPrintXMLStreamWriter(StaxUtils.createXMLStreamWriter(swriter), 2); XMLStreamReader xreader = StaxUtils.createXMLStreamReader(new StringReader(payload)); try { StaxUtils.copy(xreader, xwriter); xwriter.flush(); <START> } catch (XMLStreamException | WstxLazyException e) { <END> if (!event.isTruncated()) { LOG.debug("Error while pretty printing cxf message, returning raw message.", e); return payload; } flush(xwriter); return swriter.toString(); } finally { close(xwriter); close(xreader); } return swriter.toString(); }</code><technical_language>This put a hard dependency woodstox in logging module. I option catch RuntimeException check if is a XMLStreamException. If not, rethrow RuntimeException, treat XMLStreamException</technical_language>

Target:
private String getPrettyMessage(LogEvent event) { String payload = event.getPayload(); StringWriter swriter = new StringWriter(estimatePrettySize(payload)); XMLStreamWriter xwriter = new PrettyPrintXMLStreamWriter(StaxUtils.createXMLStreamWriter(swriter), 2); XMLStreamReader xreader = StaxUtils.createXMLStreamReader(new StringReader(payload)); try { StaxUtils.copy(xreader, xwriter); xwriter.flush(); } catch (XMLStreamException xse) { return getPrettyMessageAfterExceptionHandling(xse, event, payload, swriter, xwriter); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof XMLStreamException)) { throw ex; } XMLStreamException xse = (XMLStreamException) ex.getCause(); return getPrettyMessageAfterExceptionHandling(xse, event, payload, swriter, xwriter); } finally { close(xwriter); close(xreader); } return swriter.toString(); }
Source:
<code>FilePerformanceStatisticsReader(PerformanceStatisticsHandler... handlers) { <START> A.ensure(handlers != null, "At least one handler expected."); <END> A.ensure(handlers.length > 0, "At least one handler expected."); this.handlers = handlers; }</code><technical_language>A.notEmpty here</technical_language>

Target:
public FilePerformanceStatisticsReader(PerformanceStatisticsHandler... handlers) { this(DFLT_READ_BUFFER_SIZE, handlers); }
Source:
<code>public void testWithoutInterval() throws Exception { runTestWithoutIntervalTask(); final Interval interval = Intervals.of("2017-12-24/P1D"); final List<DataSegment> oldSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, oldSegments.size()); runTestWithoutIntervalTask(); final List<DataSegment> newSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, newSegments.size()); <START> Assert.assertNotEquals(oldSegments.get(0).getVersion(), newSegments.get(0).getVersion()); <END> }</code><technical_language>nit: check newSegment a newer version one</technical_language>

Target:
public void testWithoutInterval() throws Exception { runTestWithoutIntervalTask(); final Interval interval = Intervals.of("2017-12-24/P1D"); final List<DataSegment> oldSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, oldSegments.size()); runTestWithoutIntervalTask(); final List<DataSegment> newSegments = getStorageCoordinator().getUsedSegmentsForInterval("dataSource", interval); Assert.assertEquals(1, newSegments.size()); Assert.assertTrue(oldSegments.get(0).getVersion().compareTo(newSegments.get(0).getVersion()) < 0); }
Source:
<code>public List<AbstractLayer> setLayersForMap (Integer mapModuleId, List<Integer> abstractLayerIds) throws Exception{ E module = this.findById(mapModuleId); List<AbstractLayer> layers = new ArrayList<AbstractLayer>(); if(module instanceof Map) { Map mapModule = (Map) module; for (Integer id : abstractLayerIds) { PersistentObject entity = this.abstractLayerService.findById(id); if(entity instanceof AbstractLayer){ AbstractLayer layer = (AbstractLayer) entity; if(layer != null){ layers.add(layer); } } } mapModule.setMapLayers(layers); this.saveOrUpdate((E) mapModule); return layers; } else { <START> throw new Exception("Layer of with given Id is not a LayerGroup."); <END> } }</code><technical_language>Please adapt error message map</technical_language>

Target:
public List<AbstractLayer> setLayersForMap (Integer mapModuleId, List<Integer> abstractLayerIds) throws Exception{ E module = this.findById(mapModuleId); List<AbstractLayer> layers = new ArrayList<AbstractLayer>(); if(module instanceof Map) { Map mapModule = (Map) module; for (Integer id : abstractLayerIds) { PersistentObject entity = this.abstractLayerService.findById(id); if(entity instanceof AbstractLayer){ AbstractLayer layer = (AbstractLayer) entity; if(layer != null){ layers.add(layer); } } } mapModule.setMapLayers(layers); this.saveOrUpdate((E) mapModule); return layers; } else { throw new Exception("Can't find mapModule with id " + mapModuleId.toString()); } }
Source:
<code>public Action<?, ?> databaseBackupFinished() { return new AbstractDatabaseBackupAction<>(DatabaseBackupSuccess.class) { @Override protected BackupRestoreContext createFlowContext(FlowParameters flowParameters, StateContext<FlowState, FlowEvent> stateContext, DatabaseBackupSuccess payload) { return BackupRestoreContext.from(flowParameters, payload, null, null); } @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupSuccess payload, Map<Object, Object> variables) { backupRestoreStatusService.backupDatabaseFinished(context.getStackId()); sendEvent(context); } @Override protected Selectable createRequest(BackupRestoreContext context) { return new StackEvent(DatabaseBackupEvent.DATABASE_BACKUP_FINALIZED_EVENT.event(), context.getStackId()); } @Override <START> protected Object getFailurePayload(DatabaseBackupSuccess payload, Optional<BackupRestoreContext> flowContext, Exception ex) { <END> return null; } }; }</code><technical_language>is this necessary</technical_language>

Target:
public Action<?, ?> databaseBackupFinished() { return new AbstractBackupRestoreActions<>(DatabaseBackupSuccess.class) { @Override protected void doExecute(BackupRestoreContext context, DatabaseBackupSuccess payload, Map<Object, Object> variables) { backupRestoreStatusService.backupDatabaseFinished(context.getStackId()); sendEvent(context); } @Override protected Selectable createRequest(BackupRestoreContext context) { return new StackEvent(DatabaseBackupEvent.DATABASE_BACKUP_FINALIZED_EVENT.event(), context.getStackId()); } }; }
Source:
<code>public SendToClientFunction getSendToClientFunction() { if (sendToClientFunction == null) { sendToClientFunction = (name, values) -> { String scriptTag = "<script type=\"text/javascript\">var " + Handlebars.Utils.escapeExpression(name) + "=" + GSON.toJson(values[0]) + ";</script>"; api.getRequestLookup().addToPlaceholder( <START> (values.length == 2 && "headJs".equalsIgnoreCase((String) values[1])) ? Placeholder.headJs : <END> Placeholder.js, scriptTag); }; } return sendToClientFunction; }</code><technical_language>I understand this bit of code. is 2 ?. magic string</technical_language>

Target:
public SendToClientFunction getSendToClientFunction() { if (sendToClientFunction == null) { sendToClientFunction = (name, values) -> { String scriptTag = "<script type=\"text/javascript\">var " + Handlebars.Utils.escapeExpression(name) + "=" + GSON.toJson(values[0]) + ";</script>"; api.getRequestLookup().addToPlaceholder( (values.length == 2 && Placeholder.headJs.name().equalsIgnoreCase((String) values[1])) ? Placeholder.headJs : Placeholder.js, scriptTag); }; } return sendToClientFunction; }
Source:
<code>public String insertCourseProblem(final String userId, final SrlProblem problem) throws AuthenticationException, DatabaseAccessException { final String resultId = CourseProblemManager.mongoInsertCourseProblem(auth, database, userId, problem); if (problem.hasProblemBankId()) { putCourseInBankProblem(problem.getCourseId(), problem.getProblemBankId(), userId, null); } try { updater.createNewItem(School.ItemType.COURSE_PROBLEM, resultId, problem.getAssignmentId(), userId, null); } catch (AuthenticationException e) { <START> throw new AuthenticationException("Faild to create auth data while inserting course problem", e); <END> } return resultId; }</code><technical_language>Misspelled 'failed'</technical_language>

Target:
public String insertCourseProblem(final String userId, final SrlProblem problem) throws AuthenticationException, DatabaseAccessException { final String resultId = CourseProblemManager.mongoInsertCourseProblem(auth, database, userId, problem); if (problem.hasProblemBankId()) { putCourseInBankProblem(problem.getCourseId(), problem.getProblemBankId(), userId, null); } try { updater.createNewItem(School.ItemType.COURSE_PROBLEM, resultId, problem.getAssignmentId(), userId, null); } catch (AuthenticationException e) { throw new AuthenticationException("Failed to create auth data while inserting course problem", e); } return resultId; }
Source:
<code>public void testQueueQueryOnAutoCreatedQueueWithFQQN() throws Exception { SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString queueName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString fqqn = addressName.concat("::").concat(queueName); try (JMSContext c = new ActiveMQConnectionFactory("vm://0").createContext()) { c.createProducer().send(c.createQueue(fqqn.toString()), c.createMessage()); assertTrue(Wait.waitFor(() -> server.locateQueue(queueName).getMessageCount() == 1, 2000, 100)); QueueQueryResult queueQueryResult = server.queueQuery(fqqn); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); queueQueryResult = server.queueQuery(queueName); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); c.createProducer().send(c.createQueue(addressName.toString()), c.createMessage()); <START> assertTrue(Wait.waitFor(() -> server.locateQueue(queueName).getMessageCount() == 2, 2000, 100)); <END> assertEquals(2, server.queueQuery(fqqn).getMessageCount()); assertEquals(2, server.queueQuery(queueName).getMessageCount()); } }</code><technical_language>used: Wait.assertEquals(100, server.locateQueue(queueName)::getMessageCount)</technical_language>

Target:
public void testQueueQueryOnAutoCreatedQueueWithFQQN() throws Exception { SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString queueName = SimpleString.toSimpleString(UUID.randomUUID().toString()); SimpleString fqqn = addressName.concat("::").concat(queueName); try (JMSContext c = new ActiveMQConnectionFactory("vm://0").createContext()) { c.createProducer().send(c.createQueue(fqqn.toString()), c.createMessage()); QueueQueryResult queueQueryResult = server.queueQuery(fqqn); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); Wait.assertEquals(1, () -> server.queueQuery(fqqn).getMessageCount()); queueQueryResult = server.queueQuery(queueName); assertEquals(queueName, queueQueryResult.getName()); assertEquals(addressName, queueQueryResult.getAddress()); assertEquals(1, queueQueryResult.getMessageCount()); c.createProducer().send(c.createQueue(addressName.toString()), c.createMessage()); Wait.assertEquals(2, () -> server.queueQuery(fqqn).getMessageCount()); Wait.assertEquals(2, () -> server.queueQuery(queueName).getMessageCount()); } }
Source:
<code><START> public void <END> show(final @NonNull CheckoutResult result) { if (result.getStatus() == CheckoutResult.Status.CONFLICTS) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.BranchResultDialog_CheckoutConflictsTitle, NLS.bind( UIText.BranchResultDialog_CheckoutConflictsMessage, Repository.shortenRefName(target)), repository, result.getConflictList()); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { BranchOperationUI op = BranchOperationUI .checkoutWithoutQuestion(repository, target); op.start(); } } }); } else if (result.getStatus() == CheckoutResult.Status.NONDELETED) { boolean show = false; List<String> pathList = result.getUndeletedList(); for (String path : pathList) if (new File(repository.getWorkTree(), path).exists()) { show = true; break; } if (!show) return; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new NonDeletedFilesDialog(shell, repository, result .getUndeletedList()).open(); } }); } else if (result.getStatus() == CheckoutResult.Status.OK) { if (RepositoryUtil.isDetachedHead(repository)) showDetachedHeadWarning(); } }</code><technical_language>private? this of EGit is walking off-limits..</technical_language>

Target:
private void show(final @NonNull CheckoutResult result) { if (result.getStatus() == CheckoutResult.Status.CONFLICTS) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.BranchResultDialog_CheckoutConflictsTitle, NLS.bind( UIText.BranchResultDialog_CheckoutConflictsMessage, Repository.shortenRefName(target)), repository, result.getConflictList()); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { BranchOperationUI op = BranchOperationUI .checkoutWithoutQuestion(repository, target); op.start(); } } }); } else if (result.getStatus() == CheckoutResult.Status.NONDELETED) { boolean show = false; List<String> pathList = result.getUndeletedList(); for (String path : pathList) if (new File(repository.getWorkTree(), path).exists()) { show = true; break; } if (!show) return; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new NonDeletedFilesDialog(shell, repository, result .getUndeletedList()).open(); } }); } else if (result.getStatus() == CheckoutResult.Status.OK) { if (RepositoryUtil.isDetachedHead(repository)) showDetachedHeadWarning(); } }
Source:
<code>private void onLocalReplaysWatchEvent(WatchKey key) { Collection<Replay> newReplays = new ArrayList<Replay>(); Collection<Replay> deletedReplays = new ArrayList<Replay>(); for (WatchEvent<?> watchEvent : key.pollEvents()) { Path path = (Path) watchEvent.context(); Path fullPathToReplay = preferencesService.getReplaysDirectory().resolve(path); if (watchEvent.kind() == ENTRY_CREATE) { try { loadLocalReplay(fullPathToReplay) .thenAccept(newReplay -> { newReplays.add(newReplay); }); } catch (Exception e) { logger.warn("Failed to load local replay file '{}'", path, e); } } else if (watchEvent.kind() == ENTRY_DELETE) { <START> Optional<Replay> existingReplay = localReplays.stream().filter(replay -> replay.getReplayFile().compareTo(fullPathToReplay) == 0).findFirst(); <END> if (existingReplay.isPresent()) { Replay deletedReplay = existingReplay.get(); deletedReplays.add(deletedReplay); localReplays.remove(deletedReplay); } } } localReplays.addAll(newReplays); eventBus.post(new LocalReplaysChangedEvent(newReplays, deletedReplays)); }</code><technical_language>IMHO long line</technical_language>

Target:
private void onLocalReplaysWatchEvent(WatchKey key) { Collection<Replay> newReplays = new ArrayList<Replay>(); Collection<Replay> deletedReplays = new ArrayList<Replay>(); for (WatchEvent<?> watchEvent : key.pollEvents()) { Path path = (Path) watchEvent.context(); Path fullPathToReplay = preferencesService.getReplaysDirectory().resolve(path); if (watchEvent.kind() == ENTRY_CREATE) { tryLoadingLocalReplay(fullPathToReplay) .thenAccept(newReplay -> newReplays.add(newReplay)); } else if (watchEvent.kind() == ENTRY_DELETE) { Optional<Replay> existingReplay = localReplays .stream() .filter(replay -> replay.getReplayFile().compareTo(fullPathToReplay) == 0) .findFirst(); if (existingReplay.isPresent()) { Replay deletedReplay = existingReplay.get(); deletedReplays.add(deletedReplay); localReplays.remove(deletedReplay); } } } localReplays.addAll(newReplays); publisher.publishEvent(new LocalReplaysChangedEvent(this, newReplays, deletedReplays)); }
Source:
<code>private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) { Objects.requireNonNull(testName, "'testName' cannot be null."); this.testName = testName; <START> this.playbackRecordName = playbackRecordName; <END> this.testMode = testMode; this.textReplacementRules = new HashMap<>(); this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord); this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord); if (allowedToReadRecordedValues) { this.recordedData = readDataFromFile(); } else if (allowedToRecordValues) { this.recordedData = new RecordedData(); } else { this.recordedData = null; } }</code><technical_language>If playbackRecordName is null, this fallback testName</technical_language>

Target:
private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) { Objects.requireNonNull(testName, "'testName' cannot be null."); this.testName = testName; this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName; this.testMode = testMode; this.textReplacementRules = new HashMap<>(); this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord); this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord); if (allowedToReadRecordedValues) { this.recordedData = readDataFromFile(); } else if (allowedToRecordValues) { this.recordedData = new RecordedData(); } else { this.recordedData = null; } }
Source:
<code>public static PointArray pointArray( Value[] maybePoints ) { PointValue[] values = new PointValue[maybePoints.length]; for ( int i = 0; i < maybePoints.length; i++ ) { Value maybePoint = maybePoints[i]; if ( !(maybePoint instanceof PointValue) ) { throw new IllegalArgumentException( format( "[%s:%s] is not a supported point value", maybePoint, maybePoint.getClass().getName() ) ); } values[i] = Values.point( (PointValue) maybePoint ); } <START> return new PointArray.Direct( values ); <END> }</code><technical_language>return pointArray(values), instead</technical_language>

Target:
public static PointArray pointArray( Value[] maybePoints ) { PointValue[] values = new PointValue[maybePoints.length]; for ( int i = 0; i < maybePoints.length; i++ ) { Value maybePoint = maybePoints[i]; if ( !(maybePoint instanceof PointValue) ) { throw new IllegalArgumentException( format( "[%s:%s] is not a supported point value", maybePoint, maybePoint.getClass().getName() ) ); } values[i] = Values.point( (PointValue) maybePoint ); } return pointArray( values ); }
Source:
<code><START> public Double randomDatum(final CopyNumberTriState state, final Random rdn) { <END> Utils.nonNull(state); Utils.nonNull(rdn); final NormalDistribution stateDistro = this.stateDistribution(state); return rdn.nextGaussian() * stateDistro.getStandardDeviation() + stateDistro.getMean(); }</code><technical_language>If @VisibleForTesting give access modifier default package protected instead of making public</technical_language>

Target:
public Double randomDatum(final CopyNumberTriState state, final Random rdn) { Utils.nonNull(state); Utils.nonNull(rdn); final NormalDistribution stateDistro = emissionDistributionByState.get(state); return rdn.nextGaussian() * stateDistro.getStandardDeviation() + stateDistro.getMean(); }
Source:
<code>public void processLeftData(final MistDataEvent event) { final long timestamp = event.getTimestamp(); if (recentLeftTimestamp > timestamp) { throw new RuntimeException("The upstream events should be ordered by timestamp."); } else if (recentLeftWatermark.getTimestamp() > timestamp){ throw new RuntimeException("The watermark should guarantee that " + "all events having less timestamp than it are arrived already."); } recentLeftTimestamp = timestamp; leftUpstreamQueue.add(event); final long leftWatermarkTimestamp = recentLeftWatermark.getTimestamp(); final long rightWatermarkTimestamp = recentRightWatermark.getTimestamp(); final long minimumWatermark = Math.min( <START> Math.max(recentLeftTimestamp, leftWatermarkTimestamp), Math.max(recentRightTimestamp, rightWatermarkTimestamp)); <END> drainUntilTimestamp(minimumWatermark); if (recentLeftWatermark != defaultWatermark && leftWatermarkTimestamp <= minimumWatermark) { outputEmitter.emitWatermark(recentLeftWatermark); recentLeftWatermark = defaultWatermark; } if (recentRightWatermark != defaultWatermark && rightWatermarkTimestamp <= minimumWatermark) { outputEmitter.emitWatermark(recentRightWatermark); recentRightWatermark = defaultWatermark; } }</code><technical_language>do compare event timestamp watermark timestamp? Is enough compare watermark timestamps? (ex. Math.min(leftWatermarkTimestamp, rightWatermarkTimestamp))</technical_language>

Target:
public void processLeftData(final MistDataEvent event) { final long timestamp = event.getTimestamp(); if (recentLeftTimestamp > timestamp) { throw new RuntimeException("The upstream events should be ordered by timestamp."); } else if (recentLeftWatermark.getTimestamp() > timestamp){ throw new RuntimeException("The watermark should guarantee that " + "all events having less timestamp than it are arrived already."); } recentLeftTimestamp = timestamp; leftUpstreamQueue.add(event); drainUntilMinimumWatermark(); }
Source:
<code>public void onMediaUploaded(OnMediaUploaded event) { if (event.media == null || mMediaLatchMap.get(event.media.getId()) == null) { AppLog.w(T.POSTS, "Media event not recognized: " + event.media); return; } if (event.completed) { AppLog.i(T.POSTS, "Media upload completed for post. Media id: " + event.media.getId() + ", post id: " + mCurrentUploadingPost.getId()); mMediaLatchMap.get(event.media.getId()).countDown(); mMediaLatchMap.remove(event.media.getId()); } else if (!event.canceled && !event.isError()) { mPostUploadNotifier.updateNotificationProgress(mCurrentUploadingPost, event.progress); <START> } <END> }</code><technical_language>cancel post upload in case of a media upload error (I'm pretty this previous behavior)</technical_language>

Target:
public void onMediaUploaded(OnMediaUploaded event) { if (event.media == null || mCurrentUploadingPost == null || mMediaLatchMap.get(event.media.getId()) == null) { AppLog.w(T.POSTS, "Media event not recognized: " + event.media); return; } if (event.isError()) { SiteModel site = mSiteStore.getSiteByLocalId(mCurrentUploadingPost.getLocalSiteId()); String message = TextUtils.isEmpty(event.error.message) ? event.error.type.toString() : event.error.message; mPostUploadNotifier.updateNotificationError(mCurrentUploadingPost, site, message, true); mFirstPublishPosts.remove(mCurrentUploadingPost.getId()); finishUpload(); return; } if (event.canceled) { return; } if (event.completed) { AppLog.i(T.POSTS, "Media upload completed for post. Media id: " + event.media.getId() + ", post id: " + mCurrentUploadingPost.getId()); mMediaLatchMap.get(event.media.getId()).countDown(); mMediaLatchMap.remove(event.media.getId()); } else { mPostUploadNotifier.updateNotificationProgress(mCurrentUploadingPost, event.progress); } }
Source:
<code>public boolean handleExisting(WriteMode writeMode, long lastModForSource, Configuration entries) { if (view == null) { try { view = Datasets.load(uri); } catch (DatasetNotFoundException e) { LOG.info("Writing to new dataset/view: " + uri); return true; } } boolean ready = false; try { ready = view.isReady(); } catch (UnsupportedOperationException ex) { } <START> boolean exists = !view.isEmpty() || ready; <END> if (exists) { switch (writeMode) { case DEFAULT: LOG.error("Dataset/view " + view + " already exists!"); throw new CrunchRuntimeException("Dataset/view already exists: " + view); case OVERWRITE: LOG.info("Deleting all data from: " + view); delete(view); break; case APPEND: LOG.info("Writing to existing dataset/view: " + view); break; case CHECKPOINT: long lastModForTarget = -1; if (view instanceof LastModifiedAccessor) { lastModForTarget = ((LastModifiedAccessor) view).getLastModified(); } if (ready && (lastModForTarget > lastModForSource)) { LOG.info("Re-starting pipeline from checkpoint dataset/view: " + view); break; } else { if (!ready) { LOG.info("Checkpoint is not ready. Deleting data from existing " + "checkpoint dataset/view: " + view); } else { LOG.info("Source data has recent updates. Deleting data from existing " + "checkpoint dataset/view: " + view); } delete(view); return false; } default: throw new CrunchRuntimeException("Unknown WriteMode: " + writeMode); } } else { LOG.info("Writing to empty dataset/view: " + view); } return exists; }</code><technical_language>describe intended behavior for checkpoint</technical_language>

Target:
public boolean handleExisting(WriteMode writeMode, long lastModForSource, Configuration entries) { if (view == null) { try { view = Datasets.load(uri); } catch (DatasetNotFoundException e) { LOG.info("Writing to new dataset/view: " + uri); return true; } } boolean ready = false; if (view instanceof Signalable) { ready = ((Signalable)view).isReady(); } boolean exists = ready || !view.isEmpty(); if (exists) { switch (writeMode) { case DEFAULT: LOG.error("Dataset/view " + view + " already exists!"); throw new CrunchRuntimeException("Dataset/view already exists: " + view); case OVERWRITE: LOG.info("Deleting all data from: " + view); delete(view); break; case APPEND: LOG.info("Writing to existing dataset/view: " + view); break; case CHECKPOINT: long lastModForTarget = -1; if (view instanceof LastModifiedAccessor) { lastModForTarget = ((LastModifiedAccessor) view).getLastModified(); } if (ready && (lastModForTarget > lastModForSource)) { LOG.info("Re-starting pipeline from checkpoint dataset/view: " + view); break; } else { if (!ready) { LOG.info("Checkpoint is not ready. Deleting data from existing " + "checkpoint dataset/view: " + view); } else { LOG.info("Source data has recent updates. Deleting data from existing " + "checkpoint dataset/view: " + view); } delete(view); return false; } default: throw new CrunchRuntimeException("Unknown WriteMode: " + writeMode); } } else { LOG.info("Writing to empty dataset/view: " + view); } return exists; }
Source:
<code>public boolean isValid(String vatIdentificationNumber) { <START> return vatIdentificationNumber.matches("^[0-9]{9}$"); <END> }</code><technical_language>Please extract constant</technical_language>

Target:
public boolean isValid(String vatIdentificationNumber) { return vatIdentificationNumber.matches(VALID_NUMBER_PATTERN); }
Source:
<code>public int getPositiveAmount(final MagicSource source, final MagicPlayer player) { <START> if (this == MagicAmountFactory.NegXCost) { <END> return Math.min(getAmount(source, player), 0); } else { return Math.max(getAmount(source, player), 0); } }</code><technical_language>this unintuitive, for getPositiveAmount return a negative in a special case</technical_language>

Target:
public int getPositiveAmount(final MagicSource source, final MagicPlayer player) { return Math.max(getAmount(source, player), 0); }
Source:
<code>Project(String name, String path, String groups) { this.name = name; this.path = path; this.groups = new HashSet<String>(); <START> if (groups != null && groups.length() > 0) { <END> this.groups.addAll(Arrays.asList(groups.split(","))); } }</code><technical_language>braces single line blocks</technical_language>

Target:
Project(String name, String path, String groups) { this.name = name; this.path = path; this.groups = new HashSet<String>(); if (groups != null && groups.length() > 0) this.groups.addAll(Arrays.asList(groups.split(","))); }
Source:
<code>protected void startServerImpl() { <START> SelendroidLogger.info("*** ServerInstrumentation#startSeverImpl() ***"); <END> if (server != null) { server.stop(); } try { if (server == null) { server = new AndroidServer(this, serverPort); } DefaultServerInstrumentation.startAndroidServer( server, wakeLock); } catch (Exception e) { SelendroidLogger.error("Error starting httpd.", e); throw new SelendroidException("Httpd failed to start!"); } }</code><technical_language>nit: Sever :)</technical_language>

Target:
protected void startServerImpl() { SelendroidLogger.info("*** ServerInstrumentation#startServerImpl() ***"); if (server != null) { server.stop(); } try { if (server == null) { server = new AndroidServer(this, serverPort); } DefaultServerInstrumentation.startAndroidServer( server, wakeLock); } catch (Exception e) { SelendroidLogger.error("Error starting httpd.", e); throw new SelendroidException("Httpd failed to start!"); } }
Source:
<code>public ValidationResult validateDeletion(Lab object) { ValidationResult result = new ValidationResult(); long usage = labDao.getUsage(object); if (usage > 0L) { <START> result.addError(new ValidationError(usage + " sample" + (usage > 1L ? "s are" : " is") + " associated with this lab")); <END> } return result; }</code><technical_language>If is a bulk delete this error is thrown, obvious lab fault (similar institute above). this distinction clarified</technical_language>

Target:
public ValidationResult validateDeletion(Lab object) { ValidationResult result = new ValidationResult(); long usage = labDao.getUsage(object); if (usage > 0L) { result.addError(new ValidationError(usage + " sample" + (usage > 1L ? "s are" : " is") + " associated with lab '" + object.getAlias() + "'")); } return result; }
Source:
<code>protected boolean undeployModuleAndWait(IModule[] module, IPath remote, int maxWait, IProgressMonitor monitor) throws CoreException { if( module.length > 1) return true; if( supportsJBoss7Markers() && Platform.getOS().equals(Platform.OS_WIN32) && getServer().getServerState() == IServer.STATE_STARTED && getFilesystemController() instanceof LocalFilesystemController ) { DeploymentMarkerUtils.removeDeployedMarker(remote, getFilesystemController()); long timeout = System.currentTimeMillis() + maxWait; boolean done = false; while( !done && System.currentTimeMillis() < timeout) { done = DeploymentMarkerUtils.markerExists(remote, getFilesystemController(), DeploymentMarkerUtils.UNDEPLOYED); if( !done ) { try { <START> Thread.sleep(500); <END> } catch(InterruptedException ie) } } return done; } return true; }</code><technical_language>a is pretty long. wait 200ms? Depends cost of calling DeploymentMarkerUtils.markerExists I guess</technical_language>

Target:
protected boolean undeployModuleAndWait(IModule[] module, IPath remote, int maxWait, IProgressMonitor monitor) throws CoreException { if( module.length > 1) return true; if( supportsJBoss7Markers() && Platform.getOS().equals(Platform.OS_WIN32) && getServer().getServerState() == IServer.STATE_STARTED && getFilesystemController() instanceof LocalFilesystemController ) { if( DeploymentMarkerUtils.markerExists(remote, getFilesystemController(), DeploymentMarkerUtils.DEPLOYED)) { DeploymentMarkerUtils.removeDeployedMarker(remote, getFilesystemController()); long timeout = System.currentTimeMillis() + maxWait; boolean done = false; while( !done && System.currentTimeMillis() < timeout) { done = DeploymentMarkerUtils.markerExists(remote, getFilesystemController(), DeploymentMarkerUtils.UNDEPLOYED); if( !done ) { try { Thread.sleep(500); } catch(InterruptedException ie) } } return done; } } return true; }
Source:
<code>public Page<UserDevfilePermissionImpl> getByInstance( String instanceId, int maxItems, long skipCount) throws ServerException { requireNonNull(instanceId, "User devfile identifier required"); checkArgument( skipCount <= Integer.MAX_VALUE, "The number of items to skip can't be greater than " + Integer.MAX_VALUE); try { final EntityManager entityManager = managerProvider.get(); final List<UserDevfilePermissionImpl> permissions = entityManager .createNamedQuery( "UserDevfilePermission.getByUserDevfileId", UserDevfilePermissionImpl.class) .setParameter("userDevfileId", instanceId) .setMaxResults(maxItems) .setFirstResult((int) skipCount) .getResultList() .stream() .map(UserDevfilePermissionImpl::new) .collect(toList()); <START> final Long workersCount = <END> entityManager .createNamedQuery("UserDevfilePermission.getCountByUserDevfileId", Long.class) .setParameter("userDevfileId", instanceId) .getSingleResult(); return new Page<>(permissions, skipCount, maxItems, workersCount); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }</code><technical_language>worker )</technical_language>

Target:
public Page<UserDevfilePermissionImpl> getByInstance( String instanceId, int maxItems, long skipCount) throws ServerException { requireNonNull(instanceId, "User devfile identifier required"); checkArgument( skipCount <= Integer.MAX_VALUE, "The number of items to skip can't be greater than " + Integer.MAX_VALUE); try { final EntityManager entityManager = managerProvider.get(); final List<UserDevfilePermissionImpl> permissions = entityManager .createNamedQuery( "UserDevfilePermission.getByUserDevfileId", UserDevfilePermissionImpl.class) .setParameter("userDevfileId", instanceId) .setMaxResults(maxItems) .setFirstResult((int) skipCount) .getResultList() .stream() .map(UserDevfilePermissionImpl::new) .collect(toList()); final Long permissionsCount = entityManager .createNamedQuery("UserDevfilePermission.getCountByUserDevfileId", Long.class) .setParameter("userDevfileId", instanceId) .getSingleResult(); return new Page<>(permissions, skipCount, maxItems, permissionsCount); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }
Source:
<code>private double[] getFirstDimensionArray(final double[][][] array, final int dim2Index, final int dim3Index) { <START> final double[] result = new double[array.length]; <END> for (int i = 0; i < result.length; i++) { result[i] = array[i][dim2Index][dim3Index]; } return result; }</code><technical_language>return Arrays.stream(array).mapToDouble(array2D -> array2D[dim2Index][dim3Index]).toArray()</technical_language>

Target:
private double[] getFirstDimensionArray(final double[][][] array, final int dim2Index, final int dim3Index) { return Arrays.stream(array).mapToDouble(array2D -> array2D[dim2Index][dim3Index]).toArray(); }
Source:
<code>public boolean sendCommand(Command command) throws Exception { long deviceId = command.getDeviceId(); if (command.getId() != 0) { <START> Command savedCommand = getById(command.getId()); <END> command.setTextChannel(savedCommand.getTextChannel()); command.setType(savedCommand.getType()); command.setAttributes(savedCommand.getAttributes()); command.setDescription(savedCommand.getDescription()); } boolean sent = true; if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); protocol.sendTextCommand(phone, command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { if (Context.getSmppManager() != null) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("SMPP client is not enabled"); } } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); } } else { ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); if (activeDevice != null) { activeDevice.sendCommand(command); } else { sent = !getDeviceQueue(deviceId).add(command); } } return sent; }</code><technical_language>instead clone object set deviceId? shorter easier manage. need modify code in case add else command</technical_language>

Target:
public boolean sendCommand(Command command) throws Exception { long deviceId = command.getDeviceId(); if (command.getId() != 0) { command = getById(command.getId()).clone(); command.setDeviceId(deviceId); } if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); protocol.sendTextCommand(phone, command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { if (Context.getSmppManager() != null) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("SMPP client is not enabled"); } } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); } } else { ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); if (activeDevice != null) { activeDevice.sendCommand(command); } else { getDeviceQueue(deviceId).add(command); return false; } } return true; }
Source:
<code>public static Instant ofEpochSecond(long epochSecond) { <START> return new Instant(epochSecond * 1000); <END> }</code><technical_language>This overflow. Need check if multiplying 1000 is safe (considering positive negative numbers) throwing ArtithmeticException if not</technical_language>

Target:
public static Instant ofEpochSecond(long epochSecond) { return new Instant(FieldUtils.safeMultiply(epochSecond, 1000)); }
Source:
<code>public void testDescribeImagesWithFilter() { String region = getFirst(ec2Api.getConfiguredRegions(), null); if (region != null) { Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assert allResults.size() >= 2 : allResults.size(); <START> Iterator<? extends Image> iterator = allResults.iterator(); <END> String id1 = iterator.next().getId(); Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("image-id", id1) .build()); assertNotNull(filterResult); assertEquals(filterResult.size(), 1); iterator = filterResult.iterator(); assertEquals(iterator.next().getId(), id1); } }</code><technical_language>[minor] inline below</technical_language>

Target:
public void testDescribeImagesWithFilter() { String region = getFirst(ec2Api.getConfiguredRegions(), null); assertNotNull(region, "region should not be null"); Set<? extends Image> allResults = client.describeImagesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 2); String id1 = allResults.iterator().next().getId(); Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("image-id", id1) .build()); assertNotNull(filterResult); assertEquals(filterResult.size(), 1); assertEquals(filterResult.iterator().next().getId(), id1); }
Source:
<code>public RestBinding[] getBindings() { List<RestBinding> descriptors = getDescriptors(XP_BINDINGS); <START> return descriptors.toArray(new RestBinding[descriptors.size()]); <END> }</code><technical_language>Give 0 size new array, faster in java</technical_language>

Target:
public RestBinding[] getBindings() { List<RestBinding> descriptors = getDescriptors(XP_BINDINGS); return descriptors.toArray(new RestBinding[0]); }
Source:
<code>protected void updateAllInBatch(String procedureName, Collection<T> paramValues, MapSqlParameterMapper<T> mapper) { List<T> sortedParamValues = new ArrayList<>(paramValues); Collections.sort(sortedParamValues, new Comparator<T>() { @Override public int compare(T o1, T o2) { <START> if (o1 instanceof Comparable) { <END> return ((Comparable)o1).compareTo(o2); } else if (o1.getId() instanceof Comparable) { return ((Comparable)o1.getId()).compareTo(o2.getId()); } return ((Integer) o1.getId().hashCode()).compareTo(o2.getId().hashCode()); } }); getCallsHandler().executeStoredProcAsBatch(procedureName == null ? getProcedureNameForUpdate() : procedureName, paramValues, mapper); }</code><technical_language>null values in collection possible</technical_language>

Target:
protected void updateAllInBatch(String procedureName, Collection<T> paramValues, MapSqlParameterMapper<T> mapper) { List<T> sortedParamValues = new ArrayList<>(paramValues); Collections.sort(sortedParamValues, new Comparator<T>() { @Override public int compare(T o1, T o2) { if (o1 == o2) return 0; if (o1 == null) return 1; if (o2 == null) return -1; if (o1 instanceof Comparable) { return ((Comparable)o1).compareTo(o2); } else if (o1.getId() instanceof Comparable) { if (o1.getId() == o2.getId()) return 0; if (o1.getId() == null) return 1; if (o2.getId() == null) return -1; return ((Comparable)o1.getId()).compareTo(o2.getId()); } return ((Integer) o1.getId().hashCode()).compareTo(o2.getId().hashCode()); } }); getCallsHandler().executeStoredProcAsBatch(procedureName == null ? getProcedureNameForUpdate() : procedureName, paramValues, mapper); }
Source:
<code>public Map<String, IndexedSymlink> getSymlinks(String projectName) { if (mappedIndexedSymlinks == null) { <START> throw new IllegalStateException("getSettings() not yet called"); <END> } String k = projectName != null ? projectName : ""; Map<String, IndexedSymlink> indexSymlinks = mappedIndexedSymlinks.get(k); if (indexSymlinks != null) { return Collections.unmodifiableMap(indexSymlinks); } return null; }</code><technical_language>is problem call getSettings()</technical_language>

Target:
public Map<String, IndexedSymlink> getSymlinks(String projectName) throws IOException { getSettings(projectName); String projectKey = projectName != null ? projectName : ""; Map<String, IndexedSymlink> indexSymlinks = mappedIndexedSymlinks.get(projectKey); if (indexSymlinks != null) { return Collections.unmodifiableMap(indexSymlinks); } return null; }
Source:
<code>public void add(@NotNull(message = "labels can't be NULL") final Iterable<String> labels ) throws IOException { <START> final Set<String> oldlabels = this.labelSet(); <END> final Set<String> addedlabels = new HashSet<String>(); final Directives dirs = new Directives().xpath(this.xpath()); for (final String label : labels) { dirs.add("label").set(label).up(); if (!oldlabels.contains(label)) { addedlabels.add(label); } } this.storage.apply(dirs); if (!addedlabels.isEmpty()) { final MkIssueEvents events = new MkIssueEvents( this.storage, this.self, this.repo ); for (final String label : addedlabels) { events.create( Event.LABELED, this.ticket, this.self, Optional.of(label) ); } } }</code><technical_language>@cvrebert name this variable existing, naming convention [here](<LINK_0></technical_language>

Target:
public void add(@NotNull(message = "labels can't be NULL") final Iterable<String> labels ) throws IOException { final Collection<String> existing = this.labels(); final Set<String> added = new HashSet<String>(); final Directives dirs = new Directives().xpath(this.xpath()); for (final String label : labels) { dirs.add("label").set(label).up(); if (!existing.contains(label)) { added.add(label); } } this.storage.apply(dirs); if (!added.isEmpty()) { final MkIssueEvents events = new MkIssueEvents( this.storage, this.self, this.repo ); for (final String label : added) { events.create( Event.LABELED, this.ticket, this.self, Optional.of(label) ); } } }
Source:
<code>public void initTopNAlgorithmSelector(TopNAlgorithmSelector selector) { if (dimensionSpec.getExtractionFn() != null) { <START> selector.setHasDimExtractionFn(true); <END> } topNMetricSpec.initTopNAlgorithmSelector(selector); }</code><technical_language>rename this future confusion a minimum</technical_language>

Target:
public void initTopNAlgorithmSelector(TopNAlgorithmSelector selector) { if (dimensionSpec.getExtractionFn() != null) { selector.setHasExtractionFn(true); } topNMetricSpec.initTopNAlgorithmSelector(selector); }
Source:
<code>public static void register(ScalarFunctionModule module) { <START> module.register(NAME, new BaseFunctionResolver(FUNCTION_PARAMS) { <END> @Override public FunctionImplementation getForTypes(List<DataType> signatureTypes) throws IllegalArgumentException { return new PgTypeofFunction(new FunctionInfo(new FunctionIdent(NAME, signatureTypes), DataTypes.STRING)); } }); }</code><technical_language>I this registered in pg-catalog schema</technical_language>

Target:
public static void register(ScalarFunctionModule module) { module.register(FQNAME, new BaseFunctionResolver(FUNCTION_PARAMS) { @Override public FunctionImplementation getForTypes(List<DataType> signatureTypes) throws IllegalArgumentException { return new PgTypeofFunction(new FunctionInfo(new FunctionIdent(FQNAME, signatureTypes), DataTypes.STRING)); } }); }
Source:
<code>public FatekDimmerItem(Item item, List<String> confItems) throws BindingConfigParseException { super(item, confItems); step = getParamsFromConfAsInt(confItems, "step", 5); if (confItems.size() != 1) { <START> throw new BindingConfigParseException("Incorect binding for dimmer item"); <END> } try { reg1 = Reg.parse(confItems.get(0)); } catch (UnknownRegNameException e) { throw new BindingConfigParseException(e.getMessage()); } if (reg1.isDiscrete()) { throw new BindingConfigParseException("Please use data reg for dimmer item"); } }</code><technical_language>"Incorrect" (please search/replace others)</technical_language>

Target:
public FatekDimmerItem(Item item, List<String> confItems) throws BindingConfigParseException { super(item, confItems); step = getParamsFromConfAsInt(confItems, "step", 5); if (confItems.size() != 1) { throw new BindingConfigParseException("Incorrect binding for dimmer item"); } try { reg1 = Reg.parse(confItems.get(0)); } catch (UnknownRegNameException e) { throw new BindingConfigParseException(e.getMessage()); } if (reg1.isDiscrete()) { throw new BindingConfigParseException("Please use data reg for dimmer item"); } }
Source:
<code>private void parseReportsXML() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/" + BaseContextPathData.getInstance().getRelativePath() + "services/reports-xml"); try { requestBuilder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { setXmlInitialized(); scheduleParseReportsXML(); } @Override public void onResponseReceived(Request request, Response response) { try { if (response.getStatusCode() == Response.SC_OK) { <START> if (response.getText().trim().equals(REPORTS_WEBAPP_NOT_DEPLOYED_MSG)) { <END> scheduleParseReportsXML(); } else if (ReportParser.getInstance().parseReport(response.getText())) { resourceMap = ReportParser.getInstance().getResourceMap(); dashboardMap = ReportParser.getInstance().getDashboardMap(); isCommunityEdition = ReportParser.getInstance().isCommunityEdition(); } } } catch (DOMParseException e) { } finally { setXmlInitialized(); } } }); } catch (RequestException e) { setXmlInitialized(); } }</code><technical_language>check return status, parse response text</technical_language>

Target:
private void parseReportsXML() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/" + BaseContextPathData.getInstance().getRelativePath() + "services/reports-xml"); try { requestBuilder.sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { scheduleCheckStatus(); setXmlInitialized(); } @Override public void onResponseReceived(Request request, Response response) { try { switch (response.getStatusCode()) { case Response.SC_NOT_FOUND: scheduleCheckStatus(); break; case Response.SC_OK: if (ReportParser.getInstance().parseReport(response.getText())) { resourceMap = ReportParser.getInstance().getResourceMap(); dashboardMap = ReportParser.getInstance().getDashboardMap(); isCommunityEdition = ReportParser.getInstance().isCommunityEdition(); } break; } } catch (DOMParseException e) { } finally { setXmlInitialized(); } } }); } catch (RequestException e) { setXmlInitialized(); } }