auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>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); <START> 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 { } <END> }</code><technical_language>is this try finally for</technical_language>

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:
<code>public void should_exclude_ignored_instructions_from_computation_of_first_and_last_lines() { InsnNode i1 = addInsn(1, false); addInsn(2, false); <START> InsnNode i2 = addInsn(3, false); <END> MethodCoverageCalculator c = new MethodCoverageCalculator(instructions); c.ignore(i1, i1); c.ignore(i2, i2); c.calculate(coverage); assertEquals(2, coverage.getFirstLine()); assertEquals(2, coverage.getLastLine()); }</code><technical_language>Rename this i3 for consistency</technical_language>

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:
<code>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) { <START> logger.error("Failed response: {}", HttpUtils.buildHttpErrorMessage(connection)); <END> return null; } else { return HttpUtils.readBody(connection); } } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }</code><technical_language>idem error log: is a good idea log everytime a user authenticate REST service</technical_language>

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:
<code>public void runInPodWithRetention() throws Exception { logs.capture(1000); r.assertBuildStatusSuccess(r.waitForCompletion(b)); <START> logs.getMessages().stream().anyMatch(msg -> msg.contains("was not deleted due to retention policy Always")); <END> assertTrue(deletePods(cloud.connect(), getLabels(this, name), false)); }</code><technical_language>Related this patch</technical_language>

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

Target:
public String getCategoryID() { return "org.eclipse.papyrus.sysml14.diagram.parametric"; }
Source:
<code>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(); <START> for (GeometrySerializationType t : GeometrySerializationType.values()) { <END> String[] r = types.get(t); if (r == null) { fail("Missing test for type: " + t); } assertFunction(r[0], VARCHAR, r[1]); } }</code><technical_language>@jwass original version of test more readable standardName getter in GeometryType enum this is longer necessary</technical_language>

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:
<code><START> public void testFailedReplicaAssigment() throws InterruptedException, IOException { <END> 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()); }</code><technical_language>main purpose of change is allow Master complete initialisation in case of meta replica failures, this test assert _HMaster.finishActiveMasterInitialization_ completes properly induced replicas assignment failures? I asserting replicas assignment fails, is want safeguard from</technical_language>

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:
<code>public int getDay(Type type, Block block, int position) { if (type.equals(DATE)) { return toIntExact(DATE.getLong(block, position)); } if (type.equals(TIMESTAMP)) { <START> long millis = block.getLong(position, 0); <END> long local = timeZone.convertUTCToLocal(millis); long days = MILLISECONDS.toDays(local); return toIntExact(days); } throw new IllegalArgumentException("Wrong type for temporal column: " + type); }</code><technical_language>This is wrong. read blocks directly. Type access block, types data representation a block</technical_language>

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:
<code>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.", <START> airdResource.getEObjectToExtensionMap().size() == 0); <END> }</code><technical_language>isEmpty</technical_language>

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:
<code>public Response listRestPathsAsHtml(@Context Dispatcher dispatcher) { List<RESTPathDiscovery.Path> discovered = RESTPathDiscovery.discover((ResourceMethodRegistry) dispatcher.getRegistry()); StringBuilder sb = new StringBuilder(); <START> sb.append("<h1>Hawkular Inventory - REST API overview</h1>") <END> .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(); }</code><technical_language>Yes, I is in RESTEasy engine. get rid a single endpoint used, adjusting output manually checking accept header. Some extra code get rid of warnings in log, I think</technical_language>

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:
<code>public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { fLineDiffer.connect(fDocument); fLineDiffer.suspend(); fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); <START> assertFalse(fLineDiffer.isSuspended()); <END> assertFalse(fLineDiffer.isSynchronized()); }</code><technical_language>"The differ stays suspended" of testing here. assertTrue</technical_language>

Target:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { fLineDiffer.connect(fDocument); fLineDiffer.suspend(); fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); assertTrue(fLineDiffer.isSuspended()); }
Source:
<code>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<>(); <START> for (ITimeGraphState state : states) { if (overlaps(state.getStartTime(), state.getDuration(), filter.getTimesRequested())) { filteredStates.add(state); } } <END> rowModels.add(new TimeGraphRowModel(id, filteredStates)); } } return new TmfModelResponse<>(rowModels, Status.COMPLETED, CommonStatusMessage.COMPLETED); }</code><technical_language>surprised a lambda... :p</technical_language>

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:
<code>private ConcurrentHashMap<String, PartitionId> mapPartitionNameToPartition(ClusterMap clusterMap, DataNodeId localNode) { <START> List<? extends ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); <END> return localReplicas.stream() .collect(Collectors.toMap(replicaId -> replicaId.getPartitionId().toPathString(), ReplicaId::getPartitionId, (e1, e2) -> e2, ConcurrentHashMap::new)); }</code><technical_language>fold this line next one</technical_language>

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:
<code><START> public Long getUpdatedAt() { <END> return updatedAt; }</code><technical_language>non-nullable primitive long</technical_language>

Target:
public long getUpdatedAt() { return updatedAt; }
Source:
<code>private void createSettings(String propertyKey) { <START> if (System.getProperty(propertyKey) != null) <END> { 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); }); } }</code><technical_language>this method does, mind elaborating...</technical_language>

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:
<code>private String buildJsArray(List<ContentType> types) { <START> String typeStr = String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); <END> return typeStr ; }</code><technical_language>Return String.join creating new String</technical_language>

Target:
private String buildJsArray(List<ContentType> types) { return String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); }
Source:
<code>private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = <START> getApplicationContext().openFileOutput(fileName, <END> Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }</code><technical_language>remove this... openFileInput(fileName) sufficient Application context is anti-pattern</technical_language>

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:
<code>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); <START> Thread t = new Thread(() -> tserver.serve()); <END> 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); }</code><technical_language>do tserver::serve</technical_language>

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:
<code>public Network update(Network incoming) { performAction(VdcActionType.AttachNetworkToVdsGroup, <START> new AttachNetworkToVdsGroupParameter(cluster.getVDSGroup(), map(incoming, map(get())))); <END> return get(); }</code><technical_language>suggested patch is RESTful [1] logically invalid [2], 1. attach of network cluster performed POST /api/clusters/xxx/networks (done BackendClusterNetworksResource) 2. perform another VdcActionType.AttachNetworkToVdsGroup attached BackendClusterNetworkResource (otherwise this resource exist) 3. performing "updating of cluster's network assignmen", UPDATE of network resource (in cluster context), if want assign this network another cluster well, done this cluster /networks collection => POST /api/clusters/yyy/networks</technical_language>

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:
<code>public TransactionToken stage(AccessToken creds, String env) throws TException { checkAccess(creds, null); TransactionToken token; <START> AtomicInteger counter = transactionCounters.get(creds).getValue(); <END> 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; }</code><technical_language>switched mapping a KeyValue, check KeyValue is null call getValue()</technical_language>

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:
<code>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); <START> LOGGER.debug("input obtained from event properties: ", inputContentType); <END> if (inputContentType != null) { ContentTypeEvaluationCriteriaImpl ctec = new ContentTypeEvaluationCriteriaImpl(this, inputContentType.toString()); status = ContentTypeEvaluator.evaluate(ctec); } LOGGER.debug("EXITING: inputContentType"); return status; }</code><technical_language>Interesting, I 'ToStringBuilder' class before</technical_language>

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:
<code>public void run(IAction action) { if (fileRevision == null) return; <START> final Repository repository = fileRevision.getRepository(); <END> 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; }</code><technical_language>Inconsistent of 'final' keyword method</technical_language>

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:
<code>private static boolean isAnnotatedAsValueBasedClass(@SlashedClassName String className) { try { ClassDescriptor classDescriptor = DescriptorFactory.createClassDescriptor(className); XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classDescriptor); <START> ClassDescriptor annotationDescriptor = DescriptorFactory.createClassDescriptor(ValueBased.class); <END> AnnotationValue annotation = xClass.getAnnotation(annotationDescriptor); return annotation != null; } catch (CheckedAnalysisException ex) { return false; } }</code><technical_language>ClassDescriptor annotationDescriptor = DescriptorFactory.createClassDescriptor(ValueBased.class); stored in static field for performance</technical_language>

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:
<code>private MessageType readMessage(String documentation) { <START> String oprefix = prefix; <END> 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); }</code><technical_language>oprefix --> oldPrefix previousPrefix something, for clarity</technical_language>

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:
<code>protected void doRemove(String workspaceId) { final SignatureKeyPairImpl keyPair = <START> managerProvider.get().find(SignatureKeyPairImpl.class, workspaceId); <END> if (keyPair != null) { final EntityManager manager = managerProvider.get(); manager.remove(keyPair); manager.flush(); } }</code><technical_language>store entity manager local variable get</technical_language>

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:
<code>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); <START> exchangeStore.remove(idByToken, exchange); <END> } 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); } } }</code><technical_language>do</technical_language>

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:
<code>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); <START> return cache.get(fromStorage(key)); <END> } return projection; }</code><technical_language>too, if cache injected in components request media type == storage media type, conversion necessary. Edit: convert request media type, I conversion explicit instead of converting key forth</technical_language>

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:
<code>int getMessageInfoListSize() { if (messageInfoList == null) { <START> return INT_FIELD_SIZE_IN_BYTES; <END> } 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; }</code><technical_language>number classes in java 1.8 BYTES size constants (like Integer.BYTES). consider here</technical_language>

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:
<code>public Matrix rotate(Factory factory) { ensureFactoryIsNotNull(factory); <START> double[][] rotatedMatrix = new double[this.columns()][this.rows()]; <END> 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); }</code><technical_language>create a matrix factory. alow safe memory do perform additional conversion. So, create a new matrix java Matrix result = factory.createMatrix(colums, rows);</technical_language>

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:
<code>public BAMIndexer(final File output, final SAMFileHeader fileHeader) { if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) { <START> throw new SAMException("BAM file be coordinate-sorted for indexing."); <END> } numReferences = fileHeader.getSequenceDictionary().size(); indexBuilder = new BAMIndexBuilder(fileHeader.getSequenceDictionary()); outputWriter = new BinaryBAMIndexWriter(numReferences, output); }</code><technical_language>Lost a word here, BAM file **must** be. include sort order is in error message</technical_language>

Target:
public BAMIndexer(final File output, final SAMFileHeader fileHeader) { this(fileHeader, numRefs -> new BinaryBAMIndexWriter(numRefs, output)); }
Source:
<code>public boolean match(final ChangeData object) throws OrmException { <START> final Change c = object.getChange(); <END> 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; }</code><technical_language>This NPE. depends ChangeData constructed, rely in a predicate. code deleted, object.change(dbProvider)... is get change</technical_language>

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:
<code>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); } <START> catch (Exception e) { <END> TestCase.assertTrue(false); } }</code><technical_language>if exception is thrown expected, test fail. need catch it</technical_language>

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); }