auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initializeProbabilityVector(MatrixLib p) { double[] pi = new double[p.numCols()]; double sum = 0.0; for (int i = 0; i < p.numCols(); i++) { double ele = p.elementAt(0, i); if (ele < 0) { throw new IllegalArgumentException("Probability " + ele + " for element " + i + " is negative."); } sum += p.elementAt(0, i); } if (sum < 1e-9) { throw new IllegalArgumentException("Probabilities sum to approx zero"); } for (int i = 0; i < p.numCols(); i++) { pi[i] = p.elementAt(0, i) / sum; } this.p = pi; this.k = this.p.length; this.pCDF = new double[k]; pCDF[0] = this.p[0]; for (int i = 1; i < k; i++) { this.pCDF[i] = pCDF[i - 1] + this.p[i]; } }

Target:
private void initializeProbabilityVector(MatrixLib p) { double sum = 0.0; for (int i = 0; i < p.numCols(); i++) { double ele = p.elementAt(0, i); if (ele < 0) { throw new IllegalArgumentException("Probability " + ele + " for element " + i + " is negative."); } sum += ele; } if (sum < 1e-9) { throw new IllegalArgumentException("Probabilities sum to approx zero"); } this.k = p.numCols(); this.p = new double[k]; this.pCDF = new double[k]; this.p[0] = p.elementAt(0, 0) / sum; pCDF[0] = this.p[0]; for (int i = 1; i < p.numCols(); i++) { this.p[i] = p.elementAt(0, i) / sum; this.pCDF[i] = pCDF[i - 1] + this.p[i]; } }
Source:
private void prepFeeders() throws JobProcessorException { fireTextStatus("Preparing feeders."); Machine machine = Configuration.get().getMachine(); for (Feeder feeder : machine.getFeeders()) { if (feeder.isEnabled() && feeder.getPart() != null) { for (JobPlacement placement : getPendingJobPlacements()) { if (placement.getPartId() == feeder.getPart().getId()) { try { feeder.prepareForJob(); } catch (Exception e) { throw new JobProcessorException(feeder, e); } } } } } }

Target:
private void prepFeeders() throws JobProcessorException { fireTextStatus("Preparing feeders."); Machine machine = Configuration.get().getMachine(); List<Feeder> feederList = new ArrayList<>(); for (Feeder feeder : machine.getFeeders()) { if (feeder.isEnabled() && feeder.getPart() != null) { for (JobPlacement placement : getPendingJobPlacements()) { if (placement.getPartId() == feeder.getPart().getId()) { feederList.add(feeder); } } } } for (Feeder feeder : feederList) { try { feeder.prepareForJob(feederList); } catch (Exception e) { throw new JobProcessorException(feeder, e); } } }
Source:
private static Comparable zeroValue(RelDataType type) { switch (type.getSqlTypeName()) { case CHAR: return new NlsString(Spaces.of(type.getPrecision()), null, null); case VARCHAR: return new NlsString("", null, null); case BINARY: return new ByteString(new byte[type.getPrecision()]); case VARBINARY: return ByteString.EMPTY; case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case DECIMAL: case FLOAT: case REAL: case DOUBLE: return BigDecimal.ZERO; case BOOLEAN: return false; case TIME: case DATE: case TIMESTAMP: return DateTimeUtils.ZERO_CALENDAR; case TIME_WITH_LOCAL_TIME_ZONE: return new TimeString(0, 0, 0); case TIMESTAMP_WITH_LOCAL_TIME_ZONE: return new TimestampString(0, 0, 0, 0, 0, 0); case TIME_WITH_TIME_ZONE: return new TimeWithTimeZoneString(0, 0, 0, "UTC"); case TIMESTAMP_WITH_TIME_ZONE: return new TimestampWithTimeZoneString(0, 0, 0, 0, 0, 0, "UTC"); default: throw Util.unexpected(type.getSqlTypeName()); } }

Target:
private static Comparable zeroValue(RelDataType type) { switch (type.getSqlTypeName()) { case CHAR: return new NlsString(Spaces.of(type.getPrecision()), null, null); case VARCHAR: return new NlsString("", null, null); case BINARY: return new ByteString(new byte[type.getPrecision()]); case VARBINARY: return ByteString.EMPTY; case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case DECIMAL: case FLOAT: case REAL: case DOUBLE: return BigDecimal.ZERO; case BOOLEAN: return false; case TIME: case DATE: case TIMESTAMP: return DateTimeUtils.ZERO_CALENDAR; case TIME_WITH_LOCAL_TIME_ZONE: return new TimeString(0, 0, 0); case TIMESTAMP_WITH_LOCAL_TIME_ZONE: return new TimestampString(0, 0, 0, 0, 0, 0); case TIME_WITH_TIME_ZONE: return new TimeWithTimeZoneString(0, 0, 0, "UTC"); case TIMESTAMP_WITH_TIME_ZONE: return new TimestampWithTimeZoneString(1970, 1, 1, 0, 0, 0, "UTC"); default: throw Util.unexpected(type.getSqlTypeName()); } }
Source:
public MythicSkillCommand() { setName("mythicskill"); setSyntax("mythicskill [<skillname>] (<location>|...) (<entity>|...) (power:<#.#>) (casters:<entity>|..)"); setRequiredArguments(1, 5); }

Target:
public MythicSkillCommand() { setName("mythicskill"); setSyntax("mythicskill [<skillname>] [<location>|.../<entity>|...] (power:<#.#>) (casters:<entity>|...)"); setRequiredArguments(2, 5); }
Source:
@Override public LinearRegressionModel train(Matrix data) { long ts1 = System.currentTimeMillis(); Vector groundTruth = extractGroundTruth(data); Matrix inputs = extractInputs(data); long ts2 = System.currentTimeMillis(); QRDecomposition decomposition = new QRDecomposition(inputs); long ts3 = System.currentTimeMillis(); QRDSolver solver = new QRDSolver(decomposition.getQ(), decomposition.getR()); Vector variables = solver.solve(groundTruth); long ts4 = System.currentTimeMillis(); Vector weights = variables.viewPart(1, variables.size() - 1); double intercept = variables.get(0); return new LinearRegressionModel(weights, intercept); }

Target:
@Override public LinearRegressionModel train(Matrix data) { Vector groundTruth = extractGroundTruth(data); Matrix inputs = extractInputs(data); QRDecomposition decomposition = new QRDecomposition(inputs); QRDSolver solver = new QRDSolver(decomposition.getQ(), decomposition.getR()); Vector variables = solver.solve(groundTruth); Vector weights = variables.viewPart(1, variables.size() - 1); double intercept = variables.get(0); return new LinearRegressionModel(weights, intercept); }
Source:
private void documentEnded(boolean pushing, String docID, String revID, int flags, C4Error error, boolean trans) { if (!pushing && error.getDomain() == LiteCoreDomain && error.getCode() == kC4ErrorConflict) { Log.i(TAG, "%s: pulled conflicting version of '%s'", this, docID); try { this.config.getDatabase().resolveConflictInDocument(docID); } catch (CouchbaseLiteException ex) { Log.e(TAG, "Failed to resolveConflict: docID -> %s", ex, docID); } } else if(error.getDomain()==0 && error.getCode()==0) { DocumentReplicatedUpdate update = new DocumentReplicatedUpdate((Replicator) this,true, flags == C4Constants.C4RevisionFlags.kRevDeleted, pushing, docID); synchronized (docEndedListenerTokens) { for (DocumentReplicatedListenerToken token : docEndedListenerTokens) token.notify(update); } Log.i(TAG, "C4ReplicatorListener.documentEnded() pushing -> %s, docID -> %s, error -> %s, trans -> %s", pushing ? "true" : false, docID, error, trans ? "true" : false); } else { Log.i(TAG, "C4ReplicatorListener.documentError() pushing -> %s, docID -> %s, error -> %s, trans -> %s", pushing ? "true" : false, docID, error, trans ? "true" : false); } }

Target:
private void documentEnded(boolean pushing, String docID, String revID, int flags, C4Error error, boolean trans) { DocumentReplication update = new DocumentReplication((Replicator) this, flags == C4Constants.C4RevisionFlags.kRevDeleted, pushing, docID, revID, flags, error, trans); if (!pushing && error.getDomain() == LiteCoreDomain && error.getCode() == kC4ErrorConflict) { Log.i(TAG, "%s: pulled conflicting version of '%s'", this, docID); try { this.config.getDatabase().resolveConflictInDocument(docID); } catch (CouchbaseLiteException ex) { Log.e(TAG, "Failed to resolveConflict: docID -> %s", ex, docID); } } notifyDocumentEnded(update); }
Source:
public MyLoggingFilter() { super(null, true); System.out.println("MyLoggingFilter running"); }

Target:
public MyLoggingFilter() { super(null, true); }
Source:
private boolean isAdAggregatorIdValid(Bond bond, HostInterfaceLineModel lineModel) { String bondAdAggregatorId = Objects.toString(bond.getAdAggregatorId()); if (bondAdAggregatorId==null) { return false; } for (HostInterface nic : lineModel.getInterfaces()) { String nicAggregatorId = Objects.toString(nic.getInterface().getAdAggregatorId()); if (!bondAdAggregatorId.equals(nicAggregatorId)) { return false; } } return true; }

Target:
private boolean isAdAggregatorIdValid(Bond bond, HostInterfaceLineModel lineModel) { Integer aggregatorId = bond.getAdAggregatorId(); if (aggregatorId == null) { return false; } String bondAdAggregatorId = Objects.toString(aggregatorId); for (HostInterface nic : lineModel.getInterfaces()) { String nicAggregatorId = Objects.toString(nic.getInterface().getAdAggregatorId()); if (!bondAdAggregatorId.equals(nicAggregatorId)) { return false; } } return true; }
Source:
protected Boolean doGetValue() { return tracked.isStale() ? Boolean.TRUE : Boolean.FALSE; }

Target:
protected Boolean doGetValue() { return tracked.isStale(); }
Source:
private String enableCapabilities() throws TransportException { final StringBuilder line = new StringBuilder(); if (noProgress) wantCapability(line, OPTION_NO_PROGRESS); if (includeTags) includeTags = wantCapability(line, OPTION_INCLUDE_TAG); if (allowOfsDelta) wantCapability(line, OPTION_OFS_DELTA); if (wantCapability(line, OPTION_MULTI_ACK_DETAILED)) { multiAck = MultiAck.DETAILED; if (statelessRPC) noDone = wantCapability(line, OPTION_NO_DONE); } else if (wantCapability(line, OPTION_MULTI_ACK)) multiAck = MultiAck.CONTINUE; else multiAck = MultiAck.OFF; if (thinPack) thinPack = wantCapability(line, OPTION_THIN_PACK); if (wantCapability(line, OPTION_SIDE_BAND_64K)) sideband = true; else if (wantCapability(line, OPTION_SIDE_BAND)) sideband = true; if (statelessRPC && multiAck != MultiAck.DETAILED) { throw new PackProtocolException(uri, MessageFormat.format( JGitText.get().statelessRPCRequiresOptionToBeEnabled, OPTION_MULTI_ACK_DETAILED)); } if (filterBlobLimit >= 0) { wantCapability(line, OPTION_FILTER); } addUserAgentCapability(line); return line.toString(); }

Target:
private String enableCapabilities() throws TransportException { final StringBuilder line = new StringBuilder(); if (noProgress) wantCapability(line, OPTION_NO_PROGRESS); if (includeTags) includeTags = wantCapability(line, OPTION_INCLUDE_TAG); if (allowOfsDelta) wantCapability(line, OPTION_OFS_DELTA); if (wantCapability(line, OPTION_MULTI_ACK_DETAILED)) { multiAck = MultiAck.DETAILED; if (statelessRPC) noDone = wantCapability(line, OPTION_NO_DONE); } else if (wantCapability(line, OPTION_MULTI_ACK)) multiAck = MultiAck.CONTINUE; else multiAck = MultiAck.OFF; if (thinPack) thinPack = wantCapability(line, OPTION_THIN_PACK); if (wantCapability(line, OPTION_SIDE_BAND_64K)) sideband = true; else if (wantCapability(line, OPTION_SIDE_BAND)) sideband = true; if (statelessRPC && multiAck != MultiAck.DETAILED) { throw new PackProtocolException(uri, MessageFormat.format( JGitText.get().statelessRPCRequiresOptionToBeEnabled, OPTION_MULTI_ACK_DETAILED)); } if (filterBlobLimit >= 0) { if (!wantCapability(line, OPTION_FILTER)) { throw new PackProtocolException(uri, JGitText.get().filterRequiresCapability); } } addUserAgentCapability(line); return line.toString(); }
Source:
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { TileAlchemyArray array = (TileAlchemyArray) world.getTileEntity(pos); if (array == null) return false; if (player.isSneaking() && array.rotateCooldown == 0) { array.setRotation(array.getRotation().rotateY()); array.rotateCooldown = 5; world.notifyBlockUpdate(pos, state, state, 3); return false; } ItemStack playerItem = player.getHeldItem(hand); if (!playerItem.isEmpty()) { if (array.getStackInSlot(0).isEmpty()) { Utils.insertItemToTile(array, player, 0); } else if (!array.getStackInSlot(0).isEmpty()) { Utils.insertItemToTile(array, player, 1); array.attemptCraft(); } else { return true; } if (array.arrayEffect instanceof AlchemyArrayEffectMovement && (playerItem.getItem() == Items.REDSTONE || playerItem.getItem() == Items.FEATHER) || array.arrayEffect instanceof AlchemyArrayEffectUpdraft && (playerItem.getItem() == Items.FEATHER || playerItem.getItem() == Items.GLOWSTONE_DUST)) { for (int i = 0; i < array.getSizeInventory(); i++) { ItemStack stack = array.getStackInSlot(i); if (stack.getItem() == playerItem.getItem()) { if (stack.getCount() < 127) { stack.setCount(stack.getCount() + 1); playerItem.shrink(1); } break; } } world.notifyBlockUpdate(pos, state, state, 3); return true; } } world.notifyBlockUpdate(pos, state, state, 3); return true; }

Target:
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { TileAlchemyArray array = (TileAlchemyArray) world.getTileEntity(pos); if (array == null) return false; if (player.isSneaking() && array.rotateCooldown == 0) { array.setRotation(array.getRotation().rotateY()); array.rotateCooldown = 5; world.notifyBlockUpdate(pos, state, state, 3); return false; } ItemStack playerItem = player.getHeldItem(hand); if (!playerItem.isEmpty()) { if (array.getStackInSlot(0).isEmpty()) { Utils.insertItemToTile(array, player, 0); } else if (!array.getStackInSlot(0).isEmpty()) { Utils.insertItemToTile(array, player, 1); array.attemptCraft(); } else { return true; } if (array.arrayEffect instanceof AlchemyArrayEffectMovement && (playerItem.getItem() == Items.REDSTONE || playerItem.getItem() == Items.FEATHER) || array.arrayEffect instanceof AlchemyArrayEffectUpdraft && (playerItem.getItem() == Items.FEATHER || playerItem.getItem() == Items.GLOWSTONE_DUST)) { for (int i = 0; i < array.getSizeInventory(); i++) { ItemStack stack = array.getStackInSlot(i); if (ItemStack.areItemsEqual(stack, playerItem)) { if (stack.getCount() < 127) { stack.setCount(stack.getCount() + 1); playerItem.shrink(1); } break; } } world.notifyBlockUpdate(pos, state, state, 3); return true; } } world.notifyBlockUpdate(pos, state, state, 3); return true; }
Source:
public void setupMocks() { dataStore = mock(DataStore.class); asyncQuery = mock(AsyncQuery.class); tx = mock(DataStoreTransaction.class); asyncQueryResultStorage = mock(AsyncQueryResultStorage.class); Map<String, Class<? extends Check>> checkMappings = new HashMap<>(); dictionary = new EntityDictionary(checkMappings); dictionary.bindEntity(AsyncQuery.class); dictionary.bindEntity(AsyncQueryResult.class); ElideSettings elideSettings = new ElideSettingsBuilder(dataStore) .withEntityDictionary(dictionary) .withJoinFilterDialect(new RSQLFilterDialect(dictionary)) .withSubqueryFilterDialect(new RSQLFilterDialect(dictionary)) .withISO8601Dates("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC")) .build(); elide = new Elide(elideSettings); when(dataStore.beginTransaction()).thenReturn(tx); asyncQueryDAO = new com.yahoo.elide.async.service.DefaultAsyncQueryDAO(elide, dataStore); defaultResultStorageEngine = new com.yahoo.elide.async.service.DefaultResultStorageEngine(elide, dataStore, "http://localhost:8080"); }

Target:
public void setupMocks() { dataStore = mock(DataStore.class); tx = mock(DataStoreTransaction.class); Map<String, Class<? extends Check>> checkMappings = new HashMap<>(); EntityDictionary dictionary = new EntityDictionary(checkMappings); dictionary.bindEntity(AsyncQuery.class); dictionary.bindEntity(AsyncQueryResult.class); ElideSettings elideSettings = new ElideSettingsBuilder(dataStore) .withEntityDictionary(dictionary) .withJoinFilterDialect(new RSQLFilterDialect(dictionary)) .withSubqueryFilterDialect(new RSQLFilterDialect(dictionary)) .withISO8601Dates("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC")) .build(); elide = new Elide(elideSettings); when(dataStore.beginTransaction()).thenReturn(tx); defaultResultStorageEngine = new DefaultResultStorageEngine("/api/v1/download", elide.getElideSettings(), dataStore); }
Source:
public void returnsEmptyIteratorOnInvalidPartRequest() throws Exception { final String body = "443 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMtFake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), new FormattedText( "Content-Length: %s", body.getBytes().length ).asString(), "Content-Disposition: form-data; name=\"t5\"" ), new RqWithHeaders( new RqFake("", "", ""), "Content-Length: 0", "Content-Disposition: form-data; name=\"data\"; filename=\"a.zip\"" ) ); MatcherAssert.assertThat( multi.part("fake").iterator().hasNext(), Matchers.is(false) ); multi.body().close(); }

Target:
public void returnsEmptyIteratorOnInvalidPartRequest() throws Exception { final String body = "443 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMtFake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), new FormattedText( RqMtFakeTest.CONTENT_LENGTH, body.getBytes().length ).asString(), new FormattedText( RqMtFakeTest.CONTENT_DISP, "name=\"t5\"" ).asString() ), new RqWithHeaders( new RqFake("", "", ""), new FormattedText(RqMtFakeTest.CONTENT_LENGTH, 0).asString(), new FormattedText( RqMtFakeTest.CONTENT_DISP, "name=\"data\"; filename=\"a.zip\"" ).asString() ) ); MatcherAssert.assertThat( multi.part("fake").iterator().hasNext(), Matchers.is(false) ); multi.body().close(); }
Source:
public static String createExclusionFieldString(List<String> excludeList) { String[] excludeArray = new String[excludeList.size()]; for (int i = 0; i < excludeList.size(); i++) { excludeArray[i] = String.format("'%s' : 0", excludeList.get(i)); } return "{ " + StringUtils.join(excludeArray, ", ") + " }"; }

Target:
public static String createExclusionFieldString(List<String> excludeList) { List<String> formattedList = excludeList.stream().map(field -> String.format("'%s' : 0", field)) .collect(Collectors.toList()); return "{ " + String.join(", ", formattedList) + " }"; }
Source:
private void scanRoot(Node n) { if (n.isFunction()) { if (inputId == null) { inputId = NodeUtil.getInputId(n); } final Node fnNameNode = n.getFirstChild(); final Node args = fnNameNode.getNext(); String fnName = fnNameNode.getString(); if (!fnName.isEmpty() && NodeUtil.isFunctionExpression(n)) { declareVar(fnNameNode); } Preconditions.checkState(args.isParamList()); for (Node a = args.getFirstChild(); a != null; a = a.getNext()) { if (a.isDefaultValue() || a.isRest()) { declareLHS(scope, a.getFirstChild()); } else { declareLHS(scope, a); } } } else if (n.isClass()) { if (scope.getParent() != null) { inputId = NodeUtil.getInputId(n); } final Node classNameNode = n.getFirstChild(); if (!classNameNode.isEmpty()) { String className = classNameNode.getString(); if (!className.isEmpty() && NodeUtil.isClassExpression(n)) { declareVar(classNameNode); } } } else if (n.isBlock() || n.isFor() || n.isForOf() || n.isSwitch()) { if (scope.getParent() != null) { inputId = NodeUtil.getInputId(n); } scanVars(n); } else { Preconditions.checkState(scope.getParent() == null); scanVars(n); } }

Target:
private void scanRoot(Node n) { if (n.isFunction()) { if (inputId == null) { inputId = NodeUtil.getInputId(n); } final Node fnNameNode = n.getFirstChild(); final Node args = fnNameNode.getNext(); String fnName = fnNameNode.getString(); if (!fnName.isEmpty() && NodeUtil.isFunctionExpression(n)) { declareVar(fnNameNode); } Preconditions.checkState(args.isParamList()); for (Node a = args.getFirstChild(); a != null; a = a.getNext()) { if (a.isDefaultValue() || a.isRest()) { declareLHS(scope, a.getFirstChild()); } else { declareLHS(scope, a); } } } else if (n.isClass()) { if (scope.getParent() != null) { inputId = NodeUtil.getInputId(n); } final Node classNameNode = n.getFirstChild(); if (!classNameNode.isEmpty()) { if (NodeUtil.isClassExpression(n)) { declareVar(classNameNode); } } } else if (n.isBlock() || n.isFor() || n.isForOf() || n.isSwitch()) { if (scope.getParent() != null) { inputId = NodeUtil.getInputId(n); } scanVars(n); } else { Preconditions.checkState(scope.getParent() == null); scanVars(n); } }
Source:
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (!active) { return; } if (cause instanceof ReadTimeoutException) { ActiveMQClientLogger.LOGGER.error("Connection without communication timeout has expired."); } ActiveMQException me = ActiveMQClientMessageBundle.BUNDLE.nettyError(); me.initCause(cause); synchronized (listener) { try { listener.connectionException(channelId(ctx.channel()), me); active = false; } catch (Exception ex) { ActiveMQClientLogger.LOGGER.errorCallingLifeCycleListener(ex); } } }

Target:
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { if (!active) { return; } ActiveMQException me = ActiveMQClientMessageBundle.BUNDLE.nettyError(); me.initCause(cause); synchronized (listener) { try { listener.connectionException(channelId(ctx.channel()), me); active = false; } catch (Exception ex) { ActiveMQClientLogger.LOGGER.errorCallingLifeCycleListener(ex); } } }
Source:
private void calculateHashes(AbstractFile file, IngestJobTotals totals) throws TskCoreException { String md5Hash = file.getMd5Hash(); String sha256Hash = file.getSha256Hash(); if ((md5Hash != null && md5Hash.isEmpty()) && (sha256Hash != null && sha256Hash.isEmpty())) { return; } TimingMetric metric = HealthMonitor.getTimingMetric("Disk Reads: Hash calculation"); long calcstart = System.currentTimeMillis(); List<HashUtility.HashResult> newHashResults = HashUtility.calculateHashes(file, Arrays.asList(HashUtility.HashType.MD5,HashUtility.HashType.SHA256 )); if (file.getSize() > 0) { if (file.getSize() < 1000000) { HealthMonitor.submitTimingMetric(metric); } else { HealthMonitor.submitNormalizedTimingMetric(metric, file.getSize() / 500000); } } for (HashUtility.HashResult hash : newHashResults) { if (hash.getType().equals(HashUtility.HashType.MD5)) { file.setMd5Hash(hash.getValue()); } else if (hash.getType().equals(HashUtility.HashType.SHA256)) { file.setSha256Hash(hash.getValue()); } } long delta = (System.currentTimeMillis() - calcstart); totals.totalCalctime.addAndGet(delta); }

Target:
private void calculateHashes(AbstractFile file, IngestJobTotals totals) throws TskCoreException { String md5Hash = file.getMd5Hash(); String sha256Hash = file.getSha256Hash(); if ((md5Hash != null && ! md5Hash.isEmpty()) && (sha256Hash != null && ! sha256Hash.isEmpty())) { return; } TimingMetric metric = HealthMonitor.getTimingMetric("Disk Reads: Hash calculation"); long calcstart = System.currentTimeMillis(); List<HashUtility.HashResult> newHashResults = HashUtility.calculateHashes(file, Arrays.asList(HashUtility.HashType.MD5,HashUtility.HashType.SHA256 )); if (file.getSize() > 0) { if (file.getSize() < 1000000) { HealthMonitor.submitTimingMetric(metric); } else { HealthMonitor.submitNormalizedTimingMetric(metric, file.getSize() / 500000); } } for (HashUtility.HashResult hash : newHashResults) { if (hash.getType().equals(HashUtility.HashType.MD5)) { file.setMd5Hash(hash.getValue()); } else if (hash.getType().equals(HashUtility.HashType.SHA256)) { file.setSha256Hash(hash.getValue()); } } long delta = (System.currentTimeMillis() - calcstart); totals.totalCalctime.addAndGet(delta); }
Source:
public String toString() { return "DatabaseInfo{" + "Location='" + mLocation + '\'' + ", OwnerName='" + mOwnerName + '\'' + ", OwnerType=" + mOwnerType + ", Comment='" + mComment + '\'' + ", Parameters=" + mParameters + '}'; }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("location", mLocation) .add("ownerName", mOwnerName) .add("ownerType", mOwnerType) .add("comment", mComment) .add("parameters", mParameters) .toString(); }
Source:
protected boolean canDoAction() { parameters = getParameters(); if (super.canDoAction() && getGeoRepSession().getStatus() == GeoRepSessionStatus.ACTIVE) { GlusterVolumeEntity masterVolume = getGlusterVolume(); if (masterVolume.getStatus() == GlusterStatus.UP) { VDS slaveVds = getVdsDAO().getByName(parameters.getSlaveHost()); if(slaveVds != null) { GlusterVolumeEntity slaveVolumeEntity = getGlusterVolumeDao().getByName(slaveVds.getVdsGroupId(), parameters.getSlaveVolumeName()); return (slaveVolumeEntity == null ? false : slaveVolumeEntity.getStatus() == GlusterStatus.UP) && (masterVolume.getAdvancedDetails().getCapacityInfo().getFreeSize() < slaveVolumeEntity.getAdvancedDetails().getCapacityInfo().getFreeSize()); } else { return true; } } else { return false; } } else { if(getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_PAUSED); } return false; } }

Target:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }
Source:
public Response uploadCompleted(@PathParam(REQUEST_BATCH_ID) String batchId , @PathParam(REQUEST_FILE_IDX) String fileIdx, String body ) throws Exception { JsonNode jsonNode = new ObjectMapper().readTree(body); Batch batch = batchManager.getBatch(batchId); if (batch == null) { return Response.status(Status.NOT_FOUND).build(); } Long fileSize = jsonNode.hasNonNull("fileSize") ? jsonNode.get("fileSize").asLong() : -1L; String md5 = jsonNode.hasNonNull("md5") ? jsonNode.get("md5").asText() : null; String name = jsonNode.hasNonNull("name") ? jsonNode.get("name").asText() : null; String mimeType = jsonNode.hasNonNull("mimeType") ? jsonNode.get("mimeType").asText(null) : null; String key = jsonNode.hasNonNull("key") ? jsonNode.get("key").asText(null) : null; String etag = jsonNode.hasNonNull("etag") ? jsonNode.get("etag").asText(null) : null; BatchFileInfo batchFileInfo = BatchFileInfo.builder() .withFileSize(fileSize) .withMd5(md5) .withName(name) .withMimeType(mimeType) .withKey(key) .build(); BatchHandler handler = batchManager.getHandlerByName(batch.getProvider()); if (handler.completeUpload(batchId, fileIdx, batchFileInfo)) { return Response.ok().build(); } return Response.status(Status.CONFLICT).build(); }

Target:
public Response uploadCompleted(@PathParam(REQUEST_BATCH_ID) String batchId, @PathParam(REQUEST_FILE_IDX) String fileIdx, String body) throws IOException { BatchManager bm = Framework.getService(BatchManager.class); JsonNode jsonNode = new ObjectMapper().readTree(body); Batch batch = bm.getBatch(batchId); if (batch == null) { return buildEmptyResponse(Status.NOT_FOUND); } String key = jsonNode.hasNonNull(KEY) ? jsonNode.get(KEY).asText(null) : null; String filename = jsonNode.hasNonNull(NAME) ? jsonNode.get(NAME).asText() : null; String mimeType = jsonNode.hasNonNull(MIMETYPE) ? jsonNode.get(MIMETYPE).asText(null) : null; Long length = jsonNode.hasNonNull(FILE_SIZE) ? jsonNode.get(FILE_SIZE).asLong() : -1L; String md5 = jsonNode.hasNonNull(MD5) ? jsonNode.get(MD5).asText() : null; BatchFileInfo batchFileInfo = new BatchFileInfo(key, filename, mimeType, length, md5); BatchHandler handler = bm.getHandler(batch.getHandlerName()); if (!handler.completeUpload(batchId, fileIdx, batchFileInfo)) { return Response.status(Status.CONFLICT).build(); } Map<String, Object> result = new HashMap<>(); result.put("uploaded", "true"); result.put("batchId", batchId); result.put("fileIdx", fileIdx); return buildResponse(Status.OK, result); }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currentLeader; String requestURI = StringUtils.toLowerCase(request.getRequestURI()); if (requestURI.startsWith(STANDARD_COORDINATOR_BASE_PATH)) { currentLeader = coordLeaderSelector.getCurrentLeader(); } else if (requestURI.startsWith(STANDARD_OVERLORD_BASE_PATH)) { currentLeader = overlordLeaderSelector.getCurrentLeader(); } else if (requestURI.startsWith(ARBITRARY_COORDINATOR_BASE_PATH)) { currentLeader = coordLeaderSelector.getCurrentLeader(); request.setAttribute( MODIFIED_PATH_ATTRIBUTE, request.getRequestURI().substring(ARBITRARY_COORDINATOR_BASE_PATH.length()) ); } else if (requestURI.startsWith(ARBITRARY_OVERLORD_BASE_PATH)) { currentLeader = overlordLeaderSelector.getCurrentLeader(); request.setAttribute( MODIFIED_PATH_ATTRIBUTE, request.getRequestURI().substring(ARBITRARY_OVERLORD_BASE_PATH.length()) ); } else { handleBadRequest(response, "Unsupported proxy destination"); return; } if (currentLeader == null) { handleBadRequest(response, "Unable to determine destination; is your coordinator/overlord running?"); return; } request.setAttribute(BASE_URI_ATTRIBUTE, currentLeader); super.service(request, response); }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currentLeader; String requestURI = StringUtils.toLowerCase(request.getRequestURI()); if (requestURI.startsWith(STANDARD_COORDINATOR_BASE_PATH)) { currentLeader = coordLeaderSelector.getCurrentLeader(); } else if (requestURI.startsWith(STANDARD_OVERLORD_BASE_PATH)) { currentLeader = overlordLeaderSelector.getCurrentLeader(); } else if (requestURI.startsWith(ARBITRARY_COORDINATOR_BASE_PATH)) { currentLeader = coordLeaderSelector.getCurrentLeader(); request.setAttribute( MODIFIED_PATH_ATTRIBUTE, request.getRequestURI().substring(ARBITRARY_COORDINATOR_BASE_PATH.length()) ); } else if (requestURI.startsWith(ARBITRARY_OVERLORD_BASE_PATH)) { currentLeader = overlordLeaderSelector.getCurrentLeader(); request.setAttribute( MODIFIED_PATH_ATTRIBUTE, request.getRequestURI().substring(ARBITRARY_OVERLORD_BASE_PATH.length()) ); } else { handleBadRequest(response, StringUtils.format("Unsupported proxy destination [%s]", request.getRequestURI())); return; } if (currentLeader == null) { handleBadRequest( response, StringUtils.format( "Unable to determine destination for [%s]; is your coordinator/overlord running?", request.getRequestURI() ) ); return; } request.setAttribute(BASE_URI_ATTRIBUTE, currentLeader); super.service(request, response); }
Source:
public Policy updatePolicy(Policy policy) { String hql = "UPDATE Policy SET policy = :policy " + "WHERE tenant = :tenant and internalId.id = :id"; Query query = this.currentSession().createQuery(hql); query.setParameter("policy", policy.getPolicy()); query.setParameter("tenant", policy.getInternalId().getTenant()); query.setParameter("id", policy.getInternalId().getId()); int result = query.executeUpdate(); System.out.println("The result of the update is " + result); return policy; }

Target:
public Policy updatePolicy(Policy policy) { String hql = "UPDATE Policy SET policy = :policy " + "WHERE tenant = :tenant and internalId.id = :id"; Query query = this.currentSession().createQuery(hql); query.setParameter("policy", policy.getPolicy()); query.setParameter("tenant", policy.getInternalId().getTenant()); query.setParameter("id", policy.getInternalId().getId()); int result = query.executeUpdate(); return policy; }
Source:
public void before() { final NoOpRecordCollector collector = new NoOpRecordCollector() { @Override public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Integer partition, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) { sent.put(key, ValueAndTimestamp.make((byte[]) value, timestamp)); } }; final StreamsMetricsImpl streamsMetrics = niceMock(StreamsMetricsImpl.class); replay(streamsMetrics); final InternalMockProcessorContext context = new InternalMockProcessorContext( TestUtils.tempDirectory(), Serdes.String(), Serdes.Long(), collector, new ThreadCache(new LogContext("testCache "), 0, streamsMetrics)); context.setTime(0); store.init(context, store); }

Target:
public void before() { final NoOpRecordCollector collector = new NoOpRecordCollector() { @Override public <K, V> void send(final String topic, final K key, final V value, final Headers headers, final Integer partition, final Long timestamp, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) { sent.put(key, ValueAndTimestamp.make((byte[]) value, timestamp)); } }; final InternalMockProcessorContext context = new InternalMockProcessorContext( TestUtils.tempDirectory(), Serdes.String(), Serdes.Long(), collector, new ThreadCache( new LogContext("testCache "), 0, new StreamsMetricsImpl(new Metrics(), "test", StreamsConfig.METRICS_LATEST))); context.setTime(0); store.init(context, store); }
Source:
public static ArrayList<Integer> johnsonLindenStraussMinDim(int n, double... eps){ return johnsonLindenstraussMinDim(new int[]{n}, eps); }

Target:
public static List<Integer> johnsonLindenStraussMinDim(int n, double... eps){ return johnsonLindenstraussMinDim(new int[]{n}, eps); }
Source:
public static void deleteCommunity(UUID uuid) throws SQLException, IOException { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Community community = communityService.find(c, uuid); if (community != null) { try { if (community.getAdministrators() != null) { Group adminGroup = community.getAdministrators(); communityService.removeAdministrators(c, community); groupService.delete(c, adminGroup); } communityService.delete(c, community); } catch (AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } } c.complete(); } }

Target:
public static void deleteCommunity(UUID uuid) throws SQLException, IOException { try (Context c = new Context()) { c.turnOffAuthorisationSystem(); Community community = communityService.find(c, uuid); if (community != null) { try { Group adminGroup = community.getAdministrators(); if (adminGroup != null) { communityService.removeAdministrators(c, community); groupService.delete(c, adminGroup); } communityService.delete(c, community); } catch (AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } } c.complete(); } }
Source:
public static int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name, int defaultValue) { String value = getDeviceConfigProperty(namespace, name, null ); try { return (value != null) ? Integer.parseInt(value) : defaultValue; } catch (NumberFormatException | NullPointerException e) { return defaultValue; } }

Target:
public static int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name, int defaultValue) { String value = getDeviceConfigProperty(namespace, name, null ); try { return (value != null) ? Integer.parseInt(value) : defaultValue; } catch (NumberFormatException e) { return defaultValue; } }
Source:
public ValueHolder<V> get(final K key) throws StoreAccessException { Chain chain = storeProxy.get(key.hashCode()); V value = null; if(!chain.isEmpty()) { ResolvedChain<K, V> resolvedChain = resolver.resolve(chain, key); Chain compactedChain = resolvedChain.getCompactedChain(); storeProxy.replaceAtHead(key.hashCode(), chain, compactedChain); Operation<K, V> resolvedOperation = resolvedChain.getResolvedOperation(key); if(resolvedOperation != null) { value = resolvedOperation.getValue(); } } return new ClusteredValueHolder<V>(value); }

Target:
public ValueHolder<V> get(final K key) throws StoreAccessException { Chain chain = storeProxy.get(key.hashCode()); V value = null; if(!chain.isEmpty()) { ResolvedChain<K, V> resolvedChain = resolver.resolve(chain, key); Chain compactedChain = resolvedChain.getCompactedChain(); storeProxy.replaceAtHead(key.hashCode(), chain, compactedChain); Result<V> resolvedResult = resolvedChain.getResolvedResult(key); if(resolvedResult != null) { value = resolvedResult.getValue(); } else { return null; } } else { return null; } return new ClusteredValueHolder<V>(value); }
Source:
public long countPhenotypesForDataset(final Integer datasetId, final List<Integer> traitIds) { final SQLQuery query = this.getSession().createSQLQuery( "SELECT COUNT(1) FROM phenotype ph " + "INNER JOIN nd_experiment e ON ph.nd_experiment_id = e.nd_experiment_id " + "WHERE e.project_id = :datasetId AND observable_id in (:traitIds);"); query.setParameter("datasetId", datasetId); query.setParameterList(TRAIT_IDS, traitIds); return ((BigInteger) query.uniqueResult()).longValue(); }

Target:
public long countPhenotypesForDataset(final Integer datasetId, final List<Integer> traitIds) { final Criteria criteria = this.getSession().createCriteria(Phenotype.class); criteria.createAlias("experiment", "experiment"); criteria.add(Restrictions.eq("experiment.project.projectId", datasetId)); criteria.add(Restrictions.in("observableId", traitIds)); criteria.setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); }
Source:
public boolean applyDetermination(ScriptPath path, ObjectTag determinationObj) { if (determinationObj instanceof LocationTag) { event.getAcceleration().copy(((LocationTag) determinationObj).toVector()); return true; } return super.applyDetermination(path, determinationObj); }

Target:
public boolean applyDetermination(ScriptPath path, ObjectTag determinationObj) { if (!isDefaultDetermination(determinationObj)) { String determination = determinationObj.toString(); if (LocationTag.matches(determination)) { event.getAcceleration().copy((LocationTag.valueOf(determination)).toVector()); return true; } } return super.applyDetermination(path, determinationObj); }
Source:
private static String _getEngineSSHPublicKey() { String keystoreFile = Config.<String>GetValue(ConfigValues.keystoreUrl); String alias = Config.<String>GetValue(ConfigValues.CertAlias); InputStream in = null; try { in = new FileInputStream(keystoreFile); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load( in, Config.<String>GetValue(ConfigValues.keystorePass).toCharArray() ); Certificate cert = ks.getCertificate(alias); if (cert == null) { throw new KeyStoreException( String.format( "Failed to find certificate store '%1$s' using alias '%2$s'", keystoreFile, alias ) ); } return OpenSSHUtils.getKeyString( cert.getPublicKey(), Config.<String>GetValue(ConfigValues.SSHKeyAlias) ); } catch (Exception e) { throw new RuntimeException( String.format( "Failed to decode own public key from store '%1$s' using alias '%2$s'", keystoreFile, alias ), e ); } finally { if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } }

Target:
private static String _getEngineSSHPublicKey() { String keystoreFile = Config.<String>GetValue(ConfigValues.keystoreUrl); String alias = Config.<String>GetValue(ConfigValues.CertAlias); char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); InputStream in = null; try { in = new FileInputStream(keystoreFile); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); final Certificate cert = ks.getCertificate(alias); if (cert == null) { throw new KeyStoreException( String.format( "Failed to find certificate store '%1$s' using alias '%2$s'", keystoreFile, alias ) ); } return OpenSSHUtils.getKeyString( cert.getPublicKey(), Config.<String>GetValue(ConfigValues.SSHKeyAlias) ); } catch (Exception e) { throw new RuntimeException( String.format( "Failed to decode own public key from store '%1$s' using alias '%2$s'", keystoreFile, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } }
Source:
public Secret(ModelNode node, IClient client, Map<String, String []> propertyKeys) { super(node, client, propertyKeys); initializeCapabilities(getModifiableCapabilities(), this, getClient()); }

Target:
public Secret(ModelNode node, IClient client, Map<String, String []> propertyKeys) { super(node, client, propertyKeys); }
Source:
public @Bean OrganisationStore organisationStore() { LookupEntryStore organisationLookupEntryStore = new MongoLookupEntryStore(db.collection("organisationLookup")); OrganisationStore organisationStore = new MongoOrganisationStore(db, TransitiveLookupWriter.explicitTransitiveLookupWriter(organisationLookupEntryStore), organisationLookupEntryStore, persistenceAuditLog()); if (Boolean.valueOf(generateIds)) { organisationStore = new IdSettingOrganisationStore(organisationStore, new MongoSequentialIdGenerator(db, "content")); } return organisationStore; }

Target:
public @Bean OrganisationStore organisationStore() { LookupEntryStore organisationLookupEntryStore = new MongoLookupEntryStore(db.collection("organisationLookup")); OrganisationStore organisationStore = new MongoOrganisationStore(db, TransitiveLookupWriter.explicitTransitiveLookupWriter(organisationLookupEntryStore), organisationLookupEntryStore, persistenceAuditLog()); if (Boolean.valueOf(generateIds)) { organisationStore = new IdSettingOrganisationStore(organisationStore, new MongoSequentialIdGenerator(db, "organisations")); } return organisationStore; }
Source:
private Class<?> findMySqlDriverClass() { Class<?> foundClass = null; for (String knownCleanupThreadClassAddress : CONNECTION_CLEANUP_THREAD_KNOWN_CLASS_ADDRESES) { try { foundClass = this.getClass().getClassLoader().loadClass(knownCleanupThreadClassAddress); } catch (ClassNotFoundException e) { logger.warn("No AbandonedConnectionCleanupThread registered with class address " + knownCleanupThreadClassAddress); } } return foundClass; }

Target:
private Class<?> findMySqlDriverClass() throws ClassNotFoundException { Class<?> foundClass = null; for (String knownCleanupThreadClassAddress : CONNECTION_CLEANUP_THREAD_KNOWN_CLASS_ADDRESES) { try { return this.getClass().getClassLoader().loadClass(knownCleanupThreadClassAddress); } catch (ClassNotFoundException e) { logger.warn("No AbandonedConnectionCleanupThread registered with class address " + knownCleanupThreadClassAddress); } } throw new ClassNotFoundException("No MySql's AbandonedConnectionCleanupThread class was found"); }
Source:
public List<CramCompressionRecord> getRecords(final Container container, ArrayList<CramCompressionRecord> records, final ValidationStringency validationStringency) throws IllegalArgumentException, IllegalAccessException { if (container.isEOF()) return Collections.emptyList(); final long time1 = System.nanoTime(); if (records == null) { records = new ArrayList<>(container.nofRecords); } for (final Slice slice : container.slices) { records.addAll(getRecords(slice, container.header, validationStringency)); } final long time2 = System.nanoTime(); container.parseTime = time2 - time1; return records; }

Target:
public List<CramCompressionRecord> getRecords(final Container container, ArrayList<CramCompressionRecord> records, final ValidationStringency validationStringency) throws IllegalArgumentException, IllegalAccessException { if (container.isEOF()) { return Collections.emptyList(); } if (records == null) { records = new ArrayList<>(container.nofRecords); } for (final Slice slice : container.slices) { records.addAll(getRecords(slice, container.header, validationStringency)); } return records; }
Source:
public void loadMoreProcessInstanceLogs() { setCurrentPage(currentPage + 1); displayVisibleLogs(); }

Target:
public void loadMoreProcessInstanceLogs() { setCurrentPage(currentPage + 1); loadTaskLogs(); }
Source:
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); Matcher keyMatched = putKeyPattern.matcher(req.getRequestURI()); if (keyMatched.find()) { String[] split = keyMatched.group().split("/"); String key = split[1]; String value = split[2]; System.out.println("put sessionId="+session.getId()+" key="+key+" val="+value); session.setAttribute(key, value); resp.getWriter().write(value.toString()); } }

Target:
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); Matcher keyMatched = putKeyPattern.matcher(req.getRequestURI()); if (keyMatched.find()) { String[] split = keyMatched.group().split("/"); String key = split[1]; String value = split[2]; session.setAttribute(key, value); resp.getWriter().write(value.toString()); } }
Source:
public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForSegmentIds( CoordinatorClient coordinatorClient, String dataSource, List<WindowedSegmentId> segmentIds ) { final SortedMap<Interval, TimelineObjectHolder<String, DataSegment>> timeline = new TreeMap<>( Comparators.intervalsByStartThenEnd() ); for (WindowedSegmentId windowedSegmentId : Preconditions.checkNotNull(segmentIds, "segmentIds")) { final DataSegment segment = coordinatorClient.fetchSegment( dataSource, windowedSegmentId.getSegmentId() ); for (Interval interval : windowedSegmentId.getIntervals()) { final TimelineObjectHolder<String, DataSegment> existingHolder = timeline.get(interval); if (existingHolder != null) { if (!existingHolder.getVersion().equals(segment.getVersion())) { throw new ISE("Timeline segments with the same interval should have the same version: " + "existing version[%s] vs new segment[%s]", existingHolder.getVersion(), segment); } existingHolder.getObject().add(segment.getShardSpec().createChunk(segment)); } else { timeline.put( interval, new TimelineObjectHolder<>( interval, segment.getInterval(), segment.getVersion(), new PartitionHolder<>(segment.getShardSpec().createChunk(segment)) ) ); } } } Interval lastInterval = null; for (Interval interval : timeline.keySet()) { if (lastInterval != null && interval.overlaps(lastInterval)) { throw new IAE( "Distinct intervals in input segments may not overlap: [%s] vs [%s]", lastInterval, interval ); } lastInterval = interval; } return new ArrayList<>(timeline.values()); }

Target:
public static List<TimelineObjectHolder<String, DataSegment>> getTimelineForSegmentIds( CoordinatorClient coordinatorClient, String dataSource, List<WindowedSegmentId> segmentIds ) { final SortedMap<Interval, TimelineObjectHolder<String, DataSegment>> timeline = new TreeMap<>( Comparators.intervalsByStartThenEnd() ); for (WindowedSegmentId windowedSegmentId : Preconditions.checkNotNull(segmentIds, "segmentIds")) { final DataSegment segment = coordinatorClient.fetchUsedSegment( dataSource, windowedSegmentId.getSegmentId() ); for (Interval interval : windowedSegmentId.getIntervals()) { final TimelineObjectHolder<String, DataSegment> existingHolder = timeline.get(interval); if (existingHolder != null) { if (!existingHolder.getVersion().equals(segment.getVersion())) { throw new ISE("Timeline segments with the same interval should have the same version: " + "existing version[%s] vs new segment[%s]", existingHolder.getVersion(), segment); } existingHolder.getObject().add(segment.getShardSpec().createChunk(segment)); } else { timeline.put( interval, new TimelineObjectHolder<>( interval, segment.getInterval(), segment.getVersion(), new PartitionHolder<>(segment.getShardSpec().createChunk(segment)) ) ); } } } Interval lastInterval = null; for (Interval interval : timeline.keySet()) { if (lastInterval != null && interval.overlaps(lastInterval)) { throw new IAE( "Distinct intervals in input segments may not overlap: [%s] vs [%s]", lastInterval, interval ); } lastInterval = interval; } return new ArrayList<>(timeline.values()); }