auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private VirtualFile createDirectory(VirtualFile parent, String name) { MutableVirtualFile file = new MutableVirtualFile(parent, name); file.withCanCreateChildren(ignored -> true); file.withCanProvideInputStream(ignored -> false); file.withCanProvideOutputStream(ignored -> false); file.withDirectoryFlagSupplier(ignored -> true); file.withExistsFlagSupplier(ignored -> true); file.withCanRenameHandler(ignored -> false); file.withCanDeleteHandler(ignored -> false); file.withCanMoveHandler(ignored -> false); file.withDeleteHandler(ignored -> false); file.withCanCreateDirectoryHandler(ignored -> false); file.withChildren(this); return file; }

Target:
private VirtualFile createDirectory(VirtualFile parent, String name) { MutableVirtualFile directory = new MutableVirtualFile(parent, name); directory.withCanCreateChildren(ignored -> true); directory.withCanProvideInputStream(ignored -> false); directory.withCanProvideOutputStream(ignored -> false); directory.withDirectoryFlagSupplier(ignored -> true); directory.withExistsFlagSupplier(ignored -> true); directory.withCanRenameHandler(ignored -> false); directory.withCanDeleteHandler(ignored -> false); directory.withCanMoveHandler(ignored -> false); directory.withDeleteHandler(ignored -> false); directory.withCanCreateDirectoryHandler(ignored -> false); directory.withChildren(this); return directory; }
Source:
private void completeWhenRetryRejected(RejectedExecutionException e) { if (context.logger.isFinestEnabled()) { context.logger.finest(e); } notifyError(new HazelcastInstanceNotActiveException(e.getMessage())); }

Target:
private void completeWhenRetryRejected(RejectedExecutionException e) { if (context.logger.isFinestEnabled()) { context.logger.finest(e); } completeExceptionally(new HazelcastInstanceNotActiveException(e.getMessage())); }
Source:
protected void registerGetters() { registerFieldGetter(Keys.ITEM_DURABILITY, () -> this.durability); registerKeyValue(Keys.ITEM_DURABILITY, this::durability); registerFieldGetter(Keys.UNBREAKABLE, this.unbreakable::get); registerKeyValue(Keys.UNBREAKABLE, this::unbreakable); }

Target:
protected void registerGetters() { registerFieldGetter(Keys.ITEM_DURABILITY, this.durability::get); registerKeyValue(Keys.ITEM_DURABILITY, this::durability); registerFieldGetter(Keys.UNBREAKABLE, this.unbreakable::get); registerKeyValue(Keys.UNBREAKABLE, this::unbreakable); }
Source:
protected boolean validate() { macPool = getMacPool(); if (getCluster() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); } List<VmNetworkInterface> nicsUnableToBeImported = getVm().getInterfaces() .stream() .filter(this::ifaceMacCannotBeAddedToMacPool) .collect(Collectors.toList()); if (!nicsUnableToBeImported.isEmpty()) { EngineMessage engineMessage = EngineMessage.ACTION_TYPE_FAILED_CANNOT_ADD_IFACE_DUE_TO_MAC_DUPLICATES; Collection<String> replacements = ReplacementUtils.getListVariableAssignmentString(engineMessage, nicsUnableToBeImported); validate(new ValidationResult(engineMessage, replacements)); } return true; }

Target:
protected boolean validate() { macPool = getMacPool(); if (getCluster() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_CLUSTER_CAN_NOT_BE_EMPTY); } List<VmNetworkInterface> nicsUnableToBeImported = getVm().getInterfaces() .stream() .filter(this::ifaceMacCannotBeAddedToMacPool) .collect(Collectors.toList()); if (!nicsUnableToBeImported.isEmpty()) { EngineMessage engineMessage = EngineMessage.ACTION_TYPE_FAILED_CANNOT_ADD_IFACE_DUE_TO_MAC_DUPLICATES; Collection<String> replacements = ReplacementUtils.getListVariableAssignmentString(engineMessage, nicsUnableToBeImported); return validate(new ValidationResult(engineMessage, replacements)); } return true; }
Source:
private SortedMap<String, RefRightsForPattern> retainExclusives( SortedMap<String, RefRightsForPattern> perPatternRights) { SortedMap<String, RefRightsForPattern> rights = new TreeMap<String, RefRightsForPattern>(); for (Iterator iterator = perPatternRights.entrySet().iterator(); iterator .hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); RefRightsForPattern patternRights = (RefRightsForPattern) entry.getValue(); if (patternRights.containsExclusive()) { rights.put((String) entry.getKey(), patternRights); } } return rights; }

Target:
private SortedMap<String, RefRightsForPattern> retainExclusives( SortedMap<String, RefRightsForPattern> perPatternRights) { SortedMap<String, RefRightsForPattern> rights = new TreeMap<String, RefRightsForPattern>(); for (Map.Entry<String, RefRightsForPattern> entry : perPatternRights.entrySet()) { RefRightsForPattern patternRights = (RefRightsForPattern) entry.getValue(); if (patternRights.containsExclusive()) { rights.put((String) entry.getKey(), patternRights); } } return rights; }
Source:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); try { expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class); } catch (IllegalArgumentException e) { assertEquals("Raw expression should be a string", e.getMessage()); } try { expressionEvaluator.evaluateUnaryExpression("! true", null, null); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("Impossible to parse the expression")); } }

Target:
public void evaluateUnaryExpression() { assertTrue(expressionEvaluator.evaluateUnaryExpression("not( true )", false, boolean.class)); assertTrue(expressionEvaluator.evaluateUnaryExpression(">2, >5", BigDecimal.valueOf(6), BigDecimal.class)); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression(new Object(), null, Object.class)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Raw expression should be a string"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("variable", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Error during evaluation:"); assertThatThrownBy(() -> expressionEvaluator.evaluateUnaryExpression("! true", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Syntax error:"); }
Source:
public void testImportVMFromConfigurationWhenStorageDomainIsInactive() { initCommand(getOvfEntityData()); StorageDomain storageDomain = createStorageDomain(); storageDomain.setStatus(StorageDomainStatus.Inactive); doReturn(storageDomain).when(cmd).getStorageDomain(); assertFalse(cmd.canDoAction()); }

Target:
public void testImportVMFromConfigurationWhenStorageDomainIsInactive() { initCommand(getOvfEntityData()); StorageDomain storageDomain = createStorageDomain(); storageDomain.setStatus(StorageDomainStatus.Inactive); doReturn(storageDomain).when(cmd).getStorageDomain(); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); }
Source:
public Object get(DataFetchingEnvironment env) { User user = MutationHelpers.getUser(env); String dataSetName = env.getArgument("dataSetName"); String capabilityListUri = env.getArgument("capabilityListUri"); String userSpecifiedDataSet = env.getArgument("userSpecifiedDataSet"); DataSet dataSet; ResourceSyncImport.ResourceSyncReport resourceSyncReport = null; try { dataSet = dataSetRepository.createDataSet(user, dataSetName); ResourceSyncImport resourceSyncImport = new ResourceSyncImport(resourceSyncFileLoader, dataSet, false); resourceSyncReport = resourceSyncImport.filterAndImport(capabilityListUri, userSpecifiedDataSet); } catch (DataStoreCreationException | IllegalDataSetNameException | IOException | CantRetrieveFileException | CantDetermineDataSetException e) { LOG.error("Failed to do a resource sync import. ", e); throw new RuntimeException(e); } return new DataSetWithDatabase(dataSet); }

Target:
public Object get(DataFetchingEnvironment env) { User user = MutationHelpers.getUser(env); String dataSetName = env.getArgument("dataSetName"); String capabilityListUri = env.getArgument("capabilityListUri"); String userSpecifiedDataSet = env.getArgument("userSpecifiedDataSet"); String authString = env.getArgument("authorization"); try { ImportInfo importInfo = new ImportInfo(capabilityListUri, Date.from(Instant.now())); DataSet dataSet = dataSetRepository.createDataSet(user, dataSetName, Lists.newArrayList(importInfo)); ResourceSyncImport resourceSyncImport = new ResourceSyncImport(resourceSyncFileLoader, dataSet, false); return resourceSyncImport.filterAndImport( capabilityListUri, userSpecifiedDataSet, false, authString ); } catch (DataStoreCreationException | IllegalDataSetNameException | IOException | CantRetrieveFileException | CantDetermineDataSetException e) { LOG.error("Failed to do a resource sync import. ", e); throw new RuntimeException(e); } }
Source:
private static List<MediaDB> getAllInLocal() { return new Select(). from(MediaDB.class). where(MediaDB_Table.filename.isNotNull()). and(MediaDB_Table.resource_url.isNotNull()). orderBy(MediaDB_Table.id_media, true). queryList(); }

Target:
private List<MediaDB> getAllInLocal() { return new Select(). from(MediaDB.class). where(MediaDB_Table.filename.isNotNull()). and(MediaDB_Table.resource_url.isNotNull()). orderBy(MediaDB_Table.id_media, true). queryList(); }
Source:
private void sanityCheckFragmentedPlan(SubPlan subPlan, WarningCollector warningCollector, int maxStageCount, int stageCountSoftLimit) { subPlan.sanityCheck(); int fragmentCount = subPlan.getAllFragments().size(); if (fragmentCount > maxStageCount) { throw new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the allowed maximum (%s). " + "If the query contains multiple DISTINCTs, please set the use_mark_distinct session property to false. " + "If the query contains multiple CTEs that are referenced more than once, please create temporary table(s) for one or more of the CTEs.", fragmentCount, maxStageCount)); } if (fragmentCount > stageCountSoftLimit) { warningCollector.add(new PrestoWarning(TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the soft limit (%s). " + "If the query contains multiple DISTINCTs, please set the use_mark_distinct session property to false. " + "If the query contains multiple CTEs that are referenced more than once, please create temporary table(s) for one or more of the CTEs.", fragmentCount, stageCountSoftLimit))); } }

Target:
private void sanityCheckFragmentedPlan(SubPlan subPlan, WarningCollector warningCollector, int maxStageCount, int stageCountSoftLimit) { subPlan.sanityCheck(); int fragmentCount = subPlan.getAllFragments().size(); if (fragmentCount > maxStageCount) { throw new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the allowed maximum (%s). " + TOO_MANY_STAGES_MESSAGE, fragmentCount, maxStageCount)); } if (fragmentCount > stageCountSoftLimit) { warningCollector.add(new PrestoWarning(TOO_MANY_STAGES, format( "Number of stages in the query (%s) exceeds the soft limit (%s). " + TOO_MANY_STAGES_MESSAGE, fragmentCount, stageCountSoftLimit))); } }
Source:
void clear() { Arrays.fill(sparse, Integer.MAX_VALUE); size = 0; }

Target:
void clear() { size = 0; }
Source:
public void onStart(ISuite suite) { if (!hasResultVersionSpecified() || !hasZapiRegexCycleSpecified()) { logger.info("ResultVersion and/or ZapiCycleRegex not set. " + "Skipping CreateJiraCycleListener as it is not needed..."); return; } final String targetProjectKey = getProjectKey(suite); final List<String> jiraTestLinksInSuite = getAllTestLinksInSuite(suite); final ProjectDto targetProjectDto = jiraService.project().getProject(targetProjectKey); createExecutionCyclesInJiraIfNeeded(targetProjectDto, jiraTestLinksInSuite); }

Target:
public void onStart(ISuite suite) { if (!hasResultVersionSpecified() || !hasZapiRegexCycleSpecified()) { logger.info("ResultVersion and/or ZapiCycleRegex was not set. " + "Skipping automated creation of JIRA version and Zephyr cycle as it is not needed..."); return; } final String targetProjectKey = getProjectKey(suite); final List<String> jiraTestLinksInSuite = getAllTestLinksInSuite(suite); final ProjectDto targetProjectDto = jiraService.project().getProject(targetProjectKey); createExecutionCyclesInJiraIfNeeded(targetProjectDto, jiraTestLinksInSuite); }
Source:
protected Map<String, String> getRecordFilterOptions() { Map<String, String> ret = new HashMap<>(); ConfigurationService configuration = Framework.getService(ConfigurationService.class); String value = configuration.getString(COMPUTATION_FILTER_STORE_KEY).orElse(null); if (value != null) { ret.put(STORE_NAME_OPTION, value); } value = configuration.getString(COMPUTATION_FILTER_PREFIX_KEY).orElse(null); if (value != null) { ret.put(PREFIX_OPTION, value); } Integer intValue = configuration.getInteger(COMPUTATION_FILTER_THRESHOLD_SIZE_KEY).orElse(null); if (intValue != null) { ret.put(THRESHOLD_SIZE_OPTION, intValue.toString()); } Duration duration = configuration.getDuration(COMPUTATION_FILTER_STORE_TTL_KEY).orElse(null); if (duration != null) { ret.put(STORE_TTL_OPTION, Long.toString(duration.toSeconds())); } return ret; }

Target:
protected Map<String, String> getRecordFilterOptions() { Map<String, String> ret = new HashMap<>(); ConfigurationService configuration = Framework.getService(ConfigurationService.class); configuration.getString(COMPUTATION_FILTER_STORE_KEY).ifPresent(value -> ret.put(STORE_NAME_OPTION, value)); configuration.getString(COMPUTATION_FILTER_PREFIX_KEY).ifPresent(value -> ret.put(PREFIX_OPTION, value)); configuration.getInteger(COMPUTATION_FILTER_THRESHOLD_SIZE_KEY) .ifPresent(value -> ret.put(THRESHOLD_SIZE_OPTION, value.toString())); configuration.getString(COMPUTATION_FILTER_STORE_TTL_KEY).ifPresent(value -> ret.put(STORE_TTL_OPTION, value)); return ret; }
Source:
public void disconnect() throws NotConnectedException, PermissionException { try { restApi().disconnect(sid); } catch (Exception e2) { throwNCEOrPE(e2); } initialized = false; }

Target:
public void disconnect() throws NotConnectedException, PermissionException { try { restApi().disconnect(sid); } catch (Exception e) { throwNCEOrPE(e); } initialized = false; }
Source:
private void removeImages() { for (final DiskImage source : getSourceImages()) { if (source.getDiskStorageType() == DiskStorageType.CINDER) { ImagesContainterParametersBase params = buildChildCommandParameters(source); Future<VdcReturnValueBase> future = CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.RemoveCinderSnapshotDisk, params, cloneContextAndDetachFromParent()); try { VdcReturnValueBase vdcReturnValueBase = future.get(); if (!vdcReturnValueBase.getSucceeded()) { log.error("Error removing snapshot for Cinder disk '{}'", source.getDiskAlias()); } } catch (InterruptedException | ExecutionException e) { log.error("Error removing snapshot for Cinder disk '{}': {}", source.getDiskAlias(), e.getMessage()); } continue; } List<DiskImage> images = getDiskImageDao().getAllSnapshotsForParent(source.getImageId()); DiskImage dest = null; if (!images.isEmpty()) { dest = images.get(0); } if (getSnapshotActionType() == VdcActionType.RemoveSnapshotSingleDisk) { VdcReturnValueBase vdcReturnValue = runInternalActionWithTasksContext( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest)); if (vdcReturnValue != null && vdcReturnValue.getInternalVdsmTaskIdList() != null) { getReturnValue().getVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } } else { CommandCoordinatorUtil.executeAsyncCommand( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest), cloneContextAndDetachFromParent()); } List<Guid> quotasToRemoveFromCache = new ArrayList<>(); quotasToRemoveFromCache.add(source.getQuotaId()); if (dest != null) { quotasToRemoveFromCache.add(dest.getQuotaId()); } getQuotaManager().removeQuotaFromCache(getStoragePoolId(), quotasToRemoveFromCache); } }

Target:
private void removeImages() { for (final DiskImage source : getSourceImages()) { if (source.getDiskStorageType() == DiskStorageType.CINDER) { handleCinderSnapshotDisk(source); continue; } List<DiskImage> images = getDiskImageDao().getAllSnapshotsForParent(source.getImageId()); DiskImage dest = null; if (!images.isEmpty()) { dest = images.get(0); } if (getSnapshotActionType() == VdcActionType.RemoveSnapshotSingleDisk) { VdcReturnValueBase vdcReturnValue = runInternalActionWithTasksContext( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest)); if (vdcReturnValue != null && vdcReturnValue.getInternalVdsmTaskIdList() != null) { getReturnValue().getVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } } else { CommandCoordinatorUtil.executeAsyncCommand( getSnapshotActionType(), buildRemoveSnapshotSingleDiskParameters(source, dest), cloneContextAndDetachFromParent()); } List<Guid> quotasToRemoveFromCache = new ArrayList<>(); quotasToRemoveFromCache.add(source.getQuotaId()); if (dest != null) { quotasToRemoveFromCache.add(dest.getQuotaId()); } getQuotaManager().removeQuotaFromCache(getStoragePoolId(), quotasToRemoveFromCache); } }
Source:
public void serialize(TypeToken<?> type, TextTemplate obj, ConfigurationNode value) throws ObjectMappingException { value.getNode(NODE_OPTIONS, NODE_OPEN_ARG).setValue(obj.getOpenArgString()); value.getNode(NODE_OPTIONS, NODE_CLOSE_ARG).setValue(obj.getCloseArgString()); value.getNode(NODE_ARGS).setValue(new TypeToken<Map<String, TextTemplate.Arg>>() {}, obj.getArguments()); value.getNode(NODE_CONTENT).setValue(TypeToken.of(Text.class), obj.toText()); }

Target:
public void serialize(TypeToken<?> type, TextTemplate obj, ConfigurationNode value) throws ObjectMappingException { value.getNode(NODE_OPTIONS, NODE_OPEN_ARG).setValue(obj.getOpenArgString()); value.getNode(NODE_OPTIONS, NODE_CLOSE_ARG).setValue(obj.getCloseArgString()); value.getNode(NODE_ARGS).setValue(TOKEN_ARGS, obj.getArguments()); value.getNode(NODE_CONTENT).setValue(TOKEN_TEXT, obj.toText()); }
Source:
private Collection<File> getPluginFiles() throws IOException { if (pluginsDir == null || !pluginsDir.exists()) { return Collections.emptyList(); } return FileUtils.listFiles(pluginsDir, new String[] {"jar"}, false); }

Target:
private List<File> getPluginFiles() throws IOException { if (pluginsDir == null || !pluginsDir.exists()) { return Collections.emptyList(); } return Arrays.asList(pluginsDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } })); }
Source:
public static synchronized CompiledPlan getCompiledPlanCalcite(SchemaPlus schemaPlus, SqlNode sqlNode) throws ValidationException, RelConversionException, PlannerFallbackException{ VoltPlanner planner = new VoltPlanner(schemaPlus); SqlNode validatedNode = planner.validate(sqlNode); RelNode rel = planner.convert(validatedNode); compileLog.info("ORIGINAL\n" + RelOptUtil.toString(rel)); RelTraitSet requiredLogicalOutputTraits = planner.getEmptyTraitSet().replace(VoltLogicalRel.CONVENTION); RelNode transformed = planner.transform( Phase.LOGICAL.ordinal(), requiredLogicalOutputTraits, rel); compileLog.info("LOGICAL\n" + RelOptUtil.toString(transformed)); planner.addRelTraitDef(RelDistributionTraitDef.INSTANCE); transformed = VoltRelUtil.addTraitRecurcively(transformed, RelDistributions.ANY); transformed = VoltPlanner.transformHep(Phase.MP_FALLBACK, transformed); RelTraitSet requiredPhysicalOutputTraits = transformed.getTraitSet() .replace(VoltPhysicalRel.CONVENTION) .replace(RelDistributions.ANY); transformed = planner.transform(Phase.PHYSICAL_CONVERSION.ordinal(), requiredPhysicalOutputTraits, transformed); transformed = VoltPlanner.transformHep(Phase.INLINE, HepMatchOrder.ARBITRARY, transformed, true); CompiledPlan compiledPlan = new CompiledPlan(false); calciteToVoltDBPlan((VoltPhysicalRel) transformed, compiledPlan); compiledPlan.explainedPlan = compiledPlan.rootPlanGraph.toExplainPlanString(); compiledPlan.resetPlanNodeIds(1); return compiledPlan; }

Target:
public static synchronized CompiledPlan getCompiledPlanCalcite(SchemaPlus schemaPlus, SqlNode sqlNode) throws ValidationException, RelConversionException, PlannerFallbackException{ VoltPlanner planner = new VoltPlanner(schemaPlus); SqlNode validatedNode = planner.validate(sqlNode); RelNode rel = planner.convert(validatedNode); compileLog.info("ORIGINAL\n" + RelOptUtil.toString(rel)); RelTraitSet requiredLogicalOutputTraits = planner.getEmptyTraitSet().replace(VoltLogicalRel.CONVENTION); RelNode transformed = planner.transform( Phase.LOGICAL.ordinal(), requiredLogicalOutputTraits, rel); compileLog.info("LOGICAL\n" + RelOptUtil.toString(transformed)); planner.addRelTraitDef(RelDistributionTraitDef.INSTANCE); transformed = VoltRelUtil.addTraitRecursively(transformed, RelDistributions.ANY); transformed = VoltPlanner.transformHep(Phase.MP_FALLBACK, transformed); RelTraitSet requiredPhysicalOutputTraits = transformed.getTraitSet() .replace(VoltPhysicalRel.CONVENTION) .replace(RelDistributions.ANY); transformed = planner.transform(Phase.PHYSICAL_CONVERSION.ordinal(), requiredPhysicalOutputTraits, transformed); transformed = VoltPlanner.transformHep(Phase.INLINE, HepMatchOrder.ARBITRARY, transformed, true); CompiledPlan compiledPlan = new CompiledPlan(false); try { calciteToVoltDBPlan((VoltPhysicalRel) transformed, compiledPlan); compiledPlan.explainedPlan = compiledPlan.rootPlanGraph.toExplainPlanString(); compiledPlan.resetPlanNodeIds(1); } catch (Exception e){ throw new PlannerFallbackException(e.getMessage()); } planner.close(); fragmentizePlan(compiledPlan); return compiledPlan; }
Source:
public void afterRefreshTreatment() { try { prometheusClient.close(); } catch (IOException e) { } }

Target:
public void afterRefreshTreatment() { try { if (prometheusClient != null) { prometheusClient.close(); } } catch (IOException e) { } }
Source:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); InstructorCreateRequest instructorRequest = getAndValidateRequestBody(InstructorCreateRequest.class); InstructorAttributes instructorToEdit = extractUpdatedInstructor(courseId, instructorRequest); updateToEnsureValidityOfInstructorsForTheCourse(courseId, instructorToEdit); try { if (instructorRequest.getId() == null) { logic.updateInstructor( InstructorAttributes .updateOptionsWithEmailBuilder(instructorToEdit.courseId, instructorRequest.getEmail()) .withName(instructorToEdit.name) .withDisplayedName(instructorToEdit.displayedName) .withIsDisplayedToStudents(instructorToEdit.isDisplayedToStudents) .withPrivileges(instructorToEdit.privileges) .withRole(instructorToEdit.role) .build()); } else { logic.updateInstructorCascade( InstructorAttributes .updateOptionsWithGoogleIdBuilder(instructorToEdit.courseId, instructorRequest.getId()) .withEmail(instructorToEdit.email) .withName(instructorToEdit.name) .withDisplayedName(instructorToEdit.displayedName) .withIsDisplayedToStudents(instructorToEdit.isDisplayedToStudents) .withPrivileges(instructorToEdit.privileges) .withRole(instructorToEdit.role) .build()); } } catch (InvalidParametersException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityDoesNotExistException ednee) { return new JsonResult(ednee.getMessage(), HttpStatus.SC_NOT_FOUND); } return new JsonResult("The changes to the instructor " + instructorRequest.getName() + " has been updated.", HttpStatus.SC_OK); }

Target:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); InstructorCreateRequest instructorRequest = getAndValidateRequestBody(InstructorCreateRequest.class); InstructorAttributes instructorToEdit = extractUpdatedInstructor(courseId, instructorRequest); updateToEnsureValidityOfInstructorsForTheCourse(courseId, instructorToEdit); try { if (instructorRequest.getId() == null) { logic.updateInstructor( InstructorAttributes .updateOptionsWithEmailBuilder(instructorToEdit.courseId, instructorRequest.getEmail()) .withName(instructorToEdit.name) .withDisplayedName(instructorToEdit.displayedName) .withIsDisplayedToStudents(instructorToEdit.isDisplayedToStudents) .withPrivileges(instructorToEdit.privileges) .withRole(instructorToEdit.role) .build()); } else { logic.updateInstructorCascade( InstructorAttributes .updateOptionsWithGoogleIdBuilder(instructorToEdit.courseId, instructorRequest.getId()) .withEmail(instructorToEdit.email) .withName(instructorToEdit.name) .withDisplayedName(instructorToEdit.displayedName) .withIsDisplayedToStudents(instructorToEdit.isDisplayedToStudents) .withPrivileges(instructorToEdit.privileges) .withRole(instructorToEdit.role) .build()); } } catch (InvalidParametersException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityDoesNotExistException ednee) { return new JsonResult(ednee.getMessage(), HttpStatus.SC_NOT_FOUND); } return new JsonResult("The instructor " + instructorRequest.getName() + " has been updated.", HttpStatus.SC_OK); }
Source:
public List<T> getFreeNodes() { List<T> result = Lists.newArrayList(); result.addAll(difference(m_nodesReady, m_outgoingEdges.keySet())); if (result.isEmpty() && m_nodesRunning.isEmpty()) { int lowestPriority = getLowestEdgeWeight(m_nodesReady); for (T node : m_nodesReady) { if (hasAllEdgesWithWeight(m_outgoingEdges, node, lowestPriority)) { result.add(node); } } } List<T> finalResult = Lists.newArrayList(); for (T node : result) { Map<T, Integer> edges = m_outgoingEdges.get(node); if (edges == null || Collections.disjoint(edges.keySet(), result)) { finalResult.add(node); } } return finalResult; }

Target:
public List<T> getFreeNodes() { Set<T> free = Sets.newLinkedHashSet(m_nodesReady); free.removeAll(m_edges.fromNodes()); if (free.isEmpty() && m_nodesRunning.isEmpty()) { int lowestWeight = m_edges.getLowestEdgeWeight(m_nodesReady); for (T node : m_nodesReady) { if (m_edges.hasAllEdgesWithWeight(node, lowestWeight)) { free.add(node); } } } List<T> finalResult = Lists.newArrayList(); for (T node : free) { Map<T, Integer> edges = m_edges.from(node); if (edges == null || Collections.disjoint(edges.keySet(), free)) { finalResult.add(node); } } return finalResult; }
Source:
Mono<Response<Document>> getDocumentWithResponse( String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { return restClient .documents() .getWithRestResponseAsync(key, selectedFields, requestOptions, context) .map(res -> { Document doc = res.getValue(); DocumentResponseConversions.cleanupDocument(doc); return new SimpleResponse<>(res, doc); }) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(Function.identity()); }

Target:
Mono<Response<Document>> getDocumentWithResponse( String key, List<String> selectedFields, RequestOptions requestOptions, Context context) { try { return restClient .documents() .getWithRestResponseAsync(key, selectedFields, requestOptions, context) .map(res -> { Document doc = res.getValue(); DocumentResponseConversions.cleanupDocument(doc); return new SimpleResponse<>(res, doc); }) .onErrorMap(DocumentResponseConversions::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } }
Source:
private void loadMachineUUID() { if (System.getProperty(PROP_UUID) != null) return; String uuid = loadExistingUUID(); if (uuid == null) { uuid = UUID.randomUUID().toString(); saveUUID(uuid); } EnvironmentInfo environment = environmentTracker.getService(); if (environment != null) { environment.setProperty(PROP_UUID, uuid); } else { System.setProperty(PROP_UUID, uuid); } }

Target:
private void loadMachineUUID() { EnvironmentInfo environment = environmentTracker.getService(); if (environment != null) { if (environment.getProperty(PROP_UUID) != null) return; } String uuid = loadExistingUUID(); if (uuid == null) { uuid = UUID.randomUUID().toString(); saveUUID(uuid); } if (environment != null) { environment.setProperty(PROP_UUID, uuid); } else { System.setProperty(PROP_UUID, uuid); } }
Source:
public TypedValueSelector makeSelectorForType(final String type) { if (BuiltInType.DATE.getName().equals(type)) { return dateSelector; } return genericSelector; }

Target:
public TypedValueSelector makeSelectorForType(final String type) { if (Objects.equals(BuiltInType.DATE.getName(), type)) { return dateSelector; } return genericSelector; }
Source:
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); return (HttpAction) currentClient.redirect(context).get(); }

Target:
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); return currentClient.redirect(context); }
Source:
private String randomTwoChoices() { int randomPosition = ThreadLocalRandom.current().nextInt(activeNodes.size()); int randomOffset = ThreadLocalRandom.current().nextInt(1, activeNodes.size()); String candidate1 = activeNodes.get(randomPosition); String candidate2 = activeNodes.get((randomPosition + randomOffset) % activeNodes.size()); if (nodeBucketCounts.get(candidate2) < nodeBucketCounts.get(candidate1)) { candidate1 = candidate2; } return candidate1; }

Target:
private String randomTwoChoices() { int randomPosition = ThreadLocalRandom.current().nextInt(activeNodes.size()); int randomOffset = ThreadLocalRandom.current().nextInt(1, activeNodes.size()); String candidate1 = activeNodes.get(randomPosition); String candidate2 = activeNodes.get((randomPosition + randomOffset) % activeNodes.size()); return (nodeBucketCounts.get(candidate1) <= nodeBucketCounts.get(candidate2)) ? candidate1 : candidate2; }
Source:
public void testOSVersion() { SystemInfo si = new SystemInfo(); OperatingSystem os = si.getOperatingSystem(); assertNotNull(os.getFamily()); assertNotNull(os.getManufacturer()); OperatingSystemVersion version = os.getVersion(); assertNotNull(version); assertNotNull(version.getVersion()); assertNotNull(version.getCodeName()); assertNotNull(version.getBuildNumber()); assertTrue(os.getOpenDescriptors() >= -1L); assertTrue(os.getMaxDescriptors() >= -1L); }

Target:
public void testOSVersion() { SystemInfo si = new SystemInfo(); OperatingSystem os = si.getOperatingSystem(); assertNotNull(os.getFamily()); assertNotNull(os.getManufacturer()); OperatingSystemVersion version = os.getVersion(); assertNotNull(version); assertNotNull(version.getVersion()); assertNotNull(version.getCodeName()); assertNotNull(version.getBuildNumber()); }
Source:
public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, List<InstructorAttributes> instructorsToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION .replace("${status}", FEEDBACK_STATUS_SESSION_OPEN); StringBuffer additionalContactInformation = new StringBuffer(getAdditionalContactInformationFragment(course)); additionalContactInformation.insert(0, HTML_NO_ACTION_REQUIRED); List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorsToNotify, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject(), FEEDBACK_ACTION_SUBMIT, additionalContactInformation.toString())); return emails; }

Target:
public List<EmailWrapper> generateFeedbackSessionReminderEmails( FeedbackSessionAttributes session, List<StudentAttributes> students, List<InstructorAttributes> instructorsToRemind, List<InstructorAttributes> instructorsToNotify) { CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_OPEN); String additionalContactInformation = HTML_NO_ACTION_REQUIRED + getAdditionalContactInformationFragment(course); List<EmailWrapper> emails = generateFeedbackSessionEmailBasesForInstructorReminders(course, session, instructorsToRemind, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject()); emails.addAll(generateFeedbackSessionEmailBases(course, session, students, instructorsToNotify, template, EmailType.FEEDBACK_SESSION_REMINDER.getSubject(), FEEDBACK_ACTION_SUBMIT, additionalContactInformation)); return emails; }
Source:
public List<StudyEntryDto> getStudyEntries(final int studyId, final StudyEntrySearchDto.Filter filter, final Pageable pageable) { final Integer plotDatasetId = datasetService.getDatasets(studyId, new HashSet<>(Arrays.asList(DatasetTypeEnum.PLOT_DATA.getId()))).get(0).getDatasetId(); final List<MeasurementVariable> entryDescriptors = this.datasetService.getObservationSetVariables(plotDatasetId, Lists .newArrayList(VariableType.GERMPLASM_DESCRIPTOR.getId())); final List<Integer> termsToRemove = Lists .newArrayList(TermId.ENTRY_CODE.getId(), TermId.DESIG.getId(), TermId.ENTRY_NO.getId(), TermId.GID.getId(), TermId.OBS_UNIT_ID.getId(), TermId.STOCKID.getId()); for (Iterator<MeasurementVariable> i = entryDescriptors.iterator(); i.hasNext(); ) { final MeasurementVariable measurementVariable = i.next(); if (termsToRemove.contains(measurementVariable.getTermId())) { i.remove(); } } final List<StudyEntryDto> studyEntryDtos = this.daoFactory.getStockDao().getStudyEntries(new StudyEntrySearchDto(studyId, entryDescriptors, filter), pageable); return studyEntryDtos; }

Target:
public List<StudyEntryDto> getStudyEntries(final int studyId, final StudyEntrySearchDto.Filter filter, final Pageable pageable) { final Integer plotDatasetId = datasetService.getDatasets(studyId, new HashSet<>(Collections.singletonList(DatasetTypeEnum.PLOT_DATA.getId()))).get(0).getDatasetId(); final List<MeasurementVariable> entryDescriptors = this.datasetService.getObservationSetVariables(plotDatasetId, Lists .newArrayList(VariableType.GERMPLASM_DESCRIPTOR.getId())); final List<MeasurementVariable> fixedEntryDescriptors = entryDescriptors.stream().filter(d -> FIXED_GERMPLASM_DESCRIPTOR_IDS.contains(d.getTermId())).collect( Collectors.toList()); final List<MeasurementVariable> variableEntryDescriptors = entryDescriptors.stream().filter(d -> !REMOVABLE_GERMPLASM_DESCRIPTOR_IDS.contains(d.getTermId())).collect( Collectors.toList()); return this.daoFactory.getStockDao() .getStudyEntries(new StudyEntrySearchDto(studyId, fixedEntryDescriptors, variableEntryDescriptors, filter), pageable); }
Source:
private static <C extends JdbiConfig<C>> C create(Class<C> configClass) { try { return configClass.newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Unable to instantiate config class " + configClass + ". Is there a public no-arg constructor?"); } }

Target:
private static <C extends JdbiConfig<C>> C create(Class<C> configClass) { try { return configClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Unable to instantiate config class " + configClass + ". Is there a public no-arg constructor?"); } }
Source:
public List<Location> getLocationsByType(final Integer type) throws MiddlewareQueryException { return this.getAllByMethod(this.getLocationDao(), GET_BY_TYPE, new Object[] { type }, new Class[] { Integer.class }); }

Target:
public List<Location> getLocationsByType(final Integer type) throws MiddlewareQueryException { return this.getAllByMethod(this.getLocationDao(), LocationDataManagerImpl.GET_BY_TYPE, new Object[] { type }, new Class[] { Integer.class }); }
Source:
private MetricsQuery buildCountComparisonQuery(final Task task) { final Consumer<Metric.Builder> setCommonFields = builder -> builder .setAggregators(ImmutableList.of( new Aggregator.Builder() .setName("count") .setSampling(new Sampling.Builder().setUnit(task.getPeriod().getSamplingUnit()).setValue(1).build()) .setAlignSampling(true) .setAlignStartTime(true) .build()) ); return new MetricsQuery.Builder() .setStartTime(task.getStartTime()) .setEndTime(task.getStartTime().plus(task.getPeriod().periodCountToDuration(1)).minusMillis(1)) .setMetrics(ImmutableList.of( ThreadLocalBuilder.build(Metric.Builder.class, b -> { setCommonFields.accept(b); b.setName(task.getSourceMetricName()); }), ThreadLocalBuilder.build(Metric.Builder.class, b -> { setCommonFields.accept(b); b.setName(task.getRollupMetricName()); }) )).build(); }

Target:
private MetricsQuery buildCountComparisonQuery(final Task task) { final Consumer<Metric.Builder> setCommonFields = builder -> builder .setAggregators(ImmutableList.of( ThreadLocalBuilder.build(Aggregator.Builder.class, aggb -> aggb .setName("count") .setSampling(ThreadLocalBuilder.build(Sampling.Builder.class, sb -> sb .setUnit(task.getPeriod().getSamplingUnit()).setValue(1).build() )) .setAlignSampling(true) .setAlignStartTime(true) )) ); return ThreadLocalBuilder.build(MetricsQuery.Builder.class, mqb -> mqb .setStartTime(task.getStartTime()) .setEndTime(task.getStartTime().plus(task.getPeriod().periodCountToDuration(1)).minusMillis(1)) .setMetrics(ImmutableList.of( ThreadLocalBuilder.build(Metric.Builder.class, mb -> { setCommonFields.accept(mb); mb.setName(task.getSourceMetricName()); }), ThreadLocalBuilder.build(Metric.Builder.class, mb -> { setCommonFields.accept(mb); mb.setName(task.getRollupMetricName()); }) )) ); }
Source:
public void testBadSegmentSubResourceNumber() throws UnsupportedEncodingException, URISyntaxException { String requestPath = "/mediaexpectedOpOrId/Segment/notAnInteger"; List<String> prefixesToRemove = new ArrayList<>(); RestRequest restRequest = RestUtilsTest.createRestRequest(RestMethod.GET, requestPath, null); try { RequestPath.parse(restRequest, prefixesToRemove, CLUSTER_NAME); } catch (RestServiceException e) { assertTrue(e.getErrorCode().equals(RestServiceErrorCode.BadRequest)); return; } fail(); }

Target:
public void testBadSegmentSubResourceNumber() throws UnsupportedEncodingException, URISyntaxException { String requestPath = "/mediaexpectedOpOrId/Segment/notAnInteger"; List<String> prefixesToRemove = new ArrayList<>(); RestRequest restRequest = RestUtilsTest.createRestRequest(RestMethod.GET, requestPath, null); try { RequestPath.parse(restRequest, prefixesToRemove, CLUSTER_NAME); fail(); } catch (RestServiceException e) { assertTrue(e.getErrorCode().equals(RestServiceErrorCode.BadRequest)); } }
Source:
public synchronized void activate(Cluster maybeUpdatedCluster, String licenseContent) { if (isActivated()) { throw new IllegalStateException("Node is already activated"); } LOGGER.info("Preparing activation of cluster: {}", maybeUpdatedCluster.toShapeString()); if (findMe(maybeUpdatedCluster) == null) { throw new IllegalArgumentException(String.format( "No match found for node: %s in cluster topology: %s", upcomingNodeContext.getNodeUID(), maybeUpdatedCluster )); } this.setUpcomingCluster(maybeUpdatedCluster); this.installLicense(licenseContent); LOGGER.info("Preparing activation of Node with validated topology: {}", upcomingNodeContext.getCluster().toShapeString()); nomadServerManager.upgradeForWrite(); LOGGER.debug("Setting nomad writable successful"); clusterActivated = true; LOGGER.info("Node activation successful"); warnIfProblematicConsistency(runtimeNodeContext); }

Target:
public synchronized void activate(Cluster maybeUpdatedCluster, String licenseContent) { if (isActivated()) { throw new IllegalStateException("Node is already activated"); } LOGGER.info("Preparing activation of cluster: {}", maybeUpdatedCluster.toShapeString()); if (findMe(maybeUpdatedCluster) == null) { throw new IllegalArgumentException(String.format( "No match found for node: %s in cluster topology: %s", upcomingNodeContext.getNodeUID(), maybeUpdatedCluster )); } this.setUpcomingCluster(maybeUpdatedCluster); this.installLicense(licenseContent); LOGGER.info("Preparing activation of Node with validated topology: {}", upcomingNodeContext.getCluster().toShapeString()); nomadServerManager.upgradeForWrite(); LOGGER.debug("Setting nomad writable successful"); clusterActivated = true; LOGGER.info("Node activation successful"); warnIfProblematicConsistency(upcomingNodeContext); }
Source:
public Collection<IDataProviderDescriptor> getDescriptors(ITmfTrace trace) { Iterable<ISegmentStoreProvider> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ISegmentStoreProvider.class); List<IDataProviderDescriptor> descriptors = new ArrayList<>(); Set<String> existingModules = new HashSet<>(); for (ISegmentStoreProvider module : modules) { IAnalysisModule analysis = (IAnalysisModule) module; if (!existingModules.contains(analysis.getId())) { DataProviderDescriptor.Builder builder = new DataProviderDescriptor.Builder(); builder.setId(SegmentStoreScatterDataProvider.ID + ':' + analysis.getId()) .setName(Objects.requireNonNull(NLS.bind(Messages.SegmentStoreScatterGraphDataProvider_title, analysis.getName()))) .setDescription(Objects.requireNonNull(NLS.bind(Messages.SegmentStoreScatterGraphDataProvider_description, analysis.getName()))) .setProviderType(ProviderType.TREE_TIME_XY); descriptors.add(builder.build()); } } return descriptors; }

Target:
public Collection<IDataProviderDescriptor> getDescriptors(ITmfTrace trace) { Iterable<ISegmentStoreProvider> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ISegmentStoreProvider.class); List<IDataProviderDescriptor> descriptors = new ArrayList<>(); Set<String> existingModules = new HashSet<>(); for (ISegmentStoreProvider module : modules) { IAnalysisModule analysis = (IAnalysisModule) module; if (!existingModules.contains(analysis.getId())) { DataProviderDescriptor.Builder builder = new DataProviderDescriptor.Builder(); builder.setId(SegmentStoreScatterDataProvider.ID + DataProviderConstants.ID_SEPARATOR + analysis.getId()) .setName(Objects.requireNonNull(NLS.bind(Messages.SegmentStoreScatterGraphDataProvider_title, analysis.getName()))) .setDescription(Objects.requireNonNull(NLS.bind(Messages.SegmentStoreScatterGraphDataProvider_description, analysis.getHelpText()))) .setProviderType(ProviderType.TREE_TIME_XY); descriptors.add(builder.build()); } } return descriptors; }
Source:
public void start() { if (started) { return; } synchronized (startStopLock) { if (started) { return; } regionNormalizerTracker.start(); if (worker != null) { pool.submit(worker); } started = true; } }

Target:
public void start() { synchronized (startStopLock) { if (started) { return; } regionNormalizerTracker.start(); if (worker != null) { pool.submit(worker); } started = true; } }
Source:
public static Object getValue(Type type, Object value) { if (type.equals(BIGINT)) { return (long) value; } else if (type.equals(INTEGER)) { return ((Number) value).intValue(); } else if (type.equals(DOUBLE)) { return (double) value; } else if (type.equals(VARCHAR)) { return ((Slice) value).toStringUtf8(); } else if (type.equals(BOOLEAN)) { return (boolean) value; } else { throw new UnsupportedOperationException("Query Builder can't handle type: " + type); } }

Target:
private static Object getValue(Type type, Object value) { if (type.equals(BIGINT)) { return value; } else if (type.equals(INTEGER)) { return ((Number) value).intValue(); } else if (type.equals(DOUBLE)) { return value; } else if (type.equals(VARCHAR)) { return ((Slice) value).toStringUtf8(); } else if (type.equals(BOOLEAN)) { return value; } throw new UnsupportedOperationException("Query Builder can't handle type: " + type); }
Source:
private List<Path> getFileDirectoriesAsPaths() { List<Path> fileDirs = new ArrayList<>(); MetaData metaData = basePanel.getBibDatabaseContext().getMetaData(); metaData.getLaTexFileDirectory(prefs.getFilePreferences().getUser()) .ifPresent(LaTexFileDirectory -> fileDirs.add(Paths.get(LaTexFileDirectory).toAbsolutePath().normalize())); return fileDirs; }

Target:
private List<Path> getFileDirectoriesAsPaths() { List<Path> fileDirs = new ArrayList<>(); MetaData metaData = basePanel.getBibDatabaseContext().getMetaData(); metaData.getLaTexFileDirectory(prefs.getFilePreferences().getUser()) .ifPresent(laTexFileDirectory -> fileDirs.add(laTexFileDirectory)); return fileDirs; }
Source:
public UpdateWorker(@NonNull Context appContext, @NonNull WorkerParameters workerParams) { super(appContext, workerParams); restApi = RestServiceBuilder.createService(RestApi.class); logger = new OpenMRSLogger(); mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { String responseMessage; switch (msg.what) { case ON_SUCCESS: String UpdateSuccessPatientName = (String) msg.obj; ToastUtil.success("Patient " + UpdateSuccessPatientName + " updated"); break; case ON_FAILURE: String UpdateFailedPatientName = (String) msg.obj; ToastUtil.error("Patient " + UpdateFailedPatientName + " cannot be updated due to server error will retry sync "); break; case ON_SUCCESS_PHOTO_UPDATE: responseMessage = (String) msg.obj; ToastUtil.error("Patient photo cannot be synced due to server error: " + responseMessage); break; case ON_FAILURE_PHOTO_UPDATE: responseMessage = (String) msg.obj; ToastUtil.notify("Patient photo cannot be synced due to error: " + responseMessage); } super.handleMessage(msg); } }; }

Target:
public UpdateWorker(@NonNull Context appContext, @NonNull WorkerParameters workerParams) { super(appContext, workerParams); restApi = RestServiceBuilder.createService(RestApi.class); logger = new OpenMRSLogger(); mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { String responseMessage; switch (msg.what) { case ON_SUCCESS: String updateSuccessPatientName = (String) msg.obj; ToastUtil.success(Resources.getSystem().getString(R.string.patient_update_successful, updateSuccessPatientName)); break; case ON_FAILURE: String updateFailedPatientName = (String) msg.obj; ToastUtil.error(Resources.getSystem().getString(R.string.patient_update_unsuccessful, updateFailedPatientName)); break; case ON_UNSUCCESSFUL_RESPONSE_PHOTO_UPDATE: responseMessage = (String) msg.obj; ToastUtil.error(Resources.getSystem().getString(R.string.patient_photo_update_unsuccessful, responseMessage)); case ON_FAILURE_RESPONSE_PHOTO_UPDATE: responseMessage = (String) msg.obj; ToastUtil.notify(Resources.getSystem().getString(R.string.patient_photo_update_unsuccessful, responseMessage)); } super.handleMessage(msg); } }; }
Source:
public void loadDataWithBaseURL(@Nullable String baseUrl, String data, @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) { if (!AbstractFlashcardViewer.this.wasDestroyed()) { super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); } else { Timber.w("Now loading card - Activity is in the process of being destroyed."); } }

Target:
public void loadDataWithBaseURL(@Nullable String baseUrl, String data, @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) { if (!AbstractFlashcardViewer.this.wasDestroyed()) { super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); } else { Timber.w("Not loading card - Activity is in the process of being destroyed."); } }