auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Sample to(SampleDto sampleDto) throws IOException { authorizationManager.throwIfUnauthenticated(); Sample sample = Dtos.to(sampleDto); sample.setProject(sqlProjectDAO.get(sampleDto.getProjectId())); if (sampleDto.getParentId() != null) { sample.setParent(sampleDao.getSample(sampleDto.getParentId())); } if (sampleDto.getSampleIdentityDto() != null) { sample.setIdentity(identityService.to(sampleDto.getSampleIdentityDto())); } if (sampleDto.getSampleAnalyte() != null) { sample.setSampleAnalyte(sampleAnalyteService.to(sampleDto.getSampleAnalyte())); } if (sampleDto.getSampleAdditionalInfo() != null) { sample.setSampleAdditionalInfo(sampleAdditionalInfoService.to(sampleDto.getSampleAdditionalInfo())); } return sample; }

Target:
Sample to(SampleDto sampleDto) throws IOException { authorizationManager.throwIfUnauthenticated(); checkArgument(sampleDto.getProjectId() != null, "A Project id must be provided to construct Sample."); Sample sample = Dtos.to(sampleDto); Project project = sqlProjectDAO.get(sampleDto.getProjectId()); ServiceUtils.throwIfNull(project, "projectId", sampleDto.getProjectId()); sample.setProject(project); if (sampleDto.getParentId() != null) { Sample parent = sampleDao.getSample(sampleDto.getParentId()); ServiceUtils.throwIfNull(parent, "parentId", sampleDto.getParentId()); sample.setParent(parent); } if (sampleDto.getSampleIdentity() != null) { sample.setIdentity(identityService.to(sampleDto.getSampleIdentity())); } if (sampleDto.getSampleAnalyte() != null) { sample.setSampleAnalyte(sampleAnalyteService.to(sampleDto.getSampleAnalyte())); } if (sampleDto.getSampleAdditionalInfo() != null) { sample.setSampleAdditionalInfo(sampleAdditionalInfoService.to(sampleDto.getSampleAdditionalInfo())); } if (sampleDto.getSampleTissue() != null) { sample.setSampleTissue(sampleTissueService.to(sampleDto.getSampleTissue())); } return sample; }
Source:
public void put(NamedKey key, byte[] value) { final byte[] hash = computeKeyHash(prefix, key); final byte[] serialized; try { serialized = serialize(key, value); } catch (NullPointerException ex) { throw Throwables.propagate(ex); } try (final Jedis client = pool.getResource()) { client.psetex(hash, expiration, serialized); } catch (JedisConnectionException ex) { Throwables.propagate(ex); } catch (JedisException ex) { errorCount.incrementAndGet(); log.warn(ex, "Error putting cache item"); } }

Target:
public void put(NamedKey key, byte[] value) { final byte[] serialized = serialize(key, value); try (ResourceHolder<ShardedJedis> clientHolder = supplier.get()) { final ShardedJedis jedis = clientHolder.get(); final byte[] itemKey = CacheImplUtils.computeKeyHash(prefix, key).getBytes(); Jedis shard = jedis.getShard(itemKey); if (expiration > 0) { shard.psetex(itemKey, expiration, serialized); } else { shard.set(itemKey, serialized); } final byte[] setKey = CacheImplUtils.computeNamespaceHash(prefix, key.namespace).getBytes(); shard = jedis.getShard(setKey); shard.sadd(setKey, key.key); } catch (IOException | JedisException ex) { this.countException(ex); log.warn(ex, "Error putting cache item"); } }
Source:
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws IOException { AvatarProvider avatarProvider = avatarProviderItem.get(); if (avatarProvider == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String user = req.getPathInfo(); if (user == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } user = user.substring(1); final Account account; try { account = accountResolver.find(user); } catch (OrmException e1) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String size = req.getParameter("size"); int imageSize = 0; if (size != null) { try { imageSize = Integer.parseInt(size); } catch (NumberFormatException e) { } } final String url = avatarProvider.getUrl(account, imageSize); rsp.sendRedirect(rsp.encodeRedirectURL(url)); }

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws IOException { AvatarProvider avatarProvider = avatarProviderItem.get(); if (avatarProvider == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String user = req.getPathInfo(); if (user == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } user = user.substring(1); final Account account; try { account = accountResolver.find(user); } catch (OrmException e1) { log.error("Exception while looking up avatar for user: " + user, e1); rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (account == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String size = req.getParameter("size"); int imageSize = 0; if (size != null) { try { imageSize = Integer.parseInt(size); } catch (NumberFormatException e) { } } final String url = avatarProvider.getUrl(account, imageSize); if (url == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } else { rsp.sendRedirect(rsp.encodeRedirectURL(url)); } }
Source:
public void testHasPermissionForPermissionOnGroupNonExistentUserTest() throws Exception { setEnvForPermissionOnGroupTests(true); Long nonExistentId = -1L; user.setId(nonExistentId); user.setGroups(Collections.<Group>emptyList()); Assert.assertFalse(evaluator.hasPermission(authentication, nonExistentId, targetType, permission)); Assert.assertFalse(evaluator.hasPermission(authentication, nonExistentId, targetType, "GeneralPermission.READ")); }

Target:
public void testHasPermissionForPermissionOnGroupNonExistentUserTest() throws Exception { setEnvForPermissionOnGroupTests(true); long nonExistentId = -1L; user.setId(nonExistentId); user.setGroups(Collections.<Group>emptyList()); when(securityService.getFullUserInfoFrom(any(Authentication.class))).thenReturn(user); Assert.assertFalse(evaluator.hasPermission(authentication, nonExistentId, targetType, permission)); Assert.assertFalse(evaluator.hasPermission(authentication, nonExistentId, targetType, "GeneralPermission.READ")); }
Source:
public void insertString(String str, SimpleAttributeSet attributes) throws BadLocationException { Matcher m = Pattern.compile("([^\r\n]*)([\r\n]*\n)?(\r+)?").matcher(str); while (m.find()) { String content = m.group(1); String newlines = m.group(2); String crs = m.group(3); int replaceLength = Math.min(content.length(), document.getLength() - insertPosition); document.replace(insertPosition, replaceLength, content, attributes); insertPosition += content.length(); if (newlines != null) { document.insertString(document.getLength(), newlines, attributes); insertPosition = document.getLength(); startOfLine = insertPosition; } if (crs != null) { insertPosition = startOfLine; } } }

Target:
public void insertString(String str, SimpleAttributeSet attributes) throws BadLocationException { Matcher m = newLinePattern.matcher(str); while (m.find()) { String content = m.group(1); String newlines = m.group(2); String crs = m.group(3); int replaceLength = Math.min(content.length(), document.getLength() - insertPosition); document.replace(insertPosition, replaceLength, content, attributes); insertPosition += content.length(); if (newlines != null) { document.insertString(document.getLength(), newlines, attributes); insertPosition = document.getLength(); startOfLine = insertPosition; } if (crs != null) { insertPosition = startOfLine; } } }
Source:
public void testElementOfJsonPathResults(){ JsonFixture cont = new JsonFixture(); cont.load(JSON); Object result = cont.elementOfJsonPath(0,jsonPathWithResults); assertEquals(expectedResult,result); }

Target:
public void testElementOfJsonPathResults() { fixture.load(JSON); Object result = fixture.elementOfJsonPath(0, "$.store.book[?(@.category==\"fiction\")].author"); assertEquals("Evelyn Waugh", result); }
Source:
public ProcMeminfoParser(String fileName) throws IOException { List<String> lines = Files.readLines(new File(fileName), Charset.defaultCharset()); ImmutableMap.Builder<String, Long> builder = ImmutableMap.builder(); Map<String, Long> newMemInfo = new HashMap<>(); for (String line : lines) { int colon = line.indexOf(':'); if (colon == -1) { continue; } String keyword = line.substring(0, colon); String valString = line.substring(colon + 1); try { long val = Long.parseLong(CharMatcher.inRange('0', '9').retainFrom(valString)); if (!newMemInfo.containsKey(keyword)) { newMemInfo.put(keyword, val); } } catch (NumberFormatException e) { } } builder.putAll(newMemInfo); memInfo = builder.build(); }

Target:
public ProcMeminfoParser(String fileName) throws IOException { List<String> lines = Files.readLines(new File(fileName), Charset.defaultCharset()); Map<String, Long> newMemInfo = new HashMap<>(); for (String line : lines) { int colon = line.indexOf(':'); if (colon == -1) { continue; } String keyword = line.substring(0, colon); String valString = line.substring(colon + 1); try { long val = Long.parseLong(CharMatcher.inRange('0', '9').retainFrom(valString)); if (!newMemInfo.containsKey(keyword)) { newMemInfo.put(keyword, val); } } catch (NumberFormatException e) { } } memInfo = ImmutableMap.copyOf(newMemInfo); }
Source:
public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThroughNormalized(playerCamera)); initSkysphere(playerCamera.getzFar() < RADIUS ? playerCamera.getzFar() : RADIUS); wireframeStateChange = new SetWireframe(true); RenderingDebugConfig renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetRenderBufferMask(READONLY_GBUFFER, displayResolutionDependentFBOs, true, false, false)); update(); displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial("engine:prog.sky")); addDesiredStateChange(new DisableDepthWriting()); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); }

Target:
public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThroughNormalized(playerCamera)); initSkysphere(playerCamera.getzFar() < RADIUS ? playerCamera.getzFar() : RADIUS); wireframeStateChange = new SetWireframe(true); RenderingDebugConfig renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new SetFboWriteMask(true, false, false, READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new EnableMaterial("engine:prog.sky")); addDesiredStateChange(new DisableDepthWriting()); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); }
Source:
public static void writeToKryo(Kryo kryo, Output output, RyaStatement object) { output.writeString(object.getSubject().getData()); output.writeString(object.getPredicate().getData()); output.writeString(object.getObject().getDataType().toString()); output.writeString(object.getObject().getData()); boolean hasContext = object.getContext() != null; output.writeBoolean(hasContext); if(hasContext){ output.writeString(object.getContext().getData()); } boolean shouldWrite = object.getColumnVisibility() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeInt(object.getColumnVisibility().length); output.writeBytes(object.getColumnVisibility()); } shouldWrite = object.getQualifer() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeString(object.getQualifer()); } shouldWrite = object.getTimestamp() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeLong(object.getTimestamp()); } shouldWrite = object.getValue() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeBytes(object.getValue()); } }

Target:
public static void writeToKryo(Kryo kryo, Output output, RyaStatement object) { Preconditions.checkNotNull(kryo); Preconditions.checkNotNull(output); Preconditions.checkNotNull(object); output.writeString(object.getSubject().getData()); output.writeString(object.getPredicate().getData()); output.writeString(object.getObject().getDataType().toString()); output.writeString(object.getObject().getData()); boolean hasContext = object.getContext() != null; output.writeBoolean(hasContext); if(hasContext){ output.writeString(object.getContext().getData()); } boolean shouldWrite = object.getColumnVisibility() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeInt(object.getColumnVisibility().length); output.writeBytes(object.getColumnVisibility()); } shouldWrite = object.getQualifer() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeString(object.getQualifer()); } shouldWrite = object.getTimestamp() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeLong(object.getTimestamp()); } shouldWrite = object.getValue() != null; output.writeBoolean(shouldWrite); if(shouldWrite){ output.writeBytes(object.getValue()); } }
Source:
private void addSubscriptions(String resourcePath, List<Subscription> subscriptions, Queue<String> pathsQueue, boolean withChildren) throws EventBrokerException { try { UserRegistry userRegistry = this.registryService.getGovernanceSystemRegistry(EventBrokerHolder.getInstance().getTenantId()); String subscriptionsPath = getSubscriptionsPath(resourcePath); if (userRegistry.resourceExists(subscriptionsPath)) { Collection collection = (Collection) userRegistry.get(subscriptionsPath); for (String subscriptionPath : collection.getChildren()) { Resource subscriptionResource = userRegistry.get(subscriptionPath); Subscription subscription = JavaUtil.getSubscription(subscriptionResource); subscription.setTopicName(removeResourcePath(resourcePath)); if (subscriptionPath.endsWith("/")) { subscriptionPath = subscriptionsPath.substring(0, subscriptionPath.lastIndexOf("/")); } subscription.setId(subscriptionPath.substring(subscriptionPath.lastIndexOf("/") + 1)); subscriptions.add(subscription); } } if (withChildren) { if (userRegistry.get(resourcePath) instanceof Collection) { Collection childResources = (Collection) userRegistry.get(resourcePath); for (String childResourcePath : childResources.getChildren()) { if ((!EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME .contains(childResourcePath)) && (!EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME .contains(childResourcePath))) { pathsQueue.add(childResourcePath); } } } } } catch (RegistryException e) { throw new EventBrokerException("Cannot access the registry", e); } }

Target:
private void addSubscriptions(String resourcePath, List<Subscription> subscriptions, Queue<String> pathsQueue, boolean withChildren) throws EventBrokerException { try { UserRegistry userRegistry = this.registryService.getGovernanceSystemRegistry(EventBrokerHolder.getInstance().getTenantId()); String subscriptionsPath = getSubscriptionsPath(resourcePath); if (userRegistry.resourceExists(subscriptionsPath)) { Collection collection = (Collection) userRegistry.get(subscriptionsPath); for (String subscriptionPath : collection.getChildren()) { Resource subscriptionResource = userRegistry.get(subscriptionPath); Subscription subscription = JavaUtil.getSubscription(subscriptionResource); subscription.setTopicName(removeResourcePath(resourcePath)); if (subscriptionPath.endsWith("/")) { subscriptionPath = subscriptionsPath.substring(0, subscriptionPath.lastIndexOf("/")); } subscription.setId(subscriptionPath.substring(subscriptionPath.lastIndexOf("/") + 1)); subscriptions.add(subscription); } } if (withChildren) { Resource resource = userRegistry.get(resourcePath); if (resource instanceof Collection) { Collection childResources = (Collection) resource; for (String childResourcePath : childResources.getChildren()) { if ((!EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME .contains(childResourcePath)) && (!EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME .contains(childResourcePath))) { pathsQueue.add(childResourcePath); } } } } } catch (RegistryException e) { throw new EventBrokerException("Cannot access the registry", e); } }
Source:
public ExternalServerIngressBuilder withLabels(Map<String, String> labels) { if (this.labels == null) { this.labels = new HashMap<>(); } this.labels.putAll(labels); return this; }

Target:
public ExternalServerIngressBuilder withLabels(Map<String, String> labels) { this.labels = labels; return this; }
Source:
public String getLabel() { return "Drop Association as ClearAssociationAction"; }

Target:
public String getLabel() { return Messages.AssociationToClearAssociationActionDropStrategy_Label; }
Source:
private static boolean parseAllowAlias(List<Option> options) { Option option = Option.findByName(options, "allow_alias"); if (option != null) { Object value = option.getValue(); return value instanceof Boolean ? (Boolean) value : "true".equals(value); } return false; }

Target:
private static boolean parseAllowAlias(List<Option> options) { Option option = Option.findByName(options, "allow_alias"); if (option != null) { Object value = option.getValue(); return value instanceof Boolean && (Boolean) value; } return false; }
Source:
public void testUtf8FrameEncoding() { StompFrame frame = new DefaultStompFrame(StompCommand.SEND, Unpooled.wrappedBuffer("body".getBytes(CharsetUtil.UTF_8))); StompHeaders incoming = frame.headers(); incoming.set(StompHeaders.DESTINATION, "/queue/№11±♛нетти♕"); incoming.set(StompHeaders.CONTENT_TYPE, AsciiString.of("text/plain")); channel.writeOutbound(frame); ByteBuf headers = channel.readOutbound(); ByteBuf content = channel.readOutbound(); ByteBuf fullFrame = new CompositeByteBuf(ByteBufAllocator.DEFAULT, false, 2) .addComponent(true, headers).addComponent(true, content); assertEquals(SEND_FRAME_UTF8, fullFrame.toString(CharsetUtil.UTF_8)); assertTrue(fullFrame.release()); }

Target:
public void testUtf8FrameEncoding() { StompFrame frame = new DefaultStompFrame(StompCommand.SEND, Unpooled.wrappedBuffer("body".getBytes(CharsetUtil.UTF_8))); StompHeaders incoming = frame.headers(); incoming.set(StompHeaders.DESTINATION, "/queue/№11±♛нетти♕"); incoming.set(StompHeaders.CONTENT_TYPE, AsciiString.of("text/plain")); channel.writeOutbound(frame); ByteBuf headers = channel.readOutbound(); ByteBuf content = channel.readOutbound(); ByteBuf fullFrame = Unpooled.wrappedBuffer(headers, content); assertEquals(SEND_FRAME_UTF8, fullFrame.toString(CharsetUtil.UTF_8)); assertTrue(fullFrame.release()); }
Source:
public void upgradeOutcomeTableRevision1To2(SQLiteDatabase db) { String commonColumns = "_id,session,notification_ids,name,timestamp"; try { db.execSQL("BEGIN TRANSACTION;"); db.execSQL("CREATE TEMPORARY TABLE outcome_backup(" + commonColumns + ");"); db.execSQL("INSERT INTO outcome_backup SELECT " + commonColumns + " FROM outcome;"); db.execSQL("DROP TABLE outcome;"); db.execSQL(SQL_CREATE_OUTCOME_ENTRIES_V2); db.execSQL("INSERT INTO outcome (" + commonColumns + ", weight) SELECT " + commonColumns + ", 0 FROM outcome_backup;"); db.execSQL("DROP TABLE outcome_backup;"); db.execSQL("COMMIT;"); } catch (SQLiteException e) { e.printStackTrace(); } }

Target:
public void upgradeOutcomeTableRevision1To2(SQLiteDatabase db) { String commonColumns = OutcomeEventsTable._ID + "," + OutcomeEventsTable.COLUMN_NAME_SESSION+ "," + OutcomeEventsTable.COLUMN_NAME_NOTIFICATION_IDS + "," + OutcomeEventsTable.COLUMN_NAME_NAME + "," + OutcomeEventsTable.COLUMN_NAME_TIMESTAMP; try { db.execSQL("BEGIN TRANSACTION;"); db.execSQL("CREATE TEMPORARY TABLE outcome_backup(" + commonColumns + ");"); db.execSQL("INSERT INTO outcome_backup SELECT " + commonColumns + " FROM outcome;"); db.execSQL("DROP TABLE outcome;"); db.execSQL(SQL_CREATE_OUTCOME_ENTRIES_V2); db.execSQL("INSERT INTO outcome (" + commonColumns + ", weight) SELECT " + commonColumns + ", 0 FROM outcome_backup;"); db.execSQL("DROP TABLE outcome_backup;"); } catch (SQLiteException e) { e.printStackTrace(); } finally { db.execSQL("COMMIT;"); } }
Source:
public Firehose connect(StringInputRowParser firehoseParser) throws IOException { if (baseDir == null) { throw new IAE("baseDir is null"); } log.info("Searching for all [%s] in and beneath [%s]", filter, baseDir.getAbsoluteFile()); Collection<File> foundFiles = FileUtils.listFiles( baseDir.getAbsoluteFile(), new WildcardFileFilter(filter), TrueFileFilter.INSTANCE); if (foundFiles == null || foundFiles.isEmpty()) { throw new ISE("Found no files to ingest! Check your schema."); } log.info("Found files: " + foundFiles); final LinkedList<File> files = Lists.newLinkedList( foundFiles); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return !files.isEmpty(); } @Override public LineIterator next() { final File f = files.poll(); try { InputStream innerInputStream = new FileInputStream(f); final InputStream outerInputStream = f.getName().endsWith(".gz") ? CompressionUtils.gzipInputStream(innerInputStream) : innerInputStream; return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(outerInputStream, Charsets.UTF_8))); } catch (Exception e) { throw Throwables.propagate(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } }, firehoseParser); }

Target:
public Firehose connect(StringInputRowParser firehoseParser) throws IOException { if (baseDir == null) { throw new IAE("baseDir is null"); } log.info("Searching for all [%s] in and beneath [%s]", filter, baseDir.getAbsoluteFile()); Collection<File> foundFiles = FileUtils.listFiles( baseDir.getAbsoluteFile(), new WildcardFileFilter(filter), TrueFileFilter.INSTANCE); if (foundFiles == null || foundFiles.isEmpty()) { throw new ISE("Found no files to ingest! Check your schema."); } log.info("Found files: " + foundFiles); final LinkedList<File> files = Lists.newLinkedList( foundFiles); return new FileIteratingFirehose( new Iterator<LineIterator>() { @Override public boolean hasNext() { return !files.isEmpty(); } @Override public LineIterator next() { final File f = files.poll(); InputStream rawInputStream = null; try { rawInputStream = new FileInputStream(f); final InputStream inputStream; String logMessage; if (CompressionUtils.isGz(f.getName())) { logMessage = "Reading gzipped file [%s]"; inputStream = CompressionUtils.gzipInputStream(rawInputStream); } else { logMessage = "Reading file [%s]"; inputStream = rawInputStream; } log.info(logMessage, f.getName()); return IOUtils.lineIterator( new BufferedReader( new InputStreamReader(inputStream, Charsets.UTF_8))); } catch (Exception e) { log.warn(e, "Failed to read file [%s]", f.getName()); if (rawInputStream != null) { try { rawInputStream.close(); } catch (IOException ioe) { Throwables.propagate(ioe); } } throw Throwables.propagate(e); } } @Override public void remove() { throw new UnsupportedOperationException(); } }, firehoseParser); }
Source:
public List<Ref> getAdditionalRefs() throws IOException { return null; }

Target:
public List<Ref> getAdditionalRefs() throws IOException { throw new UnsupportedOperationException(); }
Source:
private IterableStream<MinedOpinions> toMinedOpinionList( com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment, List<DocumentSentiment> documentSentimentList) { final List<SentenceAspect> sentenceAspects = sentenceSentiment.getAspects(); if (sentenceAspects == null) { return null; } final List<MinedOpinions> minedOpinions = new ArrayList<>(); sentenceAspects.forEach(sentenceAspect -> { final List<OpinionSentiment> opinionSentiments = new ArrayList<>(); sentenceAspect.getRelations().forEach(aspectRelation -> { final AspectRelationType aspectRelationType = aspectRelation.getRelationType(); final String opinionPointer = aspectRelation.getRef(); if (AspectRelationType.OPINION == aspectRelationType) { opinionSentiments.add(toOpinionSentiment( findSentimentOpinion(opinionPointer, documentSentimentList))); } }); minedOpinions.add(new MinedOpinions( new AspectSentiment(sentenceAspect.getText(), TextSentiment.fromString(sentenceAspect.getSentiment().toString()), sentenceAspect.getOffset(), sentenceAspect.getLength(), toSentimentConfidenceScores(sentenceAspect.getConfidenceScores())), new IterableStream<>(opinionSentiments))); }); return new IterableStream<>(minedOpinions); }

Target:
private IterableStream<MinedOpinion> toMinedOpinionList( com.azure.ai.textanalytics.implementation.models.SentenceSentiment sentenceSentiment, List<DocumentSentiment> documentSentimentList) { final List<SentenceAspect> sentenceAspects = sentenceSentiment.getAspects(); if (sentenceAspects == null) { return null; } final List<MinedOpinion> minedOpinions = new ArrayList<>(); sentenceAspects.forEach(sentenceAspect -> { final List<OpinionSentiment> opinionSentiments = new ArrayList<>(); sentenceAspect.getRelations().forEach(aspectRelation -> { final AspectRelationType aspectRelationType = aspectRelation.getRelationType(); final String opinionPointer = aspectRelation.getRef(); if (AspectRelationType.OPINION == aspectRelationType) { opinionSentiments.add(toOpinionSentiment( findSentimentOpinion(opinionPointer, documentSentimentList))); } }); minedOpinions.add(new MinedOpinion( new AspectSentiment(sentenceAspect.getText(), TextSentiment.fromString(sentenceAspect.getSentiment().toString()), sentenceAspect.getOffset(), sentenceAspect.getLength(), toSentimentConfidenceScores(sentenceAspect.getConfidenceScores())), new IterableStream<>(opinionSentiments))); }); return new IterableStream<>(minedOpinions); }
Source:
private ByteBuffer getContent(Queue<HttpObject> contents, long expectedContentLength) { ByteBuffer buffer = ByteBuffer.allocate((int) expectedContentLength); boolean endMarkerFound = false; for (HttpObject object : contents) { assertFalse("There should have been no more data after the end marker was found", endMarkerFound); HttpContent content = (HttpContent) object; buffer.put(content.content().nioBuffer()); endMarkerFound = object instanceof LastHttpContent; ReferenceCountUtil.release(content); } Assert.assertEquals("Content length did not match expected", expectedContentLength, buffer.position()); return buffer; }

Target:
private ByteBuffer getContent(Queue<HttpObject> contents, long expectedContentLength) { ByteBuffer buffer = ByteBuffer.allocate((int) expectedContentLength); boolean endMarkerFound = false; for (HttpObject object : contents) { assertFalse("There should have been no more data after the end marker was found", endMarkerFound); HttpContent content = (HttpContent) object; buffer.put(content.content().nioBuffer()); endMarkerFound = object instanceof LastHttpContent; ReferenceCountUtil.release(content); } assertEquals("Content length did not match expected", expectedContentLength, buffer.position()); assertTrue("End marker was not found", endMarkerFound); return buffer; }
Source:
public void logPattern() throws Exception { TaskId taskId = TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L); taskLogger = new TaskLogger(taskId, "myhost"); assertEquals("", taskLogger.getLogs().getAllLogs(false)); taskLogger.getOutputSink().println("hello"); String quotedStringTaskId = Pattern.quote(taskId.toString()); assertTrue(taskLogger.getLogs() .getAllLogs(true) .matches("\\[" + quotedStringTaskId + "@myhost;[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\] hello\n? *\n+")); taskLogger.getErrorSink().println("error"); assertTrue(taskLogger.getLogs() .getStderrLogs(true) .matches("\\[" + quotedStringTaskId + "@myhost;[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\] error\n? *\n+")); }

Target:
public void logPattern() throws Exception { TaskId taskId = TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L); taskLogger = new TaskLogger(taskId, "myhost"); assertEquals("", taskLogger.getLogs().getAllLogs(false)); taskLogger.getOutputSink().println("hello"); String quotedStringTaskId = Pattern.quote(taskId.toString()); assertTrue(taskLogger.getLogs() .getAllLogs(true) .matches("\\[" + quotedStringTaskId + "@myhost;[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\] hello\r?\n? *\r?\n+")); taskLogger.getErrorSink().println("error"); assertTrue(taskLogger.getLogs() .getStderrLogs(true) .matches("\\[" + quotedStringTaskId + "@myhost;[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\] error\r?\n? *\r?\n+")); }
Source:
public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { GetLightPowerRequest powerPacket = new GetLightPowerRequest(); GetRequest colorPacket = new GetRequest(); try { switch (channelUID.getId()) { case CHANNEL_COLOR: case CHANNEL_BRIGHTNESS: sendPacket(powerPacket); sendPacket(colorPacket); break; case CHANNEL_TEMPERATURE: sendPacket(colorPacket); break; default: break; } } catch (Exception ex) { logger.error("Error while refreshing a chanel for the bulb: {}", ex.getMessage(), ex); } } else { try { switch (channelUID.getId()) { case CHANNEL_COLOR: if (command instanceof HSBType) { handleHSBCommand((HSBType) command); return; } break; case CHANNEL_BRIGHTNESS: if (command instanceof PercentType) { handlePercentCommand((PercentType) command); } else if (command instanceof OnOffType) { handleOnOffCommand((OnOffType) command); } else if (command instanceof IncreaseDecreaseType) { handleIncreaseDecreaseCommand((IncreaseDecreaseType) command); } break; case CHANNEL_TEMPERATURE: if (command instanceof PercentType) { handleTemperatureCommand((PercentType) command); } else if (command instanceof IncreaseDecreaseType) { handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command); } break; default: break; } } catch (Exception ex) { logger.error("Error while updating bulb: {}", ex.getMessage(), ex); } } }

Target:
public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { GetLightPowerRequest powerPacket = new GetLightPowerRequest(); GetRequest colorPacket = new GetRequest(); try { switch (channelUID.getId()) { case CHANNEL_COLOR: case CHANNEL_BRIGHTNESS: sendPacket(powerPacket); sendPacket(colorPacket); break; case CHANNEL_TEMPERATURE: sendPacket(colorPacket); break; default: break; } } catch (Exception ex) { logger.error("Error while refreshing a channel for the bulb: {}", ex.getMessage(), ex); } } else { try { switch (channelUID.getId()) { case CHANNEL_COLOR: if (command instanceof HSBType) { handleHSBCommand((HSBType) command); return; } break; case CHANNEL_BRIGHTNESS: if (command instanceof PercentType) { handlePercentCommand((PercentType) command); } else if (command instanceof OnOffType) { handleOnOffCommand((OnOffType) command); } else if (command instanceof IncreaseDecreaseType) { handleIncreaseDecreaseCommand((IncreaseDecreaseType) command); } break; case CHANNEL_TEMPERATURE: if (command instanceof PercentType) { handleTemperatureCommand((PercentType) command); } else if (command instanceof IncreaseDecreaseType) { handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command); } break; default: break; } } catch (Exception ex) { logger.error("Error while updating bulb: {}", ex.getMessage(), ex); } } }
Source:
public boolean isEmpty() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Closed"); } assertions(); for (PBDSegment s : m_segments.values()) { final boolean wasClosed = s.isClosed(); try { if (!s.isOpenForReading(m_cursorId)) { s.openForRead(m_cursorId); } if (s.hasMoreEntries(m_cursorId)) return false; } finally { if (wasClosed) { s.close(); } } } return true; } }

Target:
public boolean isEmpty() throws IOException { synchronized(PersistentBinaryDeque.this) { if (m_closed) { throw new IOException("Closed"); } assertions(); moveToValidSegment(); boolean inclusive = true; if (m_segment.isOpenForReading(m_cursorId)) { if (m_segment.getReader(m_cursorId).hasMoreEntries()) return false; inclusive = false; } for (PBDSegment currSegment : m_segments.tailMap(m_segment.segmentId(), inclusive).values()) { if (currSegment.getNumEntries() > 0) return false; } return true; } }
Source:
private List<ServiceReference<?>> asList(ServiceReference<?>[] refs) { if (refs == null) return Collections.EMPTY_LIST; return Arrays.asList(refs); }

Target:
private List<ServiceReference<?>> asList(ServiceReference<?>[] refs) { if (refs == null) return Collections.emptyList(); return Arrays.asList(refs); }
Source:
String gtk_rgba_to_css_string (GdkRGBA rgba) { String color; if (rgba != null) { color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; } else { GdkColor defaultGdkColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND).handle; GdkRGBA defaultRGBA = new GdkRGBA (); defaultRGBA.alpha = 1.0; defaultRGBA.red = (defaultGdkColor.red & 0xFFFF) / (float)0xFFFF; defaultRGBA.green = (defaultGdkColor.green & 0xFFFF) / (float)0xFFFF; defaultRGBA.blue = (defaultGdkColor.blue & 0xFFFF) / (float)0xFFFF; color = "rgba(" + (int)(defaultRGBA.red * 255) + "," + (int)(defaultRGBA.green * 255) + "," + (int)(defaultRGBA.blue * 255) + ",1.0)"; } return color; }

Target:
String gtk_rgba_to_css_string (GdkRGBA rgba) { GdkRGBA toConvert; if (rgba != null) { toConvert = rgba; } else { GdkColor defaultGdkColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND).handle; toConvert = new GdkRGBA (); toConvert.alpha = 1.0; toConvert.red = (defaultGdkColor.red & 0xFFFF) / (float)0xFFFF; toConvert.green = (defaultGdkColor.green & 0xFFFF) / (float)0xFFFF; toConvert.blue = (defaultGdkColor.blue & 0xFFFF) / (float)0xFFFF; } long str = OS.gdk_rgba_to_string (toConvert); int length = OS.strlen (str); byte buffer = new byte [length]; OS.memmove (buffer, str, length); return new String (Converter.mbcsToWcs (null, buffer)); }
Source:
public void activate(Context context) { try { scan = operationScan(); scanner = getStore().getTable().getScanner(scan); readThread = new Thread(new Runnable() { @Override public void run() { try { Result result; while ((result = scanner.next()) != null) { while (!resultQueue.offer(result)) { Thread.sleep(DEF_SLEEP_MILLIS); } } } catch (Exception e) { logger.debug("Exception in fetching results"); throw new RuntimeException(e.getMessage()); } finally { scanner.close(); } } }); } catch (Exception ex) { throw new RuntimeException(ex); } readThread.start(); }

Target:
public void activate(Context context) { startReadThread(); }
Source:
public ScoredCandidates<Container> generate( Container content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Container Child Equivalence Generator"); OptionalMap<String,EquivalenceSummary> childSummaries = summaryStore.summariesForUris( Iterables.transform(content.getChildRefs(), ChildRef.TO_URI) ); Multiset<String> parents = HashMultiset.create(); for (EquivalenceSummary summary : Optional.presentInstances(childSummaries.values())) { if (publishers == null) { Iterables.addAll(parents, Iterables.filter(Iterables.transform( summary.getEquivalents().values(), TO_PARENT ), Predicates.notNull())); } else { Iterables.addAll(parents, Iterables.filter(summary.getEquivalents() .values() .stream() .filter(input -> publishers == null || publishers.contains(input.getPublisher())) .map(TO_PARENT::apply) .collect(Collectors.toList() ), Predicates.notNull())); } } return scoreContainers( parents, childSummaries.size(), desc, equivToTelescopeResult, generatorComponent ); }

Target:
public ScoredCandidates<Container> generate( Container content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName("Container Child Equivalence Generator"); OptionalMap<String,EquivalenceSummary> childSummaries = summaryStore.summariesForUris( Iterables.transform(content.getChildRefs(), ChildRef.TO_URI) ); Multiset<String> parents = HashMultiset.create(); for (EquivalenceSummary summary : Optional.presentInstances(childSummaries.values())) { Iterables.addAll( parents, summary.getEquivalents() .values() .stream() .filter(input -> publishers == null || publishers.contains(input.getPublisher())) .map(TO_PARENT::apply) .filter(Objects::nonNull) .collect(Collectors.toList()) ); } return scoreContainers( parents, childSummaries.size(), desc, equivToTelescopeResult, generatorComponent ); }
Source:
public void testAttachmentOnCenterLabelSelection() { testAttachmentOnCenterLabelSelection(false); testAttachmentOnCenterLabelSelection(true); }

Target:
public void testAttachmentOnCenterLabelSelection() { testAttachmentOnCenterLabelSelection(false); editor.getDiagramGraphicalViewer().deselectAll(); testAttachmentOnCenterLabelSelection(true); }
Source:
public void testGetAttributeAsStringList() { final VariantContext context = basicBuilder .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertEquals(context.getAttributeAsStringList("DefaultIntegerList", "empty"), Arrays.asList("0", "0", "0", "0", "0")); Assert.assertEquals(context.getAttributeAsStringList("ListWithMissing", "empty"), Arrays.asList("1", "empty", "empty")); Assert.assertEquals(context.getAttributeAsStringList("IntegerList", "empty"), Arrays.asList("0", "1", "2", "3")); Assert.assertEquals(context.getAttributeAsStringList("DoubleList", "empty"), Arrays.asList("1.8", "1.6", "2.1")); Assert.assertEquals(context.getAttributeAsStringList("StringList", "empty"), Arrays.asList("1", "2")); Assert.assertEquals(context.getAttributeAsStringList("NotNumeric", "empty"), Arrays.asList("A", "B")); }

Target:
public void testGetAttributeAsStringList() { final VariantContext context = basicBuilder .attribute("Empty", new int[0]) .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertTrue(context.getAttributeAsStringList("Empty", "empty").isEmpty()); Assert.assertEquals(context.getAttributeAsStringList("DefaultIntegerList", "empty"), Arrays.asList("0", "0", "0", "0", "0")); Assert.assertEquals(context.getAttributeAsStringList("ListWithMissing", "empty"), Arrays.asList("1", "empty", "empty")); Assert.assertEquals(context.getAttributeAsStringList("IntegerList", "empty"), Arrays.asList("0", "1", "2", "3")); Assert.assertEquals(context.getAttributeAsStringList("DoubleList", "empty"), Arrays.asList("1.8", "1.6", "2.1")); Assert.assertEquals(context.getAttributeAsStringList("StringList", "empty"), Arrays.asList("1", "2")); Assert.assertEquals(context.getAttributeAsStringList("NotNumeric", "empty"), Arrays.asList("A", "B")); Assert.assertTrue(context.getAttributeAsStringList("MissingList", "empty").isEmpty()); }
Source:
private void onSceneAddedInternal(InternalScene scene) { logger.debug(scene.getSceneType()); if (scene != null && scene.getSceneType().equals(sceneType)) { if (!ignoredScene(scene.getSceneID()) && !ignoreGroup(scene.getGroupID())) { ThingUID thingUID = getThingUID(scene); if (thingUID != null) { ThingUID bridgeUID = bridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(4); properties.put(ZONE_ID, scene.getZoneID()); properties.put(GROUP_ID, scene.getGroupID()); if (SceneEnum.containsScene(scene.getSceneID())) { properties.put(SCENE_ID, SceneEnum.getScene(scene.getSceneID()).toString()); } else { logger.debug("discovered scene: name '{}' with id have an invalid scene-ID", scene.getSceneName(), scene.getID()); } DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) .withBridge(bridgeUID).withLabel(scene.getSceneName()).build(); thingDiscovered(discoveryResult); } else { logger.debug("discovered unsupported scene: name '{}' with id {}", scene.getSceneName(), scene.getID()); } } } }

Target:
private void onSceneAddedInternal(InternalScene scene) { logger.debug("{}", scene.getSceneType()); if (scene != null && scene.getSceneType().equals(sceneType)) { if (!ignoredScene(scene.getSceneID()) && !ignoreGroup(scene.getGroupID())) { ThingUID thingUID = getThingUID(scene); if (thingUID != null) { ThingUID bridgeUID = bridgeHandler.getThing().getUID(); Map<String, Object> properties = new HashMap<>(); properties.put(ZONE_ID, scene.getZoneID()); properties.put(GROUP_ID, scene.getGroupID()); if (SceneEnum.containsScene(scene.getSceneID())) { properties.put(SCENE_ID, SceneEnum.getScene(scene.getSceneID()).toString()); } else { logger.debug("discovered scene: name '{}' with id have an invalid scene-ID", scene.getSceneName(), scene.getID()); } DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) .withBridge(bridgeUID).withLabel(scene.getSceneName()).build(); thingDiscovered(discoveryResult); } else { logger.debug("discovered unsupported scene: name '{}' with id {}", scene.getSceneName(), scene.getID()); } } } }
Source:
public void popout() { if (rmdPreviewParams_ != null && !rmdPreviewParams_.isShinyDocument()) { globalDisplay_.showHtmlFile(rmdPreviewParams_.getOutputFile()); } else if (frame_ != null && !StringUtil.equals(frame_.getIFrame().getCurrentUrl(), getUrl())) { globalDisplay_.openWindow(frame_.getIFrame().getCurrentUrl()); } else if (unmodifiedUrl_ != null) { globalDisplay_.openWindow(unmodifiedUrl_); } }

Target:
public void popout() { if (rmdPreviewParams_ != null && !rmdPreviewParams_.isShinyDocument()) { globalDisplay_.showHtmlFile(rmdPreviewParams_.getOutputFile()); } else if (frame_ != null && frame_.getIFrame().getCurrentUrl() != null && !StringUtil.equals(frame_.getIFrame().getCurrentUrl(), getUrl())) { globalDisplay_.openWindow(frame_.getIFrame().getCurrentUrl()); } else if (unmodifiedUrl_ != null) { globalDisplay_.openWindow(unmodifiedUrl_); } }
Source:
static OperationDefinition getOperationDefinition() { assert TIMEOUT != null; return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) .setParameters(TIMEOUT) .setReplyType(ModelType.STRING) .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }

Target:
static OperationDefinition getOperationDefinition() { assert TIMEOUT != null; return new SimpleOperationDefinitionBuilder(OPERATION_NAME, HostResolver.getResolver("host.server")) .setParameters(TIMEOUT) .setRuntimeOnly() .withFlag(OperationEntry.Flag.HOST_CONTROLLER_ONLY) .build(); }
Source:
public static String fromUtf8(final ByteBuffer buffer, final int numBytes) { final byte[] bytes = new byte[numBytes]; buffer.get(bytes); return StringUtils.fromUtf8(bytes); }

Target:
public static String fromUtf8(final ByteBuffer buffer, final int numBytes) { final byte[] bytes = new byte[numBytes]; buffer.get(bytes); return fromUtf8(bytes); }
Source:
public Response createEvent( @ApiParam(value = "Event to be created. Category and Text fields required", name = "event", required = true) final Event event) { try { if (null != event) { event.setTenantId(tenantId); if (null != alertsService.getEvent(tenantId, event.getId(), true)) { return ResponseUtil.badRequest("Event with ID [" + event.getId() + "] exists."); } alertsService.sendEvent(event); log.debugf("Event: %s ", event.toString()); return ResponseUtil.ok(event); } else { return ResponseUtil.badRequest("Event is null"); } } catch (Exception e) { log.debugf(e.getMessage(), e); return ResponseUtil.internalError(e.getMessage()); } }

Target:
public Response createEvent( @ApiParam(value = "Event to be created. Category and Text fields required", name = "event", required = true) final Event event) { try { if (null != event) { event.setTenantId(tenantId); if (null != alertsService.getEvent(tenantId, event.getId(), true)) { return ResponseUtil.badRequest("Event with ID [" + event.getId() + "] exists."); } alertsService.addEvents(Collections.singletonList(event)); log.debugf("Event: %s ", event.toString()); return ResponseUtil.ok(event); } else { return ResponseUtil.badRequest("Event is null"); } } catch (Exception e) { log.debugf(e.getMessage(), e); return ResponseUtil.internalError(e.getMessage()); } }
Source:
public ObjectId insert(final int type, long len, final InputStream is, boolean createDuplicate) throws IOException { if (len <= buffer().length) { byte[] buf = buffer(); int actLen = IO.readFully(is, buf, 0); return insert(type, buf, 0, actLen, createDuplicate); } else { MessageDigest md = digest(); File tmp = toTemp(md, type, len, is); ObjectId id = ObjectId.fromRaw(md.digest()); return insertOneObject(tmp, id, createDuplicate); } }

Target:
ObjectId insert(final int type, long len, final InputStream is, boolean createDuplicate) throws IOException { if (len <= buffer().length) { byte[] buf = buffer(); int actLen = IO.readFully(is, buf, 0); return insert(type, buf, 0, actLen, createDuplicate); } else { MessageDigest md = digest(); File tmp = toTemp(md, type, len, is); ObjectId id = ObjectId.fromRaw(md.digest()); return insertOneObject(tmp, id, createDuplicate); } }
Source:
private void globalRebalance(ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput, RebalanceAlgorithm algorithm) throws HelixRebalanceException { _changeDetector.updateSnapshots(clusterData); final Map<HelixConstants.ChangeType, Set<String>> clusterChanges = _changeDetector.getChangeTypes().stream() .collect(Collectors.toMap(changeType -> changeType, changeType -> { Set<String> itemKeys = new HashSet<>(); itemKeys.addAll(_changeDetector.getAdditionsByType(changeType)); itemKeys.addAll(_changeDetector.getChangesByType(changeType)); itemKeys.addAll(_changeDetector.getRemovalsByType(changeType)); return itemKeys; })).entrySet().stream().filter(changeEntry -> !changeEntry.getValue().isEmpty()) .collect(Collectors .toMap(changeEntry -> changeEntry.getKey(), changeEntry -> changeEntry.getValue())); if (clusterChanges.keySet().stream() .anyMatch(GLOBAL_REBALANCE_REQUIRED_CHANGE_TYPES::contains)) { Map<String, ResourceAssignment> currentBaseline = getBaselineAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); ClusterModel clusterModel; try { clusterModel = ClusterModelProvider .generateClusterModelForBaseline(clusterData, resourceMap, clusterData.getAllInstances(), clusterChanges, currentBaseline); } catch (Exception ex) { throw new HelixRebalanceException("Failed to generate cluster model for global rebalance.", HelixRebalanceException.Type.INVALID_CLUSTER_STATUS, ex); } refreshBaseline(clusterModel, algorithm); } }

Target:
private void globalRebalance(ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput, RebalanceAlgorithm algorithm) throws HelixRebalanceException { _changeDetector.updateSnapshots(clusterData); final Map<HelixConstants.ChangeType, Set<String>> clusterChanges = _changeDetector.getAllChanges(); if (clusterChanges.keySet().stream() .anyMatch(GLOBAL_REBALANCE_REQUIRED_CHANGE_TYPES::contains)) { Map<String, ResourceAssignment> currentBaseline = getBaselineAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); ClusterModel clusterModel; try { clusterModel = ClusterModelProvider .generateClusterModelForBaseline(clusterData, resourceMap, clusterData.getAllInstances(), clusterChanges, currentBaseline); } catch (Exception ex) { throw new HelixRebalanceException("Failed to generate cluster model for global rebalance.", HelixRebalanceException.Type.INVALID_CLUSTER_STATUS, ex); } calculateAndUpdateBaseline(clusterModel, algorithm); } }