auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public NewsSet getNewsSet(String fname, PortletRequest request) { PortletSession session = request.getPortletSession(); String userId = request.getRemoteUser(); if (userId == null) { userId = "guest"; } NewsSet set; Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { log.debug("Got Mutex: "+mutex); set = newsStore.getNewsSet(userId, fname); if (set == null) { log.debug("No existing set found for "+userId+", creating and saving new set."); set = new NewsSet(); set.setUserId(userId); set.setName(fname); newsStore.storeNewsSet(set); } if (session.getAttribute("setId", PortletSession.PORTLET_SCOPE) == null) { log.debug("re-initalising loaded newsSet "+set.getName()); @SuppressWarnings("unchecked") Set<String> roles = (Set<String>) session.getAttribute("userRoles", PortletSession.PORTLET_SCOPE); newsStore.initNews(set, roles); newsStore.storeNewsSet(set); session.setAttribute("setId", set.getId(), PortletSession.PORTLET_SCOPE); } } return set; }

Target:
public NewsSet getNewsSet(String fname, PortletRequest request) { PortletSession session = request.getPortletSession(); String userId = request.getRemoteUser(); if (userId == null) { userId = "guest"; } NewsSet set; Object mutex = PortletUtils.getSessionMutex(session); synchronized (mutex) { log.debug("Got Mutex: "+mutex); set = newsStore.getNewsSet(userId, fname); if (set == null) { log.debug("No existing set found for "+userId+", creating and saving new set."); set = new NewsSet(); set.setUserId(userId); set.setName(fname); newsStore.storeNewsSet(set); } if (session.getAttribute("setId", PortletSession.PORTLET_SCOPE) == null) { log.debug("re-initalising loaded newsSet "+set.getName()); @SuppressWarnings("unchecked") Set<String> roles = (Set<String>) session.getAttribute("userRoles", PortletSession.PORTLET_SCOPE); if(roles != null) { newsStore.initNews(set, roles); newsStore.storeNewsSet(set); session.setAttribute("setId", set.getId(), PortletSession.PORTLET_SCOPE); } } } return set; }
Source:
public double evaluate(double... values) throws EvaluationException { for (int i = 0; i < values.length; ++i) { final String variableName = variableNames[i]; final RValue invokable = variables.get(variableName); if (!(invokable instanceof Variable)) { throw new EvaluationException(invokable.getPosition(), "Tried to assign constant " + variableName + "."); } ((Variable) invokable).value = values[i]; } pushInstance(); try { Future<Double> result = evalThread.submit(new Callable<Double>() { @Override public Double call() throws Exception { return root.getValue(); } }); try { return result.get(WorldEdit.getInstance().getConfiguration().calculationTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ReturnException) { return ((ReturnException) cause).getValue(); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } catch (TimeoutException e) { result.cancel(true); throw new EvaluationException(-1, "Calculations exceeded time limit."); } } finally { popInstance(); } }

Target:
public double evaluate(double... values) throws EvaluationException { for (int i = 0; i < values.length; ++i) { final String variableName = variableNames[i]; final RValue invokable = variables.get(variableName); if (!(invokable instanceof Variable)) { throw new EvaluationException(invokable.getPosition(), "Tried to assign constant " + variableName + "."); } ((Variable) invokable).value = values[i]; } Future<Double> result = evalThread.submit(new Callable<Double>() { @Override public Double call() throws Exception { pushInstance(); try { return root.getValue(); } finally { popInstance(); } } }); try { return result.get(WorldEdit.getInstance().getConfiguration().calculationTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof ReturnException) { return ((ReturnException) cause).getValue(); } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } catch (TimeoutException e) { result.cancel(true); throw new EvaluationException(-1, "Calculations exceeded time limit."); } }
Source:
private List<JSONPathParser.FieldSpec> convertFieldSpecs(List<JSONPathFieldSpec> druidFieldSpecs) { List<JSONPathParser.FieldSpec> newSpecs = new ArrayList<>(); for(JSONPathFieldSpec druidSpec : druidFieldSpecs) { JSONPathParser.FieldType type; if (druidSpec.getType() == JSONPathFieldType.ROOT) { type = JSONPathParser.FieldType.ROOT; } else { type = JSONPathParser.FieldType.NESTED; } JSONPathParser.FieldSpec newSpec = new JSONPathParser.FieldSpec(type, druidSpec.getName(), druidSpec.getExpr()); newSpecs.add(newSpec); } return newSpecs; }

Target:
private List<JSONPathParser.FieldSpec> convertFieldSpecs(List<JSONPathFieldSpec> druidFieldSpecs) { List<JSONPathParser.FieldSpec> newSpecs = new ArrayList<>(); for (JSONPathFieldSpec druidSpec : druidFieldSpecs) { JSONPathParser.FieldType type; switch (druidSpec.getType()) { case ROOT: type = JSONPathParser.FieldType.ROOT; break; case PATH: type = JSONPathParser.FieldType.PATH; break; default: throw new IllegalArgumentException("Invalid type for field " + druidSpec.getName()); } JSONPathParser.FieldSpec newSpec = new JSONPathParser.FieldSpec( type, druidSpec.getName(), druidSpec.getExpr() ); newSpecs.add(newSpec); } return newSpecs; }
Source:
public void startGroup() { if (DEBUG) log("startGroup()"); GroupColumnIO group = (GroupColumnIO) currentColumnIO; if (hasNullCache(group)) flushCachedNulls(group); ++currentLevel; r[currentLevel] = r[currentLevel - 1]; int fieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[currentLevel].reset(fieldsCount); if (DEBUG) printState(); }

Target:
public void startGroup() { if (DEBUG) log("startGroup()"); GroupColumnIO group = (GroupColumnIO) currentColumnIO; if (hasNullCache(group)) { flushCachedNulls(group); } ++currentLevel; r[currentLevel] = r[currentLevel - 1]; int fieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[currentLevel].reset(fieldsCount); if (DEBUG) printState(); }
Source:
public void testGetChildrenOfFolder() throws Exception { String uniqueId = this.commonTestProject.getUniqueID(); DmsProject mainFolder = this.studyTDI.createFolderTestData(uniqueId); int subFolderID = this.manager.addSubFolder(mainFolder.getProjectId(), "Sub folder", "Sub Folder", uniqueId); List<Reference> childrenNodes = this.manager.getChildrenOfFolder(mainFolder.getProjectId(), this.commonTestProject.getUniqueID(), StudyType.nurseriesAndTrials()); Assert.assertNotNull(childrenNodes); Assert.assertTrue("The size should be one.", childrenNodes.size() == 1); Assert.assertTrue("The id of the subFolder should be " + subFolderID, subFolderID == childrenNodes.get(0).getId()); }

Target:
public void testGetChildrenOfFolder() throws Exception { final String uniqueId = this.commonTestProject.getUniqueID(); final DmsProject mainFolder = this.studyTDI.createFolderTestData(uniqueId); final int subFolderID = this.manager.addSubFolder(mainFolder.getProjectId(), "Sub folder", "Sub Folder", uniqueId); final List<Reference> childrenNodes = this.manager.getChildrenOfFolder(mainFolder.getProjectId(), this.commonTestProject.getUniqueID(), StudyType.nurseriesAndTrials()); Assert.assertNotNull(childrenNodes); Assert.assertEquals("The size should be one.", 1, childrenNodes.size()); Assert.assertTrue("The id of the subFolder should be " + subFolderID, subFolderID == childrenNodes.get(0).getId()); }
Source:
private boolean removeVm() { VM vm = getVm(); hasImages = vm.getDiskList().size() > 0; final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskList(), true, false); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { removeVmFromDb(); if (getParameters().isRemoveDisks()) { for (DiskImage image : diskImages) { getCompensationContext().snapshotEntityStatus(image.getImage(), ImageStatus.ILLEGAL); } ImagesHandler.updateDiskImagesStatus(diskImages, ImageStatus.LOCKED); getCompensationContext().stateChanged(); } return null; } }); if (getParameters().isRemoveDisks() && hasImages) { Collection<DiskImage> unremovedDisks = (Collection<DiskImage>)removeVmImages(diskImages).getActionReturnValue(); if (!unremovedDisks.isEmpty()) { processUnremovedDisks(unremovedDisks); setSucceeded(false); } } return true; }

Target:
private boolean removeVm() { final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskList(), true, false); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { removeVmFromDb(); if (getParameters().isRemoveDisks()) { for (DiskImage image : diskImages) { getCompensationContext().snapshotEntityStatus(image.getImage(), ImageStatus.ILLEGAL); ImagesHandler.updateImageStatus(image.getImage().getId(), ImageStatus.LOCKED); } getCompensationContext().stateChanged(); } return null; } }); if (getParameters().isRemoveDisks() && !diskImages.isEmpty()) { Collection<DiskImage> unremovedDisks = (Collection<DiskImage>)removeVmImages(diskImages).getActionReturnValue(); if (!unremovedDisks.isEmpty()) { processUnremovedDisks(unremovedDisks); return false; } } return true; }
Source:
public void done(IJobChangeEvent event) { final Map<Repository, Object> res = new HashMap<Repository, Object>( PullOperationUI.this.results); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); for (Entry<Repository, Object> entry : res.entrySet()) { Object result = entry.getValue(); if (result instanceof PullResult) { PullResult pullResult = (PullResult) result; if (pullResult.getRebaseResult() != null && RebaseResult.Status.UNCOMMITTED_CHANGES == pullResult .getRebaseResult().getStatus()) { boolean handledSeparately = handleUncommittedChanges( entry.getKey(), pullResult .getRebaseResult() .getUncommittedChanges(), shell); if (handledSeparately) tasksToWaitFor.incrementAndGet(); } } } if (tasksToWaitFor.decrementAndGet() == 0 && !results.isEmpty()) showResults(shell); } }); }

Target:
public void done(IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Map<Repository, Object> res = new HashMap<Repository, Object>( PullOperationUI.this.results); Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); handlePullResults(res, shell); } }); }
Source:
public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); if (fcrepoBinaryUri == null) { Document msgBody = MessageUtil.getDocumentBody(in); Element body = msgBody.getRootElement(); String pidValue = body.getChild("pid", ATOM_NS).getTextTrim(); PID objPid = PIDs.get(pidValue); try { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(objPid); log.info("Adding enhancement headers for " + pidValue); in.setHeader(FCREPO_URI, pidValue); if (repoObj instanceof CollectionObject) { in.setHeader(FCREPO_RESOURCE_TYPE, repoObj.getTypes()); } else { in.setHeader(FCREPO_RESOURCE_TYPE, Binary.getURI()); } } catch (ObjectTypeMismatchException e) { log.warn("{} is not a repository object. No enhancement headers added", objPid.getURI()); } } }

Target:
public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); if (fcrepoBinaryUri == null) { Document msgBody = MessageUtil.getDocumentBody(in); Element body = msgBody.getRootElement(); Element enhancementsEl = body.getChild(RUN_ENHANCEMENTS.getName(), CDR_MESSAGE_NS); if (enhancementsEl != null) { String pidValue = enhancementsEl.getChild("pid", CDR_MESSAGE_NS).getTextTrim(); PID objPid = PIDs.get(pidValue); try { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(objPid); log.info("Adding enhancement headers for " + pidValue); in.setHeader(FCREPO_URI, pidValue); in.setHeader(FCREPO_RESOURCE_TYPE, String.join(",", repoObj.getTypes())); } catch (ObjectTypeMismatchException e) { log.warn("{} is not a repository object. No enhancement headers added", objPid.getURI()); } } } }
Source:
public Mono<Void> createOrReplaceOrder(Order order) { return this.throwRandomError() .then(Mono.fromRunnable(() -> { if (order.getId() == null) { Order newOrder = new Order(); newOrder.setId(UUID.randomUUID().toString()); newOrder.setContent(order.getContent()); logger.info(String.format("Order created: %s", newOrder)); } else { logger.info(String.format("Order updated %s", order)); } })).then(this.throwRandomError()); }

Target:
public Mono<Void> createOrReplaceOrder(Order order) { return this.throwRandomError() .then(Mono.delay(Duration.ofMillis(50))) .then(Mono.fromRunnable(() -> { if (order.getId() == null) { Order newOrder = new Order(); newOrder.setId(UUID.randomUUID().toString()); newOrder.setContent(order.getContent()); logger.info(String.format("Order created: %s", newOrder)); } else { logger.info(String.format("Order updated %s", order)); } })).then(this.throwRandomError()); }
Source:
public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new AlarmRegisterConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasResponseConverter()); mapperFactory.getConverterFactory().registerConverter(AmrProfileStatusCodeConverter.CONVERTER_ID, new AmrProfileStatusCodeConverter()); mapperFactory.getConverterFactory().registerConverter(PeriodicMeterReadsGasConverter.CONVERTER_ID, new PeriodicMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(PeriodicMeterReadsConverter.CONVERTER_ID, new PeriodicMeterReadsConverter()); }

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new AlarmRegisterConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new AmrProfileStatusCodeConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsConverter()); }
Source:
public ConsoleDetail(final AbstractBuild<?, ?> owner, final int from, final int to) { this.owner = owner; this.from = from; this.to = to; start = Math.max(0, from - 10); end = to + 10; readConsole(); }

Target:
public ConsoleDetail(final AbstractBuild<?, ?> owner, final int from, final int to) { this((Run<?, ?>) owner, from ,to); }
Source:
private BoundaryBox getLayerBoundingBox(String layerName, WMSLayer layer, String srs) { WMSLayer wmsLayer = find(layerName, layer); BoundaryBox bbox = wmsLayer.getBbox(srs); while ((bbox == null) && (wmsLayer.getParent() != null)) { wmsLayer = wmsLayer.getParent(); bbox = wmsLayer.getBbox(srs); } if (bbox == null) { bbox = new BoundaryBox(); bbox.setXmin(0); bbox.setYmin(0); bbox.setXmax(100); bbox.setYmax(100); bbox.setSrs(srs); } return bbox; }

Target:
private BoundaryBox getLayerBoundingBox(String layerName, WMSLayer layer, String srs) throws DriverException { WMSLayer wmsLayer = find(layerName, layer); BoundaryBox bbox = wmsLayer.getBbox(srs); while ((bbox == null) && (wmsLayer.getParent() != null)) { wmsLayer = wmsLayer.getParent(); bbox = wmsLayer.getBbox(srs); } if (bbox == null) { throw new DriverException("Could not find a valid bounding box for the layer " + layerName); } return bbox; }
Source:
public static String waitForPortFree(int port, Duration timeout, boolean failOnTimeout) { long secs = Math.max(timeout.toSeconds(), 1); String netstatCommand = "sudo netstat -antp TCP"; String grepCommand = "grep -E '(:|\\.)"+port+"($|\\s)' > /dev/null"; List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}; do", " "+alternativesGroup( "which netstat", chain("echo \"No netstat to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+alternativesGroup( chainGroup("which awk", "AWK_EXEC=awk"), chainGroup("which gawk", "AWK_EXEC=gawk"), chainGroup("which /usr/bin/awk", "AWK_EXEC=/usr/bin/awk"), chainGroup("echo \"No awk to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+netstatCommand+" | $AWK_EXEC '{print $4}' | "+grepCommand+" && result=0 || result=$?", " [ \"$result\" != 0 ] && break", " sleep 1", "done", "if test \"$result\" -eq 0; then", " "+ (failOnTimeout ? "echo \"Port "+port+" still in use (according to netstat); aborting\" && exit 1" : "echo \"Port "+port+" still in use (according to netstat); continuing\""), "fi"); return Joiner.on("\n").join(commands); }

Target:
public static String waitForPortFree(int port, Duration timeout, boolean failOnTimeout) { long secs = Math.max(timeout.toSeconds(), 1); String netstatCommand = alternativesGroup( "sudo netstat -antp --tcp", "sudo netstat -antp TCP"); String grepCommand = "grep -E '(:|\\.)"+port+"($|\\s)' > /dev/null"; List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}; do", " "+BashCommands.requireExecutable("netstat"), " "+alternativesGroup( chainGroup("which awk", "AWK_EXEC=awk"), chainGroup("which gawk", "AWK_EXEC=gawk"), chainGroup("which /usr/bin/awk", "AWK_EXEC=/usr/bin/awk"), chainGroup("echo \"No awk to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+netstatCommand+" | $AWK_EXEC '{print $4}' | "+grepCommand+" && result=0 || result=$?", " [ \"$result\" != 0 ] && break", " sleep 1", "done", "if test \"$result\" -eq 0; then", " "+ (failOnTimeout ? "echo \"Port "+port+" still in use (according to netstat); aborting\" && exit 1" : "echo \"Port "+port+" still in use (according to netstat); continuing\""), "fi"); return Joiner.on("\n").join(commands); }
Source:
public void storeMessagesToDb(final List<AuditerMessage> messages) { synchronized (LOCK_DB_TABLE_AUDITER_LOG) { try { jdbc.batchUpdate("insert into auditer_log (id, msg, actor, created_at, created_by_uid) values (?,?,?," + Compatibility.getSysdate() + ",?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { final AuditerMessage auditerMessage = messages.get(i); final String message = auditerMessage.getMessage(); final PerunSession session = auditerMessage.getOriginaterPerunSession(); log.info("AUDIT: {}", message); try { ps.setInt(1, Utils.getNewId(jdbc, "auditer_log_id_seq")); } catch (InternalErrorException e) { log.error("Cannot get unique id for new auditer log message ['{}'], exception: {}", message, e); } ps.setString(2, message); ps.setString(3, session.getPerunPrincipal().getActor()); ps.setInt(4, session.getPerunPrincipal().getUserId()); } @Override public int getBatchSize() { return messages.size(); } }); } catch (RuntimeException e) { log.error("Cannot store auditer log message in batch for list ['{}'], exception: {}", messages, e); } catch (InternalErrorException e) { log.error("Could not get system date identifier for the DB", e); } } }

Target:
public void storeMessagesToDb(final List<AuditerMessage> messages) { synchronized (LOCK_DB_TABLE_AUDITER_LOG) { try { jdbc.batchUpdate("insert into auditer_log (id, msg, actor, created_at, created_by_uid) values (?,?,?," + Compatibility.getSysdate() + ",?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { final AuditerMessage auditerMessage = messages.get(i); final String message = auditerMessage.getMessage(); final PerunSession session = auditerMessage.getOriginaterPerunSession(); log.info("AUDIT: {}", message); try { ps.setInt(1, Utils.getNewId(jdbc, "auditer_log_id_seq")); } catch (InternalErrorException e) { throw new SQLException("Cannot get unique id for new auditer log message ['" + message + "']", e); } ps.setString(2, message); ps.setString(3, session.getPerunPrincipal().getActor()); ps.setInt(4, session.getPerunPrincipal().getUserId()); } @Override public int getBatchSize() { return messages.size(); } }); } catch (RuntimeException e) { log.error("Cannot store auditer log message in batch for list ['{}'], exception: {}", messages, e); } catch (InternalErrorException e) { log.error("Could not get system date identifier for the DB", e); } } }
Source:
public void testGetReferencedComponentId() { String expectedStringValue; String referencedComponentId; expectedStringValue = "SomeStringValue"; closeProperties.referencedComponent.componentInstanceId.setValue(expectedStringValue); referencedComponentId = closeProperties.getReferencedComponentId(); assertEquals(referencedComponentId, expectedStringValue); }

Target:
public void testGetReferencedComponentId() { String expectedStringValue = "SomeStringValue";; String referencedComponentId; closeProperties.referencedComponent.componentInstanceId.setValue(expectedStringValue); referencedComponentId = closeProperties.getReferencedComponentId(); assertEquals(referencedComponentId, expectedStringValue); }
Source:
public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if (representationDescription.getEndUserDocumentation() != null && !representationDescription.getEndUserDocumentation().isEmpty()) { userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }

Target:
public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if (representationDescription.getEndUserDocumentation() != null && !StringUtil.isEmpty(representationDescription.getEndUserDocumentation())) { userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }
Source:
public void getDependentJarsFromManifest(JarFile jarFile, Set<String> set) throws IOException { String value = jarFile.getManifest().getMainAttributes().getValue(APEX_DEPENDENCIES); if (!StringUtils.isEmpty(value)) { Path folderPath = Paths.get(jarFile.getName()).getParent(); for (String jar : value.split(",")) { File file = folderPath.resolve(jar).toFile(); if (file.exists()) { set.add(file.getPath()); logger.debug("Jar-file was added as a dependent jar", file.getPath()); } else { logger.warn("Jar-file does not exist", file.getPath()); } } } }

Target:
public void getDependentJarsFromManifest(JarFile jarFile, Set<String> set) throws IOException { String value = jarFile.getManifest().getMainAttributes().getValue(APEX_DEPENDENCIES); if (!StringUtils.isEmpty(value)) { Path folderPath = Paths.get(jarFile.getName()).getParent(); for (String jar : value.split(",")) { File file = folderPath.resolve(jar).toFile(); if (file.exists()) { set.add(file.getPath()); logger.debug("The file was added as a dependent of the jar {}", file.getPath(), jarFile.getName()); } else { logger.warn("The dependent file of the jar does not exist", file.getPath(), jarFile.getName()); } } } }
Source:
public IRequestablePage newPageInstance(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters) { try { MockPage page; page = (MockPage)pageClass.newInstance(); page.setPageId(++idCounter); page.setBookmarkable(true); page.setCreatedBookmarkable(true); if (pageParameters != null) { page.getPageParameters().overwriteWith(pageParameters); } return page; } catch (Exception e) { throw new WicketRuntimeException(e); } }

Target:
public IRequestablePage newPageInstance(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters) { try { MockPage page; page = (MockPage)pageClass.getDeclaredConstructor().newInstance(); page.setPageId(++idCounter); page.setBookmarkable(true); page.setCreatedBookmarkable(true); if (pageParameters != null) { page.getPageParameters().overwriteWith(pageParameters); } return page; } catch (Exception e) { throw new WicketRuntimeException(e); } }
Source:
private double matchPrice(HashMap<Double, ArrayList<Integer>> orderbook) { ArrayList<Double> priceList=new ArrayList<Double>(); for(double prce:orderbook.keySet()){ priceList.add(prce); } Collections.sort(priceList, Collections.reverseOrder()); ArrayList<Integer> buyCum=new ArrayList<Integer>(priceList.size()); ArrayList<Integer> sellCum=new ArrayList<Integer>(priceList.size()); double key=priceList.get(0); buyCum.add(orderbook.get(key).get(0)); for(int i=1; i<priceList.size(); i++){ key=priceList.get(i); buyCum.add(orderbook.get(key).get(0)+buyCum.get(i-1)); } key=priceList.get(priceList.size()-1); sellCum.add(orderbook.get(key).get(1)); for(int i=priceList.size()-2;i>-1; i--){ key=priceList.get(i); sellCum.add(orderbook.get(key).get(1)+sellCum.get(priceList.size()-i-2)); } double matchPrice=0; int max=0; for(int i=0; i<priceList.size(); i++){ int min=Math.min(sellCum.get(i),buyCum.get(priceList.size()-1-i)); if (min>max){ max=min; matchPrice=priceList.get(i); } } return matchPrice; }

Target:
private double matchPrice(HashMap<Double, ArrayList<Integer>> orderbook) { ArrayList<Double> priceList=new ArrayList<Double>(); for(double prce:orderbook.keySet()){ priceList.add(prce); } Collections.sort(priceList, Collections.reverseOrder()); ArrayList<Integer> buyPriceList=new ArrayList<Integer>(priceList.size()); ArrayList<Integer> sellPriceList=new ArrayList<Integer>(priceList.size()); double price=priceList.get(0); buyPriceList.add(orderbook.get(price).get(0)); for(int i=1; i<priceList.size(); i++){ price=priceList.get(i); buyPriceList.add(orderbook.get(price).get(0)+buyPriceList.get(i-1)); } price=priceList.get(priceList.size()-1); sellPriceList.add(orderbook.get(price).get(1)); for(int i=priceList.size()-2;i>-1; i--){ price=priceList.get(i); int index=priceList.size()-i-2; sellPriceList.add(orderbook.get(price).get(1)+sellPriceList.get(index)); } double matchPrice=0; int max=0; for(int i=0; i<priceList.size(); i++){ int index=priceList.size()-1-i; int min=Math.min(sellPriceList.get(i),buyPriceList.get(index)); if (min>max){ max=min; matchPrice=priceList.get(i); } } return matchPrice; }
Source:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); YarnConfiguration conf = new YarnConfiguration(); if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); String scheme = ConfigUtils.getSchemePrefix(conf); String hostname = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName(); this.appMasterTrackingUrl = scheme + hostname + ":" + webApp.port(); LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }

Target:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }
Source:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); } if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); } }

Target:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); } } }
Source:
public void addBranch(final String newBranchName, final String baseBranchName, final WorkspaceProject project) { projectService.addBranch(newBranchName, baseBranchName, project); Repository repository = repoService.getRepositoryFromSpace( project.getSpace(), project.getRepository().getAlias()); RepositoryUpdatedEvent event = new RepositoryUpdatedEvent(repository); repositoryUpdatedEvent.fire(event); newBranchEvent.fire(new NewBranchEvent(repository, newBranchName, baseBranchName, sessionInfo.getIdentity())); }

Target:
public void addBranch(final String newBranchName, final String baseBranchName, final WorkspaceProject project) { projectService.addBranch(newBranchName, baseBranchName, project, sessionInfo.getIdentity().getIdentifier()); }
Source:
public void validateRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; serverMetrics.securityServiceValidateRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("ServerSecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null) { throw new IllegalArgumentException("restRequest is null"); } serverMetrics.securityServiceValidateRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }

Target:
public void validateRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; serverMetrics.securityServiceValidateRequestRate.mark(); if (!isOpen) { exception = new RestServiceException("ServerSecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null) { throw new IllegalArgumentException("restRequest is null"); } callback.onCompletion(null, exception); }
Source:
public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { switch (opcode) { case ByteOps.ANEWARRAY: { machine.popArgs(frame, Type.INT); break; } case ByteOps.PUTSTATIC: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, fieldType); break; } case ByteOps.GETFIELD: case ByteOps.CHECKCAST: case ByteOps.INSTANCEOF: { machine.popArgs(frame, Type.OBJECT); break; } case ByteOps.PUTFIELD: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, Type.OBJECT, fieldType); break; } case ByteOps.INVOKEINTERFACE: { cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } case ByteOps.INVOKEVIRTUAL: case ByteOps.INVOKESPECIAL: { if (cst instanceof CstInterfaceMethodRef) { cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } Prototype prototype = ((CstMethodRef) cst).getPrototype(false); machine.popArgs(frame, prototype); break; } case ByteOps.INVOKESTATIC: { if (cst instanceof CstInterfaceMethodRef) { cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } Prototype prototype = ((CstMethodRef) cst).getPrototype(true); machine.popArgs(frame, prototype); break; } case ByteOps.MULTIANEWARRAY: { Prototype prototype = Prototype.internInts(Type.VOID, value); machine.popArgs(frame, prototype); break; } default: { machine.clearArgs(); break; } } machine.auxIntArg(value); machine.auxCstArg(cst); machine.run(frame, offset, opcode); }

Target:
public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { switch (opcode) { case ByteOps.ANEWARRAY: { machine.popArgs(frame, Type.INT); break; } case ByteOps.PUTSTATIC: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, fieldType); break; } case ByteOps.GETFIELD: case ByteOps.CHECKCAST: case ByteOps.INSTANCEOF: { machine.popArgs(frame, Type.OBJECT); break; } case ByteOps.PUTFIELD: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, Type.OBJECT, fieldType); break; } case ByteOps.INVOKEINTERFACE: case ByteOps.INVOKEVIRTUAL: case ByteOps.INVOKESPECIAL: case ByteOps.INVOKESTATIC: { if (cst instanceof CstInterfaceMethodRef) { if (opcode != ByteOps.INVOKEINTERFACE) { if (!dexOptions.canUseDefaultInterfaceMethods()) { throw new SimException( "default or static interface method used without --min-sdk-version >= 24"); } } cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } boolean staticMethod = (opcode == ByteOps.INVOKESTATIC); Prototype prototype = ((CstMethodRef) cst).getPrototype(staticMethod); machine.popArgs(frame, prototype); break; } case ByteOps.MULTIANEWARRAY: { Prototype prototype = Prototype.internInts(Type.VOID, value); machine.popArgs(frame, prototype); break; } default: { machine.clearArgs(); break; } } machine.auxIntArg(value); machine.auxCstArg(cst); machine.run(frame, offset, opcode); }
Source:
public Builder registerAction( @NonNull String alias, @NonNull String actionName, @NonNull Class<? extends Action> actionClass){ List<Field> fields = new ArrayList<>(); for (Field field : actionClass.getDeclaredFields()) { if (!field.getName().equals("this$0")){ fields.add(field); } } if (fields.size() != 1) { throw new IllegalArgumentException("action class must contain only one field."); } Gson gson = new Gson(); Action action = gson.fromJson(new JsonObject(), actionClass); if (TextUtils.isEmpty(action.getActionName())) { throw new IllegalArgumentException("getActionName() return null or empty"); } this.actionTypes.put(ThingIFAPI.actionsMapKey(alias, actionName), actionClass); return this; }

Target:
public Builder registerAction( @NonNull String alias, @NonNull String actionName, @NonNull Class<? extends Action> actionClass){ if (actionClass.getEnclosingClass() != null && !Modifier.isStatic(actionClass.getModifiers())) { throw new IllegalArgumentException("non static inner class is not allowed to be Action"); } if(actionClass.getDeclaredFields().length != 1) { throw new IllegalArgumentException("action class must contain only one field."); } Gson gson = new Gson(); Action action = gson.fromJson(new JsonObject(), actionClass); if (TextUtils.isEmpty(action.getActionName())) { throw new IllegalArgumentException("getActionName() return null or empty"); } this.actionTypes.put(ThingIFAPI.actionsMapKey(alias, actionName), actionClass); return this; }
Source:
public void error(final String msg) { throw new UnsupportedOperationException(); }

Target:
public void error(final String msg) { logMessageWithFormat("ERROR", msg); }
Source:
private static String getTimegraphSelectionName(final SWTBotView view) { final TimeGraphControl timegraph = view.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); return UIThreadRunnable.syncExec(new StringResult() { @Override public String run() { ISelection selection = timegraph.getSelectionTrace(); if (selection instanceof TimeGraphSelection) { TimeGraphSelection sel = (TimeGraphSelection) selection; ITimeGraphEntry entry = (ITimeGraphEntry) sel.getFirstElement(); return entry.getName(); } return null; } }); }

Target:
private static String getTimegraphSelectionName(final SWTBotView view) { final TimeGraphControl timegraph = view.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); return UIThreadRunnable.syncExec(() -> { ISelection selection = timegraph.getSelectionTrace(); if (selection instanceof TimeGraphSelection) { TimeGraphSelection sel = (TimeGraphSelection) selection; ITimeGraphEntry entry = (ITimeGraphEntry) sel.getFirstElement(); return entry.getName(); } return null; }); }
Source:
private void doCreateProject() { final String projectName = createTxt.getText().trim(); String parentName = null; if (showParentCandidates.getValue()) { parentName = suggestedParents.getItemText(suggestedParents.getSelectedIndex()); if (parentName.equals(NO_PARENT_SELECTED)) { parentName = ""; } } else { parentName = parentTxt.getText(); } Util.PROJECT_SVC.createNewProject(projectName, parentName, new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { super.onFailure(caught); enableForm(true); } }); }

Target:
private void doCreateProject() { final String projectName = createTxt.getText().trim(); final String parentName = parentTxt.getText(); enableForm(false); Util.PROJECT_SVC.createNewProject(projectName, parentName, emptyCommit .getValue(), new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { super.onFailure(caught); enableForm(true); } }); }
Source:
private void generateRequestImplementation(Method method) { Name name = method.getName(); String request = getRequestName(method); String requestImpl = getRequestImplName(method); buffer.addLine("private class %1$s implements %2$s {", requestImpl, request); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterImplementation); buffer.addImport(Map.class); buffer.addLine( "private Map<String, String> headers;"); buffer.addLine( "public %1s headers(Map<String, String> headers) {", request); buffer.addLine( "this.headers = headers;"); buffer.addLine( "return this;"); buffer.addLine("}"); buffer.addLine( "private Map<String, String> query;"); buffer.addLine( "public %1s query(Map<String, String> query) {", request); buffer.addLine( "this.query = query;"); buffer.addLine( "return this;"); buffer.addLine("}"); buffer.addLine("public %1$s send() {", getResponseName(method)); if (ADD.equals(name)) { generateAddRequestImplementation(method); } else if (GET.equals(name) || LIST.equals(name)) { generateListRequestImplementation(method); } else if (REMOVE.equals(name)) { generateRemoveRequestImplementation(method); } else if (UPDATE.equals(name)) { generateUpdateRequestImplementation(method); } else { generateActionRequestImplementation(method); } buffer.addLine("}"); buffer.addLine(); buffer.addLine("}"); buffer.addLine(); }

Target:
private void generateRequestImplementation(Method method) { buffer.addImport(BASE_PACKAGE + ".BaseRequest"); Name name = method.getName(); String request = getRequestName(method); String response = getResponseName(method); String requestImpl = getRequestImplName(method); buffer.addLine("private class %1$s extends BaseRequest<%2$s, %3$s> implements %2$s {", requestImpl, request, response); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterImplementation); buffer.addLine("public %1$s send() {", getResponseName(method)); if (ADD.equals(name)) { generateAddRequestImplementation(method); } else if (GET.equals(name) || LIST.equals(name)) { generateListRequestImplementation(method); } else if (REMOVE.equals(name)) { generateRemoveRequestImplementation(method); } else if (UPDATE.equals(name)) { generateUpdateRequestImplementation(method); } else { generateActionRequestImplementation(method); } buffer.addLine("}"); buffer.addLine(); buffer.addLine("}"); buffer.addLine(); }
Source:
protected ProcessHolder.Classes getClasses() { return environment().getClasses(); }

Target:
protected ClassesHolder.Classes getClasses() { return environment().getClasses(); }
Source:
public ExtensionJobList getExtensionJobs( @PathParam("extension-name") String extensionName, @DefaultValue(ASCENDING_SORT_ORDER) @QueryParam("sortOrder") String sortOrder, @DefaultValue("") @QueryParam("doAs") String doAsUser) { checkIfExtensionServiceIsEnabled(); checkIfExtensionExists(extensionName); try { Map<String, String> jobAndExtensionNames = new HashMap<>(); List<ExtensionJobsBean> extensionJobs = null; if (extensionName != null) { extensionJobs = ExtensionStore.getMetaStore().getJobsForAnExtension(extensionName); } else { extensionJobs = ExtensionStore.getMetaStore().getAllExtensionJobs(); } switch (sortOrder.toLowerCase()) { case DESCENDING_SORT_ORDER: Collections.sort(extensionJobs, new Comparator<ExtensionJobsBean>() { public int compare(ExtensionJobsBean o1, ExtensionJobsBean o2) { return o2.getJobName().compareTo(o1.getJobName()); } }); break; default: Collections.sort(extensionJobs, new Comparator<ExtensionJobsBean>() { public int compare(ExtensionJobsBean o1, ExtensionJobsBean o2) { return o1.getJobName().compareTo(o2.getJobName()); } }); } for (ExtensionJobsBean job : extensionJobs) { jobAndExtensionNames.put(job.getJobName(), job.getExtensionName()); } return new ExtensionJobList(extensionJobs.size(), jobAndExtensionNames); } catch (Throwable e) { LOG.error("Failed to get extension job list of " + extensionName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
public ExtensionJobList getExtensionJobs( @PathParam("extension-name") String extensionName, @DefaultValue(ASCENDING_SORT_ORDER) @QueryParam("sortOrder") String sortOrder, @DefaultValue("") @QueryParam("doAs") String doAsUser) { checkIfExtensionServiceIsEnabled(); checkIfExtensionExists(extensionName); try { return super.getExtensionJobs(extensionName, sortOrder, doAsUser); } catch (Throwable e) { LOG.error("Failed to get extension job list of " + extensionName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
private static JavaMajorVersion detectCurrentVersion() { final ILogger logger = Logger.getLogger(JavaVersion.class); final Class runtimeClass; final Class versionClass; try { runtimeClass = Class.forName("java.lang.Runtime"); } catch (ClassNotFoundException e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } try { versionClass = Class.forName("java.lang.Runtime$Version"); } catch (ClassNotFoundException e) { logger.info("Detected runtime version: Java 8"); return JAVA_8; } try { Method versionMethod = runtimeClass.getDeclaredMethod("version"); Object versionObj = versionMethod.invoke(Runtime.getRuntime()); Method majorMethod = versionClass.getDeclaredMethod("major"); int majorVersion = (int) majorMethod.invoke(versionObj); logger.info("Detected runtime version: Java " + majorVersion); JavaVersion foundVersion = valueOf(majorVersion); if (foundVersion != null) { return foundVersion; } return new FutureJavaVersion(majorVersion); } catch (Exception e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } }

Target:
private static JavaMajorVersion detectCurrentVersion() { final ILogger logger = Logger.getLogger(JavaVersion.class); final Class runtimeClass = Runtime.class; final Class versionClass; try { versionClass = Class.forName("java.lang.Runtime$Version"); } catch (ClassNotFoundException e) { if (logger.isFineEnabled()) { logger.fine("Detected runtime version: Java 8"); } return JAVA_8; } try { Method versionMethod = runtimeClass.getDeclaredMethod("version"); Object versionObj = versionMethod.invoke(Runtime.getRuntime()); Method majorMethod = versionClass.getDeclaredMethod("major"); int majorVersion = (int) majorMethod.invoke(versionObj); if (logger.isFineEnabled()) { logger.fine("Detected runtime version: Java " + majorVersion); } JavaVersion foundVersion = valueOf(majorVersion); if (foundVersion != null) { return foundVersion; } return new FutureJavaVersion(majorVersion); } catch (Exception e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user_brick_list, container, false); setHasOptionsMenu(true); addUserBrickButton = view.findViewById(R.id.add_user_brick); addUserBrickButton.setOnClickListener(this); ((AppCompatActivity) getActivity()) .getSupportActionBar().setTitle(R.string.category_user_bricks); return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user_brick_list, container, false); setHasOptionsMenu(true); addUserBrickButton = view.findViewById(R.id.add_user_brick); addUserBrickButton.setOnClickListener(this); AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity(); if (appCompatActivity != null && appCompatActivity.getSupportActionBar() != null) { appCompatActivity.getSupportActionBar().setTitle(R.string.category_user_bricks); } return view; }