auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void fail(Throwable e) { // The error must be recorded before setting the finish marker to make sure // isFinished will observe failure instead of successful completion. // Only record the first error message. if (setIf(stateReference, State.failed(e), state -> state.getKind() == INITIAL)) { // Stop the split loader before finishing the queue. // Once the queue is finished, it will always return a completed future to avoid blocking any caller. // This could lead to a short period of busy loop in splitLoader (although unlikely in general setup). splitLoader.stop(); queues.finish(); } checkState(stateReference.get().getKind() == FAILED, "Another thread raced to complete this split source before failure info is recorded"); }

Target:
void fail(Throwable e) { // The error must be recorded before setting the finish marker to make sure // isFinished will observe failure instead of successful completion. // Only record the first error message. if (setIf(stateReference, State.failed(e), state -> state.getKind() == INITIAL)) { // Stop the split loader before finishing the queue. // Once the queue is finished, it will always return a completed future to avoid blocking any caller. // This could lead to a short period of busy loop in splitLoader (although unlikely in general setup). splitLoader.stop(); queues.finish(); } }
Source:
public long getSizeInBytes() { // channels is a List created with ImmutableList#copyOf. // Each element of the List is an ObjectArrayList<Block>. // Hence, the memory used by channels is estimated as // <header-size-of-ImmutableList> + // <instance-size-of-ObjectArrayList> * <length-of-outer-list> + // <sum-of-all-Blocks> return INSTANCE_SIZE + IMMUTABLE_LIST_HEADER_SIZE + OBJECT_ARRAY_LIST_INSTANCE_SIZE * channels.size() + channels.stream() .flatMap(List::stream) .mapToLong(Block::getRetainedSizeInBytes) .sum(); }

Target:
public long getSizeInBytes() { return INSTANCE_SIZE + channels.stream() .flatMap(List::stream) .mapToLong(Block::getRetainedSizeInBytes) .sum(); }
Source:
public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table) { ElasticsearchTableHandle handle = checkType(table, ElasticsearchTableHandle.class, "table"); checkArgument(handle.getConnectorId().equals(connectorId), "tableHandle is not for this connector"); SchemaTableName tableName = new SchemaTableName(handle.getSchemaName(), handle.getTableName()); return getTableMetadata(session, tableName); }

Target:
public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table) { ElasticsearchTableHandle handle = (ElasticsearchTableHandle) table; SchemaTableName tableName = new SchemaTableName(handle.getSchemaName(), handle.getTableName()); return getTableMetadata(tableName); }
Source:
public void cleanUp() { es.shutdown(); }

Target:
private void cleanUp() { es.shutdown(); }
Source:
public void close() { checkState(initialized.get(), "Driver is not initialized"); // mark the service for destruction if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) { return; } exclusiveLock.interruptCurrentOwner(); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown tryWithLock(() -> TRUE); }

Target:
public void close() { // mark the service for destruction if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) { return; } exclusiveLock.interruptCurrentOwner(); // if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown tryWithLock(() -> TRUE); }
Source:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { this.hostLocationHandle = requireNonNull(hostLocationHandle, "hostLocationHandle is null"); this.prestoThriftService = requireNonNull(prestoThriftService, "prestoThriftService is null"); }

Target:
public DefaultThriftService(PrestoThriftService prestoThriftService, HostLocationHandle hostLocationHandle) { this.prestoThriftService = requireNonNull(prestoThriftService, "prestoThriftService is null"); this.hostLocationHandle = requireNonNull(hostLocationHandle, "hostLocationHandle is null"); }
Source:
public static ColumnIO getArrayElementColumn(ColumnIO columnIO) { while ((columnIO instanceof GroupColumnIO) && !columnIO.getType().isRepetition(REPEATED)) { columnIO = ((GroupColumnIO) columnIO).getChild(0); } if (columnIO instanceof GroupColumnIO && columnIO.getType().getOriginalType() == null && ((GroupColumnIO) columnIO).getChildrenCount() == 1) { return ((GroupColumnIO) columnIO).getChild(0); } return columnIO; }

Target:
public static ColumnIO getArrayElementColumn(ColumnIO columnIO) { while (columnIO instanceof GroupColumnIO && !columnIO.getType().isRepetition(REPEATED)) { columnIO = ((GroupColumnIO) columnIO).getChild(0); } /* If array has a standard 3-level structure with middle level repeated group with a single field: * optional group my_list (LIST) { * repeated group element { * required binary str (UTF8); * }; * } */ if (columnIO instanceof GroupColumnIO && columnIO.getType().getOriginalType() == null && ((GroupColumnIO) columnIO).getChildrenCount() == 1) { return ((GroupColumnIO) columnIO).getChild(0); } /* Backward-compatibility support for 2-level arrays where a repeated field is not a group: * optional group my_list (LIST) { * repeated int32 element; * } */ return columnIO; }
Source:
public void testClientTagsBasedSelection() throws InterruptedException { InternalResourceGroupManager manager = queryRunner.getCoordinator().getResourceGroupManager().get(); DbResourceGroupConfigurationManager dbConfigurationManager = (DbResourceGroupConfigurationManager) manager.getConfigurationManager(); dbConfigurationManager.load(); assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), "global.bi-user"); assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), "global.user-user.adhoc-user"); }

Target:
public void testClientTagsBasedSelection() throws InterruptedException { assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), "global.bi-user"); assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), "global.user-user.adhoc-user"); }
Source:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = OGCGeometry.createFromEsriGeometry(new Point(x, y), null); return serialize(geometry); }

Target:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = createFromEsriGeometry(new Point(x, y), null); return serialize(geometry); }
Source:
static Expression rewrite(Expression expression, Rule.Context context) { return LambdaCaptureDesugaringRewriter.rewrite(expression, context.getSymbolAllocator().getTypes(), context.getSymbolAllocator()); }

Target:
private static Expression rewrite(Expression expression, Rule.Context context) { return LambdaCaptureDesugaringRewriter.rewrite(expression, context.getSymbolAllocator().getTypes(), context.getSymbolAllocator()); }
Source:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); checkArgument(!(expression instanceof GroupingOperation), "GroupingOperation should have been re-written to a FunctionCall before execution"); if (expression instanceof SymbolReference) { return expression; } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList()); // parameters already replaced return rewrite(expression, expressionTypes); }

Target:
public static Expression rewrite(Expression expression, Session session, Metadata metadata, SqlParser sqlParser, SymbolAllocator symbolAllocator) { requireNonNull(metadata, "metadata is null"); requireNonNull(sqlParser, "sqlParser is null"); if (expression instanceof SymbolReference) { return expression; } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, metadata, sqlParser, symbolAllocator.getTypes(), expression, emptyList()); // parameters already replaced return rewrite(expression, expressionTypes); }
Source:
public String toString() { String predicate = Joiner.on("AND") .join(filterExpectedMappings.entrySet().stream() .map(entry -> entry.getKey() + " = " + entry.getValue()) .collect(toImmutableList())); return toStringHelper(this) .add("predicate", filterExpectedMappings) .toString(); }

Target:
public String toString() { String predicate = Joiner.on("AND") .join(filterExpectedMappings.entrySet().stream() .map(entry -> entry.getKey() + " = " + entry.getValue()) .collect(toImmutableList())); return toStringHelper(this) .add("predicate", predicate) .toString(); }
Source:
void trivialMatchers() { //any assertMatch(any(), 42); assertMatch(any(), "John Doe"); //class based assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); }

Target:
public void trivialMatchers() { //any assertMatch(any(), 42); assertMatch(any(), "John Doe"); //class based assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); }
Source:
public ListeningScheduledExecutorService createRetryDriverScheduledExecutor(ThriftConnectorConfig config) { return MoreExecutors.listeningDecorator(newScheduledThreadPool(config.getRetryDriverThreads(), threadsNamed("thrift-retry-driver-%s"))); }

Target:
public ListeningScheduledExecutorService createRetryDriverScheduledExecutor(ThriftConnectorConfig config) { return listeningDecorator(newScheduledThreadPool(config.getRetryDriverThreads(), threadsNamed("thrift-retry-driver-%s"))); }
Source:
private String convertDaysToMidnightTimestamp(String columnName) { // A date is stored as an integer of days from 1970-01-01. Multiplying it by milliseconds per day renders the UTC midnight timestamp, which is stored as a bigint. return format("(CAST (%s AS BIGINT) * %s)", columnName, TimeUnit.DAYS.toMillis(1)); }

Target:
private String convertDaysToMidnightTimestamp(String columnName) { // A date is stored as an integer of days from 1970-01-01. Multiplying it by milliseconds per day renders the UTC midnight timestamp, which is stored as a bigint. return format("(CAST (%s AS BIGINT) * %s)", columnName, DAYS.toMillis(1)); }
Source:
private static Iterable<Expression> pullNullableConjunctsThroughOuterJoin(List<Expression> conjuncts, Collection<Symbol> outputSymbols, Predicate<Symbol>... nullSymbolScopes) { // Conjuncts without any symbol dependencies cannot be applied to the effective predicate (e.g. FALSE literal) return conjuncts.stream() .map(expression -> pullExpressionThroughSymbols(expression, outputSymbols)) .map(expression -> SymbolsExtractor.extractAll(expression).anyMatch(alwaysTrue()) ? TRUE_LITERAL : expression) .map(expressionOrNullSymbols(nullSymbolScopes)) .collect(toImmutableList()); }

Target:
private static Iterable<Expression> pullNullableConjunctsThroughOuterJoin(List<Expression> conjuncts, Collection<Symbol> outputSymbols, Predicate<Symbol>... nullSymbolScopes) { // Conjuncts without any symbol dependencies cannot be applied to the effective predicate (e.g. FALSE literal) return conjuncts.stream() .map(expression -> pullExpressionThroughSymbols(expression, outputSymbols)) .map(expression -> isEmpty(SymbolsExtractor.extractAll(expression)) ? TRUE_LITERAL : expression) .map(expressionOrNullSymbols(nullSymbolScopes)) .collect(toImmutableList()); }
Source:
private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getDomains().get().entrySet().stream() .filter(entrySet -> isPathColumnHandle(entrySet.getKey())) .findFirst() .map(entrySet -> entrySet.getValue()); }

Target:
private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getDomains().get().entrySet().stream() .filter(entry -> isPathColumnHandle(entry.getKey())) .findFirst() .map(Map.Entry::getValue); }
Source:
public static Slice crc32(@SqlType(StandardTypes.VARBINARY) Slice slice) { Slice hash = Slices.allocate(Long.BYTES); CRC32 crc32 = new CRC32(); crc32.update(slice.toByteBuffer()); // The expectation is that CRC32 is unsigned, so this won't fit // correctly in a 32 signed integer, therefore this uses a long. long crc32Value = crc32.getValue(); hash.setLong(0, Long.reverseBytes(crc32Value)); return hash; }

Target:
public static long crc32(@SqlType(StandardTypes.VARBINARY) Slice slice) { CRC32 crc32 = new CRC32(); crc32.update(slice.toByteBuffer()); return crc32.getValue(); }
Source:
public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); // process any pending reads from the client buffers for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { if (masterBuffer.isEmpty()) { clientBuffer.setNoMorePages(); } else { clientBuffer.loadPagesIfNecessary(masterBuffer); } } checkFlushComplete(); }

Target:
public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); // process any pending reads from the client buffers for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { clientBuffer.loadPagesIfNecessary(masterBuffer); } checkFlushComplete(); }
Source:
private void reset() { probeIndexBuilder.reset(); buildPageBuilder.reset(); // Reset source page when probe reached the end. if (reachedProbeEnd) { probe = null; } }

Target:
private void reset() { probeIndexBuilder.clear(); buildPageBuilder.reset(); // Reset source page when probe reached the end. if (reachedProbeEnd) { probe = null; } }
Source:
public Optional<Decorrelated> visitFilter(FilterNode node, PlanNode reference) { Optional<Decorrelated> result = decorrelate(node.getSource()); return result.map(decorrelated -> { return new Decorrelated( ImmutableList.<Expression>builder() .addAll(decorrelated.getCorrelatedPredicates()) // No need to retain uncorrelated conditions, predicate push down will push them back .add(node.getPredicate()) .build(), decorrelated.getDecorrelatedNode() ); }); }

Target:
public Optional<Decorrelated> visitFilter(FilterNode node, PlanNode reference) { Optional<Decorrelated> result = decorrelate(node.getSource()); return result.map(decorrelated -> new Decorrelated( ImmutableList.<Expression>builder() .addAll(decorrelated.getCorrelatedPredicates()) // No need to retain uncorrelated conditions, predicate push down will push them back .add(node.getPredicate()) .build(), decorrelated.getDecorrelatedNode() )); }
Source:
public String idFromValueAndType(Object value, Class<?> suggestedType) { requireNonNull(value, "value is null"); if(value instanceof TupleExpression) { TupleExpression expression = (TupleExpression)value; if(expression instanceof DomainExpression) { return expression.getName() + "@@" + nameResolver.apply((ColumnHandle) ((DomainExpression) expression).getColumn()) ; } return expression.getName(); } else return null; }

Target:
public String idFromValueAndType(Object value, Class<?> suggestedType) { requireNonNull(value, "value is null"); if (value instanceof TupleExpression) { TupleExpression expression = (TupleExpression) value; if (expression instanceof DomainExpression) { return expression.getName() + "@@" + nameResolver.apply((ColumnHandle) ((DomainExpression) expression).getColumn()); } return expression.getName(); } else { return null; } }
Source:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { try { start.await(); point.proceed(); // @checkstyle IllegalCatchCheck (1 line) } catch (Throwable ex) { return ex; } return null; } }; }

Target:
private Callable<Throwable> callable(final ProceedingJoinPoint point, final CountDownLatch start) { return new Callable<Throwable>() { @Override public Throwable call() { Throwable result = null; try { start.await(); point.proceed(); // @checkstyle IllegalCatchCheck (1 line) } catch (Throwable ex) { result = ex; } return result; } }; }
Source:
protected void removeAllAnnotations() { // clear normal markers for (int i = 0; i < timarkers.size(); i++) { TiMarker timarker = timarkers.get(i); if (timarker.getMarker() != null) { timarker.getMarker().remove(); timarker.release(); } } timarkers.clear(); // clear cluster markers if (mClusterManager != null) { mClusterManager.clearItems(); mClusterManager.cluster(); } }

Target:
protected void removeAllAnnotations() { // clear normal markers for (int i = 0; i < timarkers.size(); i++) { TiMarker timarker = timarkers.get(i); if (timarker.getMarker() != null) { timarker.getMarker().remove(); } timarker.release(); } timarkers.clear(); // clear cluster markers if (mClusterManager != null) { mClusterManager.clearItems(); mClusterManager.cluster(); } }
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions.build(), (JavascriptStateValidator) (driver, output, events) -> { assertThat(jsDriver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }

Target:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { testExecutor.configure().init(defaultArguments()); JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }
Source:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { try { testExecutor.configure() .init(defaultArguments()); } catch (WebDriverException ex) { // should happen } JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }

Target:
public void testScopeInLoginOptionsShouldBeConsideredByLoginUrl() { testExecutor.configure().init(defaultArguments()); JSObjectBuilder loginOptions = JSObjectBuilder.create().add("scope", "profile email phone"); testExecutor.login(loginOptions, (JavascriptStateValidator) (driver, output, events) -> { assertThat(driver.getCurrentUrl(), containsString("&scope=openid%20profile%20email%20phone")); }); }
Source:
public void setAttribute(String name, List<String> values) { // Remove all existing removeAttribute(name); List<String> nonNullValues = values.stream().filter(Objects::nonNull).collect(Collectors.toList()); // Put all new nonNull values for (String value : nonNullValues) { persistAttributeValue(name, value); } }

Target:
public void setAttribute(String name, List<String> values) { // Remove all existing removeAttribute(name); for (Iterator<String> it = values.stream().filter(Objects::nonNull).iterator(); it.hasNext();) { persistAttributeValue(name, it.next()); } }
Source:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { String result = detail.substring(0, maxDetailLength).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }

Target:
private String trimToMaxLength(String detail) { if (detail != null && detail.length() > maxDetailLength) { // (maxDetailLength - 3) takes "..." into account String result = detail.substring(0, maxDetailLength - 3).concat("..."); logger.warn("Detail was truncated to " + result); return result; } else { return detail; } }
Source:
public VaultRawSecret getRawSecret(final String value) { String entryId = this.getVaultEntryKey(value); if (entryId != null) { if (this.provider == null) { throw new IllegalStateException("Required VaultProvider not found - check vault configuration"); } // we have a valid ${vault.<KEY>} string, use the provider to retrieve the entry. return this.provider.obtainSecret(entryId); } else { // this should be avoided by calling isVaultEntry with the value before attempting to use this method. ByteBuffer buffer = value != null ? ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)) : null; return DefaultVaultRawSecret.forBuffer(Optional.ofNullable(buffer)); } }

Target:
public VaultRawSecret getRawSecret(final String value) { String entryId = this.getVaultEntryKey(value); if (entryId != null) { // we have a valid ${vault.<KEY>} string, use the provider to retrieve the entry. return this.provider.obtainSecret(entryId); } else { // not a vault expression - encode the value itself as a byte buffer. ByteBuffer buffer = value != null ? ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)) : null; return DefaultVaultRawSecret.forBuffer(Optional.ofNullable(buffer)); } }
Source:
public List<GroupModel> getGroups() { List<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { // Use just group mappings from LDAP return ldapGroupMappings; } else { // Merge mappings from both DB and LDAP List<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }

Target:
public Set<GroupModel> getGroups() { Set<GroupModel> ldapGroupMappings = getLDAPGroupMappingsConverted(); if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) { // Use just group mappings from LDAP return ldapGroupMappings; } else { // Merge mappings from both DB and LDAP Set<GroupModel> modelGroupMappings = super.getGroups(); ldapGroupMappings.addAll(modelGroupMappings); return ldapGroupMappings; } }
Source:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; // KEYCLOAK-8460 client signed signature verification SignatureVerifierContext verifier(ClientModel client, JWSInput input) throws VerificationException; @Override default void close() { }

Target:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; @Override default void close() { }
Source:
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { if (request.getSession(false) == null && KeycloakCookieBasedRedirect.getRedirectUrlFromCookie(request) == null) { // If no session exists yet at this point, then apparently the redirect URL is not // stored in a session. We'll store it in a cookie instead. response.addCookie(KeycloakCookieBasedRedirect.createCookieFromRedirectUrl(request.getRequestURI())); } String contextAwareLoginUri = request.getContextPath() + loginUri; log.debug("Redirecting to login URI {}", contextAwareLoginUri); response.sendRedirect(contextAwareLoginUri); }

Target:
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { String contextAwareLoginUri = request.getContextPath() + loginUri; log.debug("Redirecting to login URI {}", contextAwareLoginUri); response.sendRedirect(contextAwareLoginUri); }
Source:
public AbstractSequence<NucleotideCompound> getSequence() throws CompoundNotFoundException { try { DNASequenceCreator creator = new DNASequenceCreator(ABITracerCompoundSet.getABITracerCompoundSet()); return creator.getSequence(sequence, 0); } catch (Exception e) { // this should be impossible! throw new CompoundNotFoundException(e.toString()); } }

Target:
public AbstractSequence<NucleotideCompound> getSequence() throws CompoundNotFoundException { DNASequenceCreator creator = new DNASequenceCreator(ABITracerCompoundSet.getABITracerCompoundSet()); return creator.getSequence(sequence, 0); }
Source:
public void testAcetylation() { try { File localFile = getLocalFileName(Dataset.ACETYLATION); List<Site> sites = Site.parseSites(localFile); assertTrue(sites.size() > 0); for (Site s : sites) { assertTrue(s.getResidue() != null); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }

Target:
public void testAcetylation() throws IOException { File localFile = getLocalFileName(Dataset.ACETYLATION); List<Site> sites = Site.parseSites(localFile); assertTrue(sites.size() > 0); for (Site s : sites) { assertTrue(s.getResidue() != null); } }
Source:
private String getClassName(String niceIndexName) throws StandardException { String cName = ""; if(niceIndexName!=null){ cName = "IndexScan["+niceIndexName+"]"; }else{ cName = "TableScan["+getPrettyTableName(); if(pastTxId >= 0){ cName += " timeTravelTx(" + pastTxId + ")"; } cName += "]"; } if(isMultiProbing()) cName = "MultiProbe"+cName; if (isDistinctScan()) cName = "Distinct" + cName; if (specialMaxScan) cName = "LastKey" + cName; return cName; }

Target:
private String getClassName(String niceIndexName) throws StandardException { String cName = ""; if(niceIndexName!=null){ cName = "IndexScan["+niceIndexName; }else{ cName = "TableScan["+getPrettyTableName(); if(pastTxId >= 0){ cName += " timeTravelTx(" + pastTxId + ")"; } cName += "]"; } if(isMultiProbing()) cName = "MultiProbe"+cName; if (isDistinctScan()) cName = "Distinct" + cName; if (specialMaxScan) cName = "LastKey" + cName; return cName; }
Source:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; this.submittedTime = (Date)submittedTime.clone(); this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }

Target:
public RunningOperation(SpliceOperation operation, Thread thread, Date submittedTime, DataSetProcessor.Type engine, UUID uuid, String rdbIntTkn) { this.operation = operation; this.thread =thread; // EI_EXPOSE_REP2: May expose internal representation by incorporating // reference to mutable object // todo(martinrupp) replace java.util.Date with java.time.Instance, see // https://stackoverflow.com/questions/36639154/convert-java-util-date-to-what-java-time-type this.submittedTime = submittedTime; this.engine = engine; this.uuid = uuid; this.rdbIntTkn = rdbIntTkn; }
Source:
public static String getDefaultBeanName(String className){ int lastDotPosition = className.lastIndexOf("."); //$NON-NLS-1$ if(lastDotPosition >= 0 && className.length() > lastDotPosition){ className = className.substring(+1); } if(className.length() > 0) { className = className.substring(0, 1).toLowerCase() + className.substring(1); } return className; }

Target:
public static String getDefaultBeanName(String className){ int lastDotPosition = className.lastIndexOf("."); //$NON-NLS-1$ if(lastDotPosition >= 0 && className.length() > lastDotPosition){ className = className.substring(lastDotPosition+1); } if(className.length() > 0) { className = className.substring(0, 1).toLowerCase() + className.substring(1); } return className; }
Source:
public String get(String name) { List<String> valuesList = values(name); String requestId = null; if (valuesList != null && valuesList.size() > 0) { requestId = valuesList.get(0); } return requestId; }

Target:
public String get(String name) { List<String> valuesList = values(name); String value = null; if (valuesList != null && valuesList.size() > 0) { value = valuesList.get(0); } return value; }
Source:
private List<Row> getKeyHeads() { List<Row> keyHeads = new ArrayList<Row>(rows.size()); for (Row row : rows) { final List<Cell> cells = row.getCellsCopy(); // Hack: replace timestamp cell with sint64 cell. keyHeads.add(new Row(cells.get(0), cells.get(1), new Cell(cells.get(2).getTimestamp()))); } return keyHeads; }

Target:
private static List<Row> getKeyHeads() { List<Row> keyHeads = new ArrayList<Row>(rows.size()); for (Row row : rows) { final List<Cell> cells = row.getCellsCopy(); keyHeads.add(new Row(cells.get(0), cells.get(1), cells.get(2))); } return keyHeads; }
Source:
public boolean isClientHealthy(RawClient client) { try { //-- First check to see if client is up client.ping(); //-- Check to see if client has joined ring by check to see if it has any buckets return !client.listBuckets().isEmpty(); } catch (IOException ioe) { return false; } }

Target:
public boolean isClientHealthy(RawClient client) { try { client.ping(); return true; } catch (IOException ioe) { return false; } }
Source:
public IContextInformation getContextInformation() { return new IContextInformation() { @Override public String getContextDisplayString() { return "Added " + bundle + " to build path"; } @Override public Image getImage() { return Icons.image("bundle"); } @Override public String getInformationDisplayString() { return "Added " + bundle + " to build path - info"; } }; }

Target:
public IContextInformation getContextInformation() { return null; }
Source:
boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) .filter(inner -> Objects.nonNull(inner.inner_name)) .anyMatch(inner -> !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); }

Target:
boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) .anyMatch(inner -> (inner.inner_name != null) && !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); }
Source:
public void testControlBulkOperationsEnabled() { boolean enabled = false; List a = Collections.singletonList(mockButton); when(rightActionsToolbar.spliterator()) .thenReturn(Spliterators.spliteratorUnknownSize(a.iterator(), 0)); when(extendedPagedTable.hasSelectedItems()).thenReturn(enabled); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(enabled); }

Target:
public void testControlBulkOperationsEnabled() { when(extendedPagedTable.hasSelectedItems()).thenReturn(true); getView().controlBulkOperations(extendedPagedTable); verify(mockButton).setEnabled(true); }
Source:
public void displayNotification(String text) { notification.fire(new NotificationEvent(text)); }

Target:
private void displayNotification(String text) { notification.fire(new NotificationEvent(text)); }
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); viewPresenter.openView(request,id); }

Target:
public void openErrorView(final String id){ viewPresenter.openErrorView(id); }
Source:
private void createScheduler() throws SchedulerException { // backwards compatibility - only use this when something is provided in // the config if (!configuration.getQuartzConfiguration().isEmpty()) { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(createProperties()); scheduler = factory.getScheduler(); return; } scheduler = StdSchedulerFactory.getDefaultScheduler(); }

Target:
private void createScheduler() throws SchedulerException { if (configuration.getQuartzConfiguration().isEmpty()) { scheduler = StdSchedulerFactory.getDefaultScheduler(); return; } StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(createProperties()); scheduler = factory.getScheduler(); }
Source:
private String applyUrlRewrites(String url) { String path = URI.create(url).getPath(); for (Map.Entry<String, String> rewrite : urlRewrites.entrySet()) { if (path.startsWith(rewrite.getKey())) { return url.replaceFirst(rewrite.getKey(), rewrite.getValue()); } } return url; }

Target:
private String applyUrlRewrites(String url) { try { String path = URI.create(url).getPath(); for (Map.Entry<String, String> rewrite : urlRewrites.entrySet()) { if (path.startsWith(rewrite.getKey())) { return url.replaceFirst(rewrite.getKey(), rewrite.getValue()); } } return url; } catch (IllegalArgumentException e) { return url; } }
Source:
public void after() throws IOException { EasyMock.verify(_mocks.toArray()); // Delete all camus data folder.delete(); }

Target:
public void after() throws IOException { // Delete all camus data folder.delete(); }
Source:
public void resourceChanged(IResourceChangeEvent event) { if(event.getType() == IResourceChangeEvent.PRE_DELETE) { IResource resource = event.getResource(); IProject project = (IProject)resource.getAdapter(IProject.class); if(project != null) { if(mockProjectStore.containsKey(project)) { System.out.println("remove " + project); } mockProjectStore.remove(project); } } }

Target:
public void resourceChanged(IResourceChangeEvent event) { if(event.getType() == IResourceChangeEvent.PRE_DELETE) { IResource resource = event.getResource(); IProject project = (IProject)resource.getAdapter(IProject.class); if(project != null) { mockProjectStore.remove(project); } } }
Source:
protected T cache( final T type ) { if ( t == null ) t = type; return type == null ? t : type; }

Target:
protected void cache( final T type ) { if ( this.type == null ) this.type = type; }
Source:
public HttpHeaders getHttpHeader(MediaType mediaType) { return HttpHeaders .of(HttpStatus.OK) .add(HttpHeaderNames.SERVER, "armeria") .add(HttpHeaderNames.DATE, DateTimeFormatter.RFC_1123_DATE_TIME .format(ZonedDateTime.now(ZoneOffset.UTC))) .contentType(mediaType); }

Target:
public static HttpHeaders getHttpHeader(MediaType mediaType) { return HttpHeaders .of(HttpStatus.OK) .add(HttpHeaderNames.SERVER, "armeria") .add(HttpHeaderNames.DATE, DateTimeFormatter.RFC_1123_DATE_TIME .format(ZonedDateTime.now(ZoneOffset.UTC))) .contentType(mediaType); }
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { BulkChange b = new BulkChange(this); SMTPAuthentication current = this.authentication; try { // reset optional authentication to default before data-binding // Would not be necessary by https://github.com/jenkinsci/jenkins/pull/3669 this.authentication = null; req.bindJSON(this, json); b.commit(); } catch (IOException e) { this.authentication = current; b.abort(); throw new FormException("Failed to apply configuration", e, null); } return true; }

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { BulkChange b = new BulkChange(this); SMTPAuthentication current = this.authentication; try { // reset optional authentication to default before data-binding // Would not be necessary by https://github.com/jenkinsci/jenkins/pull/3669 this.authentication = null; req.bindJSON(this, json); b.commit(); } catch (IOException e) { b.abort(); throw new FormException("Failed to apply configuration", e, null); } finally { this.authentication = current; } return true; }
Source:
public void autoService() { JavaSourcesSubject.assertThat( JavaFileObjects.forResource("test/SomeService.java"), JavaFileObjects.forResource("test/SomeServiceProvider1.java"), JavaFileObjects.forResource("test/SomeServiceProvider2.java"), JavaFileObjects.forResource("test/Enclosing.java"), JavaFileObjects.forResource("test/AnotherService.java"), JavaFileObjects.forResource("test/AnotherServiceProvider.java")) .processedWith(new AutoServiceProcessor()) .compilesWithoutError() .and().generatesFiles( JavaFileObjects.forResource("META-INF/services/test.SomeService"), JavaFileObjects.forResource("META-INF/services/test.AnotherService")); }

Target:
public void autoService() { assertThat( JavaFileObjects.forResource("test/SomeService.java"), JavaFileObjects.forResource("test/SomeServiceProvider1.java"), JavaFileObjects.forResource("test/SomeServiceProvider2.java"), JavaFileObjects.forResource("test/Enclosing.java"), JavaFileObjects.forResource("test/AnotherService.java"), JavaFileObjects.forResource("test/AnotherServiceProvider.java")) .processedWith(new AutoServiceProcessor()) .compilesWithoutError() .and().generatesFiles( JavaFileObjects.forResource("META-INF/services/test.SomeService"), JavaFileObjects.forResource("META-INF/services/test.AnotherService")); }
Source:
public Parser<String, Object> makeParser() { if(flattenSpec != null) { return new JSONPathParser(convertFieldSpecs(flattenSpec.getFields()), flattenSpec.isUseFieldDiscovery(), null); } else { return new JSONParser(objectMapper, null); } }

Target:
public Parser<String, Object> makeParser() { return new JSONPathParser( convertFieldSpecs(flattenSpec.getFields()), flattenSpec.isUseFieldDiscovery(), objectMapper ); }
Source:
private static CuRequisitionDocument buildMockCuRequisitionDocument() { PowerMockito.suppress(PowerMockito.constructor(LedgerPostingDocumentBase.class)); CuRequisitionDocument document = PowerMockito.spy(new CuRequisitionDocument()); return document; }

Target:
private static CuRequisitionDocument buildMockCuRequisitionDocument() { CuRequisitionDocument document = PowerMockito.spy(new CuRequisitionDocument()); return document; }
Source:
private void logAccountingLineBaseList(List accountingLines, StringBuilder sb) { List<AccountingLineBase> accountingLineBases = accountingLines; accountingLineBases.stream().map(line -> line.toString()).forEach(sb::append); }

Target:
private void logAccountingLineBaseList(List accountingLines, StringBuilder sb) { List<AccountingLineBase> accountingLineBases = accountingLines; accountingLineBases.stream().map(AccountingLineBase::toString).forEach(sb::append); }
Source:
public boolean fileApprovedAmountsMatchHeaderApprovedAmount(ConcurRequestExtractFile requestExtractFile) { KualiDecimal detailLinesAmountSumKualiDecimal = getTotalRequestFileRequestAmount(requestExtractFile); if (detailLinesAmountSumKualiDecimal.doubleValue() == requestExtractFile.getTotalApprovedAmount().doubleValue()) { return true; } else { LOG.error("Header amount validation failed. Header amount was =" + requestExtractFile.getTotalApprovedAmount().toString() + "= while file calculated amount was =" + detailLinesAmountSumKualiDecimal.toString() + "="); return false; } }

Target:
private boolean fileApprovedAmountsMatchHeaderApprovedAmount(ConcurRequestExtractFile requestExtractFile) { KualiDecimal detailLinesAmountSumKualiDecimal = getTotalRequestFileRequestAmount(requestExtractFile); if (detailLinesAmountSumKualiDecimal.equals(requestExtractFile.getTotalApprovedAmount())) { return true; } else { LOG.error("Header amount validation failed. Header amount was =" + requestExtractFile.getTotalApprovedAmount().toString() + "= while file calculated amount was =" + detailLinesAmountSumKualiDecimal.toString() + "="); return false; } }
Source:
Loader( final TaskScheduler taskScheduler, final Environment environment, final GenieFileTransferService fileTransferService, final MeterRegistry registry ) { this.environment = environment; this.registry = registry; this.fileTransferService = fileTransferService; // Schedule the task to run with the configured refresh rate // Task will be stopped when the system stops final long refreshRate = environment.getProperty( ScriptLoadBalancerProperties.REFRESH_RATE_PROPERTY, Long.class, 300_000L ); taskScheduler.scheduleWithFixedDelay(this::refresh, refreshRate); }

Target:
protected Loader( final TaskScheduler taskScheduler, final Environment environment, final GenieFileTransferService fileTransferService, final MeterRegistry registry ) { this.environment = environment; this.registry = registry; this.fileTransferService = fileTransferService; // Schedule the task to run with the configured refresh rate // Task will be stopped when the system stops final long refreshRate = environment.getProperty( ScriptLoadBalancerProperties.REFRESH_RATE_PROPERTY, Long.class, 300_000L ); taskScheduler.scheduleWithFixedDelay(this::refresh, refreshRate); }
Source:
public void jobUpdate(final JobEntity jobEntity) { final JobStatus currentState = jobEntity.getStatus(); final JobStatus previouslyNotifiedState = jobEntity.getNotifiedJobStatus(); final String jobId = jobEntity.getUniqueId(); if (currentState != previouslyNotifiedState) { log.info( "Detected state change for job: from: to: {}", jobId, previouslyNotifiedState, currentState ); // Notify observer if not null if (this.persistedJobStatusObserver != null) { this.persistedJobStatusObserver.notify(jobId, previouslyNotifiedState, currentState); } // Save this as the latest published state jobEntity.setNotifiedJobStatus(currentState); } }

Target:
public void jobUpdate(final JobEntity jobEntity) { final JobStatus currentState = jobEntity.getStatus(); final JobStatus previouslyNotifiedState = jobEntity.getNotifiedJobStatus(); final String jobId = jobEntity.getUniqueId(); if (currentState != previouslyNotifiedState) { log.info( "Detected state change for job: from: to: {}", jobId, previouslyNotifiedState, currentState ); // Notify observer this.persistedJobStatusObserver.notify(jobId, previouslyNotifiedState, currentState); // Save this as the latest published state jobEntity.setNotifiedJobStatus(currentState); } }
Source:
public Server gRpcServer( @Value("${grpc.server.port:0}") final int port, final Set<BindableService> services, final List<ServerInterceptor> serverInterceptors ) { final NettyServerBuilder builder = NettyServerBuilder.forPort( port == RANDOM_PORT ? SocketUtils.findAvailableTcpPort() : port ); // Add Service interceptors and add services to the server services .stream() .map(BindableService::bindService) .map(serviceDefinition -> ServerInterceptors.intercept(serviceDefinition, serverInterceptors)) .forEach(builder::addService); return builder.build(); }

Target:
public Server gRpcServer( @Value("${grpc.server.port:0}") final int port, // TODO: finalize how to get configure this property final Set<BindableService> services, final List<ServerInterceptor> serverInterceptors ) { final NettyServerBuilder builder = NettyServerBuilder.forPort(port); // Add Service interceptors and add services to the server services .stream() .map(BindableService::bindService) .map(serviceDefinition -> ServerInterceptors.intercept(serviceDefinition, serverInterceptors)) .forEach(builder::addService); return builder.build(); }
Source:
public static String[] getOptionArguments(final String[] args) { final List<String> temporary = Arrays.asList(args); final int index = temporary.indexOf(BARE_DOUBLE_DASH); if (index == -1) { // All arguments are options if no explicit double dash is passed return args; } else if (index == 0) { // Double dash as first argument means all arguments are parameters return new String[0]; } else { // All argument up to (and not including) the double dash return temporary.subList(0, index).toArray(new String[index]); } }

Target:
public static String[] getOptionArguments(final String[] args) { final List<String> temporary = new ArrayList<>(args.length); for (int i = 0; i < args.length; i++) { if (BARE_DOUBLE_DASH.equals(args[i])) { break; } temporary.add(args[i]); } return temporary.toArray(new String[temporary.size()]); }
Source:
public void setUp() throws IOException { final Registry registry = Mockito.mock(Registry.class); this.initialSetupTask = new InitialSetupTask(registry); this.temporaryTestDirectory = Files.createTempDirectory(this.getClass().getSimpleName() + "-"); }

Target:
public void setUp() throws IOException { final Registry registry = Mockito.mock(Registry.class); this.initialSetupTask = new InitialSetupTask(registry); }
Source:
private void validateHostAndUpdateErrorCount(final String host) { final boolean isNodeHealthy = isNodeHealthy(host); // // If node is healthy, remove the entry from the errorCounts. // If node is not healthy, update the entry in errorCounts // if (isNodeHealthy) { if (errorCounts.containsKey(host)) { errorCounts.remove(host); } } else { if (this.errorCounts.containsKey(host)) { this.errorCounts.put(host, this.errorCounts.get(host) + 1); } else { this.errorCounts.put(host, 1); } } }

Target:
private void validateHostAndUpdateErrorCount(final String host) { // // If node is healthy, remove the entry from the errorCounts. // If node is not healthy, update the entry in errorCounts // if (isNodeHealthy(host)) { if (errorCounts.containsKey(host)) { errorCounts.remove(host); } } else { if (this.errorCounts.containsKey(host)) { this.errorCounts.put(host, this.errorCounts.get(host) + 1); } else { this.errorCounts.put(host, 1); } } }
Source:
public void executeTask( @NotNull final Map<String, Object> context ) throws GenieException { log.debug("Executing JobKillLogic Task in the workflow."); super.executeTask(context); // Append logic for handling job kill signal Utils.appendToWriter(writer, JobConstants.JOB_KILL_HANDLER_LOGIC.toString()); }

Target:
public void executeTask( @NotNull final Map<String, Object> context ) throws GenieException { log.debug("Executing JobKillLogic Task in the workflow."); super.executeTask(context); // Append logic for handling job kill signal Utils.appendToWriter(writer, JobConstants.JOB_KILL_HANDLER_LOGIC); }
Source:
public TopologyInfo getTopologyInfoByNameWithOpts(String name, GetInfoOptions options) throws NotAliveException, AuthorizationException, TException { try { getTopologyInfoByNameWithOptsCalls.mark(); return getTopologyInfoByNameImpl(name, options); } catch (Exception e) { LOG.warn("get topology info withOpts by name exception. (topology name={})", name, e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }

Target:
public TopologyInfo getTopologyInfoByNameWithOpts(String name, GetInfoOptions options) throws TException { try { getTopologyInfoByNameWithOptsCalls.mark(); return getTopologyInfoByNameImpl(name, options); } catch (Exception e) { LOG.warn("get topology info withOpts by name exception. (topology name={})", name, e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
public List<TopologySummary> getTopologySummaries() throws AuthorizationException, TException { try { getTopologySummariesCalls.mark(); checkAuthorization(null, null, "getTopologySummaries"); return getTopologySummariesImpl(); } catch (Exception e) { LOG.warn("Get TopologySummary info exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }

Target:
public List<TopologySummary> getTopologySummaries() throws TException { try { getTopologySummariesCalls.mark(); checkAuthorization(null, null, "getTopologySummaries"); return getTopologySummariesImpl(); } catch (Exception e) { LOG.warn("Get TopologySummary info exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
private void seekOffsetByStartTimeStamp(TopicPartition tp) { long startTimeStampOffset; Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes = consumer.offsetsForTimes(Collections.singletonMap(tp, startTimeStamp)); OffsetAndTimestamp startOffsetAndTimeStamp = offsetsForTimes.get(tp); startTimeStampOffset = startOffsetAndTimeStamp.offset(); LOG.debug("First poll for topic partition [{}], seeking to partition from startTimeStamp [{}]", tp, startTimeStamp); consumer.seek(tp, startTimeStampOffset); }

Target:
private void seekOffsetByStartTimeStamp(TopicPartition tp) { Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes = consumer.offsetsForTimes(Collections.singletonMap(tp, startTimeStamp)); OffsetAndTimestamp startOffsetAndTimeStamp = offsetsForTimes.get(tp); long startTimeStampOffset = startOffsetAndTimeStamp.offset(); LOG.debug("First poll for topic partition [{}], seeking to partition from startTimeStamp [{}]", tp, startTimeStamp); consumer.seek(tp, startTimeStampOffset); }