auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static EntropyEstimator createEstimator(String type, String base) { if(EmpiricalEntropyEstimator.EMPIRICAL_ESTIMATOR.equalsIgnoreCase(type)) { return new EmpiricalEntropyEstimator(base); } if(EmpiricalEntropyEstimator.CHAOSHEN_ESTIMATOR.equalsIgnoreCase(type)) { return new ChaoShenEntropyEstimator(base); } return null; }

Target:
public static EntropyEstimator createEstimator(String type, String base) throws IllegalArgumentException { if(EmpiricalEntropyEstimator.EMPIRICAL_ESTIMATOR.equalsIgnoreCase(type)) { return new EmpiricalEntropyEstimator(base); } if(EmpiricalEntropyEstimator.CHAOSHEN_ESTIMATOR.equalsIgnoreCase(type)) { return new ChaoShenEntropyEstimator(base); } throw new IllegalArgumentException("invalid input entropy estimator type. " + "Please refer to StreamingEntropy's javadoc for the supported estimator types"); }
Source:
private boolean TxBegin() { if (!TransactionalContext.isInTransaction()) { corfuRuntime.getObjectsView() .TXBuild() .type(TransactionType.OPTIMISTIC) .build().begin(); return true; } return false; }

Target:
private boolean TxBegin() { if (TransactionalContext.isInTransaction()) { return false; } corfuRuntime.getObjectsView() .TXBuild() .type(TransactionType.OPTIMISTIC) .build() .begin(); return true; }
Source:
private BundleDependency getPluginBundleDependency(Plugin plugin, List<BundleDependency> mulePlugins) { return mulePlugins.stream().filter(mulePlugin -> mulePlugin.getDescriptor().getArtifactId().equals(plugin.getArtifactId()) && mulePlugin.getDescriptor().getGroupId().equals(plugin.getGroupId())) .findFirst() .orElseThrow(() -> new MuleRuntimeException(createStaticMessage("Declared additional dependencies for a plugin not present: " + plugin))); }

Target:
private BundleDependency getPluginBundleDependency(Plugin plugin, List<BundleDependency> mulePlugins) { return mulePlugins.stream() .filter(mulePlugin -> StringUtils.equals(mulePlugin.getDescriptor().getArtifactId(), plugin.getArtifactId()) && StringUtils.equals(mulePlugin.getDescriptor().getGroupId(), plugin.getGroupId())) .findFirst() .orElseThrow(() -> new MuleRuntimeException(createStaticMessage("Declared additional dependencies for a plugin not present: " + plugin))); }
Source:
public List<DataSegment> getUsedSegmentsForInterval(final String dataSource, final Interval interval) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = connector.getDBI().withHandle( new HandleCallback<VersionedIntervalTimeline<String, DataSegment>>() { @Override public VersionedIntervalTimeline<String, DataSegment> withHandle(Handle handle) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<String, DataSegment>( Ordering.natural() ); final ResultIterator<byte[]> dbSegments = handle.createQuery( String.format( "SELECT payload FROM %s WHERE used = true AND dataSource = :dataSource AND start >= :start and \"end\" <= :end AND used = true", dbTables.getSegmentsTable() ) ) .bind("dataSource", dataSource) .bind("start", interval.getStart().toString()) .bind("end", interval.getEnd().toString()) .map(ByteArrayMapper.FIRST) .iterator(); while (dbSegments.hasNext()) { final byte[] payload = dbSegments.next(); DataSegment segment = jsonMapper.readValue( payload, DataSegment.class ); timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); } dbSegments.close(); return timeline; } } ); return Lists.newArrayList( Iterables.concat( Iterables.transform( timeline.lookup(interval), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); }

Target:
public List<DataSegment> getUsedSegmentsForInterval(final String dataSource, final Interval interval) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = connector.getDBI().withHandle( new HandleCallback<VersionedIntervalTimeline<String, DataSegment>>() { @Override public VersionedIntervalTimeline<String, DataSegment> withHandle(Handle handle) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<String, DataSegment>( Ordering.natural() ); final ResultIterator<byte[]> dbSegments = handle.createQuery( String.format( "SELECT payload FROM %s WHERE used = true AND dataSource = :dataSource AND start <= :end and \"end\" >= :start AND used = true", dbTables.getSegmentsTable() ) ) .bind("dataSource", dataSource) .bind("start", interval.getStart().toString()) .bind("end", interval.getEnd().toString()) .map(ByteArrayMapper.FIRST) .iterator(); while (dbSegments.hasNext()) { final byte[] payload = dbSegments.next(); DataSegment segment = jsonMapper.readValue( payload, DataSegment.class ); timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); } dbSegments.close(); return timeline; } } ); return Lists.newArrayList( Iterables.concat( Iterables.transform( timeline.lookup(interval), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); }
Source:
private static void validateScanStartupMode(ReadableConfig tableOptions) { tableOptions.getOptional(SCAN_STARTUP_MODE) .map(String::toLowerCase) .ifPresent(mode -> { if (!SCAN_STARTUP_MODE_ENUMS.contains(mode)) { throw new ValidationException( String.format("Invalid value for option '%s'. Supported values are %s, but was: %s", SCAN_STARTUP_MODE.key(), "[earliest-offset, latest-offset, group-offsets, specific-offsets, timestamp]", mode)); } if (mode.equals(SCAN_STARTUP_MODE_VALUE_TIMESTAMP)) { if (!tableOptions.getOptional(SCAN_STARTUP_TIMESTAMP_MILLIS).isPresent()) { throw new ValidationException(String.format("'%s' is required in '%s' startup mode" + " but missing.", SCAN_STARTUP_TIMESTAMP_MILLIS.key(), SCAN_STARTUP_MODE_VALUE_TIMESTAMP)); } } if (mode.equals(SCAN_STARTUP_MODE_VALUE_SPECIFIC_OFFSETS)) { if (!tableOptions.getOptional(SCAN_STARTUP_SPECIFIC_OFFSETS).isPresent()) { throw new ValidationException(String.format("'%s' is required in '%s' startup mode" + " but missing.", SCAN_STARTUP_SPECIFIC_OFFSETS.key(), SCAN_STARTUP_MODE_VALUE_SPECIFIC_OFFSETS)); } if (!tableOptions.getOptional(TOPIC).isPresent() || tableOptions.get(TOPIC).split(",").length > 1){ throw new ValidationException("Currently Kafka source only supports specific offset for single topic."); } String specificOffsets = tableOptions.get(SCAN_STARTUP_SPECIFIC_OFFSETS); parseSpecificOffsets(specificOffsets, SCAN_STARTUP_SPECIFIC_OFFSETS.key()); } }); }

Target:
private static void validateScanStartupMode(ReadableConfig tableOptions) { tableOptions.getOptional(SCAN_STARTUP_MODE) .map(String::toLowerCase) .ifPresent(mode -> { if (!SCAN_STARTUP_MODE_ENUMS.contains(mode)) { throw new ValidationException( String.format("Invalid value for option '%s'. Supported values are %s, but was: %s", SCAN_STARTUP_MODE.key(), "[earliest-offset, latest-offset, group-offsets, specific-offsets, timestamp]", mode)); } if (mode.equals(SCAN_STARTUP_MODE_VALUE_TIMESTAMP)) { if (!tableOptions.getOptional(SCAN_STARTUP_TIMESTAMP_MILLIS).isPresent()) { throw new ValidationException(String.format("'%s' is required in '%s' startup mode" + " but missing.", SCAN_STARTUP_TIMESTAMP_MILLIS.key(), SCAN_STARTUP_MODE_VALUE_TIMESTAMP)); } } if (mode.equals(SCAN_STARTUP_MODE_VALUE_SPECIFIC_OFFSETS)) { if (!tableOptions.getOptional(SCAN_STARTUP_SPECIFIC_OFFSETS).isPresent()) { throw new ValidationException(String.format("'%s' is required in '%s' startup mode" + " but missing.", SCAN_STARTUP_SPECIFIC_OFFSETS.key(), SCAN_STARTUP_MODE_VALUE_SPECIFIC_OFFSETS)); } if (!isSingleTopic(tableOptions)){ throw new ValidationException("Currently Kafka source only supports specific offset for single topic."); } String specificOffsets = tableOptions.get(SCAN_STARTUP_SPECIFIC_OFFSETS); parseSpecificOffsets(specificOffsets, SCAN_STARTUP_SPECIFIC_OFFSETS.key()); } }); }
Source:
public void testSetTime() throws Exception { checkSetTime(0L); checkSetTime(31536000000L); checkSetTime(315187200000L); checkSetTime(315705600000L); checkSetTime(ENTRY_TIME); checkSetTime(4134153600000L); }

Target:
public void testSetTime() throws Exception { checkSetTime(0L); checkSetTime(31536000000L); checkSetTime(315187200000L); checkSetTime(LocalDate.of(1980, 1, 1).atStartOfDay().minus(1, ChronoUnit.SECONDS) .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); checkSetTime(LocalDate.of(1980, 1, 1).atStartOfDay().minus(1, ChronoUnit.SECONDS) .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); checkSetTime(315705600000L); checkSetTime(ENTRY_TIME); checkSetTime(4134153600000L); }
Source:
protected final void processAnnotationOnMethod(MethodMetadata data, Annotation annotation, Method method) { if (methodAnnotationProcessors.stream() .anyMatch(processor -> processor.test(annotation))) { methodAnnotationProcessors.stream() .filter(processor -> processor.test(annotation)) .forEach(processor -> processor.process(annotation, data)); } else { data.addWarning(String.format( "Method %s has an annotation %s that is not used by contract %s", method.getName(), annotation.annotationType() .getSimpleName(), getClass().getSimpleName())); } }

Target:
protected final void processAnnotationOnMethod(MethodMetadata data, Annotation annotation, Method method) { List<GuardedAnnotationProcessor> processors = methodAnnotationProcessors.stream() .filter(processor -> processor.test(annotation)) .collect(Collectors.toList()); if (!processors.isEmpty()) { processors.forEach(processor -> processor.process(annotation, data)); } else { data.addWarning(String.format( "Method %s has an annotation %s that is not used by contract %s", method.getName(), annotation.annotationType() .getSimpleName(), getClass().getSimpleName())); } }
Source:
public static void waitForVMtoStart(final CloudStackClient client, final String vmName) { checkNotEmpty(vmName); VirtualMachine machine = getVirtualMachineByName(client, vmName); String id = machine.getId(); long startTime = System.currentTimeMillis(); while (machine.getState() == STARTING) { try { LOG.info("Waiting for VM - id to start", machine.getName(), machine.getId()); TimeUnit.SECONDS.sleep(BETWEEN_REQUESTS_SLEEP_TIME); machine = client.getVirtualMachineClient().getVirtualMachine(id); } catch (InterruptedException e) { LOG.info("Interrupted while waiting for VM's to start"); } if (timeOutExceeded(startTime)) { break; } } switch (machine.getState()) { case RUNNING: LOG.info("VM is running, as expected", vmName); break; default: throw new IllegalStateException("VM " + machine + "is not in RUNNING state"); } }

Target:
public static void waitForVMtoStart(final CloudStackClient client, final String vmName) { checkNotEmpty(vmName); VirtualMachine machine = getVirtualMachineByName(client, vmName); String id = machine.getId(); long startTime = System.currentTimeMillis(); while (machine.getState() == STARTING) { try { LOG.info("Waiting for VM - id to start", machine.getName(), machine.getId()); TimeUnit.SECONDS.sleep(BETWEEN_REQUESTS_SLEEP_TIME); machine = client.getVirtualMachineClient().getVirtualMachine(id); } catch (InterruptedException e) { LOG.info("Interrupted while waiting for VM's to start"); Throwables.propagateIfPossible(e); } if (timeOutExceeded(startTime)) { break; } } switch (machine.getState()) { case RUNNING: LOG.info("VM is running, as expected", vmName); break; default: throw new IllegalStateException("VM " + machine + "is not in RUNNING state"); } }
Source:
private List<DRepresentationElement> extractSelectionFromUIState(DRepresentation currentRep, List<DRepresentationElement> notifiedElements) { List<DRepresentationElement> selectedElements = null; List<DRepresentationElement> dRepElements = new ArrayList<>(); List<EObject> semanticElements = new ArrayList<>(); if (currentRep == null) { return null; } UIState uiState = currentRep.getUiState(); if (uiState != null && uiState.isSetElementsToSelect()) { Collection<EObject> elementsToSelectFromUIState = uiState.getElementsToSelect(); boolean hasRepElement = false; boolean hasSemanticElement = false; boolean hasRepresentation = false; for (EObject currentElement : elementsToSelectFromUIState) { if (currentElement instanceof DRepresentationElement) { hasRepElement = true; dRepElements.add((DRepresentationElement) currentElement); } else if (currentElement instanceof DRepresentation) { hasRepresentation = true; break; } else { hasSemanticElement = true; semanticElements.add(currentElement); } } if (hasSemanticElement && !hasRepresentation && !hasRepElement) { selectedElements = new ArrayList<>(); caseHasSemanticElement(selectedElements, notifiedElements, semanticElements, currentRep); } else if (hasRepElement && !hasRepresentation && !hasSemanticElement) { if (!notifiedElements.isEmpty()) { dRepElements.retainAll(notifiedElements); } selectedElements = new ArrayList<DRepresentationElement>(dRepElements); } else { selectedElements = new ArrayList<>(); } } return selectedElements; }

Target:
private List<DRepresentationElement> extractSelectionFromUIState(DRepresentation currentRep, List<DRepresentationElement> notifiedElements) { List<DRepresentationElement> selectedElements = null; List<DRepresentationElement> dRepElements = new ArrayList<>(); List<EObject> semanticElements = new ArrayList<>(); UIState uiState = currentRep.getUiState(); if (uiState != null && uiState.isSetElementsToSelect()) { Collection<EObject> elementsToSelectFromUIState = uiState.getElementsToSelect(); boolean hasRepElement = false; boolean hasSemanticElement = false; boolean hasRepresentation = false; for (EObject currentElement : elementsToSelectFromUIState) { if (currentElement instanceof DRepresentationElement) { hasRepElement = true; dRepElements.add((DRepresentationElement) currentElement); } else if (currentElement instanceof DRepresentation) { hasRepresentation = true; break; } else { hasSemanticElement = true; semanticElements.add(currentElement); } } if (hasSemanticElement && !hasRepresentation && !hasRepElement) { selectedElements = new ArrayList<>(); caseHasSemanticElement(selectedElements, notifiedElements, semanticElements, currentRep); } else if (hasRepElement && !hasRepresentation && !hasSemanticElement) { if (!notifiedElements.isEmpty()) { dRepElements.retainAll(notifiedElements); } selectedElements = new ArrayList<DRepresentationElement>(dRepElements); } else { selectedElements = new ArrayList<>(); } } return selectedElements; }
Source:
public static Observable<Boolean> observeInternetConnectivity(final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs) { if (initialIntervalInMs < 0) { throw new IllegalArgumentException("initialIntervalInMs is not a non-zero number"); } Preconditions.checkPositive(intervalInMs, "intervalInMs is not positive number"); Preconditions.checkNotNullOrEmpty(host, "host is null or empty"); Preconditions.checkPositive(port, "port is not positive number"); Preconditions.checkPositive(timeoutInMs, "timeoutInMs is not positive number"); return Observable.interval(initialIntervalInMs, intervalInMs, TimeUnit.MILLISECONDS, Schedulers.io()) .map(new Func1<Long, Boolean>() { @Override public Boolean call(Long tick) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), timeoutInMs); return socket.isConnected(); } catch (IOException e) { return Boolean.FALSE; } } }) .distinctUntilChanged(); }

Target:
public static Observable<Boolean> observeInternetConnectivity(final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs) { if (initialIntervalInMs < 0) { throw new IllegalArgumentException("initialIntervalInMs is not a positive number nor a positive number"); } Preconditions.checkPositive(intervalInMs, "intervalInMs is not positive number"); Preconditions.checkNotNullOrEmpty(host, "host is null or empty"); Preconditions.checkPositive(port, "port is not positive number"); Preconditions.checkPositive(timeoutInMs, "timeoutInMs is not positive number"); return Observable.interval(initialIntervalInMs, intervalInMs, TimeUnit.MILLISECONDS, Schedulers.io()) .map(new Func1<Long, Boolean>() { @Override public Boolean call(Long tick) { try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), timeoutInMs); return socket.isConnected(); } catch (IOException e) { return Boolean.FALSE; } } }) .distinctUntilChanged(); }
Source:
public BackupGetSendingSiteCommand() { super(0); }

Target:
public BackupGetSendingSiteCommand() { super(1); }
Source:
private String buildCoordinateWhere(final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon) { StringBuilder where = new StringBuilder(); double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double llCache; if (latMin > latMax) { llCache = latMax; latMax = latMin; latMin = llCache; } if (lonMin > lonMax) { llCache = lonMax; lonMax = lonMin; lonMin = llCache; } if (where.length() > 0) { where.append(" and "); } where.append("(latitude >= "); where.append(String.format((Locale) null, "%.6f", latMin)); where.append(" and latitude <= "); where.append(String.format((Locale) null, "%.6f", latMax)); where.append(" and longitude >= "); where.append(String.format((Locale) null, "%.6f", lonMin)); where.append(" and longitude <= "); where.append(String.format((Locale) null, "%.6f", lonMax)); where.append(')'); return where.toString(); }

Target:
private static StringBuilder buildCoordinateWhere(final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon) { StringBuilder where = new StringBuilder(); double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double llCache; if (latMin > latMax) { llCache = latMax; latMax = latMin; latMin = llCache; } if (lonMin > lonMax) { llCache = lonMax; lonMax = lonMin; lonMin = llCache; } where.append("(latitude >= "); where.append(String.format((Locale) null, "%.6f", latMin)); where.append(" and latitude <= "); where.append(String.format((Locale) null, "%.6f", latMax)); where.append(" and longitude >= "); where.append(String.format((Locale) null, "%.6f", lonMin)); where.append(" and longitude <= "); where.append(String.format((Locale) null, "%.6f", lonMax)); where.append(')'); return where; }
Source:
private static IActivityListener createForwarder(final IActivityConsumer target) { return new IActivityListener() { @Override public void created(IActivity activity) { if (activity instanceof GitRequestActivity) { target.exec(rewriteGitRequestActivity((GitRequestActivity) activity)); } else if (activity instanceof GitCollectActivity) { target.exec(rewriteGitCollectActivity((GitCollectActivity) activity)); } else if (activity instanceof GitSendBundleActivity) { target.exec(rewriteGitSendBundleActivity((GitSendBundleActivity) activity)); } else { return; } } }; }

Target:
private static IActivityListener createForwarder(final IActivityConsumer target) { return new IActivityListener() { @Override public void created(IActivity activity) { if (activity instanceof GitRequestActivity) { target.exec(rewriteGitRequestActivity((GitRequestActivity) activity)); } else if (activity instanceof GitCollectActivity) { target.exec(rewriteGitCollectActivity((GitCollectActivity) activity)); } else if (activity instanceof GitSendBundleActivity) { target.exec(rewriteGitSendBundleActivity((GitSendBundleActivity) activity)); } } }; }
Source:
private PropertyPath makePropertyPath(org.hibernate.hql.ast.origin.hql.resolve.path.PropertyPath propertyPath) { AggregationPropertyPath.Type aggregationType = propertyPath instanceof AggregationPropertyPath ? ((AggregationPropertyPath) propertyPath).getType() : null; PropertyPath.AggregationType _aggregationType = null; if (aggregationType != null) { switch (aggregationType) { case SUM: _aggregationType = PropertyPath.AggregationType.SUM; break; case AVG: _aggregationType = PropertyPath.AggregationType.AVG; break; case MIN: _aggregationType = PropertyPath.AggregationType.MIN; break; case MAX: _aggregationType = PropertyPath.AggregationType.MAX; break; case COUNT: _aggregationType = PropertyPath.AggregationType.COUNT; break; default: throw new IllegalStateException("Aggregation " + aggregationType.name() + " is not supported"); } } return new PropertyPath(_aggregationType, propertyPath.getNodeNamesWithoutAlias()); }

Target:
private PropertyPath makePropertyPath(org.hibernate.hql.ast.origin.hql.resolve.path.PropertyPath propertyPath) { AggregationPropertyPath.Type aggregationType = propertyPath instanceof AggregationPropertyPath ? ((AggregationPropertyPath) propertyPath).getType() : null; return new PropertyPath(PropertyPath.AggregationType.from(aggregationType), propertyPath.getNodeNamesWithoutAlias()); }
Source:
public void asyncReadLastEntry(ReadCallback cb, Object ctx) { asyncReadLastConfirmed(new ReadLastConfirmedCallback() { @Override public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { if (lastConfirmed < 0) { cb.readComplete(BKException.Code.NoSuchEntryException, ReadOnlyLedgerHandle.this, null, ctx); } else { asyncReadEntriesInternal(lastConfirmed, lastConfirmed, cb, ctx); } } }, ctx); }

Target:
public void asyncReadLastEntry(ReadCallback cb, Object ctx) { asyncReadLastConfirmed(new ReadLastConfirmedCallback() { @Override public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { if (rc == BKException.Code.OK) { if (lastConfirmed < 0) { cb.readComplete(BKException.Code.NoSuchEntryException, ReadOnlyLedgerHandle.this, null, ctx); } else { asyncReadEntriesInternal(lastConfirmed, lastConfirmed, cb, ctx); } } else { LOG.error("ReadException in asyncReadLastEntry, ledgerId: {}, lac: {}, rc:{}", lastConfirmed, ledgerId, rc); cb.readComplete(rc, ReadOnlyLedgerHandle.this, null, ctx); } } }, ctx); }
Source:
private OsFamily extractOsFamily(final String name) { Optional<OsFamily> family = tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() { @Override public boolean apply(OsFamily input) { return name.toLowerCase().startsWith(input.name().toLowerCase()); } }); if (family.isPresent()) { logger.warn("could not find the operating system family for image: %s", name); } return family.or(OsFamily.UNRECOGNIZED); }

Target:
private OsFamily extractOsFamily(final String name) { final String lowerCaseName = name.toLowerCase(); Optional<OsFamily> family = tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() { @Override public boolean apply(OsFamily input) { return lowerCaseName.startsWith(input.name().toLowerCase()); } }); if (family.isPresent()) { logger.warn("could not find the operating system family for image: %s", name); } return family.or(OsFamily.UNRECOGNIZED); }
Source:
public void handleData(final ITmfEvent event) { super.handleData(event); if (event.getTrace() == trace) { count++; if (count == fGranularity) { count = 0; try { ITmfStateSystemBuilder PartialSS = PartialHistoryBackend.this.fPartialSS; PartialSS.incrementAttribute(event.getTimestamp().getValue(), fCheckpointQuark); } catch (StateValueTypeException | TimeRangeException | AttributeNotFoundException e) { e.printStackTrace(); } } sci.processEvent(event); } }

Target:
public void handleData(final ITmfEvent event) { super.handleData(event); if (event.getTrace() == trace) { count++; if (count == getGranularity()) { count = 0; try { ITmfStateSystemBuilder PartialSS = PartialHistoryBackend.this.fPartialSS; PartialSS.incrementAttribute(event.getTimestamp().getValue(), fCheckpointQuark); } catch (StateValueTypeException | TimeRangeException | AttributeNotFoundException e) { e.printStackTrace(); } } sci.processEvent(event); } }
Source:
public boolean shearEntity(ItemStack stack, World world, EntityPlayer player, Entity entity, int distance, int fortune) { if(!(entity instanceof IShearable)) { return false; } IShearable shearable = (IShearable)entity; if(shearable.isShearable(stack, world, entity.getPosition())) { List<ItemStack> drops = shearable.onSheared(stack, world, entity.getPosition(), fortune); Random rand = world.rand; for(ItemStack drop : drops) { net.minecraft.entity.item.EntityItem ent = entity.entityDropItem(drop, 1.0F); ent.motionY += rand.nextFloat() * 0.05F; ent.motionX += (rand.nextFloat() - rand.nextFloat()) * 0.1F; ent.motionZ += (rand.nextFloat() - rand.nextFloat()) * 0.1F; } ToolHelper.damageTool(stack, 1, player); return true; } return false; }

Target:
public boolean shearEntity(ItemStack stack, World world, EntityPlayer player, Entity entity, int distance, int fortune) { if(!(entity instanceof IShearable)) { return false; } IShearable shearable = (IShearable)entity; if(shearable.isShearable(stack, world, entity.getPosition())) { if(!world.isRemote) { List<ItemStack> drops = shearable.onSheared(stack, world, entity.getPosition(), fortune); Random rand = world.rand; for(ItemStack drop : drops) { net.minecraft.entity.item.EntityItem ent = entity.entityDropItem(drop, 1.0F); ent.motionY += rand.nextFloat() * 0.05F; ent.motionX += (rand.nextFloat() - rand.nextFloat()) * 0.1F; ent.motionZ += (rand.nextFloat() - rand.nextFloat()) * 0.1F; } } ToolHelper.damageTool(stack, 1, player); return true; } return false; }
Source:
protected final Collection<T> sortItems(Collection<T> items) { if (items == null || comparator == null) { return items; } initPositions(items); SortedSet<T> sortedItems = new TreeSet<T>(comparator); sortedItems.addAll(items); return sortedItems; }

Target:
protected final Collection<T> sortItems(Collection<T> items) { if (items == null || comparator == null) { return items; } insertionIndex.clear(); SortedSet<T> sortedItems = new TreeSet<T>(comparator) { private int counter = 0; @Override public boolean add(T e) { insertionIndex.put(e, counter++); return super.add(e); } @Override public boolean remove(Object o) { insertionIndex.remove(o); return super.remove(o); } }; sortedItems.addAll(items); return sortedItems; }
Source:
public void handleError(HttpCommand command, HttpResponse response) { String message = parseMessage(response); Exception exception = null; try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 404: if (command.getCurrentRequest().getMethod().equals("DELETE")) { if (command.getCurrentRequest().getEndpoint().getPath().startsWith( "/" + EtcdApiMetadata.API_VERSION + "/members") && message.contains("No such member")) { exception = new ResourceNotFoundException(message, new HttpResponseException(command, response, message)); } } break; case 409: if (command.getCurrentRequest().getMethod().equals("POST")) { if (command.getCurrentRequest().getEndpoint().getPath().endsWith( EtcdApiMetadata.API_VERSION + "/members") && message.contains("etcdserver: ID exists")) exception = new HttpResponseException(message, command, response); } break; default: exception = new HttpResponseException(message, command, response); break; } } catch (Exception e) { exception = new HttpResponseException(command, response, e); } finally { if (exception == null) { exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); } closeQuietly(response.getPayload()); command.setException(exception); } }

Target:
public void handleError(HttpCommand command, HttpResponse response) { String message = parseMessage(response); Exception exception = null; try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: exception = new IllegalArgumentException(message); break; case 404: exception = new ResourceNotFoundException(message); break; case 409: exception = new ResourceAlreadyExistsException(message); break; default: exception = new HttpResponseException(message, command, response); break; } } catch (Exception e) { exception = new HttpResponseException(command, response, e); } finally { if (exception == null) { exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); } closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
public Matrix feedForward(final Matrix input) { if (scale == null || !scale.hasSameSize(input)) { scale = matrixFactory.create(input.getRows(), input.getColumns()); } for (int n = 0; n < input.getColumns(); ++n) { final Matrix paddedImg = matrixFactory.zeros(input.getRows() + (paddingSize * 2 * inputSize), 1); for (int i = 0; i < input.getRows(); ++i) { paddedImg.put(i + paddingSize * inputSize, input.get(i, n) * input.get(i, n)); } computeLocalSum(scale, paddedImg, n); } scale.muli(alpha / localSize).addi(k); return MatrixFunctions.pow(scale, -beta).muli(input); }

Target:
public Matrix feedForward(final Matrix input) { this.scale = matrixFactory.create(input.getRows(), input.getColumns()); for (int n = 0; n < input.getColumns(); ++n) { final Matrix paddedImg = matrixFactory.zeros(input.getRows() + (paddingSize * 2 * inputSize), 1); for (int i = 0; i < input.getRows(); ++i) { paddedImg.put(i + paddingSize * inputSize, input.get(i, n) * input.get(i, n)); } computeLocalSum(scale, paddedImg, n); } scale.muli(alpha / localSize).addi(k); return MatrixFunctions.pow(scale, -beta).muli(input); }
Source:
public <T> List<T> createChildren(Object parent) { if (parent instanceof Connection) { List<T> activeProjects = new ArrayList<>(); List<IResource> projectResources = ((Connection) parent).getResources(ResourceKind.PROJECT); for (IResource projectResource: projectResources) { IProject project = (IProject)projectResource; if (!"Terminating".equals(project.getStatus())) { activeProjects.add((T)project); } } return activeProjects; } else if (parent instanceof IProject) { IProject project = (IProject) parent; Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); Collection appSources = loadTemplates(project, conn); appSources.addAll(loadImageStreams(project, conn)); return (List<T>) new ArrayList<>(appSources); } return Collections.emptyList(); }

Target:
public <T> List<T> createChildren(Object parent) { if (parent instanceof Connection) { List<T> activeProjects = new ArrayList<>(); List<IResource> projectResources = ((Connection) parent).getResources(ResourceKind.PROJECT); for (IResource projectResource: projectResources) { IProject project = (IProject)projectResource; if (!ResourceStatus.TERMINATING.equals(project.getStatus())) { activeProjects.add((T)project); } } return activeProjects; } else if (parent instanceof IProject) { IProject project = (IProject) parent; Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); Collection appSources = loadTemplates(project, conn); appSources.addAll(loadImageStreams(project, conn)); return (List<T>) new ArrayList<>(appSources); } return Collections.emptyList(); }
Source:
private WaiterTimeoutCallback(final Callback<T> callback) { _timeout = new SingleTimeout<>(_timeoutExecutor, _waiterTimeout, TimeUnit.MILLISECONDS, callback, (callback1) -> { synchronized (_lock) { _waiters.remove(this); _statsTracker.incrementWaiterTimedOut(); } LOG.debug("{}: failing waiter due to waiter timeout", _poolName); callback1.onError( new WaiterTimeoutException( "Exceeded waiter timeout of " + _waiterTimeout + "ms: in Pool: "+ _poolName)); }); }

Target:
private WaiterTimeoutCallback(final Callback<T> callback) { _timeout = new SingleTimeout<>(_timeoutExecutor, _waiterTimeout, TimeUnit.MILLISECONDS, callback, (callbackIfTimeout) -> { synchronized (_lock) { _waiters.remove(this); _statsTracker.incrementWaiterTimedOut(); } LOG.debug("{}: failing waiter due to waiter timeout", _poolName); callbackIfTimeout.onError( new WaiterTimeoutException( "Exceeded waiter timeout of " + _waiterTimeout + "ms: in Pool: "+ _poolName)); }); }
Source:
private boolean binaryFilterApplies(CallExpression binExpr, Row row) { List<Expression> children = binExpr.getChildren(); Preconditions.checkArgument(children.size() == 2); Object lhsValue = getValue(children.get(0), row); Object rhsValue = getValue(children.get(1), row); if (!isComparable(lhsValue, binExpr) || !isComparable(rhsValue, binExpr)) { return false; } FunctionDefinition functionDefinition = binExpr.getFunctionDefinition(); if (BuiltInFunctionDefinitions.GREATER_THAN.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) > 0; } else if (BuiltInFunctionDefinitions.LESS_THAN.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) < 0; } else if (BuiltInFunctionDefinitions.GREATER_THAN_OR_EQUAL.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) >= 0; } else if (BuiltInFunctionDefinitions.LESS_THAN_OR_EQUAL.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) <= 0; } else if (BuiltInFunctionDefinitions.EQUALS.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) == 0; } else if (BuiltInFunctionDefinitions.NOT_EQUALS.equals(functionDefinition)) { return ((Comparable) lhsValue).compareTo(rhsValue) != 0; } else { return false; } }

Target:
private boolean binaryFilterApplies(CallExpression binExpr, Row row) { List<Expression> children = binExpr.getChildren(); Preconditions.checkArgument(children.size() == 2); Comparable lhsValue = getValue(children.get(0), row); Comparable rhsValue = getValue(children.get(1), row); FunctionDefinition functionDefinition = binExpr.getFunctionDefinition(); if (BuiltInFunctionDefinitions.GREATER_THAN.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) > 0; } else if (BuiltInFunctionDefinitions.LESS_THAN.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) < 0; } else if (BuiltInFunctionDefinitions.GREATER_THAN_OR_EQUAL.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) >= 0; } else if (BuiltInFunctionDefinitions.LESS_THAN_OR_EQUAL.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) <= 0; } else if (BuiltInFunctionDefinitions.EQUALS.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) == 0; } else if (BuiltInFunctionDefinitions.NOT_EQUALS.equals(functionDefinition)) { return lhsValue.compareTo(rhsValue) != 0; } else { return false; } }
Source:
static List<JavaFileScannerContext.Location> secondaryLocations(List<Tree> methodInvocationTrees) { return methodInvocationTrees.stream() .map(expr -> new JavaFileScannerContext.Location("This call can throw an expected exception", expr)) .collect(Collectors.toList()); }

Target:
static List<JavaFileScannerContext.Location> secondaryLocations(List<Tree> methodInvocationTrees) { return methodInvocationTrees.stream() .map(expr -> new JavaFileScannerContext.Location("Throws an exception", expr)) .collect(Collectors.toList()); }
Source:
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); if (cancelled()) { if (logger.isDebugEnabled()) { logger.debug("Rejecting delivery '" + deliveryTag + "' for " + BlockingQueueConsumer.this); } BlockingQueueConsumer.this.channel.basicReject(deliveryTag, true); } else { if (logger.isDebugEnabled()) { logger.debug("Storing delivery '" + deliveryTag + "' for " + BlockingQueueConsumer.this); } try { BlockingQueueConsumer.this.queue.put(new Delivery(consumerTag, envelope, properties, body)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }

Target:
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Storing delivery for " + BlockingQueueConsumer.this); } try { BlockingQueueConsumer.this.queue.put(new Delivery(consumerTag, envelope, properties, body)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
public void setGameData(final GameData data) { this.data = data; battleTreeCalculator.setGameData(this.data); hardAiCalculator.setGameData(this.data); }

Target:
public void setGameData(final GameData data) { battleTreeCalculator.setGameData(data); hardAiCalculator.setGameData(data); }
Source:
public void createTopicWithInsufficientPollSubject_ShouldFail() throws Exception { User user = User.admin(); Users.signIn(user); Topic topic = new Topic("subject", "message"); topic.withTopicStarter(user); Poll poll = new Poll("ab", new String[]{"option1", "option2", "option3"}); topic.setPoll(poll); Topics.createTopic(topic); }

Target:
public void createTopicWithInsufficientPollSubject_ShouldFail() throws Exception { Users.signUpAndSignIn(); Topic topic = new Topic(); Poll poll = new Poll("ab"); topic.setPoll(poll); Topics.createTopic(topic); }
Source:
public boolean put(String lookupName, final LookupExtractorFactory lookupExtractorFactory) { try { startStopLock.readLock().lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); } try { assertStarted(); if (lookupMap.containsKey(lookupName)) { LOGGER.warn("lookup [%s] is not add, another lookup with the same name already exist", lookupName); return false; } if (!lookupExtractorFactory.start()) { throw new ISE("start method returned false for lookup [%s]", lookupName); } final boolean noPrior = null == lookupMap.putIfAbsent(lookupName, lookupExtractorFactory); if (noPrior) { if (lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } } else { if (!lookupExtractorFactory.close()) { throw new ISE("Error closing [%s] on race condition", lookupName); } } return noPrior; } finally { startStopLock.readLock().unlock(); } }

Target:
public boolean put(String lookupName, final LookupExtractorFactory lookupExtractorFactory) { try { startStopLock.readLock().lockInterruptibly(); } catch (InterruptedException e) { throw Throwables.propagate(e); } try { assertStarted(); if (lookupMap.containsKey(lookupName)) { LOGGER.warn("lookup [%s] is not add, another lookup with the same name already exist", lookupName); return false; } if (!lookupExtractorFactory.start()) { throw new ISE("start method returned false for lookup [%s]", lookupName); } final boolean noPrior = null == lookupMap.putIfAbsent(lookupName, lookupExtractorFactory); if (noPrior) { if (lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } } else { if (!lookupExtractorFactory.close()) { throw new ISE("Error closing [%s] on race condition", lookupName); } } return noPrior; } finally { startStopLock.readLock().unlock(); } }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>(); permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, getActionType().getActionGroup())); permissionList.add(new PermissionSubject(getVmTemplateId(), VdcObjectType.VmTemplate, getActionType().getActionGroup())); if (getVmTemplate() != null && !getVmTemplate().getDiskList().isEmpty()) { for (DiskImage disk : getParameters().getDiskInfoDestinationMap().values()) { if (disk.getStorageIds() != null && !disk.getStorageIds().isEmpty()) { permissionList.add(new PermissionSubject(GuidUtils.getGuidValue(getStoragePoolId()), VdcObjectType.Storage, ActionGroup.CREATE_DISK)); } } } addPermissionSubjectForAdminLevelProperties(permissionList); return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = new ArrayList<PermissionSubject>(); permissionList.add(new PermissionSubject(getVdsGroupId(), VdcObjectType.VdsGroups, getActionType().getActionGroup())); permissionList.add(new PermissionSubject(getVmTemplateId(), VdcObjectType.VmTemplate, getActionType().getActionGroup())); if (getVmTemplate() != null && !getVmTemplate().getDiskList().isEmpty()) { for (DiskImage disk : getParameters().getDiskInfoDestinationMap().values()) { if (disk.getStorageIds() != null && !disk.getStorageIds().isEmpty()) { permissionList.add(new PermissionSubject(GuidUtils.getGuidValue(getStorageDomainId()), VdcObjectType.Storage, ActionGroup.CREATE_DISK)); } } } addPermissionSubjectForAdminLevelProperties(permissionList); return permissionList; }
Source:
public FSDataInputStream open(Path f, int bufferSize) throws IOException { ChannelSftp channel = connect(); Path workDir; try { workDir = new Path(channel.pwd()); } catch (SftpException e) { throw new IOException(e); } Path absolute = makeAbsolute(workDir, f); FileStatus fileStat = getFileStatus(channel, absolute); if (fileStat.isDirectory()) { disconnect(channel); throw new IOException(String.format(E_PATH_DIR, f)); } try { absolute = new Path("/", channel.realpath(absolute.toUri().getPath())); } catch (SftpException e) { throw new IOException(e); } return new FSDataInputStream( new SFTPInputStream(channel, absolute, statistics)){ @Override public void close() throws IOException { super.close(); disconnect(channel); } }; }

Target:
public FSDataInputStream open(Path f, int bufferSize) throws IOException { ChannelSftp channel = connect(); Path workDir; try { workDir = new Path(channel.pwd()); } catch (SftpException e) { throw new IOException(e); } Path absolute = makeAbsolute(workDir, f); FileStatus fileStat = getFileStatus(channel, absolute); if (fileStat.isDirectory()) { disconnect(channel); throw new IOException(String.format(E_PATH_DIR, f)); } try { absolute = new Path("/", channel.realpath(absolute.toUri().getPath())); } catch (SftpException e) { throw new IOException(e); } return new FSDataInputStream( new SFTPInputStream(channel, absolute, statistics)){ @Override public void close() throws IOException { try { super.close(); } finally { disconnect(channel); } } }; }
Source:
private void onRemove() { if (getProgress() != null) { return; } ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>(); for (ExternalSubnet subnet : getSubnets()) { VdcActionParametersBase parameters = new ExternalSubnetParameters(subnet); list.add(parameters); } startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.RemoveSubnetFromProvider, list, false, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { stopProgress(); cancel(); } }, null); }

Target:
private void onRemove() { ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>(); for (ExternalSubnet subnet : getSubnets()) { VdcActionParametersBase parameters = new ExternalSubnetParameters(subnet); list.add(parameters); } startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.RemoveSubnetFromProvider, list, false, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { stopProgress(); sourceListModel.getSearchCommand().execute(); cancel(); } }, null); }
Source:
public @NonNull CTFCallsite parse(CommonTree tree, ICommonTreeParserParameter param) { final String emptyString = ""; final String regex = "^\"|\"$"; String fileName = null, funcName = null, name = null; long lineNumber =-1, ip = -1; List<CommonTree> children = tree.getChildren(); for (CommonTree child : children) { String left = child.getChild(0).getChild(0).getChild(0).getText(); if (left.equals(NAME)) { name = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(FUNC)) { funcName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(IP)) { ip = Long.decode(child.getChild(1).getChild(0).getChild(0).getText()); } else if (left.equals(FILE)) { fileName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(LINE)) { lineNumber = Long.parseLong(child.getChild(1).getChild(0).getChild(0).getText()); } } if (name == null || funcName == null || fileName == null) { throw new NullPointerException("CTFCallsite parameters shouldn't be null!"); } return new CTFCallsite(name, funcName, ip, fileName, lineNumber); }

Target:
public @NonNull CTFCallsite parse(CommonTree tree, ICommonTreeParserParameter param) { final String emptyString = ""; final String regex = "^\"|\"$"; String fileName = null; String funcName = null; String name = null; long lineNumber =-1; long ip = -1; List<CommonTree> children = tree.getChildren(); for (CommonTree child : children) { String left = child.getChild(0).getChild(0).getChild(0).getText(); if (left.equals(NAME)) { name = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(FUNC)) { funcName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(IP)) { ip = Long.decode(child.getChild(1).getChild(0).getChild(0).getText()); } else if (left.equals(FILE)) { fileName = child.getChild(1).getChild(0).getChild(0).getText().replaceAll(regex, emptyString); } else if (left.equals(LINE)) { lineNumber = Long.parseLong(child.getChild(1).getChild(0).getChild(0).getText()); } } if (name == null || funcName == null || fileName == null) { throw new NullPointerException("CTFCallsite parameters shouldn't be null!"); } return new CTFCallsite(name, funcName, ip, fileName, lineNumber); }
Source:
Collection<String> revsDiffBatch(SQLDatabase db, String docId, Collection<String> revs) throws DatastoreException { Set<String> missingRevs = new HashSet<String>(revs); final String sql = String.format( "SELECT revs.revid FROM docs, revs " + "WHERE docs.doc_id = revs.doc_id AND docs.docid = %s AND revs.revid IN " + "(%s) ", DatabaseUtils.makePlaceholders(1), DatabaseUtils.makePlaceholders(revs.size())); String[] args = new String[1 + revs.size()]; args[0] = docId; System.arraycopy(revs.toArray(new String[revs.size()]), 0, args, 1, revs.size()); Cursor cursor = null; try { cursor = db.rawQuery(sql, args); while (cursor.moveToNext()) { String revId = cursor.getString(cursor.getColumnIndex("revid")); missingRevs.remove(revId); } } catch (SQLException e) { throw new DatastoreException(e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return missingRevs; }

Target:
Collection<String> revsDiffBatch(SQLDatabase db, String docId, Collection<String> revs) throws DatastoreException { Set<String> missingRevs = new HashSet<String>(revs); final String sql = String.format( "SELECT revs.revid FROM docs, revs " + "WHERE docs.doc_id = revs.doc_id AND docs.docid = ? AND revs.revid IN " + "(%s) ", DatabaseUtils.makePlaceholders(revs.size())); String[] args = new String[1 + revs.size()]; args[0] = docId; System.arraycopy(revs.toArray(new String[revs.size()]), 0, args, 1, revs.size()); Cursor cursor = null; try { cursor = db.rawQuery(sql, args); while (cursor.moveToNext()) { String revId = cursor.getString(cursor.getColumnIndex("revid")); missingRevs.remove(revId); } } catch (SQLException e) { throw new DatastoreException(e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return missingRevs; }
Source:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis / 1000)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }

Target:
private void startDiscovery() { discoveryService.scheduleWithFixedDelay(() -> { try { MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1, organizationDiscoveryIntervalMillis)); log.info("Running shard organizer..."); submitJobs(discoverAndInitializeTablesToOrganize()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error running shard organizer"); } }, 0, organizationDiscoveryIntervalMillis, TimeUnit.MILLISECONDS); }