auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static synchronized ProfilingLogger getLogger(final ImmutableMap<String, Object> execEnvVars) { if (instance == null) { try { instance = new ProfilingLogger(execEnvVars); } catch (DbException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Failed to initialize profiling logger:", e); } } } Preconditions.checkArgument(instance.connectionInfo == (ConnectionInfo) execEnvVars .get(MyriaConstants.EXEC_ENV_VAR_DATABASE_CONN_INFO), "Connection info should not change."); return instance; }

Target:
public static synchronized ProfilingLogger getLogger(final ImmutableMap<String, Object> execEnvVars) { if (instance == null) { try { instance = new ProfilingLogger(execEnvVars); } catch (DbException e) { LOGGER.error("Failed to initialize profiling logger:", e); } } Preconditions.checkArgument(instance.connectionInfo == (ConnectionInfo) execEnvVars .get(MyriaConstants.EXEC_ENV_VAR_DATABASE_CONN_INFO), "Connection info should not change."); return instance; }
Source:
protected void logExceptions(final Context context, RetriesExhaustedWithDetailsException exception) { List<Throwable> causes = exception.getCauses(); String failEventId = UUID.randomUUID().toString(); LOG.warn(String.format("%s: %s occured during finishing: %s", context, failEventId, exception.getMessage())); for (Throwable cause : causes) { LOG.warn(failEventId + ": " + context + " see cause: " + cause.getMessage(), cause); } }

Target:
protected void logExceptions(final Context context, RetriesExhaustedWithDetailsException exception) { List<Throwable> causes = exception.getCauses(); String failEventId = UUID.randomUUID().toString(); String message = String.format("For context %s: eventId: %s occured during bulk writing.", context, failEventId); LOG.warn(message, exception); for (int i = 0; i < causes.size(); i++) { LOG.warn(String.format("context %s: eventId %s excepition %d", context, failEventId, i), causes.get(i)); } }
Source:
public void executeBatch() { if ( threadLocalQueue != null ) { dialect.executeBatch( threadLocalQueue.get() ); threadLocalQueue = null; } }

Target:
public void executeBatch() { if ( operationsQueue.get() != null ) { dialect.executeBatch( operationsQueue.get() ); operationsQueue.set( null ); } }
Source:
private void showPostInfo(Post post) { StringBuilder text = new StringBuilder(); for (PostImage image : post.images) { text.append("Filename: ") .append(image.filename).append(".").append(image.extension) .append(" \nDimensions: ") .append(image.imageWidth).append("x").append(image.imageHeight) .append("\nSize: ") .append(AndroidUtils.getReadableFileSize(image.size, false)); if (image.spoiler) { text.append("\nSpoilered"); } text.append("\n"); } text.append("Posted: ").append(PostHelper.getLocalDate(post)); if (!TextUtils.isEmpty(post.id)) { text.append("\nId: ").append(post.id); } if (!TextUtils.isEmpty(post.tripcode)) { text.append("\nTripcode: ").append(post.tripcode); } if (post.httpIcons != null && !post.httpIcons.isEmpty()) { for (PostHttpIcon icon : post.httpIcons) { if (icon.url.toString().contains("troll")) { text.append("\nTroll Country: ").append(icon.name); } else if (icon.url.toString().contains("country")) { text.append("\nCountry: ").append(icon.name); } else { text.append("\n4chan Pass Year: ").append(icon.name); } } } if (!TextUtils.isEmpty(post.capcode)) { text.append("\nCapcode: ").append(post.capcode); } threadPresenterCallback.showPostInfo(text.toString()); }

Target:
private void showPostInfo(Post post) { StringBuilder text = new StringBuilder(); for (PostImage image : post.images) { text.append("Filename: ") .append(image.filename).append(".").append(image.extension) .append(" \nDimensions: ") .append(image.imageWidth).append("x").append(image.imageHeight) .append("\nSize: ") .append(AndroidUtils.getReadableFileSize(image.size)); if (image.spoiler) { text.append("\nSpoilered"); } text.append("\n"); } text.append("Posted: ").append(PostHelper.getLocalDate(post)); if (!TextUtils.isEmpty(post.id)) { text.append("\nId: ").append(post.id); } if (!TextUtils.isEmpty(post.tripcode)) { text.append("\nTripcode: ").append(post.tripcode); } if (post.httpIcons != null && !post.httpIcons.isEmpty()) { for (PostHttpIcon icon : post.httpIcons) { if (icon.url.toString().contains("troll")) { text.append("\nTroll Country: ").append(icon.name); } else if (icon.url.toString().contains("country")) { text.append("\nCountry: ").append(icon.name); } else if (icon.url.toString().contains("minileaf")) { text.append("\n4chan Pass Year: ").append(icon.name); } } } if (!TextUtils.isEmpty(post.capcode)) { text.append("\nCapcode: ").append(post.capcode); } threadPresenterCallback.showPostInfo(text.toString()); }
Source:
public void transferCorrupted(TransferEvent event) { logger.error(event.getException().getMessage()); }

Target:
public void transferCorrupted(TransferEvent event) { logger.error("Corrupted transfer", event.getException()); }
Source:
public boolean isMapDatabaseSwitchSupported() { return !getMapGenerator().requiresInternetConnection() && null != Settings.getMapFile(); }

Target:
public boolean isMapDatabaseSwitchSupported() { if (getMapGenerator().requiresInternetConnection()) { return false; } if (null == Settings.getMapFile()) { return false; } return true; }
Source:
public static int maxProfit(int[] prices) { if(prices == null || prices.length == 0 || prices.length == 1){ return 0; } int max = 0; int minPrice = prices[0]; for(int i = 0; i < prices.length; i++){ minPrice = Math.min(minPrice, prices[i]); max = Math.max(max, prices[i] - minPrice); } return max; }

Target:
public static int maxProfit(int[] prices) { if(prices == null || prices.length < 2){ return 0; } int max = 0; int minPrice = prices[0]; for(int i = 1; i < prices.length; i++){ minPrice = Math.min(minPrice, prices[i]); max = Math.max(max, prices[i] - minPrice); } return max; }
Source:
public Comparator getComparator(List<AggregatorFactory> aggregatorSpecs, List<PostAggregator> postAggregatorSpecs) { return ComparatorUtils.NATURAL_COMPARATOR; }

Target:
public Comparator getComparator(List<AggregatorFactory> aggregatorSpecs, List<PostAggregator> postAggregatorSpecs) { return comparator; }
Source:
public void remove(final Collection<TopicPartition> revokedChangelogs) { final List<TopicPartition> revokedInitializedChangelogs = new ArrayList<>(); for (final TopicPartition partition : revokedChangelogs) { final ChangelogMetadata changelogMetadata = changelogs.remove(partition); if (changelogMetadata != null) { if (changelogMetadata.state() != ChangelogState.REGISTERED) { revokedInitializedChangelogs.add(partition); } changelogMetadata.clear(); } } removeChangelogsFromRestoreConsumer(revokedInitializedChangelogs); }

Target:
public void remove(final Collection<TopicPartition> revokedChangelogs) { final List<TopicPartition> revokedInitializedChangelogs = new ArrayList<>(); for (final TopicPartition partition : revokedChangelogs) { final ChangelogMetadata changelogMetadata = changelogs.remove(partition); if (changelogMetadata != null) { if (changelogMetadata.state() != ChangelogState.REGISTERED) { revokedInitializedChangelogs.add(partition); } changelogMetadata.clear(); } else { log.debug("Changelog partition could not be found, " + "it could be already cleaned up during the handling" + "of task corruption and never restore again", partition); } } removeChangelogsFromRestoreConsumer(revokedInitializedChangelogs); }
Source:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final List<RpslAttribute> mntByAttribute = update.getUpdatedObject().findAttributes(AttributeType.MNT_BY); if (mntByAttribute.size() !=1 || !mntByAttribute.get(0).getCleanValue().equals(POETC_FORM_MAINTAINER)) { updateContext.addMessage(update, mntByAttribute.get(0), UpdateMessages.poeticFormRequiresDbmMaintainer()); } }

Target:
public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final List<RpslAttribute> mntByAttribute = update.getUpdatedObject().findAttributes(AttributeType.MNT_BY); if (mntByAttribute.size() !=1 || !mntByAttribute.get(0).getCleanValue().equals(POETIC_FORM_MAINTAINER)) { updateContext.addMessage(update, mntByAttribute.get(0), UpdateMessages.poeticFormRequiresDbmMaintainer()); } }
Source:
public void receivePushHookOnWorkflow() throws Exception { j.jenkins.getInjector().injectMembers(this); WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "Test Workflow"); GitHubPushTrigger trigger = new GitHubPushTrigger(); trigger.start(job, false); job.addTrigger(trigger); job.setDefinition(new CpsFlowDefinition("node {" + "git '<LINK_1>'" + "}")); WorkflowRun lastRun = j.assertBuildStatusSuccess(job.scheduleBuild2(0)); lastRun.getActions(BuildData.class).get(0).buildsByBranchName = new HashMap<String, Build>(); new DefaultPushGHEventSubscriber() .onEvent(GHEvent.PUSH, GitHubWebHookFullTest.classpath("payloads/push-wf.json")); Run build = waitForBuild(2, job); j.assertBuildStatusSuccess(build); }

Target:
public void receivePushHookOnWorkflow() throws Exception { WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "Test Workflow"); GitHubPushTrigger trigger = new GitHubPushTrigger(); trigger.start(job, false); job.addTrigger(trigger); job.setDefinition(new CpsFlowDefinition("node {" + "git '<LINK_1>'" + "}")); WorkflowRun lastRun = j.assertBuildStatusSuccess(job.scheduleBuild2(0)); lastRun.getActions(BuildData.class).get(0).buildsByBranchName = new HashMap<String, Build>(); new DefaultPushGHEventSubscriber() .onEvent(GHEvent.PUSH, GitHubWebHookFullTest.classpath("payloads/push-wf.json")); j.waitUntilNoActivity(); j.assertBuildStatusSuccess(job.getBuildByNumber(2)); }
Source:
protected Collection<? extends IEditCommandRequest> getRequests(List<Object> newValues, Collection<?> removedValues) { LinkedList<IEditCommandRequest> requests = new LinkedList<IEditCommandRequest>(); if(feature instanceof EReference && ((EReference)feature).isContainment() && removedValues != null) { for(Object o : removedValues) { if(o instanceof EObject) { requests.add(new DestroyElementRequest((TransactionalEditingDomain)editingDomain, (EObject)o, false)); } } } List<Object> ownedComments = new LinkedList<Object>(); for(EObject ownedComment : ((ElementImpl)source).getOwnedComments()) { ownedComments.add(ownedComment); if(removedValues != null) { if(removedValues.contains(ownedComment)) { ownedComments.remove(ownedComment); } } } for(Object value : newValues) { if(value instanceof Comment) { if(((Comment)value).eContainer() == null) { ownedComments.add(value); } } } requests.add(new SetRequest((TransactionalEditingDomain)editingDomain, source, feature, ownedComments)); return requests; }

Target:
protected Collection<? extends IEditCommandRequest> getRequests(List<Object> newValues, Collection<?> removedValues) { LinkedList<IEditCommandRequest> requests = new LinkedList<IEditCommandRequest>(); if(feature instanceof EReference && ((EReference)feature).isContainment() && removedValues != null) { for(Object o : removedValues) { if(o instanceof EObject) { requests.add(new DestroyElementRequest((TransactionalEditingDomain)editingDomain, (EObject)o, false)); } } } List<Object> ownedComments = new ArrayList<Object>(); for(EObject ownedComment : ((Element)source).getOwnedComments()) { if(removedValues == null || !removedValues.contains(ownedComment)) { ownedComments.add(ownedComment); } } for(Object value : newValues) { if(value instanceof Comment) { if(((Comment)value).eContainer() == null) { ownedComments.add(value); } } } requests.add(new SetRequest((TransactionalEditingDomain)editingDomain, source, feature, ownedComments)); return requests; }
Source:
public static Expression<Number> mod(Expression<Number> number1, Expression<Number> number2) { return new OperatorExpression<Number>("$divide", number1, number2); }

Target:
public static Expression<Number> mod(Expression<Number> number1, Expression<Number> number2) { return new OperatorExpression<Number>("$mod", number1, number2); }
Source:
private boolean isDraft(final ReceiveCommand cmd) { String refName = cmd.getRefName(); if (refName.startsWith(NEW_DRAFT_CHANGE)) { return true; } return false; }

Target:
private boolean isDraft(final ReceiveCommand cmd) { return cmd.getRefName().startsWith(NEW_DRAFT_CHANGE); }
Source:
public MimeMessage sendRegistrationInviteToInstructor(String courseId, String instructorEmail) throws EntityDoesNotExistException { CourseAttributes course = coursesLogic.getCourse(courseId); if (course == null) { throw new EntityDoesNotExistException( "Course does not exist [" + courseId + "], " + "trying to send invite email to student [" + instructorEmail + "]"); } InstructorAttributes instructorData = getInstructorForEmail(courseId, instructorEmail); if (instructorData == null) { throw new EntityDoesNotExistException( "Instructor [" + instructorEmail + "] does not exist in course [" + courseId + "]"); } Emails emailMgr = new Emails(); try { MimeMessage email = emailMgr.generateInstructorCourseJoinEmail(course, instructorData); emailMgr.sendEmailWithLogging(email); return email; } catch (Exception e) { throw new RuntimeException("Unexpected error while sending email", e); } }

Target:
public MimeMessage sendRegistrationInviteToInstructor(String courseId, String instructorEmail) throws EntityDoesNotExistException { CourseAttributes course = coursesLogic.getCourse(courseId); if (course == null) { throw new EntityDoesNotExistException( "Course does not exist [" + courseId + "], " + "trying to send invite email to instructor [" + instructorEmail + "]"); } InstructorAttributes instructorData = getInstructorForEmail(courseId, instructorEmail); if (instructorData == null) { throw new EntityDoesNotExistException( "Instructor [" + instructorEmail + "] does not exist in course [" + courseId + "]"); } try { MimeMessage email = new EmailGenerator().generateInstructorCourseJoinEmail(course, instructorData); new Emails().sendEmailWithLogging(email); return email; } catch (Exception e) { throw new RuntimeException("Unexpected error while sending email", e); } }
Source:
public MeasureAndDispatchResourceServerTokenServices(final MetricRegistry metricRegistry, final SecuritySettings securitySettings, final RestTemplate restTemplate, final FeatureToggleService featureToggleService) { remoteService = new TokenInfoResourceServerTokenServices( securitySettings.getTokenInfoUrl(), securitySettings.getClientId(), new DefaultAuthenticationExtractor(), new DefaultUserRolesProvider(), restTemplate); localService = new TokenInfoResourceServerTokenServices( securitySettings.getTokenInfoUrl(), securitySettings.getClientId(), new DefaultAuthenticationExtractor(), new DefaultUserRolesProvider(), restTemplate); timer = metricRegistry.timer(MetricUtils.NAKADI_PREFIX + "general.accessTokenValidation"); this.featureToggleService = featureToggleService; }

Target:
public MeasureAndDispatchResourceServerTokenServices(final MetricRegistry metricRegistry, final SecuritySettings securitySettings, final RestTemplate restTemplate, final FeatureToggleService featureToggleService) { remoteService = new TokenInfoResourceServerTokenServices( securitySettings.getTokenInfoUrl(), securitySettings.getClientId(), new DefaultAuthenticationExtractor(), new DefaultUserRolesProvider(), restTemplate); localService = new TokenInfoResourceServerTokenServices( securitySettings.getLocalTokenInfoUrl(), securitySettings.getClientId(), new DefaultAuthenticationExtractor(), new DefaultUserRolesProvider(), restTemplate); timer = metricRegistry.timer(MetricUtils.NAKADI_PREFIX + "general.accessTokenValidation"); this.featureToggleService = featureToggleService; }
Source:
private void handleException() { Publisher<CoreEvent> pub = checkLogHandler.route(just(mock(CoreEvent.class))); pub.subscribe(new Subscriber<CoreEvent>() { @Override public void onSubscribe(Subscription s) { } @Override public void onNext(CoreEvent event) { } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); }

Target:
private void handleException() { Flux.from(checkLogHandler.route(just(mock(CoreEvent.class)))).subscribe(e -> { }, e -> { }); }
Source:
private void recreatePK(StatementExecutor executor, String tableName, PrimaryKey pk) throws OrmException { try { if (pk.oldNameInDb == null) { ui.message("WARN: primary key for table %s didn't exist\n", tableName); } else { if (dialect instanceof DialectPostgreSQL) { executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT " + pk.oldNameInDb); } else { executor.execute("ALTER TABLE " + tableName + " DROP PRIMARY KEY"); } } } catch (OrmException ignore) { ui.message("WARN: %s\n", ignore.getMessage()); } executor.execute("ALTER TABLE " + tableName + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")"); }

Target:
private void recreatePK(StatementExecutor executor, String tableName, PrimaryKey pk) throws OrmException { try { if (pk.oldNameInDb == null) { ui.message("WARN: primary key for table %s didn't exist ... ", tableName); } else { if (dialect instanceof DialectPostgreSQL) { executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT " + pk.oldNameInDb); } else { executor.execute("ALTER TABLE " + tableName + " DROP PRIMARY KEY"); } } } catch (OrmException ignore) { ui.message("WARN: %s\n", ignore.getMessage()); } executor.execute("ALTER TABLE " + tableName + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")"); }
Source:
private void doBuild(IProgressMonitor monitor) throws CoreException, OperationCanceledException { SubMonitor subMonitor = SubMonitor.convert(monitor, Policy.opWork + Policy.endOpWork + 1); final ISchedulingRule rule = workspace.getRuleFactory().buildRule(); try { workspace.prepareOperation(rule, subMonitor.split(1)); workspace.beginOperation(true); final int trigger = IncrementalProjectBuilder.AUTO_BUILD; workspace.broadcastBuildEvent(workspace, IResourceChangeEvent.PRE_BUILD, trigger); IStatus result = Status.OK_STATUS; try { if (shouldBuild()) result = workspace.getBuildManager().build(workspace.getBuildOrder(), ICoreConstants.EMPTY_BUILD_CONFIG_ARRAY, trigger, subMonitor.split(Policy.opWork)); } finally { workspace.broadcastBuildEvent(workspace, IResourceChangeEvent.POST_BUILD, trigger); } if (!result.isOK()) { throw new ResourceException(result); } buildNeeded = false; } finally { if (workspace.getElementTree().isImmutable()) { workspace.newWorkingTree(); } workspace.endOperation(rule, false); } }

Target:
private void doBuild(IProgressMonitor monitor) throws CoreException, OperationCanceledException { SubMonitor subMonitor = SubMonitor.convert(monitor, Policy.opWork + 1); final ISchedulingRule rule = workspace.getRuleFactory().buildRule(); try { workspace.prepareOperation(rule, subMonitor.split(1)); workspace.beginOperation(true); final int trigger = IncrementalProjectBuilder.AUTO_BUILD; workspace.broadcastBuildEvent(workspace, IResourceChangeEvent.PRE_BUILD, trigger); IStatus result = Status.OK_STATUS; try { if (shouldBuild()) result = workspace.getBuildManager().build(workspace.getBuildOrder(), ICoreConstants.EMPTY_BUILD_CONFIG_ARRAY, trigger, subMonitor.split(Policy.opWork)); } finally { workspace.broadcastBuildEvent(workspace, IResourceChangeEvent.POST_BUILD, trigger); } if (!result.isOK()) { throw new ResourceException(result); } buildNeeded = false; } finally { if (workspace.getElementTree().isImmutable()) { workspace.newWorkingTree(); } workspace.endOperation(rule, false); } }
Source:
public String getServerSpecificRoot(String hostId) { if (!m_hostRoots.containsKey(hostId)) { throw new RuntimeException("getServerSpecificRoot possibly called before cluster has started."); } return m_hostRoots.get(hostId) + "/voltdbroot"; }

Target:
public String getServerSpecificRoot(String hostId) { if (!m_hostRoots.containsKey(hostId)) { throw new IllegalArgumentException("getServerSpecificRoot possibly called before cluster has started."); } return m_hostRoots.get(hostId) + "/voltdbroot"; }
Source:
public PaginatedArrayList<Map<String, Object>> getItems(final User user, final int limit, final int offset, final Map<String, Object> params) throws PaginationException { try { final PaginatedArrayList<Map<String, Object>> result = new PaginatedArrayList(); final List<Relationship> relationships = relationshipAPI .getOneSidedRelationships((ContentType) params.get(CONTENT_TYPE_PARAM), limit, offset); result.add(relationships.stream() .collect(Collectors.toMap(Relationship::getInode, r -> r))); return result; } catch (DotDataException e) { throw new DotRuntimeException(e); } }

Target:
public PaginatedArrayList<Map<String, Object>> getItems(final User user, final int limit, final int offset, final Map<String, Object> params) throws PaginationException { try { final PaginatedArrayList<Map<String, Object>> result = new PaginatedArrayList(); final List<Relationship> relationships = relationshipAPI .getOneSidedRelationships((ContentType) params.get(CONTENT_TYPE_PARAM), limit, offset); result.add(relationships.stream() .collect(Collectors.toMap(Relationship::getInode, r -> r))); return result; } catch (DotDataException e) { Logger.error(this, "Error getting relationships", e); throw new DotRuntimeException(e); } }
Source:
public void delete(MailboxSession session, Mailbox mailbox, List<MessageUid> expungedUids) throws MailboxException { try { indexer.deleteMessages(expungedUids.stream() .map(uid -> indexIdFor(mailbox, uid)) .collect(Collectors.toList())); } catch (Exception e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error when deleting messages in mailbox from index", mailbox.getMailboxId().serialize(), ImmutableList.copyOf(expungedUids), e); } } }

Target:
public void delete(MailboxSession session, Mailbox mailbox, List<MessageUid> expungedUids) throws MailboxException { try { indexer.deleteMessages(expungedUids.stream() .map(uid -> indexIdFor(mailbox, uid)) .collect(Collectors.toList())); } catch (Exception e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error when deleting messages in mailbox from index", mailbox.getMailboxId().serialize(), expungedUids.toArray(), e); } } }
Source:
public ResourceHolder<T> get() { CountingHolder obj; if(size.getAndIncrement() > maxCapacity) { size.decrementAndGet(); do { obj = objects.remove(); } while(obj == null); obj.count.incrementAndGet(); objects.offer(obj); return obj; } else { obj = new CountingHolder(generator.get()); obj.count.incrementAndGet(); objects.offer(obj); return obj; } }

Target:
public ResourceHolder<T> get() { final CountingHolder holder; try { holder = queue.take(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } synchronized (holder) { holder.count.incrementAndGet(); queue.offer(holder); } return holder; }
Source:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource("schemas/common.xsd"), new ClassPathResource("schemas/ts-adhocmanagement.xsd"), new ClassPathResource("schemas/ts-schedulemanagement.xsd") }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }

Target:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource(COMMON_XSD_PATH), new ClassPathResource(TS_ADHOCMANAGEMENT_XSD_PATH), new ClassPathResource(TS_SCHEDULE_MANAGEMENT_XSD_PATH) }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }
Source:
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } if (!TypeUtil.isCollectionTypeHomogenous(list, Boolean.class)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean")); } for ( final Object element : list ) { if (element == null || element == Boolean.FALSE) { return FEELFnResult.ofResult( false ); } } return FEELFnResult.ofResult( true ); }

Target:
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = true; boolean containsNull = false; for ( final Object element : list ) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean")); } else { if (element != null) { result &= (Boolean) element; } else if (!containsNull) { containsNull = true; } } } if (containsNull && result) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( result ); } }
Source:
public void updateDiseaseOccurrenceIsValidatedValues(int diseaseGroupId, DateTime modelRunPrepDate) { int numRemovedFromValidator = 0; List<DiseaseOccurrence> occurrences = diseaseService.getDiseaseOccurrencesInValidation(diseaseGroupId); Set<DiseaseOccurrence> reviewedOccurrences = getAllReviewedOccurrences(diseaseGroupId); Boolean isValidated; for (DiseaseOccurrence occurrence : occurrences) { isValidated = false; if (duringDiseaseSetUp(occurrence.getDiseaseGroup())) { isValidated = true; } else { if (occurrenceHasBeenInReviewForMoreThanAWeek(occurrence, modelRunPrepDate)) { isValidated = reviewedOccurrences.contains(occurrence) ? true : null; } } if (isValidated == null || isValidated) { occurrence.setValidated(isValidated); diseaseService.saveDiseaseOccurrence(occurrence); numRemovedFromValidator++; } } logResults(occurrences.size(), numRemovedFromValidator); }

Target:
public void updateDiseaseOccurrenceIsValidatedValues(int diseaseGroupId, DateTime modelRunPrepDate) { int numRemovedFromValidator = 0; List<DiseaseOccurrence> occurrences = diseaseService.getDiseaseOccurrencesInValidation(diseaseGroupId); Set<DiseaseOccurrence> reviewedOccurrences = getAllReviewedOccurrences(diseaseGroupId); Boolean isValidated; for (DiseaseOccurrence occurrence : occurrences) { isValidated = false; if (duringDiseaseSetUp(occurrence.getDiseaseGroup())) { isValidated = true; } else if (occurrenceHasBeenInReviewForMoreThanAWeek(occurrence, modelRunPrepDate)) { isValidated = reviewedOccurrences.contains(occurrence) ? true : null; } if (isValidated == null || isValidated) { occurrence.setValidated(isValidated); diseaseService.saveDiseaseOccurrence(occurrence); numRemovedFromValidator++; } } logResults(occurrences.size(), numRemovedFromValidator); }
Source:
protected void executeVmCommand() { Set<Guid> mImagesToBeRemoved = new HashSet<Guid>(); List<DiskImage> images = getParameters().Images; if (images == null) { images = ImagesHandler.filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(getVmId()), true, false); } for (DiskImage image : images) { if (Boolean.TRUE.equals(image.getActive())) { mImagesToBeRemoved.add(image.getImageId()); } } Collection<DiskImage> failedToBeRemoved = new LinkedList<>(); for (final DiskImage image : images) { if (mImagesToBeRemoved.contains(image.getImageId())) { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(VdcActionType.RemoveImage, buildRemoveImageParameters(image), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (vdcReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().addAll(vdcReturnValue.getInternalTaskIdList()); } else { failedToBeRemoved.add(image); log.errorFormat("Can't remove image id: {0} for VM id: {1} due to: {2}. Image will be set at illegal state with no snapshot id.", image.getImageId(), getParameters().getVmId(), vdcReturnValue.getFault().getMessage()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { updateDiskImagesToIllegal(image); return true; } }); } } } setActionReturnValue(failedToBeRemoved); setSucceeded(true); }

Target:
protected void executeVmCommand() { Set<Guid> mImagesToBeRemoved = new HashSet<Guid>(); List<DiskImage> images = getParameters().Images; if (images == null) { images = ImagesHandler.filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(getVmId()), true, false); } for (DiskImage image : images) { if (Boolean.TRUE.equals(image.getActive())) { mImagesToBeRemoved.add(image.getImageId()); } } Collection<DiskImage> failedRemoving = new LinkedList<>(); for (final DiskImage image : images) { if (mImagesToBeRemoved.contains(image.getImageId())) { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction(VdcActionType.RemoveImage, buildRemoveImageParameters(image), ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (vdcReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().addAll(vdcReturnValue.getInternalTaskIdList()); } else { failedRemoving.add(image); log.errorFormat("Can't remove image id: {0} for VM id: {1} due to: {2}. Image will be set at illegal state with no snapshot id.", image.getImageId(), getParameters().getVmId(), vdcReturnValue.getFault().getMessage()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { updateDiskImagesToIllegal(image); return true; } }); } } } setActionReturnValue(failedRemoving); setSucceeded(true); }
Source:
public OseeGroup(IArtifactToken token) { this.token = token; this.groupArtifact = null; this.groupArtifact = null; }

Target:
public OseeGroup(IArtifactToken token) { this.token = token; this.groupArtifact = null; }
Source:
private static int setDiskBootOrder(List<VmDevice> devices, int bootOrder) { VM vm = DbFacade.getInstance().getVmDAO().get(vmBaseInstance.getId()); boolean isOldCluster = VmDeviceCommonUtils.isOldClusterVersion(vm.getvds_group_compatibility_version()); for (VmDevice device : devices) { if (device.getType() .equals(VmDeviceType.getName(VmDeviceType.DISK)) && device.getDevice().equals( VmDeviceType.getName(VmDeviceType.DISK))) { Guid id = device.getDeviceId(); Disk disk = DbFacade.getInstance().getDiskDao().get(id); if (id != null && !id.equals(Guid.Empty)) { if (isOldCluster) { if (disk != null && disk.getDiskType().equals(DiskType.System)) { device.setBootOrder(bootOrder++); break; } } else { device.setBootOrder(bootOrder++); } } } } return bootOrder; }

Target:
private static int setDiskBootOrder(List<VmDevice> devices, int bootOrder) { VM vm = DbFacade.getInstance().getVmDAO().get(vmBaseInstance.getId()); boolean isOldCluster = VmDeviceCommonUtils.isOldClusterVersion(vm.getvds_group_compatibility_version()); for (VmDevice device : devices) { if (device.getType() .equals(VmDeviceType.DISK.getName()) && device.getDevice().equals( VmDeviceType.DISK.getName())) { Guid id = device.getDeviceId(); Disk disk = DbFacade.getInstance().getDiskDao().get(id); if (id != null && !id.equals(Guid.Empty)) { if (isOldCluster) { if (disk != null && disk.getDiskType().equals(DiskType.System)) { device.setBootOrder(bootOrder++); break; } } else { device.setBootOrder(bootOrder++); } } } } return bootOrder; }
Source:
public boolean canCustomize(String text) { return (COMPILATION_MESSAGE.exec(text) != null || LINKER_MESSAGE.exec(text) != null); }

Target:
public boolean canCustomize(String text) { return (COMPILATION_MESSAGE.test(text) || LINKER_MESSAGE.test(text)); }
Source:
public List<OrganizationDto> getAllRoot() throws Exception { List<OrganizationDto> organizations = requestFactory.fromUrl(getApiUrl()).request().asList(OrganizationDto.class); organizations.removeIf((o -> nonNull(o.getParent()))); return organizations; }

Target:
public List<OrganizationDto> getAllRoot() throws Exception { List<OrganizationDto> organizations = requestFactory.fromUrl(getApiUrl()).request().asList(OrganizationDto.class); organizations.removeIf(o -> o.getParent() != null); return organizations; }
Source:
private static boolean restore(PageStore pageStore, PageStoreOptions options, MetaStore metaStore, CacheEvictor evictor) { Path rootDir = Paths.get(options.getRootDir()); if (!Files.exists(rootDir)) { LOG.error("Failed to restore PageStore: Directory does not exist", rootDir); return false; } try (Stream<PageInfo> stream = pageStore.getPages()) { Iterator<PageInfo> iterator = stream.iterator(); while (iterator.hasNext()) { PageInfo pageInfo = iterator.next(); if (pageInfo == null) { LOG.error("Invalid page info"); return false; } metaStore.addPage(pageInfo.getPageId(), pageInfo); evictor.updateOnPut(pageInfo.getPageId()); if (metaStore.bytes() > pageStore.getCacheSize()) { LOG.error("Loaded pages exceed cache capacity ({} bytes)", pageStore.getCacheSize()); return false; } } } catch (Exception e) { LOG.error("Failed to restore PageStore", e); return false; } LOG.info("Restored PageStore with existing pages and bytes", metaStore.pages(), metaStore.bytes()); return true; }

Target:
private static boolean restore(PageStore pageStore, PageStoreOptions options, MetaStore metaStore, CacheEvictor evictor) { LOG.info("Attempt to restore PageStore with {}", options); Path rootDir = Paths.get(options.getRootDir()); if (!Files.exists(rootDir)) { LOG.error("Failed to restore PageStore: Directory does not exist", rootDir); return false; } try (Stream<PageInfo> stream = pageStore.getPages()) { Iterator<PageInfo> iterator = stream.iterator(); while (iterator.hasNext()) { PageInfo pageInfo = iterator.next(); if (pageInfo == null) { LOG.error("Invalid page info"); return false; } metaStore.addPage(pageInfo.getPageId(), pageInfo); evictor.updateOnPut(pageInfo.getPageId()); if (metaStore.bytes() > pageStore.getCacheSize()) { LOG.error("Loaded pages exceed cache capacity ({} bytes)", pageStore.getCacheSize()); return false; } } } catch (Exception e) { LOG.error("Failed to restore PageStore", e); return false; } LOG.info("Restored PageStore with existing pages and bytes", metaStore.pages(), metaStore.bytes()); return true; }
Source:
public void updateDNS() { synchronized (sync) { if (shutdown) { return; } long ttl = Integer.MAX_VALUE; try { List<LookupResult> lookupResults = srvResolver.resolve(srvRecord); List<HostAndPort> hosts = Lists.newArrayListWithCapacity(lookupResults.size()); for (LookupResult lookupResult : lookupResults) { hosts.add(HostAndPort.fromParts(lookupResult.host(), lookupResult.port())); ttl = Math.min(ttl, lookupResult.ttl()); } List<HostAndPort> newAddresses = Ordering.from(HostAndPortComparator.INSTANCE) .sortedCopy(hosts); if (!newAddresses.equals(addresses)) { addresses = newAddresses; log.info("Connecting to " + newAddresses); List<AddressAndClient> addressAndClients = getAddressesAndClients(newAddresses); setPendingClient(addressAndClients); } } finally { long delay = clamp(MIN_DNS_WAIT_TIME, MAX_DNS_WAIT_TIME, ttl); refreshJob = this.executor.schedule(refreshRunnable, delay, TimeUnit.SECONDS); } } }

Target:
public void updateDNS() { synchronized (sync) { if (shutdown) { return; } long ttl = TimeUnit.SECONDS.convert(period, periodUnit); try { List<LookupResult> lookupResults = srvResolver.resolve(srvRecord); List<HostAndPort> hosts = Lists.newArrayListWithCapacity(lookupResults.size()); for (LookupResult lookupResult : lookupResults) { hosts.add(HostAndPort.fromParts(lookupResult.host(), lookupResult.port())); ttl = Math.min(ttl, lookupResult.ttl()); } List<HostAndPort> newAddresses = Ordering.from(HostAndPortComparator.INSTANCE) .sortedCopy(hosts); if (!newAddresses.equals(addresses)) { addresses = newAddresses; log.info("Connecting to " + newAddresses); List<AddressAndClient> addressAndClients = getAddressesAndClients(newAddresses); setPendingClient(addressAndClients); } } finally { long delay = clamp(MIN_DNS_WAIT_TIME, MAX_DNS_WAIT_TIME, ttl); refreshJob = this.executor.schedule(refreshRunnable, delay, TimeUnit.SECONDS); } } }
Source:
public void testReplaceAtHeadSucceedsMappingExistsHeadMatches() { ServerStore store = newStore(); populateStore(store); Chain existingMapping = store.get(1); store.append(1, getPayload(11)); store.replaceAtHead(1, existingMapping, chainBuilder.build(compactChain(existingMapping, getPayload(111)))); Chain chain = store.get(1); Iterator<Element> elements = chain.iterator(); assertThat(readPayLoad(elements.next().getPayload()), is(Long.valueOf(111))); assertThat(readPayLoad(elements.next().getPayload()), is(Long.valueOf(11))); store.append(2, getPayload(22)); existingMapping = store.get(2); store.append(2, getPayload(222)); store.replaceAtHead(2, existingMapping, chainBuilder.build(compactChain(existingMapping, getPayload(2222)))); chain = store.get(2); elements = chain.iterator(); assertThat(readPayLoad(elements.next().getPayload()), is(Long.valueOf(2222))); assertThat(readPayLoad(elements.next().getPayload()), is(Long.valueOf(222))); }

Target:
public void testReplaceAtHeadSucceedsMappingExistsHeadMatches() { ServerStore store = newStore(); populateStore(store); Chain existingMapping = store.get(1); store.append(1, createPayload(11)); store.replaceAtHead(1, existingMapping, chainBuilder.build(elementBuilder.build(createPayload(111)))); Chain chain = store.get(1); assertChainAndReverseChainOnlyHave(chain, 111, 11); store.append(2, createPayload(22)); existingMapping = store.get(2); store.append(2, createPayload(222)); store.replaceAtHead(2, existingMapping, chainBuilder.build(elementBuilder.build(createPayload(2222)))); chain = store.get(2); assertChainAndReverseChainOnlyHave(chain, 2222, 222); }
Source:
public Object execute(ComplexEvent event) { try { Boolean condition = (attributeExpressionExecutors[0].execute(event) != null && attributeExpressionExecutors[0].execute(event).equals(Boolean.TRUE)); return execute( new Object[]{ condition, (condition) ? attributeExpressionExecutors[1].execute(event) : null, (!condition) ? attributeExpressionExecutors[2].execute(event) : null } ); } catch (Exception e) { log.error("Exception on execution plan '" + executionPlanContext.getName() + "' on class '" + this.getClass().getName() + "', " + e.getMessage(), e); return null; } }

Target:
public Object execute(ComplexEvent event) { try { Boolean condition = Boolean.TRUE.equals(attributeExpressionExecutors[0].execute(event)); return execute( new Object[]{ condition, (condition) ? attributeExpressionExecutors[1].execute(event) : null, (!condition) ? attributeExpressionExecutors[2].execute(event) : null } ); } catch (Exception e) { log.error("Exception on execution plan '" + executionPlanContext.getName() + "' on class '" + this.getClass().getName() + "', " + e.getMessage(), e); return null; } }
Source:
protected @NonNull List<IMarkerEvent> getViewMarkerList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { ITimeGraphEntry[] expandedElements = getTimeGraphViewer().getExpandedElements(); List<IMarkerEvent> markers = new ArrayList<>(); for (ITimeGraphEntry element : expandedElements) { if (((TimeGraphEntry) element).getModel() instanceof SpanLifeEntryModel) { SpanLifeEntryModel model = (SpanLifeEntryModel) ((TimeGraphEntry) element).getModel(); for (LogEvent log : model.getLogs()) { markers.add(new SpanMarkerEvent(element, log.getTime(), MARKER_COLOR, log.getType())); } if (model.getErrorTag()) { markers.add(new SpanMarkerEvent(element, model.getStartTime(), MARKER_COLOR, "error.object")); } } } return markers; }

Target:
protected @NonNull List<IMarkerEvent> getViewMarkerList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { ITimeGraphEntry[] expandedElements = getTimeGraphViewer().getExpandedElements(); List<IMarkerEvent> markers = new ArrayList<>(); for (ITimeGraphEntry element : expandedElements) { if (((TimeGraphEntry) element).getModel() instanceof SpanLifeEntryModel) { SpanLifeEntryModel model = (SpanLifeEntryModel) ((TimeGraphEntry) element).getModel(); for (LogEvent log : model.getLogs()) { markers.add(new SpanMarkerEvent(element, log.getTime(), MARKER_COLOR, log.getType())); } } } return markers; }
Source:
protected InstructorAttributes getInstructorOfCourseFromRequest(String courseId) { if (userInfo == null || !userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor account is required to access this resource"); } String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); if (!StringHelper.isEmpty(moderatedPerson)) { return logic.getInstructorForEmail(courseId, moderatedPerson); } else if (!StringHelper.isEmpty(previewAsPerson)) { return logic.getInstructorForEmail(courseId, previewAsPerson); } else { return logic.getInstructorForGoogleId(courseId, userInfo.getId()); } }

Target:
protected InstructorAttributes getInstructorOfCourseFromRequest(String courseId) { String moderatedPerson = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON); String previewAsPerson = getRequestParamValue(Const.ParamsNames.PREVIEWAS); if (!StringHelper.isEmpty(moderatedPerson)) { return logic.getInstructorForEmail(courseId, moderatedPerson); } else if (!StringHelper.isEmpty(previewAsPerson)) { return logic.getInstructorForEmail(courseId, previewAsPerson); } else { gateKeeper.verifyLoggedInUserPrivileges(); return logic.getInstructorForGoogleId(courseId, userInfo.getId()); } }
Source:
public static boolean renameFile(File src, File dst){ boolean renamed = false; Path srcPath = Paths.get(src.toURI()); Path dstPath = Paths.get(dst.toURI()); Path moved = null; try{ moved = Files.move(srcPath, dstPath, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e){ if(log.isWarnEnabled()){ log.warn("An error occurred when executing atomic file renaming. Falling back to the old File.renameTo() method", e); } } if(moved == null || !Files.exists(moved)){ renamed = src.renameTo(dst); } else { renamed = true; } return renamed; }

Target:
public static boolean renameFile(File src, File dst){ boolean renamed = false; Path srcPath = Paths.get(src.toURI()); Path dstPath = Paths.get(dst.toURI()); Path moved = null; try{ moved = Files.move(srcPath, dstPath, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e){ if(log.isDebugEnabled()){ log.debug("An error occurred when executing atomic file renaming. Falling back to the old File.renameTo() method", e); } } if(moved == null || !Files.exists(moved)){ renamed = src.renameTo(dst); } else { renamed = true; } return renamed; }
Source:
public String toString() { return this.getClass().getSimpleName() + ": " + mode; }

Target:
public String toString() { String status = "disabled"; if (mode == ENABLED) { status = "enabled"; } return String.format("%s: wireframe %s", this.getClass().getSimpleName(), status); }
Source:
public AsyncFutureImpl<Executable> getStartCondition() { return start; }

Target:
public Future<Executable> getStartCondition() { return start; }
Source:
public void onlyOneGroupIfNoSuicideOnHit() { final List<Unit> units = List.of( givenUnitWithSuicideOnHit("type1", false), givenUnitWithSuicideOnHit("type2", false)); final List<FiringGroup> groups = FiringGroup.groupBySuicideOnHit("test", units, List.of(mock(Unit.class))); assertThat("There should only be one group", groups, hasSize(1)); assertThat("The group name should have no prefix", groups.get(0).getDisplayName(), is("test")); assertThat( "The group should have all of the units", groups.get(0).getFiringUnits().toArray(), is(units.toArray())); assertThat("The group should not be suicide on hit", groups.get(0).isSuicideOnHit(), is(false)); }

Target:
public void onlyOneGroupIfNoSuicideOnHit() { final List<Unit> units = List.of(givenUnit(givenUnitType("type1")), givenUnit(givenUnitType("type2"))); final List<FiringGroup> groups = FiringGroup.groupBySuicideOnHit(GROUP_NAME, units, List.of(mock(Unit.class))); assertThat("All non-suicide units are in a single group", groups, hasSize(1)); assertThat( "The group name should have no prefix", groups.get(0).getDisplayName(), is(GROUP_NAME)); assertThat( "The group should have all of the units", groups.get(0).getFiringUnits().toArray(), is(units.toArray())); assertThat("The group should not be suicide on hit", groups.get(0).isSuicideOnHit(), is(false)); }
Source:
private void insertToByteArray(byte[] array, int pos) { if (pos < 0 || (pos + 6) > array.length) { throw new IllegalArgumentException("Illegal offset ("+pos+"), need room for 6 bytes"); } int i = (int) (_address >> 32); array[pos++] = (byte) (i >> 8); array[pos++] = (byte) i; i = (int) _address; array[pos++] = (byte) (i >> 24); array[pos++] = (byte) (i >> 16); array[pos++] = (byte) (i >> 8); array[pos] = (byte) i; }

Target:
private void insertToByteArray(byte[] array, int pos) { if (pos < 0 || (pos + 6) > array.length) { throw new IllegalArgumentException("Illegal offset (" + pos + "), need room for 6 bytes"); } int i = (int) (address >> 32); array[pos++] = (byte) (i >> 8); array[pos++] = (byte) i; i = (int) address; array[pos++] = (byte) (i >> 24); array[pos++] = (byte) (i >> 16); array[pos++] = (byte) (i >> 8); array[pos] = (byte) i; }
Source:
private void compare(ByteString a, ByteString b) { Assert.assertTrue(underTest.compare(a, b) < 0); Assert.assertTrue(underTest.compare(b, a) > 0); Assert.assertTrue(underTest.compare(b, b) == 0); Assert.assertTrue("test", false); }

Target:
private void compare(ByteString a, ByteString b) { Assert.assertTrue(underTest.compare(a, b) < 0); Assert.assertTrue(underTest.compare(b, a) > 0); Assert.assertTrue(underTest.compare(b, b) == 0); }
Source:
public void whenExpectingAssumptionViolatedExceptionStatementsPassingShouldFail() throws Exception { ExpectException expectException = new ExpectException(new PassingStatement(), AssumptionViolatedException.class); try { expectException.evaluate(); fail("ExpectException should throw when the given statement passes"); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("Expected exception: " + AssumptionViolatedException.class.getName())); } }

Target:
public void whenExpectingAssumptionViolatedExceptionStatementsPassingShouldFail() throws Exception { ExpectException expectException = new ExpectException(new PassingStatement(), AssumptionViolatedException.class); try { expectException.evaluate(); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("Expected exception: " + AssumptionViolatedException.class.getName())); return; } fail("ExpectException should throw when the given statement passes"); }