auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static <T> TSpliterator<T> spliterator(Object[] array, int additionalCharacteristics) { TArrayList<T> list = new TArrayList<T>(); for (Object element : array) { list.add((T) element); } return list.spliterator(); }

Target:
public static <T> TSpliterator<T> spliterator(Object[] array, int additionalCharacteristics) { return new TSpliterator<T>() { private int index; @Override public boolean tryAdvance(Consumer<? super T> action) { if (index >= array.length) { return false; } action.accept((T) array[index]); index++; return true; } @Override public TSpliterator<T> trySplit() { return null; } @Override public long estimateSize() { return array.length; } @Override public int characteristics() { return additionalCharacteristics | TSpliterator.SIZED; } }; }
Source:
private PublicKey decodePublicKey(String key) throws Exception { InputStream stream = new ClassPathResource(key).getInputStream(); byte[] keyBytes = StreamUtils.copyToByteArray(stream); while (keyBytes[keyBytes.length - 1] == 0x0a || keyBytes[keyBytes.length - 1] == 0x0c) { keyBytes = Arrays.copyOf(keyBytes, keyBytes.length - 1); } byte[] decodeBuffer = Base64Utils.decode(keyBytes); ByteBuffer bb = ByteBuffer.wrap(decodeBuffer); int len = bb.getInt(); byte[] type = new byte[len]; bb.get(type); if ("ssh-rsa".equals(new String(type))) { BigInteger e = decodeBigInt(bb); BigInteger m = decodeBigInt(bb); RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); return KeyFactory.getInstance("RSA").generatePublic(spec); } else { throw new IllegalArgumentException("Only supports RSA"); } }

Target:
private PublicKey decodePublicKey(String key) throws Exception { InputStream stream = new ClassPathResource(key).getInputStream(); byte[] keyBytes = StreamUtils.copyToByteArray(stream); while (keyBytes[keyBytes.length - 1] == 0x0a || keyBytes[keyBytes.length - 1] == 0x0d) { keyBytes = Arrays.copyOf(keyBytes, keyBytes.length - 1); } byte[] decodeBuffer = Base64Utils.decode(keyBytes); ByteBuffer bb = ByteBuffer.wrap(decodeBuffer); int len = bb.getInt(); byte[] type = new byte[len]; bb.get(type); if ("ssh-rsa".equals(new String(type))) { BigInteger e = decodeBigInt(bb); BigInteger m = decodeBigInt(bb); RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e); return KeyFactory.getInstance("RSA").generatePublic(spec); } else { throw new IllegalArgumentException("Only supports RSA"); } }
Source:
private void addCommandsToResponse(final String deviceName, final Integer firmwareVersion, final OutputProtos.SyncResponse.Builder responseBuilder) { LOGGER.info("Response commands allowed for DeviceId: {}", deviceName); final List<ResponseCommand> respCommandsToFetch = new ArrayList<>(); respCommandsToFetch.add(ResponseCommand.RESET_TO_FACTORY_FW); respCommandsToFetch.add(ResponseCommand.RESET_MCU); respCommandsToFetch.add(ResponseCommand.SET_LOG_LEVEL); Map<ResponseCommand,String> commandMap = responseCommandsDAODynamoDB.getResponseCommands(deviceName, firmwareVersion, respCommandsToFetch); if (!commandMap.isEmpty()) { for (final ResponseCommand cmd : respCommandsToFetch) { if (commandMap.containsKey(cmd)) { final String cmdValue = commandMap.get(cmd); switch(cmd) { case RESET_TO_FACTORY_FW: responseBuilder.setResetToFactoryFw(Boolean.parseBoolean(cmdValue)); break; case RESET_MCU: responseBuilder.setResetMcu(Boolean.parseBoolean(cmdValue)); break; case SET_LOG_LEVEL: responseBuilder.setUploadLogLevel(Integer.parseInt(cmdValue)); break; } } } } }

Target:
private void addCommandsToResponse(final String deviceName, final Integer firmwareVersion, final OutputProtos.SyncResponse.Builder responseBuilder) { LOGGER.info("Response commands allowed for DeviceId: {}", deviceName); final List<ResponseCommand> respCommandsToFetch = Lists.newArrayList( ResponseCommand.RESET_TO_FACTORY_FW, ResponseCommand.RESET_MCU, ResponseCommand.SET_LOG_LEVEL ); final Map<ResponseCommand, String> commandMap = responseCommandsDAODynamoDB.getResponseCommands(deviceName, firmwareVersion, respCommandsToFetch); if (commandMap.isEmpty()) { return; } for (final ResponseCommand cmd : respCommandsToFetch) { if (!commandMap.containsKey(cmd)) { continue; } final String cmdValue = commandMap.get(cmd); switch (cmd) { case RESET_TO_FACTORY_FW: responseBuilder.setResetToFactoryFw(Boolean.parseBoolean(cmdValue)); break; case RESET_MCU: responseBuilder.setResetMcu(Boolean.parseBoolean(cmdValue)); break; case SET_LOG_LEVEL: try { final Integer logLevel = Integer.parseInt(cmdValue); if (!SenseLogLevelUtil.isAllowedLogLevel(logLevel)) { LOGGER.warn("Log level value '%03X' not allowed.", logLevel); continue; } responseBuilder.setUploadLogLevel(logLevel); } catch (NumberFormatException nfe) { LOGGER.warn("Bad log level value passed with 'set_log_level' response command."); return; } break; } } }
Source:
private List<String> getLatestDirectoryNames() throws IOException { String inputLine; List<String> currentDirectories = Lists.newArrayList(); Pattern itunesPattern = Pattern.compile("itunes\\d{8}"); Pattern pricingPattern = Pattern.compile("pricing\\d{8}"); URL currentUrl = new URL(feedPath); URLConnection urlConnection = currentUrl.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( urlConnection.getInputStream() )); while ((inputLine = in.readLine()) != null) { Matcher itunesMatcher = itunesPattern.matcher(inputLine); Matcher pricingMatcher = pricingPattern.matcher(inputLine); if (itunesMatcher.find()) { currentDirectories.add(itunesMatcher.group(0)); } else if (pricingMatcher.find()) { currentDirectories.add(pricingMatcher.group(0)); } } in.close(); return currentDirectories; }

Target:
private void getLatestDirectoryNames() throws IOException { String inputLine; List<String> currentDirectories = Lists.newArrayList(); Pattern itunesPattern = Pattern.compile("itunes\\d{8}"); Pattern pricingPattern = Pattern.compile("pricing\\d{8}"); URL currentUrl = new URL(feedPath); URLConnection urlConnection = currentUrl.openConnection(); try (BufferedReader in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream()) )) { while ((inputLine = in.readLine()) != null) { Matcher itunesMatcher = itunesPattern.matcher(inputLine); Matcher pricingMatcher = pricingPattern.matcher(inputLine); if (itunesMatcher.find()) { currentDirectories.add(itunesMatcher.group(0)); } else if (pricingMatcher.find()) { currentDirectories.add(pricingMatcher.group(0)); } } } itunesDirectory = currentDirectories.get(0); pricingDirectory = currentDirectories.get(1); }
Source:
private List<WireRecord> buildWireRecord(final KuraPayload payload) throws IOException { requireNonNull(payload, wireMessages.payloadNonNull()); Map<String, Object> kuraPayloadProperties = payload.metrics(); Map<String, TypedValue<?>> wireProperties = new HashMap<>(); for (Entry<String, Object> entry : kuraPayloadProperties.entrySet()) { String entryKey = entry.getKey(); Object entryValue = entry.getValue(); TypedValue<?> convertedValue; if (entryValue instanceof Boolean) { final boolean value = Boolean.parseBoolean(String.valueOf(entryValue)); convertedValue = TypedValues.newBooleanValue(value); } else if (entryValue instanceof Byte) { final byte value = Byte.parseByte(String.valueOf(entryValue)); convertedValue = TypedValues.newByteValue(value); } else if (entryValue instanceof Long) { final long value = Long.parseLong(String.valueOf(entryValue)); convertedValue = TypedValues.newLongValue(value); } else if (entryValue instanceof Double) { final double value = Double.parseDouble(String.valueOf(entryValue)); convertedValue = TypedValues.newDoubleValue(value); } else if (entryValue instanceof Integer) { final int value = Integer.parseInt(String.valueOf(entryValue)); convertedValue = TypedValues.newIntegerValue(value); } else if (entryValue instanceof Short) { final short value = Short.parseShort(String.valueOf(entryValue)); convertedValue = TypedValues.newShortValue(value); } else if (entryValue instanceof String) { final String value = String.valueOf(entryValue); convertedValue = TypedValues.newStringValue(value); } else if (entryValue instanceof byte[]) { final byte[] value = TypeUtil.objectToByteArray(entryValue); convertedValue = TypedValues.newByteArrayValue(value); } else { throw new IllegalArgumentException("Unknown metric type"); } wireProperties.put(entryKey, convertedValue); } final WireRecord wireRecord = new WireRecord(wireProperties); return Arrays.asList(wireRecord); }

Target:
private List<WireRecord> buildWireRecord(final KuraPayload payload) throws IOException { requireNonNull(payload, wireMessages.payloadNonNull()); final Map<String, Object> kuraPayloadProperties = payload.metrics(); final Map<String, TypedValue<?>> wireProperties = new HashMap<>(); for (Entry<String, Object> entry : kuraPayloadProperties.entrySet()) { final String entryKey = entry.getKey(); final Object entryValue = entry.getValue(); final TypedValue<?> convertedValue = TypedValues.newTypedValue(entryValue); wireProperties.put(entryKey, convertedValue); } final WireRecord wireRecord = new WireRecord(wireProperties); return Arrays.asList(wireRecord); }
Source:
private ResourceId(final String id) { if (id == null) { this.subscriptionId = null; this.resourceGroupName = null; this.name = null; this.providerNamespace = null; this.resourceType = null; this.id = null; this.parentId = null; return; } else { String[] splits = (id.startsWith("/")) ? id.substring(1).split("/") : id.split("/"); if (splits.length % 2 == 1) { throw new InvalidParameterException(badIdErrorText(id)); } this.id = id; if (splits.length < 2) { throw new InvalidParameterException(badIdErrorText(id)); } else { this.name = splits[splits.length - 1]; this.resourceType = splits[splits.length - 2]; } if (splits.length < 10) { this.parentId = null; } else { String[] parentSplits = new String[splits.length - 2]; System.arraycopy(splits, 0, parentSplits, 0, splits.length - 2); this.parentId = "/" + String.join("/", parentSplits); } if (!splits[0].equalsIgnoreCase("subscriptions")) { throw new InvalidParameterException(badIdErrorText(id)); } this.subscriptionId = splits[1]; if (!splits[2].equalsIgnoreCase("resourceGroups")) { throw new InvalidParameterException(badIdErrorText(id)); } this.resourceGroupName = splits[3]; if (!splits[4].equalsIgnoreCase("providers")) { throw new InvalidParameterException(badIdErrorText(id)); } this.providerNamespace = splits[5]; } }

Target:
private ResourceId(final String id) { if (id == null) { this.subscriptionId = null; this.resourceGroupName = null; this.name = null; this.providerNamespace = null; this.resourceType = null; this.id = null; this.parentId = null; return; } else { String[] splits = (id.startsWith("/")) ? id.substring(1).split("/") : id.split("/"); if (splits.length % 2 == 1) { throw new InvalidParameterException(badIdErrorText(id)); } this.id = id; if (splits.length < 2) { throw new InvalidParameterException(badIdErrorText(id)); } else { this.name = splits[splits.length - 1]; this.resourceType = splits[splits.length - 2]; } if (splits.length < 10) { this.parentId = null; } else { String[] parentSplits = new String[splits.length - 2]; System.arraycopy(splits, 0, parentSplits, 0, splits.length - 2); this.parentId = "/" + String.join("/", parentSplits); } if (splits.length > 0 && !splits[0].equalsIgnoreCase("subscriptions")) { throw new InvalidParameterException(badIdErrorText(id)); } this.subscriptionId = splits.length > 1 ? splits[1] : null; if (splits.length > 2 && !splits[2].equalsIgnoreCase("resourceGroups")) { throw new InvalidParameterException(badIdErrorText(id)); } this.resourceGroupName = splits.length > 3 ? splits[3] : null; if (splits.length > 4 && !splits[4].equalsIgnoreCase("providers")) { throw new InvalidParameterException(badIdErrorText(id)); } this.providerNamespace = splits.length > 5 ? splits[5] : null; } }
Source:
public LongObjectHashMap<Long> measureGroupingOnLongArray() { LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>(); for (long number : numbers) { sumByKey.compute(number, (key, oldValue) -> { if (oldValue == null) { return 0L; } else { return oldValue + number; } }); } return sumByKey; }

Target:
public LongObjectHashMap<Long> measureGroupingOnLongArray() { LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>(); for (long number : numbers) { sumByKey.compute(number, (key, oldValue) -> { if (oldValue == null) { return number; } else { return oldValue + number; } }); } return sumByKey; }
Source:
public Work addPage(Page page) { Work work = new AddPageWork(page.getBlock(hashChannel)); work.process(); return work; }

Target:
public Work<?> addPage(Page page) { currentPageSizeInBytes = page.getRetainedSizeInBytes(); return new AddPageWork(page.getBlock(hashChannel)); }
Source:
public void resetClearsInitMainThreadHandler() throws Exception { RxAndroidPlugins .setInitMainThreadSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(Callable<Scheduler> scheduler) { throw new RuntimeException(); } }); final Scheduler scheduler = new EmptyScheduler(); Callable<Scheduler> schedulerCallable = new Callable<Scheduler>() { @Override public Scheduler call() throws Exception { return scheduler; } }; RxAndroidPlugins.reset(); Scheduler actual = RxAndroidPlugins.initMainThreadScheduler(schedulerCallable); assertSame(schedulerCallable.call(), actual); }

Target:
public void resetClearsInitMainThreadHandler() throws Exception { RxAndroidPlugins .setInitMainThreadSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(Callable<Scheduler> scheduler) { throw new AssertionError(); } }); final Scheduler scheduler = new EmptyScheduler(); Callable<Scheduler> schedulerCallable = new Callable<Scheduler>() { @Override public Scheduler call() throws Exception { return scheduler; } }; RxAndroidPlugins.reset(); Scheduler actual = RxAndroidPlugins.initMainThreadScheduler(schedulerCallable); assertSame(schedulerCallable.call(), actual); }
Source:
SessionCreationPolicy getSessionCreationPolicy() { if (this.sessionPolicy != null) { return this.sessionPolicy; } SessionCreationPolicy shared = getBuilder().getSharedObject(SessionCreationPolicy.class); return shared == null ? SessionCreationPolicy.IF_REQUIRED : shared; }

Target:
SessionCreationPolicy getSessionCreationPolicy() { if (this.sessionPolicy != null) { return this.sessionPolicy; } SessionCreationPolicy sessionPolicy = getBuilder().getSharedObject(SessionCreationPolicy.class); return sessionPolicy == null ? SessionCreationPolicy.IF_REQUIRED : sessionPolicy; }
Source:
private List<String> getCurrentCycle(Node start) { List<String> cycle = new ArrayList<String>(); boolean inCycle = false; for ( Node n : currentPath ) { if ( n.getName().equals( start.getName() ) ) { inCycle = true; } if ( inCycle ) { cycle.add( n.getName() ); } } return cycle; }

Target:
private List<String> getCurrentCycle(Node start) { List<String> cycle = new ArrayList<String>(); boolean inCycle = false; for ( Node n : currentPath ) { if ( !inCycle && n.equals( start ) ) { inCycle = true; } if ( inCycle ) { cycle.add( n.getName() ); } } return cycle; }
Source:
public SimulatedRead getNextRead() throws IOException { SimulatedRead read; final String nameLine = fastqBr.readLine(); if (nameLine == null) { return null; } if (nameLine.trim().length() < 1) { log.warning("got empty string at FASTQ line " + fastqBr.getLineNumber()); return null; } ArtAlnRecord alnRecord; if ((alnRecord = artAlnR.getNextAln()) == null) { return null; } final String nameFields[] = nameLine.trim().substring(1).split("[-/]"); if (nameFields.length < 2) { log.warning("expect at least 2 fields at fastq line " + fastqBr.getLineNumber() + ": " + nameLine); return null; } read = new SimulatedRead(); read.fragment = Integer.parseInt(nameFields[nameFields.length - 1]); read.setReadId(nameFields[nameFields.length - 2]); read.sequence = fastqBr.readLine().trim(); if (forceFiveBaseEncoding) { read.sequence = nonACGTPattern.matcher(read.sequence).replaceAll("N"); } fastqBr.readLine(); read.quality = fastqBr.readLine().trim(); if (read.fragment == 1) { read.locs1.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.origLocs1.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.alignedBases1 = alnRecord.alignedBases; } else { read.locs2.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.origLocs2.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.alignedBases2 = alnRecord.alignedBases; } return read; }

Target:
public SimulatedRead getNextRead() throws IOException { SimulatedRead read; final String nameLine = fastqBr.readLine(); if (nameLine == null) { return null; } if (nameLine.trim().length() < 1) { log.error("got empty name string at FASTQ line " + fastqBr.getLineNumber()); return null; } ArtAlnRecord alnRecord; if ((alnRecord = artAlnR.getNextAln()) == null) { return null; } final String nameFields[] = nameLine.trim().substring(1).split("[-/]"); if (nameFields.length < 2) { log.warn("expect at least 2 fields at fastq line " + fastqBr.getLineNumber() + ": " + nameLine); return null; } read = new SimulatedRead(); read.fragment = Integer.parseInt(nameFields[nameFields.length - 1]); read.setReadId(nameFields[nameFields.length - 2]); read.sequence = fastqBr.readLine().trim(); if (forceFiveBaseEncoding) { read.sequence = nonACGTPattern.matcher(read.sequence).replaceAll("N"); } fastqBr.readLine(); read.quality = fastqBr.readLine().trim(); if (read.fragment == 1) { read.locs1.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.origLocs1.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.alignedBases1 = alnRecord.alignedBases; } else { read.locs2.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.origLocs2.add(new GenomeLocation(alnRecord.chromosome, alnRecord.location, alnRecord.direction)); read.alignedBases2 = alnRecord.alignedBases; } return read; }
Source:
private static void resolveMetadata(Properties props) { try { DatabaseType dbType = DatabaseType.valueOf( props.getProperty(JdbcStorageConfig.DATABASE_TYPE.getPropertyName())); LOGGER.debug("Resolving db type: {}", dbType.toString()); if (dbType == DatabaseType.METASTORE) { HiveConf hconf = Hive.get().getConf(); props.setProperty(JdbcStorageConfig.JDBC_URL.getPropertyName(), getMetastoreConnectionURL(hconf)); props.setProperty(JdbcStorageConfig.JDBC_DRIVER_CLASS.getPropertyName(), getMetastoreDriver(hconf)); String user = getMetastoreJdbcUser(hconf); if (user != null) { props.setProperty("hive.sql.dbcp.username", user); } String pwd = getMetastoreJdbcPasswd(hconf); if (pwd != null) { props.setProperty(CONFIG_PWD, pwd); } props.setProperty(JdbcStorageConfig.DATABASE_TYPE.getPropertyName(), getMetastoreDatabaseType(hconf)); } } catch (Exception e) }

Target:
private static void resolveMetadata(Properties props) throws HiveException, IOException { DatabaseType dbType = DatabaseType.valueOf( props.getProperty(JdbcStorageConfig.DATABASE_TYPE.getPropertyName())); LOGGER.debug("Resolving db type: {}", dbType.toString()); if (dbType == DatabaseType.METASTORE) { HiveConf hconf = Hive.get().getConf(); props.setProperty(JdbcStorageConfig.JDBC_URL.getPropertyName(), getMetastoreConnectionURL(hconf)); props.setProperty(JdbcStorageConfig.JDBC_DRIVER_CLASS.getPropertyName(), getMetastoreDriver(hconf)); String user = getMetastoreJdbcUser(hconf); if (user != null) { props.setProperty(CONFIG_USERNAME, user); } String pwd = getMetastoreJdbcPasswd(hconf); if (pwd != null) { props.setProperty(CONFIG_PWD, pwd); } props.setProperty(JdbcStorageConfig.DATABASE_TYPE.getPropertyName(), getMetastoreDatabaseType(hconf)); } }
Source:
public TestObject() { id = UUID.randomUUID().toString(); }

Target:
public TestObject() { id = Identifiers.makeRandomId(8); }
Source:
public Response moveDataset(@PathParam("id") String id, @PathParam("targetDataverseAlias") String targetDataverseAlias, @QueryParam("forceMove") Boolean force) { try{ User u = findUserOrDie(); Dataset ds = findDatasetOrDie(id); Dataverse target = dataverseService.findByAlias(targetDataverseAlias); if (target == null){ return error(Response.Status.BAD_REQUEST, "Target Dataverse not found."); } execCommand(new MoveDatasetCommand( createDataverseRequest(u), ds, target, force )); return ok("Dataset moved successfully"); } catch (WrappedResponse ex) { if (ex.getCause() instanceof UnforcedCommandException) { return ex.refineResponse("Use the query parameter forceMove=true to complete the move."); } else { return ex.getResponse(); } } }

Target:
public Response moveDataset(@PathParam("id") String id, @PathParam("targetDataverseAlias") String targetDataverseAlias, @QueryParam("forceMove") Boolean force) { try { User u = findUserOrDie(); Dataset ds = findDatasetOrDie(id); Dataverse target = dataverseService.findByAlias(targetDataverseAlias); if (target == null) { return error(Response.Status.BAD_REQUEST, BundleUtil.getStringFromBundle("datasets.api.moveDataset.error.targetDataverseNotFound")); } execCommand(new MoveDatasetCommand( createDataverseRequest(u), ds, target, force )); return ok(BundleUtil.getStringFromBundle("datasets.api.moveDataset.success")); } catch (WrappedResponse ex) { if (ex.getCause() instanceof UnforcedCommandException) { return ex.refineResponse(BundleUtil.getStringFromBundle("datasets.api.moveDataset.error.suggestForce")); } else { return ex.getResponse(); } } }
Source:
public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); String mimeType = findMimeType(rootNode); Pattern base64Pattern = Pattern.compile("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"); Embedding embedding; if (base64Pattern.matcher(data).matches()) { embedding = new Embedding(mimeType, data); } else { embedding = new Embedding(mimeType, new String(Base64.encodeBase64(data.getBytes(UTF_8)), UTF_8)); } storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }

Target:
public Embedding deserialize(JsonNode rootNode, Configuration configuration) { String data = rootNode.get("data").asText(); String mimeType = findMimeType(rootNode); String encodedData = getBase64EncodedData(data); Embedding embedding; String nameField = "name"; if (rootNode.has(nameField)) { String name = rootNode.get(nameField).asText(); embedding = new Embedding(mimeType, encodedData, name); } else { embedding = new Embedding(mimeType, encodedData); } storeEmbedding(embedding, configuration.getEmbeddingDirectory()); return embedding; }
Source:
public CompletableFuture<ArchivedExecutionGraph> requestJob(JobID jobId, Time timeout) { Function<Throwable, ArchivedExecutionGraph> checkExecutionGraphStoreeOnException = throwable -> { final ArchivedExecutionGraph archivedExecutionGraph = archivedExecutionGraphStore.get(jobId); if (archivedExecutionGraph == null) { throw new CompletionException(ExceptionUtils.stripCompletionException(throwable)); } else { return archivedExecutionGraph; } }; Optional<DispatcherJob> maybeJob = getDispatcherJob(jobId); if (maybeJob.isPresent()) { DispatcherJob job = maybeJob.get(); return job.requestJob(timeout).exceptionally(checkExecutionGraphStoreeOnException); } else { return CompletableFuture.completedFuture(checkExecutionGraphStoreeOnException.apply(new FlinkJobNotFoundException(jobId))); } }

Target:
public CompletableFuture<ArchivedExecutionGraph> requestJob(JobID jobId, Time timeout) { Function<Throwable, ArchivedExecutionGraph> checkExecutionGraphStoreOnException = throwable -> { final ArchivedExecutionGraph archivedExecutionGraph = archivedExecutionGraphStore.get(jobId); if (archivedExecutionGraph == null) { throw new CompletionException(ExceptionUtils.stripCompletionException(throwable)); } else { return archivedExecutionGraph; } }; Optional<DispatcherJob> maybeJob = getDispatcherJob(jobId); return maybeJob.map(job -> job.requestJob(timeout)) .orElse(FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId))) .exceptionally(checkExecutionGraphStoreOnException); }
Source:
public void prepareRun(BatchAggregatorContext context) throws Exception { super.prepareRun(context); validate(context.getInputSchema(), conf.getFields(), context.getFailureCollector()); context.getFailureCollector().getOrThrowException(); if (SchemaValidator.canRecordLineage(context.getOutputSchema(), "output")) { List<String> fields = conf.getFields() == null ? TransformLineageRecorderUtils.getFields(context.getInputSchema()) : Lists.newArrayList(conf.getFields()); context.record(TransformLineageRecorderUtils.generateOneToOnes(fields, "distinctAggregator", "Removed duplicates in input records.")); } }

Target:
public void prepareRun(BatchAggregatorContext context) throws Exception { super.prepareRun(context); validate(context.getInputSchema(), conf.getFields(), context.getFailureCollector()); context.getFailureCollector().getOrThrowException(); if (SchemaValidator.canRecordLineage(context.getOutputSchema(), context.getStageName())) { List<String> fields = conf.getFields() == null ? TransformLineageRecorderUtils.getFields(context.getInputSchema()) : Lists.newArrayList(conf.getFields()); context.record(TransformLineageRecorderUtils.generateOneToOnes(fields, "distinctAggregator", "Removed duplicates in input records.")); } }
Source:
private void notifyListeners(XMPPContact contact, UpdateType updateType) { log.debug("updated " + contact + " - " + updateType); Optional<XMPPContact> optionalContact = Optional.ofNullable(contact); updateListeners.forEach(listener -> listener.update(optionalContact, updateType)); }

Target:
private void notifyListeners(XMPPContact contact, UpdateType updateType) { log.debug("updated " + contact + " - " + updateType); Optional<XMPPContact> optionalContact = Optional.ofNullable(contact); for (IContactsUpdate listener : updateListeners) { try { listener.update(optionalContact, updateType); } catch (RuntimeException e) { log.error("invoking listener: " + listener + " failed", e); } } }
Source:
public void commit() throws IOException { commit((RepositoryStreamWriteContext) getContext()); }

Target:
protected void commit() throws IOException { commit((RepositoryStreamWriteContext) getContext()); }
Source:
public Response buildResponse(final UriInfo uriInfo, final Class<? extends JaxrsResource> theClass, final String getMethodName, final Object objectId) { final URI location = buildLocation(uriInfo, theClass, getMethodName, objectId); return !jaxrsConfig.isJaxrsLocationFullUrl() ? Response.ok().header("Location", location.getPath()).build() : Response.created(location).build(); }

Target:
public Response buildResponse(final UriInfo uriInfo, final Class<? extends JaxrsResource> theClass, final String getMethodName, final Object objectId) { final URI location = buildLocation(uriInfo, theClass, getMethodName, objectId); return !jaxrsConfig.isJaxrsLocationFullUrl() ? Response.status(Response.Status.CREATED).header("Location", location.getPath()).build() : Response.created(location).build(); }
Source:
public void showChangePattern(ClickEvent w) { final ListBox pats = this.loadPatterns(); if (pats.getItemCount() == 0) { showNewPatternDialog(); return; } final FormStylePopup pop = new FormStylePopup(GuidedDecisionTableConstants.INSTANCE.FactType()); pop.addAttribute(GuidedDecisionTableConstants.INSTANCE.ChooseExistingPatternToAddColumnTo(), pats); pop.add(new ModalFooterChangePattern(new Command() { @Override public void execute() { String[] val = pats.getValue(pats.getSelectedIndex()).split("\\s"); final Optional<Pattern52> p = extractEditingPattern(val); editingPattern = p.orElseThrow(IllegalStateException::new); editingCol.setFactField(null); editingCol.setOperator(null); view.setEntryPointName(editingPattern.getEntryPointName()); view.selectOperator(editingPattern.getWindow().getOperator()); makeLimitedValueWidget(); makeDefaultValueWidget(); displayCEPOperators(); doPatternLabel(); doValueList(); doCalculationType(); doImageButtons(); pop.hide(); view.enableFooter(true); } }, new Command() { @Override public void execute() { pop.hide(); showNewPatternDialog(); } }, new Command() { @Override public void execute() { pop.hide(); view.enableFooter(true); } } )); view.enableFooter(false); pop.show(); }

Target:
public void showChangePattern(ClickEvent w) { final ListBox pats = this.loadPatterns(); if (pats.getItemCount() == 0) { showNewPatternDialog(); return; } final FormStylePopup pop = new FormStylePopup(GuidedDecisionTableConstants.INSTANCE.FactType()); pop.addAttribute(GuidedDecisionTableConstants.INSTANCE.ChooseExistingPatternToAddColumnTo(), pats); pop.add(new ModalFooterChangePattern(getShowPatternOKCommand(pats, pop), () -> { pop.hide(); showNewPatternDialog(); }, () -> { pop.hide(); view.enableFooter(true); } )); view.enableFooter(false); pop.show(); }
Source:
private static void registerTransactionsSchemaVersionMetrics(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService, TimestampService timestampService) { Supplier<ValueAndBound<TimestampPartitioningMap<Integer>>> timestampMapSupplier = () -> { Optional<ValueAndBound<InternalSchemaMetadata>> latestValue = metadataCoordinationService.getLastKnownLocalValue(); return latestValue .map(ValueAndBound::value) .flatMap(Function.identity()) .map(InternalSchemaMetadata::timestampToTransactionsTableSchemaVersion) .map(partitioningMap -> ValueAndBound.of(partitioningMap, latestValue.get().bound())) .orElse(null); }; registerMetricForTransactionsSchemaVersionAtTimestamp(metricsManager, AtlasDbMetricNames.COORDINATION_EVENTUAL_TRANSACTIONS_SCHEMA_VERSION, timestampMapSupplier, ValueAndBound::bound); registerMetricForTransactionsSchemaVersionAtTimestamp(metricsManager, AtlasDbMetricNames.COORDINATION_CURRENT_TRANSACTIONS_SCHEMA_VERSION, timestampMapSupplier, unused -> timestampService.getFreshTimestamp()); }

Target:
private static void registerTransactionsSchemaVersionMetrics(MetricsManager metricsManager, CoordinationService<InternalSchemaMetadata> metadataCoordinationService, TimestampService timestampService) { Supplier<ValueAndBound<TimestampPartitioningMap<Integer>>> valueAndBoundSupplier = () -> MetadataCoordinationServiceMetrics.getTimestampToTransactionsTableSchemaVersionMap( metadataCoordinationService); registerMetricForTransactionsSchemaVersionAtTimestamp(metricsManager, AtlasDbMetricNames.COORDINATION_EVENTUAL_TRANSACTIONS_SCHEMA_VERSION, valueAndBoundSupplier, ValueAndBound::bound); registerMetricForTransactionsSchemaVersionAtTimestamp(metricsManager, AtlasDbMetricNames.COORDINATION_CURRENT_TRANSACTIONS_SCHEMA_VERSION, valueAndBoundSupplier, unused -> timestampService.getFreshTimestamp()); }
Source:
public Session findSession(String id) throws IOException { Session result = super.findSession(id); if (result == null) { if (id != null) { Map<String, Object> attrs = null; try { RMap map = getMap(id); if (map.isExists()) { attrs = map.getAll(RedissonSession.ATTRS); } } catch (Exception e) { log.error("Can't read session object by id: " + id, e); } if (attrs == null) { log.info("Session " + id + " can't be found"); return null; } RedissonSession session = (RedissonSession) createEmptySession(); session.load(attrs); session.setId(id); session.access(); session.endAccess(); return session; } return null; } result.access(); result.endAccess(); return result; }

Target:
public Session findSession(String id) throws IOException { Session result = super.findSession(id); if (result == null) { if (id != null) { Map<String, Object> attrs = new HashMap<String, Object>(); try { attrs = getMap(id).getAll(RedissonSession.ATTRS); } catch (Exception e) { log.error("Can't read session object by id: " + id, e); } if (attrs.isEmpty()) { log.info("Session " + id + " can't be found"); return null; } RedissonSession session = (RedissonSession) createEmptySession(); session.load(attrs); session.setId(id); session.access(); session.endAccess(); return session; } return null; } result.access(); result.endAccess(); return result; }
Source:
public void testRegisterStreamConsumerThrottled() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture.supplyAsync(() -> { throw ResourceNotFoundException.builder().build(); }); final CompletableFuture<RegisterStreamConsumerResponse> rscFuture = CompletableFuture.supplyAsync(() -> { throw LimitExceededException.builder().build(); }); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); when(client.registerStreamConsumer(any(RegisterStreamConsumerRequest.class))).thenReturn(rscFuture); try { consumerRegistration.getOrCreateStreamConsumerArn(); } finally { verify(client, times(RSC_RETRIES)) .registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); verify(client).describeStreamConsumer(any(DescribeStreamConsumerRequest.class)); } }

Target:
public void testRegisterStreamConsumerThrottled() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture.supplyAsync(() -> { throw ResourceNotFoundException.builder().build(); }); final CompletableFuture<RegisterStreamConsumerResponse> rscFuture = CompletableFuture.supplyAsync(() -> { throw LimitExceededException.builder().build(); }); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); when(client.registerStreamConsumer(any(RegisterStreamConsumerRequest.class))).thenReturn(rscFuture); try { consumerRegistration.getOrCreateStreamConsumerArn(); } finally { verify(client, times(RSC_RETRIES)) .registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); } }
Source:
private TypeInference(FunctionLike functionDef) { for (Symbol variable : functionDef.localVariables()) { Set<Usage.Kind> unsupportedKinds = variable.usages().stream() .map(Usage::kind) .filter(k -> k != Usage.Kind.ASSIGNMENT_LHS && k != Usage.Kind.OTHER) .collect(Collectors.toSet()); if (unsupportedKinds.isEmpty()) { trackedVars.add((SymbolImpl) variable); } } }

Target:
private TypeInference(FunctionLike functionDef) { for (Symbol variable : functionDef.localVariables()) { if (variable.usages().stream() .map(Usage::kind) .allMatch(k -> k == Usage.Kind.ASSIGNMENT_LHS || k == Usage.Kind.OTHER)) { trackedVars.add((SymbolImpl) variable); } } }
Source:
private static String normalizePhone(String data) throws CorrelationAttributeNormalizationException { String phoneNumber = data.replaceAll("[^0-9\\+]", ""); if(phoneNumber.matches("\\+?[0-9]+")){ return phoneNumber; } else { throw new CorrelationAttributeNormalizationException(String.format("Data was expected to be a valid phone number: %s", data)); } }

Target:
private static String normalizePhone(String data) throws CorrelationAttributeNormalizationException { if(data.matches("\\+?[0-9()\\-\\s]+")){ String phoneNumber = data.replaceAll("[^0-9\\+]", ""); return phoneNumber; } else { throw new CorrelationAttributeNormalizationException(String.format("Data was expected to be a valid phone number: %s", data)); } }
Source:
<T> T computeSync(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { ByRef<T> future = new ByRef<>(null); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (trace) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (trace) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); future.set(result); if (trace) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return future.get(); }

Target:
<T> T computeSync(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { ByRef<T> ref = new ByRef<>(null); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (trace) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (trace) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); ref.set(result); if (trace) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return ref.get(); }
Source:
protected InstantOperatorInfo getInstantOpInfo() { final InstantOperatorInfo.Builder iOpInfoBuilder = InstantOperatorInfo.newBuilder(); iOpInfoBuilder.setInstantOperatorType(InstantOperatorTypeEnum.APPLY_STATEFUL); final List<ByteBuffer> serializedObjectList = new ArrayList<>(); serializedObjectList.add(ByteBuffer.wrap(SerializationUtils.serialize(applyStatefulFunction))); iOpInfoBuilder.setObjects(serializedObjectList); iOpInfoBuilder.setKeyIndex(null); return iOpInfoBuilder.build(); }

Target:
protected InstantOperatorInfo getInstantOpInfo() { final InstantOperatorInfo.Builder iOpInfoBuilder = InstantOperatorInfo.newBuilder(); iOpInfoBuilder.setInstantOperatorType(InstantOperatorTypeEnum.APPLY_STATEFUL); final List<ByteBuffer> serializedFunctionList = new ArrayList<>(); serializedFunctionList.add(ByteBuffer.wrap(SerializationUtils.serialize(applyStatefulFunction))); iOpInfoBuilder.setFunctions(serializedFunctionList); iOpInfoBuilder.setKeyIndex(null); return iOpInfoBuilder.build(); }
Source:
private void analyzeTypes(List<JavaClass> types) { List<JavaClass> sortedTypes = new LinkedList<>(); Iterator<JavaClass> iterator = types.iterator(); while (iterator.hasNext()) { JavaClass javaClass = iterator.next(); if (javaClass.isEnum()) { analyzeEnum(javaClass); } else { addSorted(sortedTypes, javaClass); } } for (JavaClass javaClass : sortedTypes) { analyzeStruct(javaClass); } }

Target:
private void analyzeTypes(List<JavaClass> types) { for (JavaClass javaClass : types) { if (javaClass.isEnum()) { analyzeEnum(javaClass); } else { analyzeStruct(javaClass); } } redefineUndefinedTypes(); }
Source:
public void fill(int index, long[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( StringUtils.safeFormat( "Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize ) ); } for (int i = 0; i < toFill.length; i++) { toFill[i] = get(index + i); } }

Target:
public void fill(int index, long[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( StringUtils.format( "Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize ) ); } for (int i = 0; i < toFill.length; i++) { toFill[i] = get(index + i); } }
Source:
public static Optional<Span> initOptionalSpan(Tracer tracer, String component, String operation) { return Optional.ofNullable(tracer.activeSpan()).map(activeSpan -> { Span span = tracer.buildSpan(component + " - " + operation) .addReference(References.FOLLOWS_FROM, activeSpan.context()) .start(); span.setTag(TracingUtil.COMPONENT, component); return span; }); }

Target:
public static Optional<Span> initOptionalSpan(Tracer tracer, String component, String operation) { return Optional.ofNullable(tracer.activeSpan()).map(activeSpan -> initFromActiveSpan(tracer, component, operation, activeSpan.context())); }
Source:
public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException("The output directory for project " + project.getName() + " does not exist"); } Jar jar = new Jar(file); try (Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } }

Target:
public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException("The output directory for project " + project.getName() + " does not exist"); } try (Jar jar = new Jar(file); Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } }
Source:
public void readFeedException() throws Exception { ArrayList<CosmosDatabaseProperties> dbs = new ArrayList<CosmosDatabaseProperties>(); dbs.add(new CosmosDatabaseProperties("db1")); dbs.add(new CosmosDatabaseProperties("db2")); ArrayList<FeedResponse<CosmosDatabaseProperties>> frps = new ArrayList<FeedResponse<CosmosDatabaseProperties>>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux<FeedResponse<CosmosDatabaseProperties>> response = Flux.merge(Flux.fromIterable(frps)) .mergeWith(Flux.error(BridgeInternal.createCosmosException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosAsyncClientWrapper mockedClientWrapper = Mockito.spy(new CosmosAsyncClientWrapper(client)); Mockito.when(mockedClientWrapper.readAllDatabases()).thenReturn(UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { pagedFluxOptions.setTracerInformation(new TracerProvider(ServiceLoader.load(Tracer.class)), "testSpan", "testEndpoint,", "testDb"); return response; })); TestSubscriber<FeedResponse<CosmosDatabaseProperties>> subscriber = new TestSubscriber<>(); mockedClientWrapper.readAllDatabases().byPage().subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); assertThat(subscriber.assertTerminated()); assertThat(subscriber.errorCount()).isEqualTo(1); }

Target:
public void readFeedException() throws Exception { ArrayList<CosmosDatabaseProperties> dbs = new ArrayList<CosmosDatabaseProperties>(); dbs.add(new CosmosDatabaseProperties("db1")); dbs.add(new CosmosDatabaseProperties("db2")); ArrayList<FeedResponse<CosmosDatabaseProperties>> frps = new ArrayList<FeedResponse<CosmosDatabaseProperties>>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux<FeedResponse<CosmosDatabaseProperties>> response = Flux.merge(Flux.fromIterable(frps)) .mergeWith(Flux.error(BridgeInternal.createCosmosException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosAsyncClientWrapper mockedClientWrapper = Mockito.spy(new CosmosAsyncClientWrapper(client)); Mockito.when(mockedClientWrapper.readAllDatabases()).thenReturn(UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { pagedFluxOptions.setTracerInformation(new TracerProvider(null), "testSpan", "testEndpoint,", "testDb"); return response; })); TestSubscriber<FeedResponse<CosmosDatabaseProperties>> subscriber = new TestSubscriber<>(); mockedClientWrapper.readAllDatabases().byPage().subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); assertThat(subscriber.assertTerminated()); assertThat(subscriber.errorCount()).isEqualTo(1); }
Source:
public void onDetach() { timer.cancel(); super.onDetach(); mDelegate = null; }

Target:
public void onDetach() { super.onDetach(); mDelegate = null; }
Source:
public void return_component_info_when_file_on_master() throws Exception { init(); OrganizationDto organization = dbTester.organizations().insertForKey("my-org2"); ComponentDto main = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample")); userSession.addProjectPermission(UserRole.USER, main); ComponentDto dirDto = newDirectory(main, "src"); componentDbTester.insertComponent(dirDto); ComponentDto fileDto = newFileDto(main, dirDto) .setUuid("abcd") .setName("Main.xoo") .setDbKey("sample:src/Main.xoo"); componentDbTester.insertComponent(fileDto); executeAndVerify(fileDto.getDbKey(), "return_component_info_when_file_on_master.json"); }

Target:
public void return_component_info_when_file_on_master() throws Exception { init(); OrganizationDto organization = dbTester.organizations().insertForKey("my-org2"); ComponentDto main = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample")); userSession.addProjectPermission(UserRole.USER, main); ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(main, "src")); ComponentDto fileDto = componentDbTester.insertComponent(newFileDto(main, dirDto) .setUuid("abcd") .setName("Main.xoo") .setDbKey("sample:src/Main.xoo")); executeAndVerify(fileDto.getDbKey(), "return_component_info_when_file_on_master.json"); }
Source:
public SyncPoller<CreateSearchResponse, PhoneNumberSearch> beginCreateSearch( CreateSearchOptions options, Duration lroDuration) { return phoneNumberAsyncClient.beginCreateSearch(options, lroDuration).getSyncPoller(); }

Target:
public SyncPoller<PhoneNumberSearch, PhoneNumberSearch> beginCreateSearch( CreateSearchOptions options, Duration lroDuration) { return phoneNumberAsyncClient.beginCreateSearch(options, lroDuration).getSyncPoller(); }
Source:
protected @Nullable List<@NonNull ITimeGraphRowModel> getRowModel(@NonNull ITmfStateSystem ss, @NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<ITimeGraphRowModel> rows = new ArrayList<>(); for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { long startTime = interval.getStartTime(); long duration = interval.getEndTime() - startTime + 1; Object state = interval.getValue(); String value = state == null ? null : state.toString(); eventList.add(new TimeGraphState(startTime, duration, entry.getKey().intValue(), value)); } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } return rows; }

Target:
protected @Nullable List<@NonNull ITimeGraphRowModel> getRowModel(@NonNull ITmfStateSystem ss, @NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<@NonNull ITimeGraphRowModel> rows = new ArrayList<>(); for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { long startTime = interval.getStartTime(); long duration = interval.getEndTime() - startTime + 1; Object state = interval.getValue(); String value = state == null ? "" : String.valueOf(state); eventList.add(new TimeGraphState(startTime, duration, Math.max(entry.getKey().intValue(), 0), value)); } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } return rows; }