auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<LeaderboardEntry> getLeaderboard(UUID challengeId){ List<LeaderboardEntry> leaderboard = new ArrayList<>(); List<Object[]> results = repository.findLeaderboardForChallenge(challengeId); for (Object[] resultEntry: results){ LeaderboardEntry entry = new LeaderboardEntry(); Result result = (Result)resultEntry[0]; entry.setUser(new UserShowDto(result.getUser())); entry.setTasksCompleted((Long)resultEntry[1]); entry.setLastLevelFinishDate((ZonedDateTime)resultEntry[2]); leaderboard.add(entry); } return leaderboard; }

Target:
public List<LeaderboardEntryDto> getLeaderboard(UUID challengeId) { List<LeaderboardEntryDto> leaderboard = new ArrayList<>(); List<Object[]> results = repository.findLeaderboardForChallenge(challengeId); for (Object[] resultEntry: results){ LeaderboardEntryDto entry = new LeaderboardEntryDto(); Result result = (Result)resultEntry[0]; entry.setUser(new UserShowDto(result.getUser())); entry.setTasksCompleted((Long)resultEntry[1]); entry.setLastLevelFinishDate((ZonedDateTime)resultEntry[2]); leaderboard.add(entry); } return leaderboard; }
Source:
public void addInstance(CollectionInstance instance) { if (this.instances == null) this.instances = new HashSet<>(); this.instances.add(instance); }

Target:
public void addInstance(CollectionInstance instance) { if (this.instances == null) { this.instances = new HashSet<>(); } this.instances.add(instance); }
Source:
public void stop() throws Exception { stopClient(httpClient); if (http2Client.isPresent()) { stopClient(http2Client.get()); } }

Target:
public void stop() throws Exception { stopClient(httpClient); http2Client.ifPresent(this::stopClient); }
Source:
protected void drive(float distance) throws AutonomousModeOverException, InterruptedException { float currentEncoder = DriveCode.leftEncoder.get(); DriveCode.allMotors.set(distance/distance); waitUntilAtLeast(DriveCode.leftEncoder, currentEncoder + distance); DriveCode.allMotors.set(0.0f); }

Target:
protected void drive(float distance) throws AutonomousModeOverException, InterruptedException { float startingEncoder = DriveCode.leftEncoder.get(); if (distance > 0) { DriveCode.allMotors.set(driveSpeed.get()); waitUntilAtLeast(DriveCode.leftEncoder, startingEncoder + distance); } else { DriveCode.allMotors.set(-driveSpeed.get()); waitUntilAtMost(DriveCode.leftEncoder, startingEncoder + distance); } DriveCode.allMotors.set(0.0f); }
Source:
public void testCodeSpanParsedToHtml() { StringWriter out = new StringWriter(); DocumentBuilder builder = new CreoleDocumentBuilder(out); builder.beginDocument(); builder.beginDocument(); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("** /nthis is code/n **"); builder.endSpan(); builder.endDocument(); assertParsedHtmlMatchesRoundTrip("<p><code>** /nthis is code/n **</code></p>", out.toString()); }

Target:
public void testCodeSpanParsedToHtml() { StringWriter out = new StringWriter(); DocumentBuilder builder = new CreoleDocumentBuilder(out); builder.beginDocument(); builder.characters("This class is called "); builder.beginSpan(SpanType.CODE, new Attributes()); builder.characters("** /nCreoleLanguageIntegrationTest/n **"); builder.endSpan(); builder.characters(" and it tests Creole markup."); builder.endDocument(); assertParsedHtmlMatchesRoundTrip( "<p>This class is called <code>** /nCreoleLanguageIntegrationTest/n **</code> and it tests Creole markup.</p>", out.toString()); }
Source:
public void setValue(Object value) { Attribute attribute = getAuthorizedAttribute(); if (attribute == null) { attribute = getAuthorizedNetworkAttribute(); } switch (attribute.getValueType()) { case BINARY: setBinaryValue((byte[]) value); return; case BOOLEAN: setBooleanValue((Boolean) value); return; case INTEGER: setIntegerValue((Integer) value); return; case NUMERIC: setNumericValue((BigDecimal) value); return; case TEXT: setTextValue((String) value); return; case TIMESTAMP: setTimestampValue((Timestamp) value); return; case JSON: setJsonValue((Timestamp) value); return; default: throw new IllegalStateException(String.format("Invalid value type: %s", attribute.getValueType())); } }

Target:
public void setValue(Object value) { Attribute attribute = getAuthorizedAttribute(); if (attribute == null) { attribute = getAuthorizedNetworkAttribute(); } switch (attribute.getValueType()) { case BINARY: setBinaryValue((byte[]) value); return; case BOOLEAN: setBooleanValue((Boolean) value); return; case INTEGER: setIntegerValue((Integer) value); return; case NUMERIC: setNumericValue((BigDecimal) value); return; case TEXT: setTextValue((String) value); return; case TIMESTAMP: setTimestampValue((Timestamp) value); return; case JSON: setJsonValue(value); return; default: throw new IllegalStateException(String.format("Invalid value type: %s", attribute.getValueType())); } }
Source:
public void testDiskView() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { IViewPart viewSite = fViewBotDisk.getViewReference().getView(true); assertTrue(viewSite instanceof DiskIOActivityView); final TmfCommonXLineChartViewer chartViewer = getChartViewer(viewSite); assertNotNull(chartViewer); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); final Chart chart = fChart; assertNotNull(chart); try { WaitUtils.waitUntil(c -> c.getSeriesSet().getSeries().length > 0, chart, "No data available"); chartViewer.setNbPoints(NUMBER_OF_POINT); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk0-res50.json", "Chart data is not valid"); TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, new TmfTimeRange(START_TIME_WHERE_THERE_IS_DISK_ACTIVITY, END_TIME_WHERE_THERE_IS_DISK_ACTIVITY))); fBot.waitUntil(ConditionHelpers.windowRange(new TmfTimeRange(START_TIME_WHERE_THERE_IS_DISK_ACTIVITY, END_TIME_WHERE_THERE_IS_DISK_ACTIVITY))); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); verifyChartStyle(chart); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk1-res50.json", "Chart data is not valid"); chartViewer.setNbPoints(MORE_POINTS); verifyChartStyle(chart); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk2-res100.json", "Chart data is not valid"); } finally { } }

Target:
public void testDiskView() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { IViewPart viewSite = fViewBotDisk.getViewReference().getView(true); assertTrue(viewSite instanceof DiskIOActivityView); final TmfCommonXLineChartViewer chartViewer = getChartViewer(viewSite); assertNotNull(chartViewer); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); final Chart chart = fChart; assertNotNull(chart); WaitUtils.waitUntil(c -> c.getSeriesSet().getSeries().length > 0, chart, "No data available"); chartViewer.setNbPoints(NUMBER_OF_POINT); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk0-res50.json", "Chart data is not valid"); TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, new TmfTimeRange(START_TIME_WHERE_THERE_IS_DISK_ACTIVITY, END_TIME_WHERE_THERE_IS_DISK_ACTIVITY))); fBot.waitUntil(ConditionHelpers.windowRange(new TmfTimeRange(START_TIME_WHERE_THERE_IS_DISK_ACTIVITY, END_TIME_WHERE_THERE_IS_DISK_ACTIVITY))); fBot.waitUntil(ConditionHelpers.xyViewerIsReadyCondition(chartViewer)); verifyChartStyle(chart); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk1-res50.json", "Chart data is not valid"); chartViewer.setNbPoints(MORE_POINTS); verifyChartStyle(chart); WaitUtils.waitUntil(json -> isChartDataValid(chart, json), "resources/disk2-res100.json", "Chart data is not valid"); }
Source:
public void should_exclude_ignored_instructions_from_computation_of_first_and_last_lines() { InsnNode i1 = addInsn(1, false); addInsn(2, false); InsnNode i2 = addInsn(3, false); MethodCoverageCalculator c = new MethodCoverageCalculator(instructions); c.ignore(i1, i1); c.ignore(i2, i2); c.calculate(coverage); assertEquals(2, coverage.getFirstLine()); assertEquals(2, coverage.getLastLine()); }

Target:
public void should_exclude_ignored_instructions_from_computation_of_first_and_last_lines() { InsnNode i1 = addInsn(1, false); addInsn(2, false); InsnNode i3 = addInsn(3, false); MethodCoverageCalculator c = new MethodCoverageCalculator(instructions); c.ignore(i1, i1); c.ignore(i3, i3); c.calculate(coverage); assertEquals(2, coverage.getFirstLine()); assertEquals(2, coverage.getLastLine()); }
Source:
protected String callRestApi(final String username, final String password) throws HttpAction, CredentialsException { final String basicAuth; try { basicAuth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes("UTF-8")); } catch (final UnsupportedEncodingException e) { throw new TechnicalException(e); } final Map<String, String> headers = new HashMap<>(); headers.put(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + basicAuth); HttpURLConnection connection = null; try { connection = HttpUtils.openPostConnection(new URL(url), headers); int code = connection.getResponseCode(); if (code != 200) { logger.error("Failed response: {}", HttpUtils.buildHttpErrorMessage(connection)); return null; } else { return HttpUtils.readBody(connection); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }

Target:
protected String callRestApi(final String username, final String password) throws HttpAction, CredentialsException { final String basicAuth; try { basicAuth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes("UTF-8")); } catch (final UnsupportedEncodingException e) { throw new TechnicalException(e); } final Map<String, String> headers = new HashMap<>(); headers.put(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + basicAuth); HttpURLConnection connection = null; try { connection = HttpUtils.openPostConnection(new URL(url), headers); int code = connection.getResponseCode(); if (code == 200) { logger.debug("Authentication success for username: {}", username); return HttpUtils.readBody(connection); } else if (code == 401 || code == 403) { logger.info("Authentication failure for username: -> {}", username, HttpUtils.buildHttpErrorMessage(connection)); return null; } else { logger.warn("Unexpected error for username: -> {}", username, HttpUtils.buildHttpErrorMessage(connection)); return null; } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }
Source:
public void runInPodWithRetention() throws Exception { logs.capture(1000); r.assertBuildStatusSuccess(r.waitForCompletion(b)); logs.getMessages().stream().anyMatch(msg -> msg.contains("was not deleted due to retention policy Always")); assertTrue(deletePods(cloud.connect(), getLabels(this, name), false)); }

Target:
public void runInPodWithRetention() throws Exception { r.assertBuildStatusSuccess(r.waitForCompletion(b)); assertTrue(deletePods(cloud.connect(), getLabels(this, name), true)); }
Source:
public String getCategoryID() { return "org.eclipse.papyrus.sysml14.diagram.parametric.dnd.ConstraintDropStrategy"; }

Target:
public String getCategoryID() { return "org.eclipse.papyrus.sysml14.diagram.parametric"; }
Source:
public void testSTGeometryType() { Map<GeometrySerializationType, String[]> types = new ImmutableMap.Builder<GeometrySerializationType, String[]>() .put(GeometrySerializationType.POINT, new String[]{"ST_GeometryType(ST_Point(1, 4))", "ST_Point"}) .put(GeometrySerializationType.LINE_STRING, new String[]{"ST_GeometryType(ST_GeometryFromText('LINESTRING (1 1, 2 2)'))", "ST_LineString"}) .put(GeometrySerializationType.POLYGON, new String[]{"ST_GeometryType(ST_GeometryFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'))", "ST_Polygon"}) .put(GeometrySerializationType.MULTI_POINT, new String[]{"ST_GeometryType(ST_GeometryFromText('MULTIPOINT (1 1, 2 2)'))", "ST_MultiPoint"}) .put(GeometrySerializationType.MULTI_LINE_STRING, new String[]{"ST_GeometryType(ST_GeometryFromText('MULTILINESTRING ((1 1, 2 2), (3 3, 4 4))'))", "ST_MultiLineString"}) .put(GeometrySerializationType.MULTI_POLYGON, new String[]{"ST_GeometryType(ST_GeometryFromText('MULTIPOLYGON (((1 1, 1 4, 4 4, 4 1)), ((1 1, 1 4, 4 4, 4 1)))'))", "ST_MultiPolygon"}) .put(GeometrySerializationType.GEOMETRY_COLLECTION, new String[]{"ST_GeometryType(ST_GeometryFromText('GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))'))", "ST_GeomCollection"}) .put(GeometrySerializationType.ENVELOPE, new String[]{"ST_GeometryType(ST_Envelope(ST_GeometryFromText('LINESTRING (1 1, 2 2)')))", "ST_Polygon"}) .build(); for (GeometrySerializationType t : GeometrySerializationType.values()) { String[] r = types.get(t); if (r == null) { fail("Missing test for type: " + t); } assertFunction(r[0], VARCHAR, r[1]); } }

Target:
public void testSTGeometryType() { assertFunction("ST_GeometryType(ST_Point(1, 4))", VARCHAR, "ST_Point"); assertFunction("ST_GeometryType(ST_GeometryFromText('LINESTRING (1 1, 2 2)'))", VARCHAR, "ST_LineString"); assertFunction("ST_GeometryType(ST_GeometryFromText('POLYGON ((1 1, 1 4, 4 4, 4 1))'))", VARCHAR, "ST_Polygon"); assertFunction("ST_GeometryType(ST_GeometryFromText('MULTIPOINT (1 1, 2 2)'))", VARCHAR, "ST_MultiPoint"); assertFunction("ST_GeometryType(ST_GeometryFromText('MULTILINESTRING ((1 1, 2 2), (3 3, 4 4))'))", VARCHAR, "ST_MultiLineString"); assertFunction("ST_GeometryType(ST_GeometryFromText('MULTIPOLYGON (((1 1, 1 4, 4 4, 4 1)), ((1 1, 1 4, 4 4, 4 1)))'))", VARCHAR, "ST_MultiPolygon"); assertFunction("ST_GeometryType(ST_GeometryFromText('GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))'))", VARCHAR, "ST_GeomCollection"); assertFunction("ST_GeometryType(ST_Envelope(ST_GeometryFromText('LINESTRING (1 1, 2 2)')))", VARCHAR, "ST_Polygon"); }
Source:
public void testFailedReplicaAssigment() throws InterruptedException, IOException { TEST_UTIL.getMiniHBaseCluster().getConfiguration().setClass(HConstants.MASTER_IMPL, BrokenMetaReplicaMaster.class, HMaster.class); TEST_UTIL.getMiniHBaseCluster().stopMaster(0).join(); HMaster newMaster = TEST_UTIL.getMiniHBaseCluster().startMaster().getMaster(); TEST_UTIL.waitFor(30000, () -> newMaster.isInitialized()); TEST_UTIL.getMiniHBaseCluster().getConfiguration().unset(HConstants.MASTER_IMPL); AssignmentManager am = TEST_UTIL.getMiniHBaseCluster().getMaster().getAssignmentManager(); RegionInfo metaReplicaHri = RegionReplicaUtil.getRegionInfoForReplica( RegionInfoBuilder.FIRST_META_REGIONINFO, 2); RegionStateNode metaReplicaRegionNode = am.getRegionStates().getOrCreateRegionStateNode(metaReplicaHri); Assert.assertNull(metaReplicaRegionNode.getRegionLocation()); }

Target:
public void testFailedReplicaAssigment() throws InterruptedException, IOException { TEST_UTIL.getMiniHBaseCluster().getConfiguration().setClass(HConstants.MASTER_IMPL, BrokenMetaReplicaMaster.class, HMaster.class); TEST_UTIL.getMiniHBaseCluster().stopMaster(0).join(); HMaster newMaster = TEST_UTIL.getMiniHBaseCluster().startMaster().getMaster(); TEST_UTIL.waitFor(30000, () -> newMaster.isInitialized()); TEST_UTIL.getMiniHBaseCluster().getConfiguration().unset(HConstants.MASTER_IMPL); AssignmentManager am = newMaster.getAssignmentManager(); RegionInfo metaReplicaHri = RegionReplicaUtil.getRegionInfoForReplica( RegionInfoBuilder.FIRST_META_REGIONINFO, 1); RegionStateNode metaReplicaRegionNode = am.getRegionStates().getOrCreateRegionStateNode(metaReplicaHri); Assert.assertNotNull(metaReplicaRegionNode.getRegionLocation()); RegionInfo metaReplicaHri2 = RegionReplicaUtil.getRegionInfoForReplica( RegionInfoBuilder.FIRST_META_REGIONINFO, 2); RegionStateNode metaReplicaRegionNode2 = am.getRegionStates().getOrCreateRegionStateNode(metaReplicaHri2); Assert.assertNull(metaReplicaRegionNode2.getRegionLocation()); Assert.assertFalse(newMaster.isStopping()); Assert.assertFalse(newMaster.isStopped()); Assert.assertTrue(newMaster.isActiveMaster()); }
Source:
public int getDay(Type type, Block block, int position) { if (type.equals(DATE)) { return toIntExact(DATE.getLong(block, position)); } if (type.equals(TIMESTAMP)) { long millis = block.getLong(position, 0); long local = timeZone.convertUTCToLocal(millis); long days = MILLISECONDS.toDays(local); return toIntExact(days); } throw new IllegalArgumentException("Wrong type for temporal column: " + type); }

Target:
public int getDay(Type type, Block block, int position) { if (type.equals(DATE)) { return toIntExact(DATE.getLong(block, position)); } if (type.equals(TIMESTAMP)) { long millis = TIMESTAMP.getLong(block, position); long local = timeZone.convertUTCToLocal(millis); long days = MILLISECONDS.toDays(local); return toIntExact(days); } throw new IllegalArgumentException("Wrong type for temporal column: " + type); }
Source:
public void testMigration() { assertEquals(1, session.getOwnedViews().size()); DView dView = session.getOwnedViews().iterator().next(); List<DRepresentation> loadedRepresentations = new DViewQuery(dView).getLoadedRepresentations(); assertEquals(1, loadedRepresentations.size()); DRepresentation dRepresentation = loadedRepresentations.get(0); assertTrue(dRepresentation instanceof DDiagram); DDiagram dDiagram = (DDiagram) dRepresentation; ComputedStyleDescriptionRegistry computedStyleDescriptionRegistry = new DDiagramInternalQuery(dDiagram).getComputedStyleDescriptionRegistry(false); assertNotNull(computedStyleDescriptionRegistry); assertEquals("Computed StyleDescriptiosshould have been shared among styles within the DDiagram", 3, computedStyleDescriptionRegistry.getComputedStyleDescriptions().size()); assertEquals("As the maps of ComputedStyleDescriptionRegistry are no more used, it should remains only the 3 computed StyleDescriptions", 3, computedStyleDescriptionRegistry.eContents().size()); XMLResource airdResource = (XMLResource) session.getSessionResource(); assertTrue("Check the migration logic.", airdResource.getEObjectToExtensionMap().size() == 0); }

Target:
public void testMigration() { assertEquals(1, session.getOwnedViews().size()); DView dView = session.getOwnedViews().iterator().next(); List<DRepresentation> loadedRepresentations = new DViewQuery(dView).getLoadedRepresentations(); assertEquals(1, loadedRepresentations.size()); DRepresentation dRepresentation = loadedRepresentations.get(0); assertTrue(dRepresentation instanceof DDiagram); DDiagram dDiagram = (DDiagram) dRepresentation; ComputedStyleDescriptionRegistry computedStyleDescriptionRegistry = new DDiagramInternalQuery(dDiagram).getComputedStyleDescriptionRegistry(false); assertNotNull(computedStyleDescriptionRegistry); assertEquals("Computed StyleDescriptiosshould have been shared among styles within the DDiagram", 3, computedStyleDescriptionRegistry.getComputedStyleDescriptions().size()); assertEquals("As the maps of ComputedStyleDescriptionRegistry are no more used, it should remains only the 3 computed StyleDescriptions", 3, computedStyleDescriptionRegistry.eContents().size()); XMLResource airdResource = (XMLResource) session.getSessionResource(); assertEquals("As the migration has done its job, the map of unknown data should be empty", 0, airdResource.getEObjectToExtensionMap().size()); }
Source:
public Response listRestPathsAsHtml(@Context Dispatcher dispatcher) { List<RESTPathDiscovery.Path> discovered = RESTPathDiscovery.discover((ResourceMethodRegistry) dispatcher.getRegistry()); StringBuilder sb = new StringBuilder(); sb.append("<h1>Hawkular Inventory - REST API overview</h1>") .append("This is a generated list of available endpoints. Click here for detailed documentation."); discovered.forEach(r -> { sb.append("<h2>").append(r.getPath()).append("</h2><ul>"); r.getMethods().forEach(rm -> { sb.append("<li>").append(rm.getVerb()).append(" "); if (rm.getConsuming() != null) { sb.append("consumes <i>").append(rm.getConsuming()).append("</i> "); } if (rm.getProducing() != null) { sb.append("produces <i>").append(rm.getProducing()).append("</i> "); } sb.append("</li>"); }); sb.append("</ul>"); }); return Response.ok(sb.toString()).build(); }

Target:
public Response listRestPathsAsHtml(@Context Dispatcher dispatcher) { List<RESTPathDiscovery.Path> discovered = RESTPathDiscovery.discover((ResourceMethodRegistry) dispatcher.getRegistry()); StringBuilder sb = new StringBuilder(); sb.append("<h1>Hawkular Inventory - REST API overview</h1>") .append("This is a generated list of available endpoints. Check the documentation for more details."); discovered.forEach(r -> { sb.append("<h2>").append(r.getPath()).append("</h2><ul>"); r.getMethods().forEach(rm -> { sb.append("<li>").append(rm.getVerb()).append(" "); if (rm.getConsuming() != null) { sb.append("consumes <i>").append(rm.getConsuming()).append("</i> "); } if (rm.getProducing() != null) { sb.append("produces <i>").append(rm.getProducing()).append("</i> "); } sb.append("</li>"); }); sb.append("</ul>"); }); return Response.ok(sb.toString()).build(); }
Source:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { fLineDiffer.connect(fDocument); fLineDiffer.suspend(); fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); assertFalse(fLineDiffer.isSuspended()); assertFalse(fLineDiffer.isSynchronized()); }

Target:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { fLineDiffer.connect(fDocument); fLineDiffer.suspend(); fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); assertTrue(fLineDiffer.isSuspended()); }
Source:
public @NonNull TmfModelResponse<@NonNull List<@NonNull ITimeGraphRowModel>> fetchRowModel(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { IGraphWorker graphWorker = getCurrent(); HorizontalLinksVisitor visitor = fHorizontalVisitorCache.getIfPresent(graphWorker); if (visitor == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } List<@NonNull ITimeGraphRowModel> rowModels = new ArrayList<>(); for (Long id : filter.getSelectedItems()) { Collection<ITimeGraphState> states = visitor.fStates.asMap().get(id); if (states != null) { List<ITimeGraphState> filteredStates = new ArrayList<>(); for (ITimeGraphState state : states) { if (overlaps(state.getStartTime(), state.getDuration(), filter.getTimesRequested())) { filteredStates.add(state); } } rowModels.add(new TimeGraphRowModel(id, filteredStates)); } } return new TmfModelResponse<>(rowModels, Status.COMPLETED, CommonStatusMessage.COMPLETED); }

Target:
public @NonNull TmfModelResponse<@NonNull List<@NonNull ITimeGraphRowModel>> fetchRowModel(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { IGraphWorker graphWorker = getCurrent(); Pair<HorizontalLinksVisitor, VerticalLinksVisitor> visitors = fHorizontalVisitorCache.getIfPresent(graphWorker); if (visitors == null) { return new TmfModelResponse<>(null, Status.COMPLETED, CommonStatusMessage.COMPLETED); } HorizontalLinksVisitor visitor = visitors.getFirst(); List<@NonNull ITimeGraphRowModel> rowModels = new ArrayList<>(); for (Long id : filter.getSelectedItems()) { Collection<ITimeGraphState> states = visitor.fStates.asMap().get(id); if (states != null) { List<ITimeGraphState> filteredStates = new ArrayList<>(); for (ITimeGraphState state : states) { if (overlaps(state.getStartTime(), state.getDuration(), filter.getTimesRequested())) { filteredStates.add(state); } } rowModels.add(new TimeGraphRowModel(id, filteredStates)); } } return new TmfModelResponse<>(rowModels, Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
private ConcurrentHashMap<String, PartitionId> mapPartitionNameToPartition(ClusterMap clusterMap, DataNodeId localNode) { List<? extends ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); return localReplicas.stream() .collect(Collectors.toMap(replicaId -> replicaId.getPartitionId().toPathString(), ReplicaId::getPartitionId, (e1, e2) -> e2, ConcurrentHashMap::new)); }

Target:
private ConcurrentHashMap<String, PartitionId> mapPartitionNameToPartition(ClusterMap clusterMap, DataNodeId localNode) { return clusterMap.getReplicaIds(localNode) .stream() .collect(Collectors.toMap(replicaId -> replicaId.getPartitionId().toPathString(), ReplicaId::getPartitionId, (e1, e2) -> e2, ConcurrentHashMap::new)); }
Source:
public Long getUpdatedAt() { return updatedAt; }

Target:
public long getUpdatedAt() { return updatedAt; }
Source:
private void createSettings(String propertyKey) { if (System.getProperty(propertyKey) != null) { String filename = System.getProperty(propertyKey); GenericParser<Configuration> parser = new GenericParser<>(Configuration.class); Configuration configuration = Try.apply(() -> parser.parse(new File(filename))).get(); withDatabase(db -> { db.save(configuration); }); } }

Target:
private synchronized void createSettings(String propertyKey) { GenericParser<Configuration> parser = new GenericParser<>(Configuration.class); String filename = System.getProperty(propertyKey); Configuration configuration; if (filename != null) { File file = new File(filename); configuration = Try.apply(() -> parser.parse(file)).get(); } else { InputStream is = getClass().getClassLoader().getResourceAsStream("etc/conf/strongbox.xml"); configuration = Try.apply(() -> parser.parse(is)).get(); } updateConfiguration(configuration); }
Source:
private String buildJsArray(List<ContentType> types) { String typeStr = String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); return typeStr ; }

Target:
private String buildJsArray(List<ContentType> types) { return String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); }
Source:
private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }

Target:
private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }
Source:
public void testThrift() throws Exception { TestReceiver tracer = new TestReceiver(); org.apache.htrace.Trace.addReceiver(tracer); ServerSocket socket = new ServerSocket(0); TServerSocket transport = new TServerSocket(socket); transport.listen(); TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport); args.processor(new Processor<Iface>(TraceWrap.service(new Service()))); final TServer tserver = new TThreadPoolServer(args); Thread t = new Thread(() -> tserver.serve()); t.start(); TTransport clientTransport = new TSocket(new Socket("localhost", socket.getLocalPort())); TestService.Iface client = new TestService.Client(new TBinaryProtocol(clientTransport), new TBinaryProtocol(clientTransport)); client = TraceWrap.client(client); assertFalse(client.checkTrace(null, "test")); Span start = Trace.on("start"); assertTrue(client.checkTrace(null, "my test")); start.stop(); assertNotNull(tracer.traces.get(start.traceId())); String traces[] = {"my test", "checkTrace", "client:checkTrace", "start"}; assertEquals(tracer.traces.get(start.traceId()).size(), traces.length); for (int i = 0; i < traces.length; i++) assertEquals(traces[i], tracer.traces.get(start.traceId()).get(i).description); tserver.stop(); t.join(100); }

Target:
public void testThrift() throws Exception { TestReceiver tracer = new TestReceiver(); org.apache.htrace.Trace.addReceiver(tracer); ServerSocket socket = new ServerSocket(0); TServerSocket transport = new TServerSocket(socket); transport.listen(); TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport); args.processor(new Processor<Iface>(TraceWrap.service(new Service()))); final TServer tserver = new TThreadPoolServer(args); Thread t = new Thread(tserver::serve); t.start(); TTransport clientTransport = new TSocket(new Socket("localhost", socket.getLocalPort())); TestService.Iface client = new TestService.Client(new TBinaryProtocol(clientTransport), new TBinaryProtocol(clientTransport)); client = TraceWrap.client(client); assertFalse(client.checkTrace(null, "test")); Span start = Trace.on("start"); assertTrue(client.checkTrace(null, "my test")); start.stop(); assertNotNull(tracer.traces.get(start.traceId())); String traces[] = {"my test", "checkTrace", "client:checkTrace", "start"}; assertEquals(tracer.traces.get(start.traceId()).size(), traces.length); for (int i = 0; i < traces.length; i++) assertEquals(traces[i], tracer.traces.get(start.traceId()).get(i).description); tserver.stop(); t.join(100); }
Source:
public Network update(Network incoming) { performAction(VdcActionType.AttachNetworkToVdsGroup, new AttachNetworkToVdsGroupParameter(cluster.getVDSGroup(), map(incoming, map(get())))); return get(); }

Target:
public Network update(Network incoming) { org.ovirt.engine.core.common.businessentities.Network network = map(incoming, map(get())); network.getCluster().setnetwork_id(network.getId()); network.getCluster().setcluster_id(cluster.getVDSGroup().getId()); performAction(VdcActionType.UpdateNetworkOnCluster, new NetworkClusterAttachmentParameters(network.getCluster())); return get(); }
Source:
public TransactionToken stage(AccessToken creds, String env) throws TException { checkAccess(creds, null); TransactionToken token; AtomicInteger counter = transactionCounters.get(creds).getValue(); if(counter == null){ counter = new AtomicInteger(); token = new TransactionToken(creds, Time.now()); Transaction transaction = getEngine(env).startTransaction(); transactions.put(token, transaction); transactionCounters.put(creds, new KeyValue<>(token, counter)); Logger.info("Started Transaction {}", transaction); } else { token = transactionCounters.get(creds).getKey(); } counter.incrementAndGet(); return token; }

Target:
public TransactionToken stage(AccessToken creds, String env) throws TException { checkAccess(creds, null); TransactionToken token; KeyValue<TransactionToken, AtomicInteger> transactionCounterPair = transactionCounters.get(creds); AtomicInteger counter = (transactionCounterPair != null) ? transactionCounterPair.getValue() : null; if(counter == null) { counter = new AtomicInteger(); token = new TransactionToken(creds, Time.now()); Transaction transaction = getEngine(env).startTransaction(); transactions.put(token, transaction); transactionCounters.put(creds, new KeyValue<TransactionToken, AtomicInteger>(token, counter)); Logger.info("Started Transaction {}", transaction); } else { token = transactionCounterPair.getKey(); } counter.incrementAndGet(); return token; }
Source:
public boolean matches(Event properties) { LOGGER.debug("ENTERING: matches"); boolean status = false; Map<String, Object> contextualMap = (Map<String, Object>) properties .getProperty(PubSubConstants.HEADER_CONTEXTUAL_KEY); String operation = (String) properties.getProperty(PubSubConstants.HEADER_OPERATION_KEY); LOGGER.debug("operation = {}", operation); if (contextualMap != null) { String metadata = (String) contextualMap.get("METADATA"); if (PubSubConstants.DELETE.equals(operation) && PubSubConstants.METADATA_DELETED.equals(metadata)) { LOGGER.debug("Detected a DELETE operation where metadata is just the word 'deleted', so send event on to subscriber"); LOGGER.debug("EXITING: matches"); return true; } } Object inputContentType = properties.getProperty(PubSubConstants.HEADER_CONTENT_TYPE_KEY); LOGGER.debug("input obtained from event properties: ", inputContentType); if (inputContentType != null) { ContentTypeEvaluationCriteriaImpl ctec = new ContentTypeEvaluationCriteriaImpl(this, inputContentType.toString()); status = ContentTypeEvaluator.evaluate(ctec); } LOGGER.debug("EXITING: inputContentType"); return status; }

Target:
public boolean matches(Event properties) { LOGGER.debug("ENTERING: matches"); boolean status = false; Map<String, Object> contextualMap = (Map<String, Object>) properties .getProperty(PubSubConstants.HEADER_CONTEXTUAL_KEY); String operation = (String) properties.getProperty(PubSubConstants.HEADER_OPERATION_KEY); LOGGER.debug("operation = {}", operation); if (contextualMap != null) { String metadata = (String) contextualMap.get("METADATA"); if (PubSubConstants.DELETE.equals(operation) && PubSubConstants.METADATA_DELETED.equals(metadata)) { LOGGER.debug("Detected a DELETE operation where metadata is just the word 'deleted', so send event on to subscriber"); LOGGER.debug("EXITING: matches"); return true; } } Object inputContentType = properties.getProperty(PubSubConstants.HEADER_CONTENT_TYPE_KEY); LOGGER.debug("input obtained from event properties: ", inputContentType); if (inputContentType != null) { ContentTypeEvaluationCriteriaImpl ctec = new ContentTypeEvaluationCriteriaImpl(this, inputContentType.toString()); status = ContentTypeEvaluator.evaluate(ctec); } LOGGER.debug("EXITING: matches"); return status; }
Source:
public void run(IAction action) { if (fileRevision == null) return; final Repository repository = fileRevision.getRepository(); ITypedElement selectedFileRevision; selectedFileRevision = CompareUtils.getFileRevisionTypedElement(fileRevision.getPath(), fileRevision.getRevCommit(), repository); ITypedElement headFileRevision; try { Ref head = repository.getRef(Constants.HEAD); RevWalk rw = new RevWalk(repository); RevCommit commit = rw.parseCommit(head.getObjectId()); headFileRevision = CompareUtils.getFileRevisionTypedElement(fileRevision.getPath(), commit, repository); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); return; } final GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( selectedFileRevision, headFileRevision, null); CompareUI.openCompareEditor(in); return; }

Target:
public void run(IAction action) { if (fileRevision == null) return; Repository repository = fileRevision.getRepository(); ITypedElement selectedFileRevision = CompareUtils.getFileRevisionTypedElement( fileRevision.getPath(), fileRevision.getRevCommit(), repository); try { Ref head = repository.getRef(Constants.HEAD); RevCommit commit = new RevWalk(repository).parseCommit(head.getObjectId()); ITypedElement headFileRevision = CompareUtils.getFileRevisionTypedElement( fileRevision.getPath(), commit, repository); GitCompareFileRevisionEditorInput in = new GitCompareFileRevisionEditorInput( selectedFileRevision, headFileRevision, null); CompareUI.openCompareEditor(in); } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } }
Source:
private static boolean isAnnotatedAsValueBasedClass(@SlashedClassName String className) { try { ClassDescriptor classDescriptor = DescriptorFactory.createClassDescriptor(className); XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDescriptor); ClassDescriptor annotationDescriptor = DescriptorFactory.createClassDescriptor(ValueBased.class); AnnotationValue annotation = xClass.getAnnotation(annotationDescriptor); return annotation != null; } catch (CheckedAnalysisException ex) { return false; } }

Target:
private static boolean isAnnotatedAsValueBasedClass(@SlashedClassName String className) { try { ClassDescriptor classDescriptor = DescriptorFactory.createClassDescriptor(className); XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDescriptor); AnnotationValue annotation = xClass.getAnnotation(VALUE_BASED_ANNOTATION_DESCRIPTOR); return annotation != null; } catch (CheckedAnalysisException ex) { String message = String.format("Accessing the global cache for the analysis of '%s' failed.", className); AnalysisContext.logError(message, ex); return false; } }
Source:
private MessageType readMessage(String documentation) { String oprefix = prefix; String name = readName(); prefix = prefix + name + "."; List<MessageType.Field> fields = new ArrayList<MessageType.Field>(); List<Type> nestedTypes = new ArrayList<Type>(); List<Extensions> extensions = new ArrayList<Extensions>(); if (readChar() != '{') throw unexpected("expected '{'"); while (true) { String nestedDocumentation = readDocumentation(); if (peekChar() == '}') { pos++; break; } Object declared = readDeclaration(nestedDocumentation, Context.MESSAGE); if (declared instanceof MessageType.Field) { fields.add((MessageType.Field) declared); } else if (declared instanceof Type) { nestedTypes.add((Type) declared); } else if (declared instanceof Extensions) { extensions.add((Extensions) declared); } } prefix = oprefix; return new MessageType(name, prefix + name, documentation, fields, nestedTypes, extensions); }

Target:
private MessageType readMessage(String documentation) { String previousPrefix = prefix; String name = readName(); prefix = prefix + name + "."; List<MessageType.Field> fields = new ArrayList<MessageType.Field>(); List<Type> nestedTypes = new ArrayList<Type>(); List<Extensions> extensions = new ArrayList<Extensions>(); if (readChar() != '{') throw unexpected("expected '{'"); while (true) { String nestedDocumentation = readDocumentation(); if (peekChar() == '}') { pos++; break; } Object declared = readDeclaration(nestedDocumentation, Context.MESSAGE); if (declared instanceof MessageType.Field) { fields.add((MessageType.Field) declared); } else if (declared instanceof Type) { nestedTypes.add((Type) declared); } else if (declared instanceof Extensions) { extensions.add((Extensions) declared); } } prefix = previousPrefix; return new MessageType(name, prefix + name, documentation, fields, nestedTypes, extensions); }
Source:
protected void doRemove(String workspaceId) { final SignatureKeyPairImpl keyPair = managerProvider.get().find(SignatureKeyPairImpl.class, workspaceId); if (keyPair != null) { final EntityManager manager = managerProvider.get(); manager.remove(keyPair); manager.flush(); } }

Target:
protected void doRemove(String workspaceId) { final EntityManager manager = managerProvider.get(); final SignatureKeyPairImpl keyPair = manager.find(SignatureKeyPairImpl.class, workspaceId); if (keyPair != null) { manager.remove(keyPair); manager.flush(); } }
Source:
public void completed(final Exchange exchange) { if (exchange.getOrigin() == Origin.LOCAL) { Request originRequest = exchange.getCurrentRequest(); if (!originRequest.hasMID()) { } else { KeyMID idByMID = KeyMID.fromOutboundMessage(originRequest); exchangeStore.remove(idByMID, exchange); } KeyToken idByToken = KeyToken.fromOutboundMessage(originRequest); exchangeStore.remove(idByToken, exchange); Request request = exchange.getRequest(); if (request != originRequest && null != request && null != request.getToken() && !Arrays.equals(request.getToken(), originRequest.getToken())) { originRequest = request; idByToken = KeyToken.fromOutboundMessage(originRequest); exchangeStore.remove(idByToken, exchange); } if (!originRequest.getOptions().hasObserve()) { exchangeStore.releaseToken(idByToken); } LOGGER.log(Level.FINER, "Exchange [{0}, origin: {1}] completed", new Object[]{idByToken, exchange.getOrigin()}); } else { Response response = exchange.getCurrentResponse(); if (response != null && response.getType() != Type.ACK) { KeyMID midKey = KeyMID.fromOutboundMessage(response); exchangeStore.remove(midKey, exchange); LOGGER.log(Level.FINER, "Exchange [{0}, {1}] completed", new Object[]{midKey, exchange.getOrigin()}); } ObserveRelation relation = exchange.getRelation(); if (relation != null) { removeNotificationsOf(relation, exchange); } } }

Target:
public void completed(final Exchange exchange) { if (exchange.getOrigin() == Origin.LOCAL) { Request originRequest = exchange.getCurrentRequest(); if (!originRequest.hasMID()) { } else { KeyMID idByMID = KeyMID.fromOutboundMessage(originRequest); exchangeStore.remove(idByMID, exchange); } KeyToken idByToken = KeyToken.fromOutboundMessage(originRequest); exchangeStore.remove(idByToken, exchange); if (exchange.isComplete()) { Request request = exchange.getRequest(); if (request != originRequest && null != request && null != request.getToken() && !Arrays.equals(request.getToken(), originRequest.getToken())) { originRequest = request; idByToken = KeyToken.fromOutboundMessage(originRequest); exchangeStore.remove(idByToken, exchange); } } if (!originRequest.getOptions().hasObserve()) { exchangeStore.releaseToken(idByToken); } LOGGER.log(Level.FINER, "Exchange [{0}, origin: {1}] completed", new Object[]{idByToken, exchange.getOrigin()}); } else { Response response = exchange.getCurrentResponse(); if (response != null && response.getType() != Type.ACK) { KeyMID midKey = KeyMID.fromOutboundMessage(response); exchangeStore.remove(midKey, exchange); LOGGER.log(Level.FINER, "Exchange [{0}, {1}] completed", new Object[]{midKey, exchange.getOrigin()}); } ObserveRelation relation = exchange.getRelation(); if (relation != null) { removeNotificationsOf(relation, exchange); } } }
Source:
Object extractValue(DocumentExtractor extractor, int docIndex) { Object[] projection; try { projection = extractor.extract(docIndex).getProjection(); } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } if (projection == null) { Object key = extractKey(extractor, docIndex); return cache.get(fromStorage(key)); } return projection; }

Target:
Object extractValue(DocumentExtractor extractor, int docIndex) { Object[] projection; try { projection = extractor.extract(docIndex).getProjection(); } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } if (projection == null) { Object key = extractKey(extractor, docIndex); return cache.get(key); } return projection; }
Source:
int getMessageInfoListSize() { if (messageInfoList == null) { return INT_FIELD_SIZE_IN_BYTES; } int size = 0; size += INT_FIELD_SIZE_IN_BYTES; for (MessageInfo messageInfo : messageInfoList) { size += messageInfo.getStoreKey().sizeInBytes(); size += LONG_FIELD_SIZE_IN_BYTES; size += LONG_FIELD_SIZE_IN_BYTES; size += 1; if (version == MessageInfoListVersion_V2 || version == MessageInfoListVersion_V3) { size += 1; if (messageInfo.getCrc() != null) { size += LONG_FIELD_SIZE_IN_BYTES; } } if (version == MessageInfoListVersion_V3) { size += SHORT_FIELD_SIZE_IN_BYTES; size += SHORT_FIELD_SIZE_IN_BYTES; size += LONG_FIELD_SIZE_IN_BYTES; } } return size; }

Target:
int getMessageInfoListSize() { if (messageInfoList == null) { return Integer.BYTES; } int size = Integer.BYTES; for (MessageInfo messageInfo : messageInfoList) { size += messageInfo.getStoreKey().sizeInBytes(); size += Long.BYTES; size += Long.BYTES; size += 1; switch (version) { case VERSION_1: break; case VERSION_2: size += 1; if (messageInfo.getCrc() != null) { size += Long.BYTES; } break; case VERSION_3: size += 1; if (messageInfo.getCrc() != null) { size += Long.BYTES; } size += Short.BYTES; size += Short.BYTES; size += Long.BYTES; break; default: throw new IllegalArgumentException("Unknown version in MessageInfoList " + version); } } return size; }
Source:
public Matrix rotate(Factory factory) { ensureFactoryIsNotNull(factory); double[][] rotatedMatrix = new double[this.columns()][this.rows()]; for (int i = 0; i < this.rows(); i++) { for (int j = 0; j < this.columns(); j++) { rotatedMatrix[j][this.rows()-1-i] = this.get(i, j); } } return factory.createMatrix(rotatedMatrix); }

Target:
public Matrix rotate(Factory factory) { ensureFactoryIsNotNull(factory); Matrix result = factory().createMatrix(columns, rows); for (int i = 0; i < rows(); i++) { for (int j = 0; j < columns(); j++) { result.set(j, rows - 1 - i, get(i, j)); } } return result; }
Source:
public BAMIndexer(final File output, final SAMFileHeader fileHeader) { if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) { throw new SAMException("BAM file be coordinate-sorted for indexing."); } numReferences = fileHeader.getSequenceDictionary().size(); indexBuilder = new BAMIndexBuilder(fileHeader.getSequenceDictionary()); outputWriter = new BinaryBAMIndexWriter(numReferences, output); }

Target:
public BAMIndexer(final File output, final SAMFileHeader fileHeader) { this(fileHeader, numRefs -> new BinaryBAMIndexWriter(numRefs, output)); }
Source:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.getChange(); final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }

Target:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.change(dbProvider); final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (p.getCategoryId().get().equals(labelType.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }
Source:
public void testGetSensorData() { DateTime date = DateTimeUtil.ymdStringToDateTime("2015-09-01"); DateTime startTime = date.withHourOfDay(18); DateTime endTime = startTime.plusHours(16); AllSensorSampleList senseData = OnlineHmmTest.getTypicalDayOfSense(startTime,endTime,0); ImmutableList<TrackerMotion> pillData = OnlineHmmTest.getTypicalDayOfPill(startTime.minusHours(4),endTime.plusHours(4),0); final ImmutableList<TimelineFeedback> emptyFeedback = ImmutableList.copyOf(Lists.<TimelineFeedback>newArrayList()); final OneDaysSensorData oneDaysSensorData = new OneDaysSensorData(senseData,pillData,pillData,emptyFeedback,pillData,pillData,date,startTime,endTime,endTime,0); try { final double[][] neuralNetInput = getSensorData(oneDaysSensorData); TestCase.assertEquals(SensorIndices.MAX_NUM_INDICES,neuralNetInput.length); TestCase.assertEquals(961,neuralNetInput[0].length); } catch (Exception e) { TestCase.assertTrue(false); } }

Target:
public void testGetSensorData() throws Exception { DateTime date = DateTimeUtil.ymdStringToDateTime("2015-09-01"); DateTime startTime = date.withHourOfDay(18); DateTime endTime = startTime.plusHours(16); AllSensorSampleList senseData = OnlineHmmTest.getTypicalDayOfSense(startTime,endTime,0); ImmutableList<TrackerMotion> pillData = OnlineHmmTest.getTypicalDayOfPill(startTime.minusHours(4),endTime.plusHours(4),0); final ImmutableList<TimelineFeedback> emptyFeedback = ImmutableList.copyOf(Lists.<TimelineFeedback>newArrayList()); final OneDaysSensorData oneDaysSensorData = new OneDaysSensorData(senseData,pillData,pillData,emptyFeedback,pillData,pillData,date,startTime,endTime,endTime,0); final double[][] neuralNetInput = getSensorData(oneDaysSensorData); TestCase.assertEquals(SensorIndices.MAX_NUM_INDICES,neuralNetInput.length); TestCase.assertEquals(961,neuralNetInput[0].length); }