auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void doStart() { logger.debug("Registering to receive notifications"); try { Assert.notNull(this.server, "MBeanServer is required."); Assert.notNull(this.objectNames, "An ObjectName is required."); Collection<ObjectName> objectNames = this.retrieveMBeanNames(); if (objectNames.size() < 1) { logger.error("No MBeans found matching ObjectName pattern(s): " + Arrays.asList(this.objectNames)); } for (ObjectName objectName : objectNames) { this.server.addNotificationListener(objectName, this, this.filter, this.handback); this.listenerRegistered = true; } } catch (InstanceNotFoundException e) { throw new IllegalStateException("Failed to find MBean instance.", e); } catch (IOException e) { throw new IllegalStateException("IOException on MBeanServerConnection.", e); } }

Target:
protected void doStart() { if (!this.listenerRegisteredOnStartup.get()) { return; } logger.debug("Registering to receive notifications"); try { Assert.notNull(this.server, "MBeanServer is required."); Assert.notNull(this.objectNames, "An ObjectName is required."); Collection<ObjectName> objectNames = this.retrieveMBeanNames(); if (objectNames.size() < 1) { logger.error("No MBeans found matching ObjectName pattern(s): " + Arrays.asList(this.objectNames)); } for (ObjectName objectName : objectNames) { this.server.addNotificationListener(objectName, this, this.filter, this.handback); } } catch (InstanceNotFoundException e) { throw new IllegalStateException("Failed to find MBean instance.", e); } catch (IOException e) { throw new IllegalStateException("IOException on MBeanServerConnection.", e); } }
Source:
public Deque<Transition<State, Alphabet>> getPath(State initialState, State finalState) { Deque<State> toProcess = new ArrayDeque<>(); HashMap<State, Transition<State, Alphabet>> considered = new HashMap<>(); toProcess.add(initialState); considered.put(initialState, null); State next; while (!toProcess.isEmpty()) { next = toProcess.remove(); for (Set<Transition<State, Alphabet>> transitions: getFrontTransitions(next)) { for (Transition<State, Alphabet> transition : transitions) { State endState = transition.getEnd(); if (endState.equals(finalState)) { Deque<Transition<State, Alphabet>> result = new ArrayDeque<>(); while (transition != null) { result.push(transition); transition = considered.get(transition.getStart()); } return result; } if (considered.containsKey(endState)) continue; considered.put(endState, transition); toProcess.add(endState); } } } return null; }

Target:
public Deque<Transition<State, Alphabet>> getPath(State initialState, State finalState) { Deque<State> toProcess = new ArrayDeque<>(); Map<State, Transition<State, Alphabet>> considered = new HashMap<>(); toProcess.add(initialState); considered.put(initialState, null); State next; while (!toProcess.isEmpty()) { next = toProcess.remove(); for (Set<Transition<State, Alphabet>> transitions: getFrontTransitions(next)) { for (Transition<State, Alphabet> transition : transitions) { State endState = transition.getEnd(); if (endState.equals(finalState)) { Deque<Transition<State, Alphabet>> result = new ArrayDeque<>(); while (transition != null) { result.push(transition); transition = considered.get(transition.getStart()); } return result; } if (considered.containsKey(endState)) continue; considered.put(endState, transition); toProcess.add(endState); } } } return null; }
Source:
protected void checkFile(@NotNull ErlangFile file, @NotNull ProblemsHolder problemsHolder) { Set<String> importedFunctionNames = ContainerUtil.newHashSet(); for (ErlangImportFunction f : file.getImportedFunctions()) { importedFunctionNames.add(ErlangPsiImplUtil.createFunctionPresentation(f)); } for (ErlangFunction function : file.getFunctions()) { String fullName = ErlangPsiImplUtil.createFunctionPresentation(function); if (importedFunctionNames.contains(fullName)) { problemsHolder.registerProblem(InspectionManager.getInstance(file.getProject()).createProblemDescriptor( function.getNameIdentifier(), function.getFunctionClauseList().get(0).getArgumentDefinitionList().getOriginalElement(), "Defining imported function '" + fullName + "'", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, new ErlangRemoveFunctionFix(), new ErlangRemoveFunctionFromImportFixBase.ErlangRemoveFunctionFromAllImportsFix())); } } }

Target:
protected void checkFile(@NotNull ErlangFile file, @NotNull ProblemsHolder problemsHolder) { Set<String> importedFunctionNames = ContainerUtil.newHashSet(); for (ErlangImportFunction f : file.getImportedFunctions()) { importedFunctionNames.add(ErlangPsiImplUtil.createFunctionPresentation(f)); } for (ErlangFunction function : file.getFunctions()) { String fullName = ErlangPsiImplUtil.createFunctionPresentation(function); if (importedFunctionNames.contains(fullName)) { problemsHolder.registerProblem(InspectionManager.getInstance(file.getProject()).createProblemDescriptor( function.getNameIdentifier(), ContainerUtil.getFirstItem(function.getFunctionClauseList()).getArgumentDefinitionList(), "Defining imported function '" + fullName + "'", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, new ErlangRemoveFunctionFix(), new ErlangRemoveFunctionFromImportFixBase.ErlangRemoveFunctionFromAllImportsFix())); } } }
Source:
private static boolean nullAgainstParam(ExpressionTree o1, ExpressionTree o2, LambdaExpressionTree tree) { if (o1.is(Tree.Kind.NULL_LITERAL) && (o2.is(Tree.Kind.IDENTIFIER))) { List<VariableTree> parameters = tree.parameters(); return parameters.size() == 1 && parameters.get(0).symbol().equals(((IdentifierTree) o2).symbol()); } return false; }

Target:
private static boolean nullAgainstParam(ExpressionTree o1, ExpressionTree o2, LambdaExpressionTree tree) { if (o1.is(Tree.Kind.NULL_LITERAL) && o2.is(Tree.Kind.IDENTIFIER)) { List<VariableTree> parameters = tree.parameters(); return parameters.size() == 1 && parameters.get(0).symbol().equals(((IdentifierTree) o2).symbol()); } return false; }
Source:
public void navigationChanged(Stack previous, Stack current) { String actionCode = null; register.setTargetHistoryToken(current.toString()); if (current.getAction() != null && FormHelper.REQUEST_INVITE_ACTION_NAME.equals(current.getAction())) { username = null;; setRequestInvite(Boolean.TRUE); } else { if (current.getAction() != null && FormHelper.COMPLETE_ACTION_NAME.equals(current.getAction()) && (actionCode = current.getParameter(FormHelper.CODE_PARAMETER_INDEX)) != null) { setRequestInvite(Boolean.FALSE); mRegisterForm.setEnabled(false); UserController.get().fetchUser(actionCode); } else { username = null; setRequestInvite(Boolean.TRUE); } } }

Target:
public void navigationChanged(Stack previous, Stack current) { String actionCode = null; register.setTargetHistoryToken(current.toString()); if (current.getAction() != null && FormHelper.REQUEST_INVITE_ACTION_NAME.equals(current.getAction())) { username = null; setRequestInvite(Boolean.TRUE); } else { if (current.getAction() != null && FormHelper.COMPLETE_ACTION_NAME.equals(current.getAction()) && (actionCode = current.getParameter(FormHelper.CODE_PARAMETER_INDEX)) != null) { setRequestInvite(Boolean.FALSE); mRegisterForm.setEnabled(false); UserController.get().fetchUser(actionCode); } else { username = null; setRequestInvite(Boolean.TRUE); } } }
Source:
private void setupKafka(String zkAddress) throws IOException { Properties brokerProps = new Properties(); brokerProps.setProperty("zookeeper.connect", zkAddress); brokerProps.setProperty("broker.id", "0"); brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); brokerProps.setProperty("listeners", "PLAINTEXT://" + LOCALHOST + ":" + KAFKA_PORT); brokerProps.setProperty("replica.socket.timeout.ms", "1000"); brokerProps.setProperty("controller.socket.timeout.ms", "1000"); brokerProps.setProperty("offsets.topic.replication.factor", "1"); KafkaConfig config = new KafkaConfig(brokerProps); kafkaServer = TestUtils.createServer(config, Time.SYSTEM); kafkaServer.startup(); AdminUtils.createTopic( zkUtils, TEST_TOPIC, 1, 1, new Properties(), null); }

Target:
private void setupKafka(String zkAddress) throws IOException { Properties brokerProps = new Properties(); brokerProps.setProperty("zookeeper.connect", zkAddress); brokerProps.setProperty("broker.id", "0"); brokerProps.setProperty("log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString()); brokerProps.setProperty("listeners", "PLAINTEXT://" + LOCALHOST + ":" + KAFKA_PORT); brokerProps.setProperty("replica.socket.timeout.ms", "1000"); brokerProps.setProperty("controller.socket.timeout.ms", "1000"); brokerProps.setProperty("offsets.topic.replication.factor", "1"); brokerProps.setProperty("offsets.topic.num.partitions", "1"); KafkaConfig config = new KafkaConfig(brokerProps); kafkaServer = TestUtils.createServer(config, Time.SYSTEM); kafkaServer.startup(); AdminUtils.createTopic( zkUtils, TEST_TOPIC, 1, 1, new Properties(), null); }
Source:
public Log4j2LoggerAdapter() { try { org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); if (logger != null) { LoggerContext context = (LoggerContext)LogManager.getContext(false); Map<String, Appender> appenders = context.getConfiguration().getAppenders(); Collection<Appender> appenderCollection = appenders.values(); for (Appender appender : appenderCollection) { if (appender instanceof FileAppender) { FileAppender fileAppender = (FileAppender)appender; String fileName = fileAppender.getFileName(); file = new File(fileName); break; } } } }catch (Throwable t){ } }

Target:
public Log4j2LoggerAdapter() { }
Source:
public PersonIdent(final String in) { final int lt = in.indexOf('<'); if (lt == -1) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().malformedpersonIdentString, in)); final int gt = in.indexOf('>', lt); if (gt == -1) throw new IllegalArgumentException(MessageFormat.format( JGitText.get().malformedpersonIdentString, in)); name = in.substring(0, lt).trim(); emailAddress = in.substring(lt + 1, gt).trim(); final int tzSeparator = lastIndexOfTrim(in, ' ', in.length() - 1); if (tzSeparator < gt) { when = 0; tzOffset = -1; return; } final int whenSeparator = Math.max(gt, lastIndexOfTrim(in, ' ', tzSeparator - 1)); if (whenSeparator >= tzSeparator - 1) { when = 0; tzOffset = -1; return; } final String tzHoursStr = in.substring(tzSeparator + 1, tzSeparator + 4).trim(); final int tzHours; if (tzHoursStr.charAt(0) == '+') tzHours = Integer.parseInt(tzHoursStr.substring(1)); else tzHours = Integer.parseInt(tzHoursStr); final int tzMins = Integer.parseInt(in.substring(tzSeparator + 4).trim()); when = Long.parseLong(in.substring(whenSeparator + 1, tzSeparator).trim()) * 1000; tzOffset = tzHours * 60 + tzMins; }

Target:
public PersonIdent(final String in) { final PersonIdent self = RawParseUtils.parsePersonIdent(in); if (self == null) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().malformedpersonIdentString, in)); } this.name = self.name; this.emailAddress = self.emailAddress; this.when = self.when; this.tzOffset = self.tzOffset; }
Source:
public void setContent(HTMLElement element) { this.content.textContent = ""; if (element != null) { this.content.appendChild(element); } }

Target:
public void setContent(HTMLElement element) { this.domUtil.removeAllElementChildren(this.content); this.content.appendChild(element); }
Source:
public byte[] getStartRow() { return this.delegateScan.getStartRow(); }

Target:
public byte[] getStartRow() { final byte[] startRow = this.delegateScan.getStartRow(); return Bytes.copy(startRow); }
Source:
private KubernetesConnectionConfiguration prepareConfiguration() throws IOException { File account = File.createTempFile("kubernetes-test-account", ""); new FileWriter(account).write("account-token"); String accountFile = account.getAbsolutePath(); KubernetesConnectionConfiguration cfg = new KubernetesConnectionConfiguration(); cfg.setNamespace(namespace); cfg.setServiceName(service); cfg.setMasterUrl("https://localhost:" + mockServer.getLocalPort()); cfg.setAccountToken(accountFile); return cfg; }

Target:
private KubernetesConnectionConfiguration prepareConfiguration() throws IOException { File account = File.createTempFile("kubernetes-test-account", ""); FileWriter fw = new FileWriter(account); fw.write("account-token"); fw.close(); String accountFile = account.getAbsolutePath(); KubernetesConnectionConfiguration cfg = new KubernetesConnectionConfiguration(); cfg.setNamespace(namespace); cfg.setServiceName(service); cfg.setMasterUrl("https://localhost:" + mockServer.getLocalPort()); cfg.setAccountToken(accountFile); return cfg; }
Source:
private boolean isLowerOrEqualParameterTypes(IService service1, IService service2) { final List<IType> paramTypes1 = service1.getParameterTypes(queryEnvironment); final List<IType> paramTypes2 = service2.getParameterTypes(queryEnvironment); boolean result = paramTypes1.size() == paramTypes2.size(); if (result) { final Iterator<IType> it1 = paramTypes1.iterator(); final Iterator<IType> it2 = paramTypes2.iterator(); while (it1.hasNext()) { IType paramType1 = it1.next(); IType paramType2 = it2.next(); if (!paramType2.isAssignableFrom(paramType1)) { result = false; break; } } } return result; }

Target:
private boolean isLowerOrEqualParameterTypes(IService service1, IService service2) { final List<IType> paramTypes1 = service1.getParameterTypes(queryEnvironment); final List<IType> paramTypes2 = service2.getParameterTypes(queryEnvironment); boolean result = paramTypes1.size() == paramTypes2.size(); final Iterator<IType> it1 = paramTypes1.iterator(); final Iterator<IType> it2 = paramTypes2.iterator(); while (result && it1.hasNext()) { IType paramType1 = it1.next(); IType paramType2 = it2.next(); if (!paramType2.isAssignableFrom(paramType1)) { result = false; } } return result; }
Source:
public Response updatePolicy(@PathParam("tenant") String tenant, @PathParam("subject") String subject, @PathParam("policyId") String policyId, String policy) { LOGGER.debug("Updating policy with id [" + policyId + "] for [" + tenant + "] and subject [" + subject + "]"); String id = URLEncoding.decode(policyId); Policy p = dao.loadPolicy(tenant, subject, id); if (p != null) { Policy newP = dao.updatePolicy(new Policy(id, tenant, subject, policy)); return Response.ok(newP.getPolicy()).build(); } else { return Response.status(404).build(); } }

Target:
public Response updatePolicy(@PathParam("tenant") String tenant, @PathParam("subject") String subject, @PathParam("policyId") String policyId, String policy) { LOGGER.debug("Updating policy with id for and subject [{}]", policyId, tenant, subject); String id = URLEncoding.decode(policyId); Policy p = dao.loadPolicy(tenant, subject, id); if (p != null) { Policy newP = dao.updatePolicy(new Policy(id, tenant, subject, policy)); return Response.ok(newP.getPolicy()).build(); } else { return Response.status(404).build(); } }
Source:
public void testList() { FluentIterable<VPC> vpcs = client.describeVpcsInRegion(null); assertTrue(!vpcs.toList().isEmpty()); }

Target:
public void testList() { FluentIterable<VPC> vpcs = client.describeVpcsInRegion(null); assertFalse(vpcs.toList().isEmpty()); }
Source:
public void delete() { KernelTransaction transaction = safeAcquireTransaction(); try { boolean deleted = transaction.dataWrite().nodeDelete( getId() ); if ( !deleted ) { throw new NotFoundException( "Unable to delete Node[" + nodeId + "] since it has already been deleted." ); } } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( AutoIndexingKernelException e ) { throw new IllegalStateException( "Auto indexing encountered a failure while deleting the node: " + e.getMessage(), e ); } catch ( EntityNotFoundException e ) { throw new NotFoundException( "Unable to delete node[" + getId() + "] since it is already deleted." ); } }

Target:
public void delete() { KernelTransaction transaction = safeAcquireTransaction(); try { boolean deleted = transaction.dataWrite().nodeDelete( getId() ); if ( !deleted ) { throw new NotFoundException( "Unable to delete Node[" + nodeId + "] since it has already been deleted." ); } } catch ( InvalidTransactionTypeKernelException e ) { throw new ConstraintViolationException( e.getMessage(), e ); } catch ( AutoIndexingKernelException e ) { throw new IllegalStateException( "Auto indexing encountered a failure while deleting the node: " + e.getMessage(), e ); } }
Source:
public void compareReplicaIndexEntriestoLogContent(String replicaRootDirectory, String logFile) throws Exception { if (logFile == null) { logger.error("logFile needs to be set for compareIndexToLog"); System.exit(0); } RandomAccessFile randomAccessFile = new RandomAccessFile(new File(logFile), "r"); logger.info("Comparing Index entries to Log "); File replicaDirectory = new File(replicaRootDirectory); for (File indexFile : replicaDirectory.listFiles(new IndexFileNameFilter())) { TreeMap<Long, Long> coveredRanges = new TreeMap<Long, Long>(); Set<Long> deleteMsgsOriginalOffsets = new HashSet<Long>(); compareIndexEntriesToLogContent(indexFile, replicaDirectory, randomAccessFile, coveredRanges, deleteMsgsOriginalOffsets); } }

Target:
public void compareReplicaIndexEntriestoLogContent(String replicaRootDirectory, String logFile) throws Exception { if (logFile == null) { logger.error("logFile needs to be set for compareIndexToLog"); System.exit(0); } RandomAccessFile randomAccessFile = new RandomAccessFile(new File(logFile), "r"); logger.info("Comparing Index entries to Log "); File replicaDirectory = new File(replicaRootDirectory); File[] replicas = replicaDirectory.listFiles(new IndexFileNameFilter()); Arrays.sort(replicas, new ConsistencyCheckerTool.IndexFileNameComparator()); for (File indexFile : replicas) { compareIndexEntriesToLogContent(indexFile, replicaDirectory, randomAccessFile); } }
Source:
private WorkerJvm startWorkerJvm(String mode) throws IOException { String workerId = "worker-" + getHostAddress() + "-" + WORKER_ID_GENERATOR.incrementAndGet() + "-" + mode; File workerHome = new File(testSuiteDir, workerId); Utils.ensureExistingDirectory(workerHome); String javaHome = getJavaHome(settings.javaVendor, settings.javaVersion); WorkerJvm workerJvm = new WorkerJvm(workerId); workerJvm.workerHome = workerHome; generateWorkerStartScript(mode, workerJvm); ProcessBuilder processBuilder = new ProcessBuilder(new String[]{"bash", "worker.sh"}) .directory(workerHome) .redirectErrorStream(true); Map<String, String> environment = processBuilder.environment(); String path = javaHome + File.pathSeparator + "bin:" + environment.get("PATH"); environment.put("PATH", path); environment.put("JAVA_HOME", javaHome); Process process = processBuilder.start(); File logFile = new File(workerHome, "out.log"); new WorkerJvmProcessOutputGobbler(process.getInputStream(), new FileOutputStream(logFile)).start(); workerJvm.process = process; workerJvm.mode = WorkerJvm.Mode.valueOf(mode.toUpperCase()); uploadResourcesToWorker(workerId); workerJVMs.put(workerId, workerJvm); return workerJvm; }

Target:
private WorkerJvm startWorkerJvm(String mode) throws IOException { String workerId = "worker-" + getHostAddress() + "-" + WORKER_ID_GENERATOR.incrementAndGet() + "-" + mode; File workerHome = new File(testSuiteDir, workerId); Utils.ensureExistingDirectory(workerHome); String javaHome = getJavaHome(settings.javaVendor, settings.javaVersion); WorkerJvm workerJvm = new WorkerJvm(workerId); workerJvm.workerHome = workerHome; generateWorkerStartScript(mode, workerJvm); ProcessBuilder processBuilder = new ProcessBuilder(new String[]{"bash", "worker.sh"}) .directory(workerHome) .redirectErrorStream(true); Map<String, String> environment = processBuilder.environment(); String path = javaHome + File.pathSeparator + "bin:" + environment.get("PATH"); environment.put("PATH", path); environment.put("JAVA_HOME", javaHome); Process process = processBuilder.start(); File logFile = new File(workerHome, "out.log"); new WorkerJvmProcessOutputGobbler(process.getInputStream(), new FileOutputStream(logFile)).start(); workerJvm.process = process; workerJvm.mode = WorkerJvm.Mode.valueOf(mode.toUpperCase()); copyResourcesToWorkerId(workerId); workerJVMs.put(workerId, workerJvm); return workerJvm; }
Source:
public void onStart(SourceCallback<T, A> sourceCallback) throws MuleException { delegate.onStart(sourceCallback); flowName = componentLocation.getRootContainerName(); inflightIdsObjectStore = objectStoreManager.getOrCreateObjectStore(formatKey(INFLIGHT_IDS_OS_NAME_SUFFIX), unmanagedTransient()); recentlyProcessedIds = objectStoreManager.getOrCreateObjectStore(formatKey(RECENTLY_PROCESSED_IDS_OS_NAME_SUFFIX), unmanagedPersistent()); idsOnUpdatedWatermark = objectStoreManager.getOrCreateObjectStore(formatKey(IDS_ON_UPDATED_WATERMARK_OS_NAME_SUFFIX), unmanagedPersistent()); watermarkObjectStore = objectStoreManager.getOrCreateObjectStore(formatKey(WATERMARK_OS_NAME_SUFFIX), unmanagedPersistent()); executor = schedulerService.customScheduler(SchedulerConfig.config() .withMaxConcurrentTasks(1) .withWaitAllowed(true) .withName(formatKey("executor"))); stopRequested.set(false); if (restarting.compareAndSet(true, false)) { delegateRunnable.setDelegate(() -> poll(sourceCallback)); poll(sourceCallback); } else { delegateRunnable = new DelegateRunnable(() -> poll(sourceCallback)); scheduler.schedule(executor, delegateRunnable); } }

Target:
public void onStart(SourceCallback<T, A> sourceCallback) throws MuleException { delegate.onStart(sourceCallback); flowName = componentLocation.getRootContainerName(); inflightIdsObjectStore = objectStoreManager.getOrCreateObjectStore(formatKey(INFLIGHT_IDS_OS_NAME_SUFFIX), unmanagedTransient()); recentlyProcessedIds = objectStoreManager.getOrCreateObjectStore(formatKey(RECENTLY_PROCESSED_IDS_OS_NAME_SUFFIX), unmanagedPersistent()); idsOnUpdatedWatermark = objectStoreManager.getOrCreateObjectStore(formatKey(IDS_ON_UPDATED_WATERMARK_OS_NAME_SUFFIX), unmanagedPersistent()); watermarkObjectStore = objectStoreManager.getOrCreateObjectStore(formatKey(WATERMARK_OS_NAME_SUFFIX), unmanagedPersistent()); stopRequested.set(false); if (restarting.compareAndSet(true, false)) { poll(sourceCallback); delegateRunnable.setDelegate(() -> poll(sourceCallback)); } else { executor = schedulerService.customScheduler(SchedulerConfig.config() .withMaxConcurrentTasks(1) .withWaitAllowed(true) .withName(formatKey("executor"))); delegateRunnable = new DelegateRunnable(() -> poll(sourceCallback)); scheduler.schedule(executor, delegateRunnable); } }
Source:
public RangePickerDecimalWidget(Context context, QuestionDetails questionDetails) { super(context, questionDetails); RangePickerViewModel rangePickerViewModel = new ViewModelProvider(((ScreenContext) getContext()).getActivity(), new ViewModelProvider.NewInstanceFactory()).get(RangePickerViewModel.class); rangePickerViewModel.getNumberPickerValue().observe(((ScreenContext) getContext()).getViewLifecycle(), answer -> { if (answer != null) { progress = rangePickerViewModel.getNumberPickerProgress(rangeStart, rangeStep, rangeEnd, answer); binding.widgetAnswerText.setText(rangePickerViewModel.getStringAnswer()); binding.widgetButton.setText(R.string.edit_value); } }); }

Target:
public RangePickerDecimalWidget(Context context, QuestionDetails questionDetails) { super(context, questionDetails); }
Source:
public String createUser(StudyParticipant participant, boolean consentUser) { session.checkSignedIn(); ObjectNode node = (ObjectNode)Utilities.getMapper().valueToTree(participant); node.put("consent", Boolean.toString(consentUser)); JsonNode sessionNode = postForJSON(config.getUsersApi(), node); return sessionNode.get("id").asText(); }

Target:
public String createUser(StudyParticipant participant, boolean consentUser) { session.checkSignedIn(); ObjectNode node = (ObjectNode)Utilities.getMapper().valueToTree(participant); node.put("consent", Boolean.toString(consentUser)); UserSession userSession = post(config.getUsersApi(), node, UserSession.class); return userSession.getStudyParticipant().getId(); }
Source:
public static int writeStreamEvent(final OutputStream outputStream, final Cursor cursor, final List<byte[]> events) throws IOException { final CountingOutputStream countingOutputStream = new CountingOutputStream(outputStream) { @Override public void flush() throws IOException { } }; final Writer writer = new OutputStreamWriter(countingOutputStream); writer.write("{\"cursor\":{\"partition\":\""); writer.write(cursor.getPartition()); writer.write("\",\"offset\":\""); writer.write(cursor.getOffset()); writer.write("\"}"); if (!events.isEmpty()) { writer.write(",\"events\":["); writer.flush(); boolean first = true; for (final byte[] event : events) { if (!first) { countingOutputStream.write(','); } countingOutputStream.write(event); first = false; } countingOutputStream.write(']'); } writer.write("}"); writer.write(BATCH_SEPARATOR); writer.flush(); outputStream.flush(); return countingOutputStream.getCount(); }

Target:
public static int writeStreamEvent(final OutputStream outputStream, final Cursor cursor, final List<byte[]> events) throws IOException { final CountingOutputStream countingOutputStream = new CountingOutputStream(outputStream) { @Override public void flush() throws IOException { } }; final Writer writer = new OutputStreamWriter(countingOutputStream, UTF_8); writer.write("{\"cursor\":{\"partition\":\""); writer.write(cursor.getPartition()); writer.write("\",\"offset\":\""); writer.write(cursor.getOffset()); writer.write("\"}"); if (!events.isEmpty()) { writer.write(",\"events\":["); writer.flush(); boolean first = true; for (final byte[] event : events) { if (!first) { countingOutputStream.write(','); } countingOutputStream.write(event); first = false; } countingOutputStream.write(']'); } writer.write("}"); writer.write(BATCH_SEPARATOR); writer.flush(); outputStream.flush(); return countingOutputStream.getCount(); }
Source:
public boolean contains(float[] coords) { int polyCorners = abscissa.length; int j = polyCorners - 1; boolean oddNodes = false; for (int i = 0; i < polyCorners; i++) { if(abscissa[i] == coords[0] && ordinate[i] == coords[1]) { return true; } if(ordinate[i] == ordinate[j] && ordinate[j] == coords[1]) { if ((abscissa[i] < abscissa[j] && abscissa[j] > coords[0] && abscissa[i] < coords[0]) || (abscissa[i] > abscissa[j] && abscissa[j] < coords[0] && abscissa[i] > coords[0])) { return true; } } if ((ordinate[i] < coords[1] && ordinate[j] >= coords[1] || ordinate[j] < coords[1] && ordinate[i] >= coords[1]) && (abscissa[i] <= coords[0] || abscissa[j] <= coords[0])) { if (abscissa[i] + (coords[1] - ordinate[i]) / (ordinate[j] - ordinate[i]) * (abscissa[j] - abscissa[i]) == coords[0]) { return true; } else if (abscissa[i] + (coords[1] - ordinate[i]) / (ordinate[j] - ordinate[i]) * (abscissa[j] - abscissa[i]) < coords[0]) { oddNodes = !oddNodes; } } j = i; } return oddNodes; }

Target:
public boolean contains(float[] coords) { int polyCorners = abscissa.length; int j = polyCorners - 1; boolean oddNodes = false; for (int i = 0; i < polyCorners; i++) { if (abscissa[i] == coords[0] && ordinate[i] == coords[1]) { return true; } if (isPointLayingOnHorizontalBound(i, j, coords)) { return true; } if (between(ordinate[i], ordinate[j], coords[1]) && (abscissa[j] <= coords[0] || abscissa[i] <= coords[0])) { float intersectionPointX = abscissa[i] + (coords[1] - ordinate[i]) / (ordinate[j] - ordinate[i]) * (abscissa[j] - abscissa[i]); if (intersectionPointX == coords[0]) { return true; } else if (intersectionPointX < coords[0]) { oddNodes = !oddNodes; } } j = i; } return oddNodes; }
Source:
private static GeometryType find( int gtype ) { for ( GeometryType type : GeometryType.values() ) { if ( type.gtype == gtype ) { return type; } } return null; }

Target:
private static GeometryType find( int gtype ) { if ( gtype < TYPES.length ) { return TYPES[gtype]; } else { return GEOMETRY_INVALID; } }
Source:
private HttpResponse readFromStream(Properties properties, long startTime, long endTime) throws Exception { String host = properties.getProperty("sink1.host"); String port = properties.getProperty("sink1.port"); boolean ssl = Boolean.parseBoolean(properties.getProperty("sink1.ssl")); String streamId = properties.getProperty("sink1.streamName"); String authClientPropertiesPath = properties.getProperty("sink1.authClientProperties"); URI baseUrl = URI.create(String.format("%s://%s:%s", ssl ? "https" : "http", host, port)); HttpGet getRequest = new HttpGet(baseUrl.resolve(String.format("/v2/streams/%s/events?start=%s&end=%s", streamId, startTime, endTime))); if (authClientPropertiesPath != null) { String authClientClassName = properties.getProperty( "sink1.authClientClass", "co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClient"); AuthenticationClient authClient = (AuthenticationClient) Class.forName(authClientClassName).newInstance(); Properties authProperties = new Properties(); InputStream inStream = null; try { inStream = new FileInputStream(authClientPropertiesPath); properties.load(inStream); authClient.configure(properties); authClient.setConnectionInfo(host, Integer.parseInt(port), ssl); AccessToken token = authClient.getAccessToken(); getRequest.setHeader("Authorization", token.getTokenType() + " " + token.getValue()); } finally { try { if (inStream != null) { inStream.close(); } } catch (IOException e) { } } } CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager( new BasicHttpClientConnectionManager()).build(); HttpResponse response = httpClient.execute(getRequest); return response; }

Target:
private String readFromStream(Properties properties, long startTime, long endTime) throws Exception { URI baseUrl = URI.create(String.format("%s://%s:%s", ssl ? "https" : "http", cdapHost, cdapPort)); HttpGet getRequest = new HttpGet(baseUrl.resolve(String.format("/v2/streams/%s/events?start=%s&end=%s", streamId, startTime, endTime))); if (authClientPropertiesPath != null) { AuthenticationClient authClient = configureAuthClient(); AccessToken token = authClient.getAccessToken(); getRequest.setHeader("Authorization", token.getTokenType() + " " + token.getValue()); } CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager( new BasicHttpClientConnectionManager()).build(); HttpResponse response = httpClient.execute(getRequest); String res = EntityUtils.toString(response.getEntity()); Closeables.close(httpClient, true); return res; }
Source:
protected void onLogin(final LoginModel loginModel) { ReportInit.getInstance().init(); ReportInit.getInstance().getReportsInitEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { updateAvailability(); } }); performLogin(loginModel); }

Target:
protected void onLogin(final LoginModel loginModel) { ReportInit.getInstance().init(); ReportInit.getInstance().getReportsInitEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { updateReportsAvailability(); } }); performLogin(loginModel); }
Source:
protected Collection<Worker> getWorkerFromZK(Collection<ZkWorker> workers) { return Collections2.transform( workers, new Function<ZkWorker, Worker>() { @Override public Worker apply(ZkWorker input) { return input.getWorker(); } } ); }

Target:
public static Collection<Worker> getWorkerFromZK(Collection<ZkWorker> workers) { return Collections2.transform( workers, new Function<ZkWorker, Worker>() { @Override public Worker apply(ZkWorker input) { return input.getWorker(); } } ); }
Source:
public ModuleManagerImpl(String masterServerAddress) { metadataReader = new ModuleMetadataJsonAdapter(); for (ModuleExtension ext : StandardModuleExtension.values()) { metadataReader.registerExtension(ext.getKey(), ext.getValueType()); } Module engineModule; try (Reader reader = new InputStreamReader(getClass().getResourceAsStream("/engine-module.txt"), TerasologyConstants.CHARSET)) { ModuleMetadata metadata = metadataReader.read(reader); engineModule = ClasspathModule.create(metadata, getClass(), Module.class, Asset.class); } catch (IOException e) { throw new RuntimeException("Failed to read engine metadata", e); } catch (URISyntaxException e) { throw new RuntimeException("Failed to convert engine library location to path", e); } registry = new TableModuleRegistry(); registry.add(engineModule); ModulePathScanner scanner = new ModulePathScanner(new ModuleLoader(metadataReader)); scanner.getModuleLoader().setModuleInfoPath(TerasologyConstants.MODULE_INFO_FILENAME); scanner.scan(registry, PathManager.getInstance().getModulePaths()); DependencyInfo engineDep = new DependencyInfo(); engineDep.setId(engineModule.getId()); engineDep.setMinVersion(engineModule.getVersion()); engineDep.setMaxVersion(engineModule.getVersion().getNextPatchVersion()); registry.stream().filter(mod -> mod != engineModule).forEach(mod -> mod.getMetadata().getDependencies().add(engineDep)); setupSandbox(); loadEnvironment(Sets.newHashSet(engineModule), true); installManager = new ModuleInstallManager(this, masterServerAddress); }

Target:
public ModuleManagerImpl(String masterServerAddress) { metadataReader = new ModuleMetadataJsonAdapter(); for (ModuleExtension ext : StandardModuleExtension.values()) { metadataReader.registerExtension(ext.getKey(), ext.getValueType()); } Module engineModule; try (Reader reader = new InputStreamReader(getClass().getResourceAsStream("/engine-module.txt"), TerasologyConstants.CHARSET)) { ModuleMetadata metadata = metadataReader.read(reader); engineModule = ClasspathModule.create(metadata, getClass(), Module.class, Asset.class); } catch (IOException e) { throw new RuntimeException("Failed to read engine metadata", e); } catch (URISyntaxException e) { throw new RuntimeException("Failed to convert engine library location to path", e); } registry = new TableModuleRegistry(); registry.add(engineModule); loadModulesFromClassPath(); ModulePathScanner scanner = new ModulePathScanner(new ModuleLoader(metadataReader)); scanner.getModuleLoader().setModuleInfoPath(TerasologyConstants.MODULE_INFO_FILENAME); scanner.scan(registry, PathManager.getInstance().getModulePaths()); DependencyInfo engineDep = new DependencyInfo(); engineDep.setId(engineModule.getId()); engineDep.setMinVersion(engineModule.getVersion()); engineDep.setMaxVersion(engineModule.getVersion().getNextPatchVersion()); registry.stream().filter(mod -> mod != engineModule).forEach(mod -> mod.getMetadata().getDependencies().add(engineDep)); setupSandbox(); loadEnvironment(Sets.newHashSet(engineModule), true); installManager = new ModuleInstallManager(this, masterServerAddress); }
Source:
public List<NearestNeighborsResult> search() { INDArray input = points.slice(record.getInputIndex()); List<NearestNeighborsResult> results = new ArrayList<>(); if (input.isVector()) { List<DataPoint> add = new ArrayList<>(); List<Double> distances = new ArrayList<>(); tree.search(input, record.getK(), add, distances); if (add.size() != distances.size()) { throw new IllegalStateException( String.format("add.size(%d) != distances.size(%d)", add.size(), distances.size())); } for (int i=0; i<add.size(); i++) { results.add(new NearestNeighborsResult(add.get(i).getIndex(), distances.get(i))); } } return results; }

Target:
public List<NearestNeighborsResult> search() { INDArray input = points.slice(record.getInputIndex()); List<NearestNeighborsResult> results = new ArrayList<>(); if (input.isVector()) { List<DataPoint> add = new ArrayList<>(); List<Double> distances = new ArrayList<>(); tree.search(input, record.getK(), add, distances); if (add.size() != distances.size()) { throw new IllegalStateException( String.format("add.size == %d != %d == distances.size", add.size(), distances.size())); } for (int i=0; i<add.size(); i++) { results.add(new NearestNeighborsResult(add.get(i).getIndex(), distances.get(i))); } } return results; }
Source:
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { if (uri == null) { if (defaultAudience != null) { uri = defaultAudience; } else { throw new IOException("JwtAccess requires Audience uri to be passed in or the " + "defaultAudience to be specified"); } } try { JwtCredentials.Claims defaultClaims = JwtCredentials.Claims.newBuilder() .setAudience(uri.toString()) .setIssuer(clientEmail) .setSubject(clientEmail) .build(); JwtCredentials credentials = credentialsCache.get(defaultClaims); return credentials.getRequestMetadata(uri); } catch (ExecutionException e) { Throwables.propagateIfPossible(e.getCause(), IOException.class); throw new IllegalStateException("generateJwtAccess threw an unexpected checked exception", e.getCause()); } catch (UncheckedExecutionException e) { Throwables.propagateIfPossible(e); throw new IllegalStateException("generateJwtAccess threw an unchecked exception that couldn't be rethrown", e); } }

Target:
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { if (uri == null) { if (defaultAudience != null) { uri = defaultAudience; } else { throw new IOException( "JwtAccess requires Audience uri to be passed in or the " + "defaultAudience to be specified"); } } try { JwtClaims defaultClaims = JwtClaims.newBuilder() .setAudience(uri.toString()) .setIssuer(clientEmail) .setSubject(clientEmail) .build(); JwtCredentials credentials = credentialsCache.get(defaultClaims); return credentials.getRequestMetadata(uri); } catch (ExecutionException e) { Throwables.propagateIfPossible(e.getCause(), IOException.class); throw new IllegalStateException( "generateJwtAccess threw an unexpected checked exception", e.getCause()); } catch (UncheckedExecutionException e) { Throwables.throwIfUnchecked(e); throw new IllegalStateException( "generateJwtAccess threw an unchecked exception that couldn't be rethrown", e); } }
Source:
public void setUp() throws Exception { tested = new CaseManagementSwitchViewServiceImpl(factoryManager, definitionSetServiceInstances); }

Target:
public void setUp() { tested = new CaseManagementSwitchViewServiceImpl(factoryManager, definitionSetServiceInstances); }
Source:
public MITIENERecogniser(String modelPath) { try { if(!(new File(modelPath)).exists()) { LOG.warn("{} does not exist", modelPath); }else { Class<?> namedEntityExtractorClass = Class.forName(NamedEntityExtractor_Class); extractorInstance = namedEntityExtractorClass.getDeclaredConstructor(new Class[]{String.class}).newInstance("/Users/manali/cs599_dr/MITIE/MITIE-models/english/ner_model.dat"); this.available = true; } } catch (Exception e) { LOG.warn("{} while trying to load the model from {}", e.getMessage(), modelPath); } LOG.info("Available for service ? {}", available); }

Target:
public MITIENERecogniser(String modelPath) { try { if(!(new File(modelPath)).exists()) { LOG.warn("{} does not exist", modelPath); }else { Class<?> namedEntityExtractorClass = Class.forName(NamedEntityExtractor_Class); extractorInstance = namedEntityExtractorClass.getDeclaredConstructor(new Class[]{String.class}).newInstance(modelPath); this.available = true; } } catch (Exception e) { LOG.warn("{} while trying to load the model from {}", e.getMessage(), modelPath); } LOG.info("Available for service ? {}", available); }
Source:
private void endInput() { stats.setNumBytesRead(this.streamPosition()); in = null; }

Target:
private void endInput() { stats.setNumBytesRead(streamPosition()); in = null; }
Source:
public void testHistoryGet() throws Exception { final String path = "git"; Response response = target("history") .queryParam("path", path) .request() .get(); HistoryDTO history = response.readEntity(new GenericType<HistoryDTO>() {}); History repoHistory = HistoryGuru.getInstance().getHistory(new File(repository.getSourceRoot(), path)); assertEquals(history, getHistoryDTO(repoHistory.getHistoryEntries())); }

Target:
public void testHistoryGet() throws Exception { final String path = "git"; int size = 5; int start = 2; Response response = target("history") .queryParam("path", path) .queryParam("max", size) .queryParam("start", start) .request() .get(); HistoryDTO history = response.readEntity(new GenericType<HistoryDTO>() {}); assertEquals(size, history.getEntries().size()); assertEquals("Kryštof Tulinger <krystof.tulinger@oracle.com>", history.getEntries().get(0).getAuthor()); History repoHistory = HistoryGuru.getInstance().getHistory(new File(repository.getSourceRoot(), path)); assertEquals(history, getHistoryDTO(repoHistory.getHistoryEntries(size, start), start, size, repoHistory.getHistoryEntries().size())); }
Source:
public void commitAssignExternalId(ExternalIdentifier externalId) { if (externalId != null) { try { mapper.save(externalId, getHealthCodeAssignedExpression(false)); } catch(ConditionalCheckFailedException e) { throw new EntityAlreadyExistsException(ExternalIdentifier.class, IDENTIFIER, externalId.getIdentifier()); } } }

Target:
public void commitAssignExternalId(ExternalIdentifier externalId) { if (externalId != null) { DynamoExternalIdentifier key = new DynamoExternalIdentifier( externalId.getStudyId(), externalId.getIdentifier()); if (externalId.getHealthCode() == null || mapper.load(key) == null) { throw new ConcurrentModificationException("External ID was concurrently deleted or assigned"); } try { mapper.save(externalId, getHealthCodeAssignedExpression(false)); } catch(ConditionalCheckFailedException e) { throw new EntityAlreadyExistsException(ExternalIdentifier.class, IDENTIFIER, externalId.getIdentifier()); } } }
Source:
private SamInputResource getRemoteResource(String objectId) { metaQuery.setObjectId(objectId); URL bamFileUrl = downloader.getUrl(objectId, 0, -1); Optional<String> indexFileId = metaQuery.getAssociatedIndexObjectId(); if (!indexFileId.isPresent()) { throw new RuntimeException(String.format("No index file associated with BAM file (object_id = {})", objectId)); } URL indexFileUrl = downloader.getUrl(indexFileId.get()); NullSourceSeekableHTTPStream bamFileHttpStream = new NullSourceSeekableHTTPStream(bamFileUrl); NullSourceSeekableHTTPStream indexFileHttpStream = new NullSourceSeekableHTTPStream(indexFileUrl); SamInputResource resource = SamInputResource.of(bamFileHttpStream).index(indexFileHttpStream); return resource; }

Target:
private SamInputResource getRemoteResource(String objectId) { metaQuery.setObjectId(objectId); URL bamFileUrl = downloader.getUrl(objectId, 0, -1); Optional<String> indexFileId = metaQuery.getAssociatedIndexObjectId(); checkState(indexFileId.isPresent(), "No index file associated with BAM file (object_id = %s)", objectId); URL indexFileUrl = downloader.getUrl(indexFileId.get()); NullSourceSeekableHTTPStream bamFileHttpStream = new NullSourceSeekableHTTPStream(bamFileUrl); NullSourceSeekableHTTPStream indexFileHttpStream = new NullSourceSeekableHTTPStream(indexFileUrl); SamInputResource resource = SamInputResource.of(bamFileHttpStream).index(indexFileHttpStream); return resource; }
Source:
RotatingFileOutputStreamSupplier( LongSupplier currentTimeSupplier, FileSystemAbstraction fileSystem, File outputFile, long rotationThresholdBytes, long rotationDelay, int maxArchives, Executor rotationExecutor, RotationListener rotationListener ) throws IOException { this.currentTimeSupplier = currentTimeSupplier; this.fileSystem = fileSystem; this.outputFile = outputFile; this.rotationThresholdBytes = rotationThresholdBytes; this.rotationDelay = rotationDelay; this.maxArchives = maxArchives; this.rotationListener = rotationListener; this.rotationExecutor = rotationExecutor; this.outRef.set( openOutputFile() ); this.streamWrapper = new OutputStream() { @Override public void write( int i ) throws IOException { synchronized ( outRef ) { outRef.get().write( i ); } } @Override public void write( byte[] bytes ) throws IOException { synchronized ( outRef ) { outRef.get().write( bytes ); } } @Override public void write( byte[] bytes, int off, int len ) throws IOException { synchronized ( outRef ) { outRef.get().write( bytes, off, len ); } } @Override public void flush() throws IOException { synchronized ( outRef ) { outRef.get().flush(); } } }; }

Target:
RotatingFileOutputStreamSupplier( LongSupplier currentTimeSupplier, FileSystemAbstraction fileSystem, File outputFile, long rotationThresholdBytes, long rotationDelay, int maxArchives, Executor rotationExecutor, RotationListener rotationListener ) throws IOException { this.currentTimeSupplier = currentTimeSupplier; this.fileSystem = fileSystem; this.outputFile = outputFile; this.rotationThresholdBytes = rotationThresholdBytes; this.rotationDelay = rotationDelay; this.maxArchives = maxArchives; this.rotationListener = rotationListener; this.rotationExecutor = rotationExecutor; this.outRef = openOutputFile(); this.streamWrapper = new OutputStream() { @Override public void write( int i ) throws IOException { logFileLock.readLock().lock(); try { outRef.write( i ); } finally { logFileLock.readLock().unlock(); } } @Override public void write( byte[] bytes ) throws IOException { logFileLock.readLock().lock(); try { outRef.write( bytes ); } finally { logFileLock.readLock().unlock(); } } @Override public void write( byte[] bytes, int off, int len ) throws IOException { logFileLock.readLock().lock(); try { outRef.write( bytes, off, len ); } finally { logFileLock.readLock().unlock(); } } @Override public void flush() throws IOException { logFileLock.readLock().lock(); try { outRef.flush(); } finally { logFileLock.readLock().unlock(); } } }; }
Source:
public void start(BundleContext context) throws Exception { Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { } setUpJena(); } }); t.start(); }

Target:
public void start(BundleContext context) throws Exception { JenaSubsystemRegistry r = new JenaSubsystemRegistryBasic() { @Override public void load() { super.load(); } }; JenaSystem.setSubsystemRegistry(r); JenaSystem.DEBUG_INIT = true; JenaSystem.init(); System.out.println("Jena-OSGi bundle configuration done!"); }
Source:
public DimFilter optimize() { if (this.getExtractionFn() instanceof LookupExtractionFn && ((LookupExtractionFn) this.getExtractionFn()).isOptimize()) { LookupExtractor lookup = ((LookupExtractionFn) this.getExtractionFn()).getLookup(); final List<String> keys = lookup.unapply(this.getValue()); final String dimensionName = this.getDimension(); if (!keys.isEmpty()) { return new OrDimFilter(Lists.transform(keys, new Function<String, DimFilter>() { @Override public DimFilter apply(String input) { return new SelectorDimFilter(dimensionName, input, null); } })); } } return this; }

Target:
public DimFilter optimize() { if (this.getExtractionFn() instanceof LookupExtractionFn && ((LookupExtractionFn) this.getExtractionFn()).isOptimize()) { LookupExtractionFn exFn = (LookupExtractionFn) this.getExtractionFn(); LookupExtractor lookup = exFn.getLookup(); final String convertedValue = Strings.emptyToNull(value); if (!exFn.isRetainMissingValue() && Objects.equals(convertedValue, exFn.getReplaceMissingValueWith())) { return this; } final String mappingForValue = lookup.apply(convertedValue); final List<String> keys = new ArrayList<>(); keys.addAll(lookup.unapply(convertedValue)); if (exFn.isRetainMissingValue() && mappingForValue == null) { keys.add(convertedValue); } if (keys.isEmpty()) { return this; } else if (keys.size() == 1) { return new SelectorDimFilter(dimension, keys.get(0), null); } else { return new InDimFilter(dimension, keys, null); } } return this; }
Source:
public void addAdditionalListeners() { super.addAdditionalListeners(); ActivityPartition lifeline = getUMLElement(); if (lifeline == null) { return; } getDiagramEventBroker().addNotificationListener(lifeline, this); if (!(lifeline.getRepresents() instanceof ConnectableElement)) { return; } ConnectableElement ce = (ConnectableElement) lifeline.getRepresents(); if (ce != null) { getDiagramEventBroker().addNotificationListener(ce, this); if (ce.getType() != null) { getDiagramEventBroker().addNotificationListener(ce.getType(), this); } } }

Target:
public void addAdditionalListeners() { super.addAdditionalListeners(); ActivityPartition activityPartition = getUMLElement(); if (activityPartition == null) { return; } getDiagramEventBroker().addNotificationListener(activityPartition, this); if (!(activityPartition.getRepresents() instanceof ConnectableElement)) { return; } Element el = (Element) activityPartition.getRepresents(); if (el != null) { getDiagramEventBroker().addNotificationListener(el, this); } }
Source:
public File getLastThreadScreenshot() { List<File> screenshots = threadScreenshots.get(); return screenshots.isEmpty() ? null : screenshots.get(screenshots.size() - 1); }

Target:
public Optional<File> getLastThreadScreenshot() { List<File> screenshots = threadScreenshots.get(); return getLastScreenshot(screenshots); }