auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
Set<Recipe> recipes() { final Group group = new GroupImpl("public", null, asList("read", "search")); final Recipe recipe1 = new RecipeImpl().withId("recipe1234567890") .withCreator("codenvy") .withType("docker") .withScript("FROM ubuntu\ntail -f \\dev\\null") .withTags(asList("ubuntu")) .withPermissions(new PermissionsImpl(null, asList(group))); final Recipe recipe2 = new RecipeImpl().withId("recipe2345678901") .withCreator("codenvy") .withType("docker") .withScript("FROM bosybox\ntail -f \\dev\\null") .withTags(asList("java", "busybox")) .withPermissions(new PermissionsImpl(null, asList(group))); return new HashSet<>(asList(recipe1, recipe2)); }

Target:
Set<Recipe> recipes() { final Group group = new GroupImpl("public", null, asList("read", "search")); final Recipe recipe1 = new RecipeImpl().withId("recipe1234567890") .withCreator("codenvy") .withType("docker") .withScript("FROM ubuntu\ntail -f \\dev\\null") .withTags(asList("ubuntu")) .withPermissions(new PermissionsImpl(null, asList(group))); final Recipe recipe2 = new RecipeImpl().withId("recipe2345678901") .withCreator("codenvy") .withType("docker") .withScript("FROM bosybox\ntail -f \\dev\\null") .withTags(asList("java", "busybox")) .withPermissions(new PermissionsImpl(null, asList(group))); return Collections.unmodifiableSet(new HashSet<>(asList(recipe1, recipe2))); }
Source:
public void testOpenMRSPatientDataSourceAndCreatePatientAction() throws InterruptedException, IOException, PatientNotFoundException { Long taskID = createPatientTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); deleteTask(taskID); checkIfPatientWasCreatedProperly(); }

Target:
public void testOpenMRSPatientDataSourceAndCreatePatientAction() throws InterruptedException, IOException, PatientNotFoundException { Long taskID = createPatientTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); checkIfPatientWasCreatedProperly(); }
Source:
private void structureDependencyHelper(String stInode) throws DotDataException, DotSecurityException{ Structure st = StructureCache.getStructureByInode(stInode); Host h = APILocator.getHostAPI().find(st.getHost(), user, false); hosts.addOrClean(st.getHost(), h.getModDate()); Folder f = APILocator.getFolderAPI().find(st.getFolder(), user, false); folders.addOrClean(st.getFolder(), f.getModDate()); try { WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(st); workflows.addOrClean(scheme.getId(), scheme.getModDate()); } catch (DotDataException e) { Logger.debug(getClass(), "Could not get the Workflow Scheme Dependency for Structure ID: " + st.getInode()); } List<Relationship> relations = RelationshipFactory.getAllRelationshipsByStructure(st); for (Relationship r : relations) { relationships.addOrClean( r.getInode(), r.getModDate()); if(!structures.contains(r.getChildStructureInode()) && config.getOperation().equals( Operation.PUBLISH)){ Structure struct = StructureCache.getStructureByInode(r.getChildStructureInode()); structures.addOrClean( r.getChildStructureInode(), struct.getModDate()); if(st!=null) structureDependencyHelper( r.getChildStructureInode() ); } if(!structures.contains(r.getParentStructureInode()) && config.getOperation().equals( Operation.PUBLISH)){ Structure struct = StructureCache.getStructureByInode(r.getChildStructureInode()); structures.addOrClean( r.getParentStructureInode(), struct.getModDate()); if(st!=null) structureDependencyHelper( r.getParentStructureInode() ); } } }

Target:
private void structureDependencyHelper(String stInode) throws DotDataException, DotSecurityException{ Structure st = StructureCache.getStructureByInode(stInode); Host h = APILocator.getHostAPI().find(st.getHost(), user, false); hosts.addOrClean(st.getHost(), h.getModDate()); Folder f = APILocator.getFolderAPI().find(st.getFolder(), user, false); folders.addOrClean(st.getFolder(), f.getModDate()); try { WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(st); workflows.addOrClean(scheme.getId(), scheme.getModDate()); } catch (DotDataException e) { Logger.debug(getClass(), "Could not get the Workflow Scheme Dependency for Structure ID: " + st.getInode()); } List<Relationship> relations = RelationshipFactory.getAllRelationshipsByStructure(st); for (Relationship r : relations) { relationships.addOrClean( r.getInode(), r.getModDate()); if(!structures.contains(r.getChildStructureInode()) && config.getOperation().equals( Operation.PUBLISH)){ Structure struct = StructureCache.getStructureByInode(r.getChildStructureInode()); structures.addOrClean( r.getChildStructureInode(), struct.getModDate()); if(st!=null) structureDependencyHelper( r.getChildStructureInode() ); } if(!structures.contains(r.getParentStructureInode()) && config.getOperation().equals( Operation.PUBLISH)){ Structure struct = StructureCache.getStructureByInode(r.getParentStructureInode()); structures.addOrClean( r.getParentStructureInode(), struct.getModDate()); if(st!=null) structureDependencyHelper( r.getParentStructureInode() ); } } }
Source:
public void setHasUpgradeOption(String mode, View.OnClickListener onLearnMoreClick){ if(mode.equalsIgnoreCase(EnrollmentMode.AUDIT.toString())) { propContainer.setVisibility(View.VISIBLE); Drawable trophyIcon = new IconDrawable(coursePropMsg.getContext(), FontAwesomeIcons.fa_trophy) .sizeRes(coursePropMsg.getContext(), R.dimen.medium_icon_size) .colorRes(coursePropMsg.getContext(), R.color.neutralBlackT); coursePropMsg.setCompoundDrawablesWithIntrinsicBounds(trophyIcon, null, null, null); learnMore.setOnClickListener(onLearnMoreClick); } else { propContainer.setVisibility(View.GONE); } }

Target:
public void setHasUpgradeOption(String mode, View.OnClickListener onLearnMoreClick) { if (mode.equalsIgnoreCase(EnrollmentMode.AUDIT.toString())) { propContainer.setVisibility(View.VISIBLE); learnMore.setOnClickListener(onLearnMoreClick); } else { propContainer.setVisibility(View.GONE); } }
Source:
protected boolean readNextPage() { definitionLevelDecoder = null; valuesDecoder = null; remainingCountInPage = 0; DataPage page = pageReader.readPage(); if (page == null) { return false; } Decoders.FlatDecodersCombo flatDecodersCombo = Decoders.readFlatPage(page, columnDescriptor, dictionary); this.definitionLevelDecoder = flatDecodersCombo.getDefinitionLevelDecoder(); this.valuesDecoder = (Int32ValuesDecoder) flatDecodersCombo.getValuesDecoder(); remainingCountInPage = page.getValueCount(); return true; }

Target:
protected boolean readNextPage() { definitionLevelDecoder = null; valuesDecoder = null; remainingCountInPage = 0; DataPage page = pageReader.readPage(); if (page == null) { return false; } FlatDecoders flatDecoders = readFlatPage(page, columnDescriptor, dictionary); this.definitionLevelDecoder = flatDecoders.getDefinitionLevelDecoder(); this.valuesDecoder = (Int32ValuesDecoder) flatDecoders.getValuesDecoder(); remainingCountInPage = page.getValueCount(); return true; }
Source:
private PinotExpression handleCast(CallExpression cast, Function<VariableReferenceExpression, Selection> context) { if (cast.getArguments().size() == 1) { RowExpression input = cast.getArguments().get(0); Type expectedType = cast.getType(); if (typeManager.canCoerce(input.getType(), expectedType)) { return input.accept(this, context); } else { throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Non implicit casts not supported: " + cast); } } throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), format("This type of CAST operator not supported. Received: %s", cast)); }

Target:
private PinotExpression handleCast(CallExpression cast, Function<VariableReferenceExpression, Selection> context) { if (cast.getArguments().size() == 1) { RowExpression input = cast.getArguments().get(0); Type expectedType = cast.getType(); if (typeManager.canCoerce(input.getType(), expectedType)) { return input.accept(this, context); } throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Non implicit casts not supported: " + cast); } throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), format("This type of CAST operator not supported. Received: %s", cast)); }
Source:
private SimpleEMTask( final MemoryStore memoryStore, final SimpleEMTaskReady simpleEMTaskReady, final HeartBeatTriggerManager heartBeatTriggerManager, final PartitionTracker partitionTracker, final DataIdFactory<Long> dataIdFactory, @Parameter(Iterations.class) final int iterations, @Parameter(PeriodMillis.class) final long periodMillis) { this.memoryStore = memoryStore; this.simpleEMTaskReady = simpleEMTaskReady; this.heartBeatTriggerManager = heartBeatTriggerManager; this.iterations = iterations; this.periodMillis = periodMillis; final long firstItem = dataIdFactory.getId(); this.memoryStore.getElasticStore().put(DATATYPE, firstItem, firstItem); for (int index = 1; index < 9; index++) { final long item = dataIdFactory.getId(); this.memoryStore.getElasticStore().put(DATATYPE, item, item); } final long lastItem = dataIdFactory.getId(); this.memoryStore.getElasticStore().put(DATATYPE, lastItem, lastItem); partitionTracker.registerPartition(DATATYPE, firstItem, lastItem); }

Target:
private SimpleEMTask( final MemoryStore memoryStore, final SimpleEMTaskReady simpleEMTaskReady, final HeartBeatTriggerManager heartBeatTriggerManager, final PartitionTracker partitionTracker, final DataIdFactory<Long> dataIdFactory, @Parameter(Iterations.class) final int iterations, @Parameter(PeriodMillis.class) final long periodMillis) throws IdGenerationException { this.memoryStore = memoryStore; this.simpleEMTaskReady = simpleEMTaskReady; this.heartBeatTriggerManager = heartBeatTriggerManager; this.iterations = iterations; this.periodMillis = periodMillis; final List<Long> ids = dataIdFactory.getIds(NUM_DATA); this.memoryStore.getElasticStore().putList(DATATYPE, ids, ids); partitionTracker.registerPartition(DATATYPE, ids.get(0), ids.get(NUM_DATA - 1)); }
Source:
public boolean acquireLock(InvocationContext ctx, Object key, long timeoutMillis, boolean skipLocking) throws InterruptedException, TimeoutException { LockInfo lockInfo = new LockInfo(ctx); updateContentionStats(key, lockInfo); boolean locked = false; long start = timeService.time(); try { locked = actual.acquireLock(ctx, key, timeoutMillis, skipLocking); } finally { long end = timeService.time(); lockInfo.lockTimeStamp = end; if (lockInfo.contention) { lockInfo.lockWaiting = timeService.timeDuration(start, end, NANOSECONDS); } if (lockInfoMap.get(key) == null && locked) { lockInfoMap.put(key, lockInfo); } else if (!locked) { lockInfo.updateStats(-1); } } return locked; }

Target:
public boolean acquireLock(InvocationContext ctx, Object key, long timeoutMillis, boolean skipLocking) throws InterruptedException, TimeoutException { LockInfo lockInfo = new LockInfo(ctx); updateContentionStats(key, lockInfo); boolean locked = false; long start = timeService.time(); try { locked = actual.acquireLock(ctx, key, timeoutMillis, skipLocking); } finally { long end = timeService.time(); lockInfo.lockTimeStamp = end; if (lockInfo.contention) { lockInfo.lockWaiting = timeService.timeDuration(start, end, NANOSECONDS); } if (locked) { lockInfoMap.putIfAbsent(key, lockInfo); } else { lockInfo.updateStats(-1); } } return locked; }
Source:
public RealmQuery<E> isNull(String fieldName) { realm.checkIfValid(); long columnIndices[] = schema.parseFieldName(fieldName); this.query.isNull(columnIndices); return this; }

Target:
public RealmQuery<E> isNull(String fieldName) { realm.checkIfValid(); long[] columnIndices = schema.getColumnIndices(fieldName); this.query.isNull(columnIndices); return this; }
Source:
public Boolean apply(WebDriver webDriver) { if (webElement == null) { return (!webDriver.findElements(By.xpath(xpath)).isEmpty() == isPresent); } else { return (!webElement.findElements(By.xpath(xpath)).isEmpty() == isPresent); } }

Target:
public Boolean apply(WebDriver webDriver) { SearchContext search = (webElement == null) ? webDriver : webElement; return search.findElements(By.xpath(xpath)).isEmpty() != isPresent; }
Source:
public List<User> getAllActiveUsersSortedByNameAndSurname() { return search("FROM User WHERE active = 1 AND visible IS NULL ORDER BY surname ASC, name ASC"); }

Target:
public List<User> getAllActiveUsersSortedByNameAndSurname() { return search("FROM User WHERE active = 1 AND deleted = 0 ORDER BY surname ASC, name ASC"); }
Source:
private Map<String, String> getMapFromJsonObject(String json) { Type stringMapType = new TypeToken<Map<String, Object>>() {}.getType(); return new Gson().fromJson(json, stringMapType); }

Target:
private Map<String, Object> getMapFromJsonObject(String json) throws JsonSyntaxException { Type typeToken = new TypeToken<Map<String, Object>>() {}.getType(); return new Gson().fromJson(json, typeToken); }
Source:
public int compareTo(ScoredSearchHit other) { int comparison = this.isExact.compareTo(other.isExact); if (comparison == 0) { return score - other.score; } return comparison; }

Target:
public int compareTo(ScoredSearchHit other) { int comparison = Boolean.compare(isExact, other.isExact); if (comparison == 0) { return Integer.compare(score, other.score); } return comparison; }
Source:
public void updateAllowedConnectionType(ConnectionType allowedConnectionType) { if (allowedConnectionType == null) { throw new IllegalArgumentException("Allowed connection type cannot be null"); } downloadConnectionAllowedChecker.updateAllowedConnectionType(allowedConnectionType); DownloadsNetworkRecoveryCreator.getInstance().updateAllowedConnection(allowedConnectionType); submitAllStoredDownloads(() -> Log.v("Allowed connectionType updated to " + allowedConnectionType + ". All jobs submitted")); }

Target:
public void updateAllowedConnectionType(ConnectionType allowedConnectionType) { if (allowedConnectionType == null) { throw new IllegalArgumentException("Allowed connection type cannot be null"); } connectionChecker.updateAllowedConnectionType(allowedConnectionType); DownloadsNetworkRecoveryCreator.getInstance().updateAllowedConnectionType(allowedConnectionType); submitAllStoredDownloads(() -> Log.v("Allowed connectionType updated to " + allowedConnectionType + ". All jobs submitted")); }
Source:
public int rank(final Set<ResourceType> resourceTypes, final Collection<ServiceConfiguration<?>> serviceConfigs) { if (findSingletonAmongst(XAStoreConfiguration.class, serviceConfigs) == null) { return 0; } final int underlyingRank = underlyingStoreProvider.rank(resourceTypes, serviceConfigs); if (underlyingRank != 0) { return 10 + underlyingRank; } else { return 0; } }

Target:
public int rank(final Set<ResourceType> resourceTypes, final Collection<ServiceConfiguration<?>> serviceConfigs) { if (findSingletonAmongst(XAStoreConfiguration.class, serviceConfigs) == null) { return 0; } final int underlyingRank; if (resourceTypes.equals(EnumSet.of(ResourceType.Core.HEAP))) { underlyingRank = 1; } else { underlyingRank = underlyingStoreProvider.rank(resourceTypes, serviceConfigs); } if (underlyingRank != 0) { return 10 + underlyingRank; } else { return 0; } }
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!getExpression().evaluate(tuple, ptr) || ptr.getLength() == 0) { return false; } PDataType type = getExpression().getDataType(); String stringValue = (String)type.toObject(ptr); BigDecimal decimalValue = (BigDecimal) getDataType().toObject(stringValue); byte[] byteValue = getDataType().toBytes(decimalValue); ptr.set(byteValue); return true; }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (!getExpression().evaluate(tuple, ptr)) { return false; } else if (ptr.getLength() == 0) { return true; } PDataType type = getExpression().getDataType(); String stringValue = (String)type.toObject(ptr); if (stringValue == null) { return false; } stringValue = stringValue.trim(); BigDecimal decimalValue = (BigDecimal) getDataType().toObject(stringValue); byte[] byteValue = getDataType().toBytes(decimalValue); ptr.set(byteValue); return true; }
Source:
public void testOpenshiftConnectionCredentials() throws Exception { CDKOpenshiftUtility util = new CDKOpenshiftUtility(); ADBInfo adb = createADB(); IServer s = mockServer("openshift33"); createCDKFile("Basic", null, null); IConnection con = util.createOpenshiftConnection(s, adb, false); assertNotNull(con); assertEquals(con.getUsername(), "openshift-dev"); assertEquals(con.getPassword(), "devel"); createCDKFile("Basic", "test", null); con = util.createOpenshiftConnection(s, adb, false); assertNotNull(con); assertEquals(con.getUsername(), "test"); assertEquals(con.getPassword(), null); createCDKFile("Basic", "test", "pass"); con = util.createOpenshiftConnection(s, adb, false); assertNotNull(con); assertEquals(con.getUsername(), "test"); assertEquals(con.getPassword(), "pass"); }

Target:
public void testOpenshiftConnectionCredentials() throws Exception { CDKOpenshiftUtility util = new CDKOpenshiftUtility(); ADBInfo adb = createADB(); IServer s = mockServer("openshift33"); createCDKFile("Basic", null, null); IConnection con = util.createOpenshiftConnection(s, adb, null); assertNotNull(con); assertEquals(con.getUsername(), "openshift-dev"); assertEquals(con.getPassword(), "devel"); createCDKFile("Basic", "test", null); con = util.createOpenshiftConnection(s, adb, null); assertNotNull(con); assertEquals(con.getUsername(), "test"); assertEquals(con.getPassword(), null); createCDKFile("Basic", "test", "pass"); con = util.createOpenshiftConnection(s, adb, null); assertNotNull(con); assertEquals(con.getUsername(), "test"); assertEquals(con.getPassword(), "pass"); }
Source:
public void testSetDatastoreProperties() throws Exception { datastoreProperties.init(); properties.init(); SandboxedInstanceTestFixture sandboxedInstanceTestFixture = new SandboxedInstanceTestFixture(); sandboxedInstanceTestFixture.setUp(); properties.setDatastoreProperties(datastoreProperties); assertThat((Iterable<String>) properties.moduleName.getPossibleValues(), containsInAnyOrder( "Account", "Customer")); assertThat(properties.selectColumnIds.getPossibleValues(), empty()); }

Target:
public void testSetDatastoreProperties() throws Exception { datastoreProperties.init(); properties.init(); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture( isA(SalesforceInputProperties.class), createDefaultTestDataset())) { testFixture.setUp(); properties.setDatastoreProperties(datastoreProperties); assertThat((Iterable<String>) properties.moduleName.getPossibleValues(), containsInAnyOrder( "Account", "Customer")); assertThat(properties.selectColumnIds.getPossibleValues(), empty()); } }
Source:
private static RelDataType inferRowType(SqlOperatorBinding opBinding) { final RelDataType inputRowType = opBinding.getOperandType(0); final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final RelDataType timestampType = typeFactory.createSqlType(SqlTypeName.TIMESTAMP); return typeFactory.builder() .kind(inputRowType.getStructKind()) .addAll(inputRowType.getFieldList()) .add("wstart", timestampType) .add("wend", timestampType) .build(); }

Target:
private static RelDataType inferRowType(SqlOperatorBinding opBinding) { final RelDataType inputRowType = opBinding.getOperandType(0); final RelDataTypeFactory typeFactory = opBinding.getTypeFactory(); final RelDataType timestampType = typeFactory.createSqlType(SqlTypeName.TIMESTAMP); return typeFactory.builder() .kind(inputRowType.getStructKind()) .addAll(inputRowType.getFieldList()) .add("window_start", timestampType) .add("window_end", timestampType) .build(); }
Source:
private void visitReturn(DetailAST ast) { if (ast.getFirstChild().getType() == TokenTypes.SEMI) { context.hasVoidReturn = true; context.visitLiteralReturn(maxForVoid); } else { context.hasVoidReturn = false; context.visitLiteralReturn(max); } }

Target:
private void visitReturn(DetailAST ast) { if (ast.getFirstChild().getType() == TokenTypes.SEMI) { context.visitLiteralReturn(maxForVoid, true); } else { context.visitLiteralReturn(max, false); } }
Source:
public void validate(final TokenCredentials credentials) { CommonHelper.assertNotBlank("signingSecret", signingSecret); final String token = credentials.getToken(); boolean verified = false; SignedJWT signedJWT = null; try { final JWT jwt = JWTParser.parse(token); if (jwt instanceof SignedJWT) { signedJWT = (SignedJWT) jwt; } else if (jwt instanceof EncryptedJWT) { final JWEObject jweObject = (JWEObject) jwt; String secret = this.encryptionSecret; if (CommonHelper.isBlank(secret)) { logger.warn("Encryption secret is not configured. Falling back to signing secret"); secret = this.signingSecret; } jweObject.decrypt(new DirectDecrypter(secret.getBytes("UTF-8"))); signedJWT = jweObject.getPayload().toSignedJWT(); } else { throw new TechnicalException("unsupported unsecured jwt"); } verified = signedJWT.verify(new MACVerifier(this.signingSecret)); } catch (final Exception e) { throw new TechnicalException("Cannot decrypt / verify JWT", e); } if (!verified) { final String message = "JWT verification failed: " + token; throw new CredentialsException(message); } try { final JWTClaimsSet claimSet = signedJWT.getJWTClaimsSet(); final UserProfile profile = ProfileHelper.buildProfile(claimSet.getSubject(), claimSet.getClaims()); credentials.setUserProfile(profile); } catch (final Exception e) { throw new TechnicalException("Cannot get claimSet", e); } }

Target:
public void validate(final TokenCredentials credentials) { CommonHelper.assertNotBlank("signingSecret", signingSecret); final String token = credentials.getToken(); boolean verified = false; SignedJWT signedJWT = null; try { final JWT jwt = JWTParser.parse(token); if (jwt instanceof SignedJWT) { signedJWT = (SignedJWT) jwt; } else if (jwt instanceof EncryptedJWT) { final JWEObject jweObject = (JWEObject) jwt; CommonHelper.assertNotBlank("encryptionSecret", encryptionSecret); jweObject.decrypt(new DirectDecrypter(this.encryptionSecret.getBytes("UTF-8"))); signedJWT = jweObject.getPayload().toSignedJWT(); } else { throw new TechnicalException("unsupported unsecured jwt"); } verified = signedJWT.verify(new MACVerifier(this.signingSecret)); } catch (final Exception e) { throw new TechnicalException("Cannot decrypt / verify JWT", e); } if (!verified) { final String message = "JWT verification failed: " + token; throw new CredentialsException(message); } try { final JWTClaimsSet claimSet = signedJWT.getJWTClaimsSet(); final UserProfile profile = ProfileHelper.buildProfile(claimSet.getSubject(), claimSet.getClaims()); credentials.setUserProfile(profile); } catch (final Exception e) { throw new TechnicalException("Cannot get claimSet", e); } }
Source:
void checksumFile(File file, Checksum checksum) { checksum.update(MountableFile.getUnixFileMode(file.toPath())); if (file.isDirectory()) { try (Stream<Path> stream = Files.walk(file.toPath())) { stream.filter(it -> !Files.isDirectory(it)).forEach(path -> { checksumFile(path.toFile(), checksum); }); } } else { FileUtils.checksum(file, checksum); } }

Target:
void checksumFile(File file, Checksum checksum) { Path path = file.toPath(); checksum.update(MountableFile.getUnixFileMode(path)); if (file.isDirectory()) { try (Stream<Path> stream = Files.walk(path)) { stream.filter(it -> it != path).forEach(it -> { checksumFile(it.toFile(), checksum); }); } } else { FileUtils.checksum(file, checksum); } }
Source:
protected String createAssertion(JsonFactory jsonFactory, long currentTime) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); payload.setIssuer(clientEmail); payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(scopes)); String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException( "Error signing service account access token request with private key.", e); } return assertion; }

Target:
String createAssertion(JsonFactory jsonFactory, long currentTime) throws IOException { JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(privateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); payload.setIssuer(clientEmail); payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(scopes)); String assertion; try { assertion = JsonWebSignature.signUsingRsaSha256( privateKey, jsonFactory, header, payload); } catch (GeneralSecurityException e) { throw new IOException( "Error signing service account access token request with private key.", e); } return assertion; }
Source:
protected void fireExpressionEditorSelectedEvent() { final Optional<BaseExpressionGrid> parentGrid = findParentGrid(parent); editorSelectedEvent.fire(new ExpressionEditorSelectedEvent(sessionManager.getCurrentSession(), parentGrid)); }

Target:
protected void fireExpressionEditorSelectedEvent() { final Optional<BaseExpressionGrid> parentGrid = findParentGrid(); editorSelectedEvent.fire(new ExpressionEditorSelectedEvent(sessionManager.getCurrentSession(), parentGrid)); }
Source:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(state == State.RUNNING, "Operator is %s", state); lifespanAndStageStateTracker.update(page); lifespanAndStageStateTracker.getStatisticsPagesToProcess(page).forEach(statisticsPage -> { OperationTimer timer = new OperationTimer(statisticsCpuTimerEnabled); statisticsAggregationOperator.addInput(statisticsPage); timer.end(statisticsTiming); }); }

Target:
public void addInput(Page page) { requireNonNull(page, "page is null"); checkState(state == State.RUNNING, "Operator is %s", state); TableCommitContext tableCommitContext = getTableCommitContext(page); lifespanAndStageStateTracker.update(page, tableCommitContext); lifespanAndStageStateTracker.getStatisticsPagesToProcess(page, tableCommitContext).forEach(statisticsPage -> { OperationTimer timer = new OperationTimer(statisticsCpuTimerEnabled); statisticsAggregationOperator.addInput(statisticsPage); timer.end(statisticsTiming); }); }
Source:
@Override public void decompressPage(ByteBuffer page, int pageSize) throws IgniteCheckedException { assert page.capacity() == pageSize; byte compressType = PageIO.getCompressionType(page); if (compressType == UNCOMPRESSED_PAGE) return; short compressedSize = PageIO.getCompressedSize(page); short compactSize = PageIO.getCompactedSize(page); assert compactSize <= pageSize && compactSize >= compressedSize; if (compressType != COMPACTED_PAGE) { ByteBuffer dst = compressBuf.get(); page.limit(compressedSize) .position(PageIO.COMMON_HEADER_END); dst.limit(compactSize - PageIO.COMMON_HEADER_END); if (compressType == ZSTD_COMPRESSED_PAGE) { Zstd.decompress(dst, page); dst.flip(); } else if (compressType == LZ4_COMPRESSED_PAGE) { Lz4.decompress(page, dst); dst.flip(); } else if (compressType == SNAPPY_COMPRESSED_PAGE) { try { Snappy.uncompress(page, dst); } catch (IOException e) { throw new IgniteException(e); } } else throw new IllegalStateException("Unknown compression: " + compressType); page.position(PageIO.COMMON_HEADER_END).limit(compactSize); page.put(dst).flip(); assert page.limit() == compactSize; } else page.position(0).limit(compactSize); CompactablePageIO io = PageIO.getPageIO(page); io.restorePage(page, pageSize); setCompressionInfo(page, null, 0, 0); }

Target:
@Override public void decompressPage(ByteBuffer page, int pageSize) throws IgniteCheckedException { assert page.capacity() == pageSize; byte compressType = PageIO.getCompressionType(page); if (compressType == UNCOMPRESSED_PAGE) return; short compressedSize = PageIO.getCompressedSize(page); short compactSize = PageIO.getCompactedSize(page); assert compactSize <= pageSize && compactSize >= compressedSize; if (compressType == COMPACTED_PAGE) { page.position(0).limit(compactSize); } else { ByteBuffer dst = compressBuf.get(); page.limit(compressedSize) .position(PageIO.COMMON_HEADER_END); dst.limit(compactSize - PageIO.COMMON_HEADER_END); switch (compressType) { case ZSTD_COMPRESSED_PAGE: Zstd.decompress(dst, page); dst.flip(); break; case LZ4_COMPRESSED_PAGE: Lz4.decompress(page, dst); dst.flip(); break; case SNAPPY_COMPRESSED_PAGE: try { Snappy.uncompress(page, dst); } catch (IOException e) { throw new IgniteException(e); } break; default: throw new IgniteException("Unknown compression: " + compressType); } page.position(PageIO.COMMON_HEADER_END).limit(compactSize); page.put(dst).flip(); assert page.limit() == compactSize; } CompactablePageIO io = PageIO.getPageIO(page); io.restorePage(page, pageSize); setCompressionInfo(page, null, 0, 0); }
Source:
private UriSchemeHandlerPreferencePage openPreferenceAndGetPage() { Shell shell = Display.getCurrent().getActiveShell(); this.dialog = PreferencesUtil.createPreferenceDialogOn(shell, "org.eclipse.ui.preferencePages.General.LinkHandlers", null, null); this.dialog.setBlockOnOpen(false); this.dialog.open(); return (UriSchemeHandlerPreferencePage) this.dialog.getSelectedPage(); }

Target:
private UriSchemeHandlerPreferencePage openPreferenceAndGetPage() { this.dialog = PreferencesUtil.createPreferenceDialogOn(new Shell(), "org.eclipse.ui.preferencePages.General.LinkHandlers", null, null); this.dialog.setBlockOnOpen(false); this.dialog.open(); return (UriSchemeHandlerPreferencePage) this.dialog.getSelectedPage(); }
Source:
protected static boolean hasIllegalCombination(DetailAST modifiers) { for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) { int modifierType = modifier.getType(); if (TokenTypes.ANNOTATION == modifierType) { if (INVALID_FINAL_ANNOTATIONS.contains(modifier.findFirstToken(TokenTypes.IDENT).getText())) { return true; } } if (INVALID_FINAL_COMBINATION.contains(modifierType)) { return true; } } return false; }

Target:
protected static boolean hasIllegalCombination(DetailAST modifiers) { if (modifiers.getType() != TokenTypes.MODIFIERS) { return false; } Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> { final int type = node.getType(); return INVALID_FINAL_COMBINATION.contains(node.getType()) || (TokenTypes.ANNOTATION == type && INVALID_FINAL_ANNOTATIONS.contains(node.findFirstToken(TokenTypes.IDENT).getText())); }); return illegalCombination.isPresent(); }
Source:
public Object getValue(final ELContext context, final Object base, final Object property) { Objects.requireNonNull(context, UndertowLogger.ROOT_LOGGER.nullNotAllowed("ELContext")); if (base != null) { return null; } if (!(property instanceof String)) { return null; } final String klassName = (String) property; final ImportHandler importHandler = context.getImportHandler(); if (importHandler == null) { return null; } Class<?> klass; if (WildFlySecurityManager.isChecking()) { klass = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { @Override public Class<?> run() { return importHandler.resolveClass(klassName); } }); } else { klass = importHandler.resolveClass(klassName); } if (klass != null) { context.setPropertyResolved(true); return new ELClass(klass); } return null; }

Target:
public Object getValue(final ELContext context, final Object base, final Object property) { Objects.requireNonNull(context, UndertowLogger.ROOT_LOGGER.nullNotAllowed("ELContext")); if (base != null) { return null; } if (!(property instanceof String)) { return null; } final String klassName = (String) property; final ImportHandler importHandler = context.getImportHandler(); if (importHandler == null) { return null; } final Class<?> klass; if (WildFlySecurityManager.isChecking()) { klass = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { @Override public Class<?> run() { return importHandler.resolveClass(klassName); } }); } else { klass = importHandler.resolveClass(klassName); } if (klass != null) { context.setPropertyResolved(true); return new ELClass(klass); } return null; }
Source:
private void addDefaultLanguageCookie(HttpServletRequest httpRequest, HttpServletResponse response) { Cookie languageCookie = null; if(!LOCALIZATION_CHINESE.equals(LOCALIZATION)) return; if(httpRequest.getCookies()!=null) { for(Cookie c : httpRequest.getCookies()) { if(DEFAULT_LANGUAGE.equals(c.getName()) && c.getName()!=null) { languageCookie = c; break; } } } if(languageCookie == null) { languageCookie = new Cookie(DEFAULT_LANGUAGE, LOCALIZATION_CHINESE); languageCookie.setPath("/"); response.addCookie(languageCookie); } }

Target:
private void addDefaultLanguageCookie(HttpServletRequest httpRequest, HttpServletResponse response) { Cookie languageCookie = null; if(!StringUtils.isNotBlank(LOCALIZATION.get())) return; if(httpRequest.getCookies()!=null) { for(Cookie c : httpRequest.getCookies()) { if(LANG.equals(c.getName()) && c.getName()!=null) { languageCookie = c; break; } } } if(languageCookie == null) { languageCookie = new Cookie(LANG, LOCALIZATION.get()); languageCookie.setPath("/"); response.addCookie(languageCookie); } }
Source:
public void writeTo(View t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { final Timer.Context context = metricRegistry.timer(name(t.getClass(), "rendering")).time(); try { for (ViewRenderer renderer : renderers) { if (renderer.isRenderable(t)) { renderer.render(t, detectLocale(headers), entityStream); return; } } throw new ViewRenderException("Unable to find a renderer for " + t.getTemplateName()); } catch (ViewRenderException e) { LOGGER.error("Template Error", e); throw new WebApplicationException(e); } finally { context.stop(); } }

Target:
public void writeTo(View t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { final Timer.Context context = metricRegistry.timer(name(t.getClass(), "rendering")).time(); try { for (ViewRenderer renderer : renderers) { if (renderer.isRenderable(t)) { renderer.render(t, detectLocale(headers), entityStream); return; } } throw new ViewRenderException("Unable to find a renderer for " + t.getTemplateName()); } catch (ViewRenderException e) { throw new WebApplicationException(e); } finally { context.stop(); } }
Source:
public boolean equals(Object object) { if (object == null) { return false; } if (!(object instanceof Connection)) { return false; } if (object == this) { return true; } Connection connection = (Connection) object; List<EObject> allFirstElements = new ArrayList<>(); allFirstElements.add(this.getOrigin()); allFirstElements.addAll(this.getTargets()); List<EObject> allSecondElements = new ArrayList<>(); allSecondElements.add(connection.getOrigin()); allSecondElements.addAll(connection.getTargets()); List<String> firstElementsIds = new ArrayList<>(); List<String> secondElementIds = new ArrayList<>(); String firstTraceType = ""; String secondTracetype = ""; for (EObject element : allFirstElements) { firstElementsIds.add(EMFHelper.getIdentifier(element)); } for (EObject element : allSecondElements) { secondElementIds.add(EMFHelper.getIdentifier(element)); } firstTraceType = EMFHelper.getIdentifier(this.getTlink().eClass()); secondTracetype = EMFHelper.getIdentifier(connection.getTlink().eClass()); return firstElementsIds.containsAll(secondElementIds) && firstTraceType.equals(secondTracetype); }

Target:
public boolean equals(Object object) { if (object == null) { return false; } if (!(object instanceof Connection)) { return false; } if (object == this) { return true; } Connection connection = (Connection) object; List<EObject> allFirstElements = new ArrayList<>(this.getTargets()); allFirstElements.add(this.getOrigin()); List<EObject> allSecondElements = new ArrayList<>(connection.getTargets()); allSecondElements.add(connection.getOrigin()); String firstTraceType = EMFHelper.getIdentifier(this.getTlink().eClass()); String secondTracetype = EMFHelper.getIdentifier(connection.getTlink().eClass()); if (!(firstTraceType.equals(secondTracetype))) { return false; } List<String> firstElementsIds = allFirstElements.stream().map(e -> EMFHelper.getIdentifier(e)) .collect(Collectors.toList()); List<String> secondElementsIds = allSecondElements.stream().map(e -> EMFHelper.getIdentifier(e)) .collect(Collectors.toList()); return firstElementsIds.containsAll(secondElementsIds); }
Source:
public void setUp() { cluster = new Cluster(); cluster.setId(clusterId); Network externalNetwork = new Network(); externalNetwork.setProvidedBy(new ProviderNetwork()); List<Network> networks = new ArrayList<>(); networks.add(new Network()); networks.add(externalNetwork); when(getQueryParameters().getId()).thenReturn(clusterId); when(clusterDao.get(clusterId)).thenReturn(cluster); when(networkDao.getAllForCluster(clusterId, getUser().getId(), getQueryParameters().isFiltered())).thenReturn( networks); }

Target:
public void setUp() { cluster = new Cluster(); cluster.setId(clusterId); externalNetwork = new Network(); setIsValidProvidedBy(true); List<Network> networks = new ArrayList<>(); networks.add(new Network()); networks.add(externalNetwork); when(getQueryParameters().getId()).thenReturn(clusterId); when(clusterDao.get(clusterId)).thenReturn(cluster); when(networkDao.getAllForCluster(clusterId, getUser().getId(), getQueryParameters().isFiltered())).thenReturn( networks); }
Source:
public String getContentTypeFieldLabelKey(){ String legacyName = LegacyFieldTypes.getLegacyName(this.getClass()); String key = legacyName.substring(0, 1).toUpperCase() + legacyName.substring(1); return key; }

Target:
public String getContentTypeFieldLabelKey(){ String legacyName = LegacyFieldTypes.getLegacyName(this.getClass()); return legacyName.substring(0, 1).toUpperCase() + legacyName.substring(1); }
Source:
public HL7Recipient(String recipientName, String recipientUrl, String recipientUsername, String recipientPassword) { this(recipientName, recipientUrl); this.recipientPassword = recipientPassword; this.recipientUsername = recipientUsername; }

Target:
public HL7Recipient(String recipientName, String recipientUrl, String recipientUsername, String recipientPassword) { this.recipientName = recipientName; this.recipientUrl = recipientUrl; this.recipientUsername = recipientUsername; this.recipientPassword = recipientPassword; }
Source:
private static boolean isPackage(String qualifier) { checkNotNull(qualifier); checkArgument(!qualifier.isEmpty()); int indexOfWildcardChar = qualifier.indexOf(PACKAGE_WILDCARD_INDICATOR); int qualifierLength = qualifier.length(); boolean result = indexOfWildcardChar == (qualifierLength - PACKAGE_WILDCARD_INDICATOR.length()); return result; }

Target:
private static boolean isPackage(String qualifier) { checkNotEmptyOrBlank(qualifier); int indexOfWildcardChar = qualifier.indexOf(PACKAGE_WILDCARD_INDICATOR); int qualifierLength = qualifier.length(); boolean result = indexOfWildcardChar == (qualifierLength - PACKAGE_WILDCARD_INDICATOR.length()); return result; }
Source:
public void addToClipboard(List<T> items) throws CloneNotSupportedException, IOException { for (T item : items) { clipboard.add((T) item.clone()); item.copyResourcesToDirectory(ClipboardHandler.getInstance().getClipboardDirectory()); } }

Target:
public void addToClipboard(List<T> items) throws CloneNotSupportedException, IOException { for (T item : items) { T clone = (T) item.clone(); clone.copyResourcesToDirectory(ClipboardHandler.getClipboardDirectory()); clipboard.add(clone); } }
Source:
public ResponseEntity<?> getPartition(@PathVariable("name") final String eventTypeName, @PathVariable("partition") final String partition, @Nullable @RequestParam(value = "consumed_offset", required = false) final String consumedOffset, final NativeWebRequest request, final Client client) { LOG.trace("Get partition endpoint for event-type '{}', partition '{}' is called", eventTypeName, partition); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); authorizeStreamRead(authorizationService, client, eventType); if (consumedOffset != null) { final CursorLag cursorLag = getCursorLag(eventTypeName, partition, consumedOffset); return ok().body(cursorLag); } else { final EventTypePartitionView result = getTopicPartition(eventTypeName, partition); return ok().body(result); } } catch (final NoSuchEventTypeException e) { return create(Problem.valueOf(NOT_FOUND, "topic not found"), request); } catch (final NakadiException e) { LOG.error("Could not get partition. Respond with SERVICE_UNAVAILABLE.", e); return create(e.asProblem(), request); } catch (final InvalidCursorException e) { return create(Problem.valueOf(MoreStatus.UNPROCESSABLE_ENTITY, INVALID_CURSOR_MESSAGE), request); } }

Target:
public ResponseEntity<?> getPartition(@PathVariable("name") final String eventTypeName, @PathVariable("partition") final String partition, @Nullable @RequestParam(value = "consumed_offset", required = false) final String consumedOffset, final NativeWebRequest request, final Client client) { LOG.trace("Get partition endpoint for event-type '{}', partition '{}' is called", eventTypeName, partition); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); authorizationValidator.authorizeStreamRead(client, eventType); if (consumedOffset != null) { final CursorLag cursorLag = getCursorLag(eventTypeName, partition, consumedOffset); return ok().body(cursorLag); } else { final EventTypePartitionView result = getTopicPartition(eventTypeName, partition); return ok().body(result); } } catch (final NoSuchEventTypeException e) { return create(Problem.valueOf(NOT_FOUND, "topic not found"), request); } catch (final NakadiException e) { LOG.error("Could not get partition. Respond with SERVICE_UNAVAILABLE.", e); return create(e.asProblem(), request); } catch (final InvalidCursorException e) { return create(Problem.valueOf(MoreStatus.UNPROCESSABLE_ENTITY, INVALID_CURSOR_MESSAGE), request); } }
Source:
public Map<Long, UserPreference> getUsersPreference(String preferenceType, String preferenceName, List<RegisteredUserDTO> users) throws SegueDatabaseException { Validate.notBlank(preferenceType); Validate.notBlank(preferenceName); Map<Long, UserPreference> usersPreferenceMap = Maps.newHashMap(); int pageSize = 10000; int fromIndex = 0; int toIndex = min(pageSize, users.size()); while (fromIndex < toIndex) { List<RegisteredUserDTO> pagedUsers = users.subList(fromIndex, toIndex); try (Connection conn = database.getDatabaseConnection()) { PreparedStatement pst; StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM user_preferences WHERE user_id IN ("); for (int i = 0; i < pagedUsers.size(); i++) { sb.append("?").append(i < pagedUsers.size() - 1 ? ", " : ""); } sb.append(") AND preference_type=? AND preference_name=? ORDER BY user_id ASC;"); pst = conn.prepareStatement(sb.toString()); for (int i = 1; i <= pagedUsers.size(); i++) { pst.setLong(i, pagedUsers.get(i - 1).getId()); } pst.setString(pagedUsers.size() + 1, preferenceType); pst.setString(pagedUsers.size() + 2, preferenceName); ResultSet results = pst.executeQuery(); while (results.next()) { Long userId = results.getLong("user_id"); UserPreference pref = new UserPreference(userId, results.getString("preference_type"), results.getString("preference_name"), results.getBoolean("preference_value")); usersPreferenceMap.put(userId, pref); } fromIndex = toIndex; toIndex = min(toIndex + pageSize, users.size()); } catch (SQLException e) { throw new SegueDatabaseException("Postgres exception", e); } } return usersPreferenceMap; }

Target:
public Map<Long, UserPreference> getUsersPreference(String preferenceType, String preferenceName, List<RegisteredUserDTO> users) throws SegueDatabaseException { Validate.notBlank(preferenceType); Validate.notBlank(preferenceName); Map<Long, UserPreference> usersPreferenceMap = Maps.newHashMap(); int pageSize = 10000; int fromIndex = 0; int toIndex = min(pageSize, users.size()); while (fromIndex < toIndex) { List<RegisteredUserDTO> pagedUsers = users.subList(fromIndex, toIndex); try (Connection conn = database.getDatabaseConnection()) { PreparedStatement pst; StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM user_preferences WHERE user_id IN ("); for (int i = 0; i < pagedUsers.size(); i++) { sb.append("?").append(i < pagedUsers.size() - 1 ? ", " : ""); } sb.append(") AND preference_type=? AND preference_name=? ORDER BY user_id ASC;"); pst = conn.prepareStatement(sb.toString()); for (int i = 1; i <= pagedUsers.size(); i++) { pst.setLong(i, pagedUsers.get(i - 1).getId()); } pst.setString(pagedUsers.size() + 1, preferenceType); pst.setString(pagedUsers.size() + 2, preferenceName); ResultSet results = pst.executeQuery(); while (results.next()) { Long userId = results.getLong("user_id"); UserPreference pref = userPreferenceFromResultSet(results); usersPreferenceMap.put(userId, pref); } fromIndex = toIndex; toIndex = min(toIndex + pageSize, users.size()); } catch (SQLException e) { throw new SegueDatabaseException("Postgres exception", e); } } return usersPreferenceMap; }
Source:
void startRenamingProcess(String name, int maxAmount) { currentName = name; currentMaxAmount = maxAmount; renamingDialog.getInputEditText().setText(name); if (maxAmount > 1) { renameAmountDialog.setActionButton(DialogAction.NEUTRAL, R.string.all_of_them); renameAmountDialog.setContent(R.string.multiple_renames_title, name , maxAmount); EditText input = renameAmountDialog.getInputEditText(); if (input != null) { input.setText("" + maxAmount); input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(String.valueOf(maxAmount).length())}); } renameAmountDialog.show(); } else { amountToRename = 1; renamingDialog.setActionButton(DialogAction.NEUTRAL, null); renamingDialog.show(); } }

Target:
public void startRenamingProcess(String name, int maxAmount) { currentName = name; currentMaxAmount = maxAmount; renamingDialog.getInputEditText().setText(name); if (maxAmount > 1) { EditText input = renameAmountDialog.getInputEditText(); if (input != null) { input.setText(""); input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(String.valueOf(maxAmount).length())}); } renameAmountDialog.show(); } else { amountToRename = 1; renamingDialog.setActionButton(DialogAction.NEUTRAL, null); renamingDialog.show(); } }
Source:
public Integer getMaxConcurrency() throws IOException { final String concurrency = (String) this.client.getConfig().get(getMaxConcurrencyConfigName()); return concurrency == null ? null : Integer.parseInt(concurrency); }

Target:
public int getMaxConcurrency() throws IOException { final String concurrency = (String) this.client.getConfig().get(getMaxConcurrencyConfigName()); return concurrency == null ? -1 : Integer.parseInt(concurrency); }
Source:
public List<Long> histogramQuery(final long start, final long end, final int nb) { final List<Long> list = new LinkedList<Long>(); final long increment = (end - start) / nb; waitUntilBuilt(); long prevTotal = (start == totalsStats.getStartTime()) ? 0 : getEventCountAt(start); long curTime = start + increment; long curTotal, count; for (int i = 0; i < nb - 1; i++) { curTotal = getEventCountAt(curTime); count = curTotal - prevTotal; list.add(count); curTime += increment; prevTotal = curTotal; } curTotal = getEventCountAt(end); count = curTotal - prevTotal; list.add(count); return list; }

Target:
public List<Long> histogramQuery(final long start, final long end, final int nb) { final List<Long> list = new LinkedList<Long>(); final long increment = (end - start) / nb; if (!totalsStats.waitUntilBuilt()) { return list; } long prevTotal = (start == totalsStats.getStartTime()) ? 0 : getEventCountAt(start); long curTime = start + increment; long curTotal, count; for (int i = 0; i < nb - 1; i++) { curTotal = getEventCountAt(curTime); count = curTotal - prevTotal; list.add(count); curTime += increment; prevTotal = curTotal; } curTotal = getEventCountAt(end); count = curTotal - prevTotal; list.add(count); return list; }