auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<MetricEntity, MetricSummaryValueEntity> getMetricSummary(Collection<MetricEntity> metrics) { Set<MetricNameDto> metricNameDtoList = new HashSet<MetricNameDto>(); Map<MetricNameDto,MetricEntity> matchMap = new HashMap<MetricNameDto, MetricEntity>(); for (MetricEntity metric : metrics) { if (metric.isSummaryAvailable()) { metricNameDtoList.add(metric.getMetricNameDto()); matchMap.put(metric.getMetricNameDto(),metric); } } List<MetricDto> metricDtoList = databaseService.getSummaryByMetricNameDto(metricNameDtoList); Map<MetricEntity,MetricSummaryValueEntity> result = new HashMap<MetricEntity,MetricSummaryValueEntity>(); for (MetricDto metricDto : metricDtoList) { MetricEntity metricEntity = matchMap.get(metricDto.getMetricName()); MetricSummaryValueEntity value = new MetricSummaryValueEntity(); value.setValue(Double.parseDouble(metricDto.getValues().iterator().next().getValue())); value.setDecision(metricDto.getValues().iterator().next().getDecision()); result.put(metricEntity,value); } return result; }

Target:
public Map<MetricEntity, MetricSummaryValueEntity> getMetricSummary(Collection<MetricEntity> metrics) { Set<MetricNameDto> metricNameDtoSet = new HashSet<MetricNameDto>(); Map<MetricNameDto,MetricEntity> matchMap = new HashMap<MetricNameDto, MetricEntity>(); for (MetricEntity metric : metrics) { if (metric.isSummaryAvailable()) { metricNameDtoSet.add(metric.getMetricNameDto()); matchMap.put(metric.getMetricNameDto(),metric); } } Collection<SummarySingleDto> metricDtoList = databaseService.getSummaryByMetricNameDto(metricNameDtoSet).values(); Map<MetricEntity,MetricSummaryValueEntity> result = new HashMap<MetricEntity,MetricSummaryValueEntity>(); for (SummarySingleDto metricDto : metricDtoList) { MetricEntity metricEntity = matchMap.get(metricDto.getMetricName()); MetricSummaryValueEntity value = new MetricSummaryValueEntity(); value.setValue(Double.parseDouble(metricDto.getValues().iterator().next().getValue())); value.setDecision(metricDto.getValues().iterator().next().getDecision()); result.put(metricEntity,value); } return result; }
Source:
private void setRawTargets(PlanContext context, Target[] targets, String[] referenceNames, Projection projection) throws PlanningException { LogicalPlan plan = context.plan; QueryBlock block = context.queryBlock; Target rawTargets = new Target[projection.getNamedExprs().length]; for (int i = 0; i < projection.getNamedExprs().length; i++) { NamedExpr namedExpr = projection.getNamedExprs()[i]; EvalNode evalNode = exprAnnotator.createEvalNode(plan, block, namedExpr.getExpr(), NameResolvingMode.SUBEXPRS_AND_RELS); rawTargets[i] = new Target(evalNode, referenceNames[i]); } block.setRawTargets(rawTargets); }

Target:
private void setRawTargets(PlanContext context, Target[] targets, String[] referenceNames, Projection projection) throws PlanningException { LogicalPlan plan = context.plan; QueryBlock block = context.queryBlock; Target rawTargets = new Target[projection.getNamedExprs().length]; for (int i = 0; i < projection.getNamedExprs().length; i++) { NamedExpr namedExpr = projection.getNamedExprs()[i]; EvalNode evalNode = exprAnnotator.createEvalNode(plan, block, namedExpr.getExpr(), NameResolvingMode.RELS_AND_SUBEXPRS); rawTargets[i] = new Target(evalNode, referenceNames[i]); } block.setRawTargets(rawTargets); }
Source:
public PrometheusMetricsTrackerFactory(CollectorRegistry registry) { if (globalCollector == null) { synchronized (PrometheusMetricsTrackerFactory.class) { if (globalCollector == null) { globalCollector = new HikariCPCollector(); } } } this.registry = registry; this.collector = globalCollector.register(registry); }

Target:
public PrometheusMetricsTrackerFactory(CollectorRegistry registry) { checkGlobalCollector(); this.registry = registry; this.collector = globalCollector.register(registry); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = getSelectedResources(event); repo = getRepository(true, event); fileListReturned = new HashSet<String>(); if (repo == null) return null; if (resources.length == 0) return null; CleanOperation op = new CleanOperation(resources); Set<String> fileList = op.dryRun(); ListSelectionDialog dialog = new ListSelectionDialog( getShell(event), fileList, new ArrayContentProvider(), new ItemLabelProvider(), UIText.CleanDialog_HeaderMessage ); dialog.setTitle(UIText.CleanDialog_TitleMessage); if (dialog.open() != IDialogConstants.OK_ID) return null; for (int i = 0; i < dialog.getResult().length; i++) { fileListReturned.add(dialog.getResult()[i].toString()); } JobUtil.scheduleUserJob(op.setPaths(fileListReturned), "Clean", JobFamilies.CLEAN); try { ResourcesPlugin.getWorkspace().getRoot().refreshLocal( IResource.DEPTH_INFINITE, null); } catch (CoreException e) { e.printStackTrace(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IResource[] resources = getSelectedResources(event); repo = getRepository(true, event); fileListReturned = new HashSet<String>(); if (repo == null) return null; if (resources.length == 0) return null; CleanOperation op = new CleanOperation(resources); Set<String> fileList = op.dryRun(); ListSelectionDialog dialog = new ListSelectionDialog( getShell(event), fileList, new ArrayContentProvider(), new ItemLabelProvider(), UIText.CleanDialog_HeaderMessage ); dialog.setTitle(UIText.CleanDialog_TitleMessage); if (dialog.open() != IDialogConstants.OK_ID) return null; for (int i = 0; i < dialog.getResult().length; i++) fileListReturned.add(dialog.getResult()[i].toString()); JobUtil.scheduleUserJob(op.setPaths(fileListReturned), "Clean", JobFamilies.CLEAN); try { ResourcesPlugin.getWorkspace().getRoot().refreshLocal( IResource.DEPTH_INFINITE, null); } catch (CoreException e) { Activator.getDefault().getLog().log( new org.eclipse.core.runtime.Status( IStatus.INFO, Activator.getPluginId(), IStatus.ERROR, e.getMessage(), e ) ); } return null; }
Source:
public List<Encounter> getEncountersModifiedOnOrAfter(@Nullable Date date) { return dao.getEncountersModifiedOnOrAfter(date); }

Target:
public List<Encounter> getEncountersModifiedOnOrAfter(@Nullable Date date) { return dao.getEncountersCreatedAtOrAfter(date); }
Source:
public void keepCurrentState(Item item) { scheduler.schedule(() -> { constructAndSendEvents(item, item.getState()); }, 200, TimeUnit.MILLISECONDS); }

Target:
public void keepCurrentState(Item item) { scheduler.schedule(() -> { constructAndSendEvents(item, item.getState()); }, REVERT_INTERVAL, TimeUnit.MILLISECONDS); }
Source:
public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) { return client.prepareSearchScroll(scrollId).setScroll(new TimeValue(scrollTime.toMillis())); }

Target:
public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) { return client.prepareSearchScroll(scrollId).setScroll(new TimeValue(scrollTimeout.toMillis())); }
Source:
public void setBackupBuffer(final StreamingStateEncoding<?> stateEncoding) { StreamingState state = null; if (stateEncoding instanceof KeepMinValueStateEncoding) { state = new KeepMinValue(((KeepMinValueStateEncoding) stateEncoding).keyColIndices, ((KeepMinValueStateEncoding) stateEncoding).valueColIndices); } else if (stateEncoding instanceof KeepAndSortOnMinValueStateEncoding) { state = new KeepAndSortOnMinValue(((KeepAndSortOnMinValueStateEncoding) stateEncoding).keyColIndices, ((KeepAndSortOnMinValueStateEncoding) stateEncoding).valueColIndices); } else if (stateEncoding instanceof DupElimStateEncoding) { state = new DupElim(); } else if (stateEncoding instanceof SimpleAppenderStateEncoding) { state = new SimpleAppender(); } else { state = new CountFilter(((CountFilterStateEncoding) stateEncoding).threshold, ((CountFilterStateEncoding) stateEncoding).keyColIndices); } List<StreamingState> states = new ArrayList<StreamingState>(); for (int i = 0; i < outputIDs.length; i++) { states.add(i, state.newInstanceFromMyself()); } setStreamingStates(states); }

Target:
public void setBackupBuffer(final StreamingStateEncoding<?> stateEncoding) { List<StreamingState> states = new ArrayList<StreamingState>(); for (int i = 0; i < outputIDs.length; i++) { states.add(i, stateEncoding.construct().duplicate()); } setStreamingStates(states); }
Source:
public Document generate(final DocumentTemplate docTemplate, final Object documentVersion) { if (false == handles(docTemplate)) { Activator.log.warn(NLS.bind("The generator {0} is not able to create the document structure for {1}.", getClass().getSimpleName(), docTemplate.toString())); return null; } final List<AbstractTemplateToStructureMapper<?>> mappers = Template2StructureRegistry.INSTANCE.getMappers(docTemplate); if (mappers.isEmpty()) { return null; } final IMappingService service = new TemplateToStructureMappingService(mappers); final List<Document> result = service.map(docTemplate, null, Document.class); if (result.isEmpty()) { return null; } Assert.isTrue(result.size() >= 1, "The generation contains more than one object as result"); final EObject res = result.iterator().next(); Assert.isTrue(res instanceof Document, "The result of the transformation is not Document."); final Document generatedDocument = (Document) res; if (documentVersion instanceof String) { generatedDocument.setVersion(createVersionFromString((String) documentVersion)); } else if (documentVersion instanceof Version) { generatedDocument.setVersion((Version) documentVersion); } if (null != documentVersion) { updateGeneratedDocumentName(generatedDocument); } return generatedDocument; }

Target:
public Document generate(final DocumentTemplate docTemplate, final Object documentVersion) { if (false == handles(docTemplate)) { Activator.log.warn(NLS.bind("The generator {0} is not able to create the document structure for {1}.", getClass().getSimpleName(), docTemplate.toString())); return null; } final List<AbstractTemplateToStructureMapper<?>> mappers = Template2StructureRegistry.INSTANCE.getMappers(docTemplate); if (mappers.isEmpty()) { return null; } final IMappingService service = new TemplateToStructureMappingService(mappers); final List<Document> result = service.map(docTemplate, null, Document.class); if (result.isEmpty()) { return null; } Assert.isTrue(result.size() >= 1, "The generation contains more than one object as result"); final EObject res = result.iterator().next(); Assert.isTrue(res instanceof Document, "The result of the transformation is not Document."); final Document generatedDocument = (Document) res; if (null != documentVersion) { if (documentVersion instanceof String) { generatedDocument.setVersion(createVersionFromString((String) documentVersion)); } else if (documentVersion instanceof Version) { generatedDocument.setVersion((Version) documentVersion); } updateGeneratedDocumentName(generatedDocument); } return generatedDocument; }
Source:
private boolean vmNotInStatusExists(VMStatus status) { for (VM vm : getVmList()) { if (vm.getStatus() != status) return true; } return false; }

Target:
private boolean vmNotInStatusExists(VMStatus status) { for (VM vm : getVmList()) { VM vmInDb = getVmDAO().get(vm.getId()); if (vmInDb != null && vmInDb.getStatus() != status) return true; } return false; }
Source:
public void afterPropertiesSet() { Path[] directoryPaths = new Path[] { this.cacheDirectory.resolve("bin"), this.cacheDirectory.resolve("gamedata") }; try { for (Path directoryPath : directoryPaths) { Files.createDirectories(directoryPath); Files.walk(directoryPath).forEach(this::deleteCachedFileIfNeeded); } } catch (IOException e) { e.printStackTrace(); } }

Target:
public void afterPropertiesSet() { Path cacheDirectory = preferencesService.getFeaturedModCachePath(); if (!Files.isDirectory(cacheDirectory)) { try { Files.createDirectories(cacheDirectory); } catch (IOException e) { log.error("Could not create Featured Mod Cache directory in ''{}''", cacheDirectory); throw new RuntimeException(MessageFormat.format("Could not create Featured Mod Cache directory in ''{}''." + " You might have to delete it or check if the needed permission are given.", cacheDirectory)); } } cleanUnusedFilesFromCache(); }
Source:
public BodyPart addPart(BodyPart bodyPart) { BodyPart temp = bodyPart; try { Multipart multipart = getMultipart(); multipart.addBodyPart(bodyPart); } catch (Exception e) { setError(e); temp = null; } return temp; }

Target:
public void addPart(BodyPart bodyPart) { addPart(null, bodyPart); }
Source:
public Integrator(final File ditaDir) { this.ditaDir = ditaDir; workspace = Configuration.workspace != null ? Configuration.workspace : ditaDir; pluginTable = new HashMap<>(16); descSet = new HashSet<>(16); loadedPlugin = new HashSet<>(16); featureTable = new Hashtable<>(16); extensionPoints = new HashSet<>(); try { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); reader = parserFactory.newSAXParser().getXMLReader(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } reader.setErrorHandler(new ErrorHandler() { @Override public void error(final SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(final SAXParseException e) throws SAXException { throw e; } @Override public void warning(final SAXParseException e) throws SAXException { throw e; } }); parser = new PluginParser(ditaDir); pluginsDoc = XMLUtils.getDocumentBuilder().newDocument(); pluginList = getPluginIds(readPlugins()); }

Target:
public Integrator(final File ditaDir) { this.ditaDir = ditaDir; workspace = Configuration.workspace.orElse(ditaDir); pluginTable = new HashMap<>(16); templateSet = new HashMap<>(16); descSet = new HashSet<>(16); loadedPlugin = new HashSet<>(16); featureTable = new Hashtable<>(16); extensionPoints = new HashSet<>(); try { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); reader = parserFactory.newSAXParser().getXMLReader(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } reader.setErrorHandler(new ErrorHandler() { @Override public void error(final SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(final SAXParseException e) throws SAXException { throw e; } @Override public void warning(final SAXParseException e) throws SAXException { throw e; } }); parser = new PluginParser(ditaDir); pluginsDoc = XMLUtils.getDocumentBuilder().newDocument(); pluginList = getPluginIds(readPlugins()); }
Source:
public static @Nullable String getLocalIpv4HostAddress() { return new NetUtil().getPrimaryIpv4HostAddress(); }

Target:
public static @Nullable String getLocalIpv4HostAddress() { return new NetUtil().getPrimaryHostAddress(); }
Source:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(r); try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { rw.release(); } } finally { r.close(); } }

Target:
private void assertTag(Project.NameKey project, String branch, String tagName) throws IOException { Repository r = repoManager.openRepository(project); try { ObjectId headCommit = r.getRef(branch).getObjectId(); ObjectId taggedCommit = r.getRef(tagName).getObjectId(); assertEquals(headCommit, taggedCommit); } finally { r.close(); } }
Source:
private String assembleEntityQuery(final boolean count) { String typeKey = template.getConverter().getTypeKey(); String typeValue = template.support().getJavaNameForEntity(domainType); final StringBuilder statement = new StringBuilder(); StringBasedN1qlQueryParser.N1qlSpelValues n1ql = StringBasedN1qlQueryParser.createN1qlSpelValues( template.getBucketName(), typeKey, typeValue, count ); if(query.hasInlineN1qlQuery()) { query.appendInlineN1qlStatement(statement); } else { query.appendString(statement,n1ql.selectEntity); } query.appendWhereString(statement,n1ql.filter); int[] paramIndexPtr=null; JsonValue params=query.getParameters(); if(params instanceof JsonArray) { if(query.hasInlineN1qlQuery()) { paramIndexPtr = new int[] { ((JsonArray) params).size() }; } else { paramIndexPtr = new int[] { 0 }; } } else { paramIndexPtr = new int[]{-1}; } if(!query.hasInlineN1qlQuery()) paramIndexPtr = null; query.appendWhere(statement, paramIndexPtr); query.appendSort(statement); query.appendSkipAndLimit(statement); return statement.toString(); }

Target:
private String assembleEntityQuery(final boolean count) { return query.toN1qlString(template, this.domainType, count); }
Source:
protected Event createSelectionEvent(int stateMask) { int stateMaskSelection = SWT.getPlatform().equals("win32") ? stateMask | SWT.BUTTON1 : stateMask; Event event = super.createSelectionEvent(stateMaskSelection); event.item = widget; return event; }

Target:
protected Event createSelectionEvent(int stateMask) { int stateMaskSelection = SWT.getPlatform().equals("gtk") ? stateMask : stateMask | SWT.BUTTON1; Event event = super.createSelectionEvent(stateMaskSelection); event.item = widget; return event; }
Source:
public void onError(Throwable e) { if (done) { RxJavaPlugins.onError(e); return; } value = null; actual.onError(e); }

Target:
public void onError(Throwable e) { if (done) { RxJavaPlugins.onError(e); return; } done = true; value = null; actual.onError(e); }
Source:
private StompFrame transformToMessage(StompFrame sendFrame, StompSubscription subscription) { StompFrame messageFrame = new DefaultStompFrame(StompCommand.MESSAGE, sendFrame.content().retainedDuplicate()); String id = UUID.randomUUID().toString(); messageFrame.headers() .set(MESSAGE_ID, id) .set(SUBSCRIPTION, subscription.id()); return messageFrame; }

Target:
private static StompFrame transformToMessage(StompFrame sendFrame, StompSubscription subscription) { StompFrame messageFrame = new DefaultStompFrame(StompCommand.MESSAGE, sendFrame.content().retainedDuplicate()); String id = UUID.randomUUID().toString(); messageFrame.headers() .set(MESSAGE_ID, id) .set(SUBSCRIPTION, subscription.id()) .set(CONTENT_LENGTH, Integer.toString(messageFrame.content().readableBytes())); CharSequence contentType = sendFrame.headers().get(CONTENT_TYPE); if (contentType != null) { messageFrame.headers().set(CONTENT_TYPE, contentType); } return messageFrame; }
Source:
public void testGetCoordinateDataFilterOptions() throws Exception { Resolver resolver = cn.getResolver(); final StringBuffer filterCalls = new StringBuffer(); Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter() { @Override public boolean includeCell(final String datacenter) {; filterCalls.append(datacenter + ":"); return true; } @Override public boolean includeUser(final String user) { filterCalls.append(user + ":"); return true; } @Override public boolean includeService(final String service) { filterCalls.append(service + ":"); return true; } @Override public boolean includeEndpointname(final String endpointName) { return endpointName.equals("foo"); } @Override public boolean includeServiceState(final ServiceState state) { return state == ServiceState.RUNNING; } }; Set<Endpoint> endpoints = resolver.getEndpoints(filter); assertEquals(1, endpoints.size()); Endpoint selectedEndpoint = endpoints.iterator().next(); assertEquals("foo", selectedEndpoint.getName()); assertEquals("cell:user:service:", filterCalls.toString()); }

Target:
public void testGetCoordinateDataFilterOptions() throws Exception { Resolver resolver = cn.getResolver(); final StringBuilder filterCalls = new StringBuilder(); Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter() { @Override public boolean includeCell(final String datacenter) { filterCalls.append(datacenter + ":"); return true; } @Override public boolean includeUser(final String user) { filterCalls.append(user + ":"); return true; } @Override public boolean includeService(final String service) { filterCalls.append(service + ":"); return true; } @Override public boolean includeEndpointname(final String endpointName) { return endpointName.equals("foo"); } @Override public boolean includeServiceState(final ServiceState state) { return state == ServiceState.RUNNING; } }; Set<Endpoint> endpoints = resolver.getEndpoints(filter); assertEquals(1, endpoints.size()); Endpoint selectedEndpoint = endpoints.iterator().next(); assertEquals("foo", selectedEndpoint.getName()); assertEquals("cell:user:service:", filterCalls.toString()); }
Source:
private RecordLayer getRecordLayerForPeer(final Connection connection) { return new RecordLayer() { @Override public void sendRecord(Record record) { sendRecord(record); } @Override public void sendFlight(DTLSFlight flight) { sendHandshakeFlight(flight, connection); } public void cancelRetransmissions() { if (config.isEarlyStopRetransmission()) connection.cancelPendingFlight(); } }; }

Target:
private RecordLayer getRecordLayerForPeer(final Connection connection) { return new RecordLayer() { @Override public void sendRecord(Record record) { sendRecord(record); } @Override public void sendFlight(DTLSFlight flight) { sendHandshakeFlight(flight, connection); } public void cancelRetransmissions() { if (config.isEarlyStopRetransmission()) { connection.cancelPendingFlight(); } } }; }
Source:
public KeyDeletingService(OzoneManager ozoneManager, ScmBlockLocationProtocol scmClient, KeyManager manager, long serviceInterval, long serviceTimeout, Configuration conf) { super("KeyDeletingService", serviceInterval, TimeUnit.MILLISECONDS, KEY_DELETING_CORE_POOL_SIZE, serviceTimeout); this.ozoneManager = ozoneManager; this.scmClient = scmClient; this.manager = manager; this.keyLimitPerTask = conf.getInt(OZONE_KEY_DELETING_LIMIT_PER_TASK, OZONE_KEY_DELETING_LIMIT_PER_TASK_DEFAULT); this.deletedKeyCount = new AtomicLong(0); this.runCount = new AtomicLong(0); }

Target:
KeyDeletingService(OzoneManager ozoneManager, ScmBlockLocationProtocol scmClient, KeyManager manager, long serviceInterval, long serviceTimeout, Configuration conf) { super("KeyDeletingService", serviceInterval, TimeUnit.MILLISECONDS, KEY_DELETING_CORE_POOL_SIZE, serviceTimeout); this.ozoneManager = ozoneManager; this.scmClient = scmClient; this.manager = manager; this.keyLimitPerTask = conf.getInt(OZONE_KEY_DELETING_LIMIT_PER_TASK, OZONE_KEY_DELETING_LIMIT_PER_TASK_DEFAULT); this.deletedKeyCount = new AtomicLong(0); this.runCount = new AtomicLong(0); }
Source:
public void testRewriteBasicLambda() throws Exception { final Map<Symbol, Type> symbols = ImmutableMap.of(new Symbol("a"), BigintType.BIGINT); final SymbolAllocator allocator = new SymbolAllocator(symbols); assertEquals(rewrite(expression("x -> a + x"), symbols, allocator), new BindExpression( ImmutableList.of(expression("a")), new LambdaExpression( ImmutableList.of("a_0", "x").stream().map(Identifier::new).map(LambdaArgumentDeclaration::new).collect(toList()), expression("a_0 + x")))); }

Target:
public void testRewriteBasicLambda() throws Exception { final Map<Symbol, Type> symbols = ImmutableMap.of(new Symbol("a"), BigintType.BIGINT); final SymbolAllocator allocator = new SymbolAllocator(symbols); assertEquals(rewrite(expression("x -> a + x"), symbols, allocator), new BindExpression( ImmutableList.of(expression("a")), new LambdaExpression( Stream.of("a_0", "x") .map(Identifier::new) .map(LambdaArgumentDeclaration::new) .collect(toList()), expression("a_0 + x")))); }
Source:
private void onLoadMore() { final int instanceLoadId = activeLoadId.get(); adapter.setProgressVisible(true); pageLoader.loadNextPage(new PageLoadCallback<T>() { @Override public void onPartialPageLoaded(List<T> newItems) { if (isResetCalled()) { return; } adapter.addAll(newItems); adapter.setProgressVisible(false); } @Override public void onPageLoaded(List<T> newItems, boolean hasMore) { if (isResetCalled()) { return; } adapter.addAll(newItems); if (!hasMore) { adapter.setProgressVisible(false); } hasMoreItems = hasMore; loading = false; } private boolean isResetCalled() { return instanceLoadId != activeLoadId.get(); } }); }

Target:
private void onLoadMore() { final int instanceLoadId = activeLoadId.get(); adapter.setProgressVisible(true); pageLoader.loadNextPage(new PageLoadCallback<T>() { @Override public void onPartialPageLoaded(List<T> newItems) { if (isAbandoned()) { return; } adapter.addAll(newItems); } @Override public void onPageLoaded(List<T> newItems, boolean hasMore) { if (isAbandoned()) { return; } adapter.addAll(newItems); if (!hasMore) { adapter.setProgressVisible(false); } hasMoreItems = hasMore; loading = false; } private boolean isAbandoned() { return instanceLoadId != activeLoadId.get(); } }); }
Source:
private Mapping(String sourceName, String sourceParameterName, String sourcePropertyName, String constant, String expression, String targetName, String dateFormat, AnnotationMirror mirror, AnnotationValue sourceAnnotationValue, AnnotationValue targetAnnotationValue) { this.sourceName = sourceName; this.sourceParameterName = sourceParameterName; this.sourcePropertyName = sourcePropertyName; this.constant = constant; this.expression = expression; Matcher javaExpressionMatcher = JAVA_EXPRESSION.matcher( expression ); this.javaExpression = javaExpressionMatcher.matches() ? javaExpressionMatcher.group( 1 ) : ""; this.targetName = targetName.equals( "" ) ? sourceName : targetName; this.dateFormat = dateFormat; this.mirror = mirror; this.sourceAnnotationValue = sourceAnnotationValue; this.targetAnnotationValue = targetAnnotationValue; }

Target:
private Mapping(String sourceName, String sourceParameterName, String sourcePropertyName, String constant, String expression, String targetName, String dateFormat, AnnotationMirror mirror, AnnotationValue sourceAnnotationValue, AnnotationValue targetAnnotationValue) { this.sourceName = sourceName; this.sourceParameterName = sourceParameterName; this.sourcePropertyName = sourcePropertyName; this.constant = constant; this.expression = expression; Matcher javaExpressionMatcher = JAVA_EXPRESSION.matcher( expression ); this.javaExpression = javaExpressionMatcher.matches() ? javaExpressionMatcher.group( 1 ).trim() : ""; this.targetName = targetName.equals( "" ) ? sourceName : targetName; this.dateFormat = dateFormat; this.mirror = mirror; this.sourceAnnotationValue = sourceAnnotationValue; this.targetAnnotationValue = targetAnnotationValue; }
Source:
public void testAddColumnAfterDropColumn() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); metadata.createTable(SESSION, buildTable(ImmutableMap.of(), tableMetadataBuilder(DEFAULT_TEST_ORDERS) .column("orderkey", BIGINT) .column("price", BIGINT)), false); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS); assertInstanceOf(tableHandle, RaptorTableHandle.class); RaptorTableHandle raptorTableHandle = (RaptorTableHandle) tableHandle; ColumnHandle lastColumn = metadata.getColumnHandles(SESSION, tableHandle).get("orderkey"); metadata.dropColumn(SESSION, raptorTableHandle, lastColumn); metadata.addColumn(SESSION, raptorTableHandle, new ColumnMetadata("new_col", BIGINT)); assertNull(metadata.getColumnHandles(SESSION, tableHandle).get("orderkey")); assertNotNull(metadata.getColumnHandles(SESSION, raptorTableHandle).get("new_col")); }

Target:
public void testAddColumnAfterDropColumn() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); metadata.createTable(SESSION, buildTable(ImmutableMap.of(), tableMetadataBuilder(DEFAULT_TEST_ORDERS) .column("orderkey", BIGINT) .column("price", BIGINT)), false); ConnectorTableHandle tableHandle = metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS); assertInstanceOf(tableHandle, RaptorTableHandle.class); RaptorTableHandle raptorTableHandle = (RaptorTableHandle) tableHandle; ColumnHandle column = metadata.getColumnHandles(SESSION, tableHandle).get("orderkey"); metadata.dropColumn(SESSION, raptorTableHandle, column); metadata.addColumn(SESSION, raptorTableHandle, new ColumnMetadata("new_col", BIGINT)); assertNull(metadata.getColumnHandles(SESSION, tableHandle).get("orderkey")); assertNotNull(metadata.getColumnHandles(SESSION, raptorTableHandle).get("new_col")); }
Source:
void addListener(final Session session) { Preconditions.checkNotNull(session); Preconditions.checkNotNull(session.getId()); sessionSet.put(session); }

Target:
void addListener(final Session session) { sessionSet.put(session); }
Source:
private EntityType cutDefaultValues(EntityType copy, CopyState state) { stream(copy.getAtomicAttributes()) .filter(EntityTypeUtils::isReferenceType) .filter(attr -> attr.getDefaultValue() != null) .forEach( attr -> { state.referenceDefaultValues().put(attr.getIdentifier(), attr.getDefaultValue()); attr.setDefaultValue(null); }); return copy; }

Target:
private EntityType cutDefaultValues(EntityType copy, CopyState state) { stream(copy.getAtomicAttributes()) .filter(EntityTypeUtils::isReferenceType) .filter(Attribute::hasDefaultValue) .forEach( attr -> { state.referenceDefaultValues().put(attr.getIdentifier(), attr.getDefaultValue()); attr.setDefaultValue(null); }); return copy; }
Source:
public void testCreateAndCaptureTransactionWithOfflineDebitCard() throws Throwable { transaction = transactionFactory.create("offline"); transaction.setCapture(true); transaction.save(); Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD); Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID); }

Target:
public void testCreateAndCaptureTransactionWithOfflineDebitCard() throws Throwable { transaction = transactionFactory.createCreditCardOfflineTransaction(); transaction.setCapture(true); transaction.save(); Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD); Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID); }
Source:
public ExtendedQueryResult<T> orderDesc(String attribute, boolean appendEntityName) { lastPaginatedQuery = null; if (!context.getRepositoryMethod().isQuery()) { context.addCriteriaBuilderPostProcessor(new OrderByCriteriaBuilderPostProcessor(attribute, OrderDirection.DESC)); } else { context.addQueryStringPostProcessor(new OrderByQueryStringPostProcessor(attribute, OrderDirection.ASC, appendEntityName)); } return this; }

Target:
public ExtendedQueryResult<T> orderDesc(String attribute, boolean appendEntityName) { lastPaginatedQuery = null; if (context.getRepositoryMethod().isQuery()) { context.addQueryStringPostProcessor(new OrderByQueryStringPostProcessor(attribute, OrderDirection.ASC, appendEntityName)); } else { context.addCriteriaBuilderPostProcessor(new OrderByCriteriaBuilderPostProcessor(attribute, OrderDirection.DESC)); } return this; }
Source:
private boolean getSucceeded() { return (result.mStatus.mCode == 0); }

Target:
private boolean getSucceeded() { return (result.getmStatus().mCode == 0); }
Source:
public List<String> getStreamConsumerArns() { return streamConsumerArns; }

Target:
public Optional<Map<String, String>> getStreamConsumerArns() { return Optional.ofNullable(streamConsumerArns); }
Source:
@Test public void clear() { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); map.clear(); assertIterationOrder(map.keySet()); assertThat(map.size()).isEqualTo(0); }

Target:
@Test public void clear() { LinkedHashTreeMap<String, String> map = new LinkedHashTreeMap<>(); map.put("a", "android"); map.put("c", "cola"); map.put("b", "bbq"); map.clear(); assertThat(map.keySet()).containsExactly(); assertThat(map).isEmpty(); }
Source:
public void testTotalPriceColumn(User user) { HomePage homePage = new HomePage(driver); UserInfoPage userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); OrderingPage orderingPage = userInfoPage.clickOrderingTab(); List<Order> tableFromView = orderingPage.getTableFromView(); tableFromView.sort(Comparator.comparing(Order::getTotalPrice)); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE.toString()); List<Order> sortedTableByTotalPriceAsc = orderingPage.getTableFromView(); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE.toString()); List<Order> sortedTableByTotalPriceDesc = orderingPage.getTableFromView(); for (int i = 0; i < tableFromView.size(); i++) { Assert.assertTrue(sortedTableByTotalPriceAsc.get(i).getTotalPrice().equals(tableFromView.get(i).getTotalPrice()), "Sorting by total price doesn't work."); } for (int i = 0, j = tableFromView.size() - 1; i < tableFromView.size(); i++, j--) { Assert.assertTrue(sortedTableByTotalPriceDesc.get(i).getTotalPrice().equals(tableFromView.get(j).getTotalPrice()), "Sorting by total price doesn't work."); } }

Target:
public void testTotalPriceColumn(User user) { HomePage homePage = new HomePage(driver); UserInfoPage userInfoPage = homePage.logIn(user.getLogin(), user.getPassword()); OrderingPage orderingPage = userInfoPage.clickOrderingTab(); List<Order> tableFromView = orderingPage.getTableFromView(); tableFromView.sort(Comparator.comparing(Order::getTotalPrice)); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE); List<Order> sortedTableByTotalPriceAsc = orderingPage.getTableFromView(); orderingPage.clickOrdersTableColumn(OrdersTable.TOTAL_PRICE); List<Order> sortedTableByTotalPriceDesc = orderingPage.getTableFromView(); for (int i = 0; i < tableFromView.size(); i++) { Assert.assertTrue(sortedTableByTotalPriceAsc.get(i).getTotalPrice().equals(tableFromView.get(i).getTotalPrice()), "Sorting by total price doesn't work."); } for (int i = 0, j = tableFromView.size() - 1; i < tableFromView.size(); i++, j--) { Assert.assertTrue(sortedTableByTotalPriceDesc.get(i).getTotalPrice().equals(tableFromView.get(j).getTotalPrice()), "Sorting by total price doesn't work."); } }
Source:
public CreateBranchPage(Repository repo, Ref baseRef) { super(CreateBranchPage.class.getName()); this.myRepository = repo; this.myBaseRef = baseRef != null ? baseRef.getName() : null; this.myBaseCommit = null; this.myValidator = ValidationUtils.getRefNameInputValidator( myRepository, Constants.R_HEADS, true); this.upstreamConfig = baseRef != null ? getDefaultUpstreamConfig(repo, baseRef.getName()) : UpstreamConfig.NONE; setTitle(UIText.CreateBranchPage_Title); setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage); }

Target:
public CreateBranchPage(Repository repo, Ref baseRef) { super(CreateBranchPage.class.getName()); this.myRepository = repo; this.myBaseRef = baseRef == null ? null : baseRef.getName(); this.myBaseCommit = null; this.myValidator = ValidationUtils.getRefNameInputValidator( myRepository, Constants.R_HEADS, true); this.upstreamConfig = baseRef != null ? getDefaultUpstreamConfig(repo, baseRef.getName()) : UpstreamConfig.NONE; setTitle(UIText.CreateBranchPage_Title); setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage); }
Source:
private void showEmailSentDialog(String email) { new AlertDialog.Builder(this) .setTitle(R.string.fui_title_confirm_recover_password) .setMessage(getString(R.string.fui_confirm_recovery_body, email)) .setOnDismissListener(this) .setPositiveButton(android.R.string.ok, null) .show(); }

Target:
private void showEmailSentDialog(String email) { new AlertDialog.Builder(this) .setTitle(R.string.fui_title_confirm_recover_password) .setMessage(getString(R.string.fui_confirm_recovery_body, email)) .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { finish(Activity.RESULT_OK, new Intent()); } }) .setPositiveButton(android.R.string.ok, null) .show(); }
Source:
public MessageChannel resolveDestination(String name) { MessageChannel channel = null; try { return super.resolveDestination(name); } catch (DestinationResolutionException e) { } if (name.contains(":")) { if (binderFactory != null) { String[] tokens = name.split(":", 2); String transport = null; String type; if (tokens.length == 2) { type = tokens[0]; } else if (tokens.length == 3) { transport = tokens[0]; type = tokens[1]; } else { throw new IllegalArgumentException("Unrecognized channel naming scheme: " + name + " , should be" + " [<transport>:]<type>:<name>"); } Binder<MessageChannel> binder = binderFactory.getBinder(transport); if ("queue".equals(type)) { channel = binder.bindDynamicProducer(name, this.producerProperties); } else { channel = binder.bindDynamicPubSubProducer(name, this.producerProperties); } } } if (channel == null) { channel = super.resolveDestination(name); } return channel; }

Target:
public MessageChannel resolveDestination(String name) { MessageChannel channel = null; DestinationResolutionException destinationResolutionException; try { return super.resolveDestination(name); } catch (DestinationResolutionException e) { destinationResolutionException = e; } synchronized (this) { try { return super.resolveDestination(name); } catch (DestinationResolutionException e) { destinationResolutionException = e; } if (this.beanFactory != null && this.binderFactory != null) { channel = new DirectChannel(); this.beanFactory.registerSingleton(name, channel); channel = (MessageChannel) this.beanFactory.initializeBean(channel, name); String transport = null; if (name.contains(":")) { String[] tokens = name.split(":", 2); if (tokens.length == 2) { transport = tokens[0]; } else if (tokens.length != 1) { throw new IllegalArgumentException("Unrecognized channel naming scheme: " + name + " , should be" + " [<transport>:]<name>"); } } String[] dynamicDestinations = null; Properties producerProperties = null; if (this.channelBindingServiceProperties != null) { dynamicDestinations = this.channelBindingServiceProperties.getDynamicDestinations(); producerProperties = this.channelBindingServiceProperties.getProducerProperties(name); } boolean dynamicAllowed = dynamicDestinations == null || dynamicDestinations.length == 0 || Arrays.asList(dynamicDestinations).contains(name); if (dynamicAllowed) { Binder<MessageChannel> binder = binderFactory.getBinder(transport); binder.bindProducer(name, channel, producerProperties); } else { throw destinationResolutionException; } } return channel; } }
Source:
public void runScenarioAlwaysCompleted() throws Exception { String experimentID = BenchFlowData.SCENARIO_ALWAYS_COMPLETED_EXPERIMENT_ID; setUpMocks(experimentID); Response response = client.target(String.format("http://localhost:%d", RULE.getLocalPort())) .path(BenchFlowConstants.getPathFromExperimentID(experimentID)) .path(BenchFlowExperimentResource.RUN_ACTION_PATH).request().post(null); Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); BenchFlowExperimentModelDAO experimentModelDAO = new BenchFlowExperimentModelDAO(mongoClient); Assert.assertNotNull(experimentModelDAO.getExperimentModel(experimentID)); executorService.awaitTermination(2, TimeUnit.SECONDS); Assert.assertEquals(BenchFlowExperimentState.TERMINATED, experimentModelDAO.getExperimentState(experimentID)); Assert.assertEquals(TerminatedState.COMPLETED, experimentModelDAO.getTerminatedState(experimentID)); long expectedExecutedTrials = 2; long executedTrials = BenchFlowExperimentManagerApplication.getExperimentModelDAO() .getNumExecutedTrials(experimentID); Assert.assertEquals(expectedExecutedTrials, executedTrials); }

Target:
public void runScenarioAlwaysCompleted() throws Exception { String experimentID = BenchFlowData.SCENARIO_ALWAYS_COMPLETED_EXPERIMENT_ID; runAlwaysCompleteOrDefaultOrFailFirst(experimentID); }
Source:
public Result login() { JsonNode json = request().body().asJson(); String username = json.findPath("username").getTextValue(); String password = json.findPath("password").getTextValue(); if (username.equals("user") && password.equals("password")) { session().clear(); session().put("email", username); return ok("Authenticated"); } else { return internalServerError("Bad email / password."); } }

Target:
public Result login() { JsonNode json = request().body().asJson(); try { expectFilledString(json, "username", "password"); } catch (InvalidJsonException e) { return badRequest("Expected username and password in Json."); } String username = json.findPath("username").getTextValue(); String password = json.findPath("password").getTextValue(); if (username.equals("user") && password.equals("password")) { session().clear(); session().put("email", username); return ok("Authenticated"); } else { return unauthorized("Bad username/password."); } }
Source:
public void stop() { logger.debug("Stopping {}", this); synchronized (this) { if (refCount == 0) { throw new IllegalStateException("Reference count is zero"); } if (--refCount > 0) { return; } if (!isActive()) { return; } } submit(new Runnable() { @Override public void run() { synchronized (DefaultEventLoop.this) { if (refCount == 0) { for (SelectionKey selectionKey : selector.keys()) { if (selectionKey.isValid()) { Channel channel = selectionKey.channel(); if (channel != null && channel.isOpen()) { Listener l = (Listener)selectionKey.attachment(); try { selectionKey.channel().close(); if (l != null) { if (l instanceof ClientListener) { ((ClientListener)l).disconnected(); } l.unregistered(selectionKey); } } catch (IOException e) { if (l != null) { l.handleException(e, DefaultEventLoop.this); } else { logger.warn("Exception while closing channel on unregistered key {}", channel, selectionKey, e); } } } } } alive = false; selector.wakeup(); } } } @Override public String toString() { return String.format("stop{%d}", refCount); } }); }

Target:
public void stop() { logger.debug("Stopping {}", this); synchronized (this) { if (refCount == 0) { throw new IllegalStateException("Reference count is zero"); } if (--refCount > 0 || !isActive()) { return; } } submit(new Runnable() { @Override public void run() { synchronized (DefaultEventLoop.this) { if (refCount == 0) { for (SelectionKey selectionKey : selector.keys()) { if (selectionKey.isValid()) { Channel channel = selectionKey.channel(); if (channel != null && channel.isOpen()) { Listener l = (Listener)selectionKey.attachment(); try { selectionKey.channel().close(); if (l != null) { if (l instanceof ClientListener) { ((ClientListener)l).disconnected(); } l.unregistered(selectionKey); } } catch (IOException e) { if (l != null) { l.handleException(e, DefaultEventLoop.this); } else { logger.warn("Exception while closing channel on unregistered key {}", channel, selectionKey, e); } } } } } alive = false; selector.wakeup(); } } } @Override public String toString() { return String.format("stop{%d}", refCount); } }); }
Source:
public Publication getPublicationById(Long id) { return publicationRepository.findById(id).orElseThrow(() -> new RestException("Not found", 404)); }

Target:
public Publication getPublicationById(Long id) { return publicationRepository.findById(id).orElseThrow(() -> new RestException("Not found", HttpServletResponse.SC_NOT_FOUND)); }
Source:
private Map<String, DropwizardMetricSpec> readMap(ObjectMapper mapper, String dimensionMapPath) { try { InputStream is; if (Strings.isNullOrEmpty(dimensionMapPath)) { log.info("Using default metric dimension and types"); is = this.getClass().getClassLoader().getResourceAsStream("defaultMetricDimensions.json"); } else { log.info("Using metric dimensions at types at [%s]", dimensionMapPath); is = new FileInputStream(new File(dimensionMapPath)); } return mapper.readerFor(new TypeReference<Map<String, DropwizardMetricSpec>>() { }).readValue(is); } catch (IOException e) { throw new ISE(e, "Failed to parse metric dimensions and types"); } }

Target:
private Map<String, DropwizardMetricSpec> readMap(ObjectMapper mapper, String dimensionMapPath) { InputStream is = null; try { if (Strings.isNullOrEmpty(dimensionMapPath)) { log.info("Using default metric dimension and types"); is = this.getClass().getClassLoader().getResourceAsStream("defaultMetricDimensions.json"); } else { log.info("Using metric dimensions at types at [%s]", dimensionMapPath); is = new FileInputStream(new File(dimensionMapPath)); } return mapper.readerFor(new TypeReference<Map<String, DropwizardMetricSpec>>() { }).readValue(is); } catch (IOException e) { throw new ISE(e, "Failed to parse metric dimensions and types"); } finally { Closeables.closeQuietly(is); } }
Source:
private AmrProfileStatusCode readAmrProfileStatusCode(final DataObject amrProfileStatusData) throws ProtocolAdapterException { AmrProfileStatusCode amrProfileStatusCode = null; if (!amrProfileStatusData.isNumber()) { throw new ProtocolAdapterException("Could not read AMR profile register data. Invalid data type."); } final Set<AmrProfileStatusCodeFlag> flags = this.amrProfileStatusHelperService .toAmrProfileStatusCodeFlags((Number) amrProfileStatusData.value()); amrProfileStatusCode = new AmrProfileStatusCode(flags); return amrProfileStatusCode; }

Target:
private AmrProfileStatusCode readAmrProfileStatusCode(final DataObject amrProfileStatusData) throws ProtocolAdapterException { AmrProfileStatusCode amrProfileStatusCode = null; if (!amrProfileStatusData.isNumber()) { throw new ProtocolAdapterException("Could not read AMR profile register data. Invalid data type."); } final Set<AmrProfileStatusCodeFlag> flags = this.amrProfileStatusCodeHelperService .toAmrProfileStatusCodeFlags((Number) amrProfileStatusData.value()); amrProfileStatusCode = new AmrProfileStatusCode(flags); return amrProfileStatusCode; }
Source:
public void updateMatrices(float fov) { prevViewProjectionMatrix.set(viewProjectionMatrix); if (cachedPosition.equals(getPosition()) && cachedViewigDirection.equals(viewingDirection) && cachedZFar == zFar && cachedZNear == zNear) { return; } projectionMatrix = new Matrix4f().ortho(left,right,top,bottom,zNear,zFar).transpose(); viewMatrix = MatrixUtils.createViewMatrix(0f, 0.0f, 0f, viewingDirection.x, viewingDirection.y, viewingDirection.z, up.x, up.y, up.z); normViewMatrix = MatrixUtils.createViewMatrix(0f, 0f, 0f, viewingDirection.x, viewingDirection.y, viewingDirection.z, up.x, up.y, up.z); viewProjectionMatrix = new Matrix4f(viewMatrix).mul(projectionMatrix); viewProjectionMatrix.invert(inverseViewProjectionMatrix); cachedPosition.set(getPosition()); cachedViewigDirection.set(viewingDirection); cachedZFar = zFar; cachedZNear = zNear; updateFrustum(); }

Target:
public void updateMatrices(float fov) { prevViewProjectionMatrix.set(viewProjectionMatrix); if (cachedPosition.equals(getPosition()) && cachedViewigDirection.equals(viewingDirection) && cachedZFar == zFar && cachedZNear == zNear) { return; } projectionMatrix = new Matrix4f().ortho(left, right, bottom, top, zNear, zFar).transpose(); viewMatrix = MatrixUtils.createViewMatrix(0f, 0.0f, 0f, viewingDirection.x, viewingDirection.y, viewingDirection.z, up.x, up.y, up.z); normViewMatrix = MatrixUtils.createViewMatrix(0f, 0f, 0f, viewingDirection.x, viewingDirection.y, viewingDirection.z, up.x, up.y, up.z); viewProjectionMatrix = new Matrix4f(viewMatrix).mul(projectionMatrix); viewProjectionMatrix.invert(inverseViewProjectionMatrix); cachedPosition.set(getPosition()); cachedViewigDirection.set(viewingDirection); cachedZFar = zFar; cachedZNear = zNear; updateFrustum(); }
Source:
private Map<String,Object> walkJson(JSONObject jsonObj) { Map<String,Object> v = Maps.newHashMap(); for (Object key: jsonObj.keySet()) { if (fields == null || fields.contains(key.toString())) v.put(key.toString(), wrap(jsonObj.get(key))); } return v; }

Target:
private Map<String,Object> walkJson(JSONObject jsonObj) { Map<String,Object> v = Maps.newHashMap(); for (Object key: jsonObj.keySet()) { v.put(key.toString(), wrap(jsonObj.get(key))); } return v; }
Source:
public List<Block> getBlocks(final String chr, final int start, final int end) { final int sequenceIndex = sequenceNames.indexOf(chr); if (sequenceIndex == -1 || indices[sequenceIndex] == null) { return Collections.emptyList(); } final List<Chunk> chunks = indices[sequenceIndex].getChunksOverlapping(start, end); if (chunks == null) { return Collections.emptyList(); } else { final List<Block> ret = new ArrayList<Block>(chunks.size()); for (final Chunk chunk : chunks) { ret.add(new Block(chunk.getChunkStart(), chunk.getChunkEnd() - chunk.getChunkStart())); } return ret; } }

Target:
public List<Block> getBlocks(final String chr, final int start, final int end) { final int sequenceIndex = sequenceNames.indexOf(chr); if (sequenceIndex == -1 || indices[sequenceIndex] == null) { return Collections.emptyList(); } final List<Chunk> chunks = indices[sequenceIndex].getChunksOverlapping(start, end); if (chunks == null) { return Collections.emptyList(); } else { final List<Block> ret = new ArrayList<>(chunks.size()); chunks.stream() .map(chunk -> new Block(chunk.getChunkStart(), chunk.getChunkEnd() - chunk.getChunkStart())) .forEach(ret::add); return ret; } }