auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public HikariPool(final HikariConfig config) { super(config); this.connectionBag = new ConcurrentBag<>(this); this.suspendResumeLock = config.isAllowPoolSuspension() ? new SuspendResumeLock() : SuspendResumeLock.FAUX_LOCK; this.houseKeepingExecutorService = initializeHouseKeepingExecutorService(); checkFailFast(); if (config.getMetricsTrackerFactory() != null) { setMetricsTrackerFactory(config.getMetricsTrackerFactory()); } else { setMetricRegistry(config.getMetricRegistry()); } setHealthCheckRegistry(config.getHealthCheckRegistry()); handleMBeans(this, true); ThreadFactory threadFactory = config.getThreadFactory(); LinkedBlockingQueue<Runnable> addQueue = new LinkedBlockingQueue<>(config.getMaximumPoolSize()); this.addConnectionQueue = unmodifiableCollection(addQueue); this.addConnectionExecutor = createAddConnectionExecutor(threadFactory, addQueue); this.closeConnectionExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection " + "closer", threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); this.leakTaskFactory = new ProxyLeakTaskFactory(config.getLeakDetectionThreshold(), houseKeepingExecutorService); this.houseKeeperTask = houseKeepingExecutorService.scheduleWithFixedDelay(new HouseKeeper(), 100L, housekeepingPeriodMs, MILLISECONDS); }

Target:
public HikariPool(final HikariConfig config) { super(config); this.connectionBag = new ConcurrentBag<>(this); this.suspendResumeLock = config.isAllowPoolSuspension() ? new SuspendResumeLock() : SuspendResumeLock.FAUX_LOCK; this.houseKeepingExecutorService = initializeHouseKeepingExecutorService(); checkFailFast(); if (config.getMetricsTrackerFactory() != null) { setMetricsTrackerFactory(config.getMetricsTrackerFactory()); } else { setMetricRegistry(config.getMetricRegistry()); } setHealthCheckRegistry(config.getHealthCheckRegistry()); handleMBeans(this, true); ThreadFactory threadFactory = config.getThreadFactory(); LinkedBlockingQueue<Runnable> addQueue = new LinkedBlockingQueue<>(config.getMaximumPoolSize()); this.addConnectionQueue = unmodifiableCollection(addQueue); this.addConnectionExecutor = createAddConnectionExecutor(threadFactory, addQueue); this.closeConnectionExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + " connection closer", threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); this.leakTaskFactory = new ProxyLeakTaskFactory(config.getLeakDetectionThreshold(), houseKeepingExecutorService); this.houseKeeperTask = houseKeepingExecutorService.scheduleWithFixedDelay(new HouseKeeper(), 100L, housekeepingPeriodMs, MILLISECONDS); if (isBlockedInitialization(config)) { blockUntilPoolInitialized(config); } }
Source:
public int compare(SearchResult o1, SearchResult o2) { if ((o1.getComponent() instanceof FeedItem) && (o2.getComponent() instanceof FeedItem)) return ((FeedItem) o2.getComponent()).getPubDate().compareTo(((FeedItem) o1.getComponent()).getPubDate()); return 0; }

Target:
public int compare(SearchResult o1, SearchResult o2) { if ((o1.getComponent() instanceof FeedItem) && (o2.getComponent() instanceof FeedItem)) { FeedItem item1 = (FeedItem) o1.getComponent(); FeedItem item2 = (FeedItem) o2.getComponent(); return item2.getPubDate().compareTo(item1.getPubDate()); } return 0; }
Source:
public static int addGracePeriod(int interval) { return interval + (int) (interval * 0.2); }

Target:
public static int addGracePeriod(int interval) { return interval + (int) (interval * GRACE_PERIOD); }
Source:
protected String addRulesBoltDependenciesFactory () { String rulesProcessorBuilderRef = addRulesProcessorBuilder(); String dependenciesFactoryId = "dependenciesFactory" + UUID_FOR_COMPONENTS; String dependenciesFactoryClassName = "com.hortonworks.iotas.streams.runtime.rule.RulesDependencyFactory"; List constructorArgs = new ArrayList(); Map ref = getRefYaml(rulesProcessorBuilderRef); constructorArgs.add(ref); constructorArgs.add("GROOVY"); this.addToComponents(this.createComponent(dependenciesFactoryId, dependenciesFactoryClassName, null, constructorArgs, null)); return dependenciesFactoryId; }

Target:
protected String addRulesBoltDependenciesFactory () { String rulesProcessorBuilderRef = addRulesProcessorBuilder(); String dependenciesFactoryId = "dependenciesFactory" + UUID_FOR_COMPONENTS; String dependenciesFactoryClassName = "com.hortonworks.iotas.streams.runtime.rule.RulesDependenciesFactory"; List constructorArgs = new ArrayList(); Map ref = getRefYaml(rulesProcessorBuilderRef); constructorArgs.add(ref); constructorArgs.add("GROOVY"); this.addToComponents(this.createComponent(dependenciesFactoryId, dependenciesFactoryClassName, null, constructorArgs, null)); return dependenciesFactoryId; }
Source:
public void getMetadataInvalid() { config.getMetadata(null); assertNotNull(logger.getMsg()); }

Target:
public void getMetadataInvalid() { assertNull(config.getMetadata(null)); assertNotNull(logger.getMsg()); }
Source:
public ImmutableSet<EventClass> rejections() { ImmutableSet<EventClass> result = commands.methods() .stream() .flatMap(m -> m.rejections().stream()) .collect(toImmutableSet()); return result; }

Target:
public ImmutableSet<EventClass> rejections() { ImmutableSet<EventClass> result = commands.methods() .stream() .map(CommandAcceptingMethod::rejections) .flatMap(ImmutableSet::stream) .collect(toImmutableSet()); return result; }
Source:
public void considersKillingVetos() throws Exception { if (ProcessTree.get() == ProcessTree.DEFAULT) return; ProcessBuilder pb = new ProcessBuilder(); pb.environment().put("cookie", "testKeepDaemonsAlive"); if (File.pathSeparatorChar == ';') { pb.command("cmd"); } else { pb.command("sleep", "5m"); } process = pb.start(); ProcessTree processTree = ProcessTree.get(); processTree.killAll(ImmutableMap.of("cookie", "testKeepDaemonsAlive")); try { process.exitValue(); fail("Process should have been excluded from the killing"); } catch (IllegalThreadStateException e) { } }

Target:
public void considersKillingVetos() throws Exception { assumeTrue(ProcessTree.get() != ProcessTree.DEFAULT); ProcessBuilder pb = new ProcessBuilder(); pb.environment().put("cookie", "testKeepDaemonsAlive"); if (File.pathSeparatorChar == ';') { pb.command("cmd"); } else { pb.command("sleep", "5m"); } process = pb.start(); ProcessTree processTree = ProcessTree.get(); processTree.killAll(ImmutableMap.of("cookie", "testKeepDaemonsAlive")); try { process.exitValue(); fail("Process should have been excluded from the killing"); } catch (IllegalThreadStateException e) { } }
Source:
public ProtostreamTranscoder(SerializationContext ctx, ClassLoader classLoader) { super(APPLICATION_PROTOSTREAM, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_JSON, APPLICATION_UNKNOWN); this.ctx = ctx; this.marshaller = new ProtoStreamMarshaller(ctx); this.classLoader = classLoader; }

Target:
public ProtostreamTranscoder(SerializationContext ctx, ClassLoader classLoader) { super(APPLICATION_PROTOSTREAM, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_JSON, APPLICATION_UNKNOWN); this.ctx = ctx; this.classLoader = classLoader; }
Source:
public void run() { try { fLaunch.terminate(); setImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_DISABLED_COLOR)); } catch (DebugException e) { GdbUIPlugin.log(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Unable to terminate launch", e)); } }

Target:
public void run() { try { fLaunch.terminate(); } catch (DebugException e) { GdbUIPlugin.log(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Unable to terminate launch", e)); } }
Source:
public long save() { validateToSave(); try { final Connection connection = DB.getConnection(); final PreparedStatement ps = connection.prepareStatement(CREATE_SQL); final long id = System.currentTimeMillis(); ps.setLong(1, id); ps.setDouble(2, getLengthInches()); ps.setString(3, getWood().name()); ps.setString(4, getCore().name()); ps.execute(); ps.close(); connection.close(); return id; } catch (final SQLException e) { throw new RuntimeException(e); } }

Target:
public long save() { validateToSave(); Connection connection = null; PreparedStatement ps = null; try { connection = DB.getConnection(); ps = connection.prepareStatement(CREATE_SQL); final long id = System.currentTimeMillis(); ps.setLong(1, id); ps.setDouble(2, getLengthInches()); ps.setString(3, getWood().name()); ps.setString(4, getCore().name()); ps.execute(); return id; } catch (final SQLException e) { throw new RuntimeException(e); } finally { DB.closePreparedStatement(ps); DB.closeConnection(connection); } }
Source:
public static KafkaStateChangelogOffset fromString(String message) { if (StringUtils.isBlank(message)) { throw new IllegalArgumentException("Invalid checkpointed changelog message: " + message); } String[] checkpointIdAndOffset = message.split(SEPARATOR); if (checkpointIdAndOffset.length < 2 || checkpointIdAndOffset.length > 3) { throw new IllegalArgumentException("Invalid checkpointed changelog offset: " + message); } CheckpointId checkpointId = CheckpointId.fromString(checkpointIdAndOffset[0]); String offset = null; if (!"null".equals(checkpointIdAndOffset[1])) { offset = checkpointIdAndOffset[1]; } return new KafkaStateChangelogOffset(checkpointId, offset); }

Target:
public static KafkaStateChangelogOffset fromString(String message) { if (StringUtils.isBlank(message)) { throw new IllegalArgumentException("Invalid checkpointed changelog message: " + message); } String[] checkpointIdAndOffset = message.split(SEPARATOR); if (checkpointIdAndOffset.length != 2) { throw new IllegalArgumentException("Invalid checkpointed changelog offset: " + message); } CheckpointId checkpointId = CheckpointId.fromString(checkpointIdAndOffset[0]); String offset = null; if (!"null".equals(checkpointIdAndOffset[1])) { offset = checkpointIdAndOffset[1]; } return new KafkaStateChangelogOffset(checkpointId, offset); }
Source:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); BCSiliconConfig.reloadConfig(EnumRestartRequirement.GAME); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }

Target:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }
Source:
private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.builder() .setHighValue(NaN) .setLowValue(NaN) .setNullsFraction(1.0) .setDistinctValuesCount(0.0) .build(); } double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); }

Target:
private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.zero(); } double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); }
Source:
public int hashCode() { int result = Objects.hashCode(summary); result += StringUtils.isEmpty(component) ? Objects.hashCode(description) : Objects.hashCode(component); return result * 31; }

Target:
public int hashCode() { return Objects.hash(summary, component, description); }
Source:
private void calcStartAngles() { startAngles[0] = firstSectorAngle; for (int i = 1; i < numberOfValues; i++) { startAngles[i] = startAngles[i - 1] + arcLengths[i - 1]; } }

Target:
private void calcStartAngles() { mStartAngles[0] = mFirstSectorAngle; for (int i = 1; i < mNumberOfValues; i++) { mStartAngles[i] = mStartAngles[i - 1] + mArcLengths[i - 1]; } }
Source:
public void testRemoveAllIdentifiableNode() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { Node node = storage.createNode(Mods.NAME); node.add(storage.createNode("http://names.example/alice")); Node bob = storage.createNode("http://names.example/bob"); node.add(bob); node.add(storage.createNode("http://names.example/charlie")); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(3)); IdentifiableNode two = storage.createNodeReference(RDF.toURL(2)); assertThat(node.removeAll(two), contains(bob)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); assertThat(node.removeAll(two), is(nullValue())); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); } }

Target:
public void testRemoveAllIdentifiableNode() { for (Storage storage : TestConfig.STORAGES_TO_TEST_AGAINST) { Node node = storage.createNode(MODS_NAME); node.add(storage.createNode("http://names.example/alice")); Node bob = storage.createNode("http://names.example/bob"); node.add(bob); node.add(storage.createNode("http://names.example/charlie")); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(3)); IdentifiableNode two = storage.createNodeReference(RDF.toURL(2)); assertThat(node.removeAll(two), contains(bob)); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); assertThat(node.removeAll(two), is(nullValue())); assertThat(node.getEnumerated().stream().mapToInt(r -> r.isAny() ? 1 : 0).sum(), is(2)); } }
Source:
private void enterSettingScreen() { getActivity(); onView(withId(R.id.decor_content_parent)).perform(TestUtils.clickScreenPosition(0, 0)); onView(withText(R.string.settings)).perform(click()); }

Target:
private void enterSettingScreen() { getActivity(); TestUtils.toggleNavigationDrawer(); onView(withText(R.string.settings)).perform(click()); }
Source:
public void print() { Iterator<Row> it = collect(); while (it.hasNext()) { Row row = it.next(); System.out.println(row.toString()); } }

Target:
public void print() { Iterator<Row> it = collect(); PrintUtils.printAsTableauForm(getTableSchema(), it, new PrintWriter(System.out)); }
Source:
public Object perform(InvocationContext ctx) throws Throwable { Map<Object, Object> map = createMap(); for (Object key : keys) { CacheEntry entry = ctx.lookupEntry(key); if (entry == null) { if (trace) { log.tracef("Entry for key %s not found", key); } if (ch == null || ch.isKeyLocalToNode(localAddress, key)) { map.put(key, null); } continue; } if (entry.isNull()) { if (trace) { log.tracef("Entry for key %s is null in current context", key); } map.put(key, null); continue; } if (entry.isRemoved()) { if (trace) { log.tracef("Entry for key %s has been deleted and is of type %s", key, entry.getClass().getSimpleName()); } map.put(key, null); continue; } if (returnEntries) { CacheEntry copy; if (ctx.isOriginLocal()) { copy = entryFactory.copy(entry); } else { copy = entry; } if (trace) { log.tracef("Found entry %s -> %s", key, entry); log.tracef("Returning copied entry %s", copy); } map.put(key, copy); } else { Object value = entry.getValue(); if (trace) { log.tracef("Found %s -> %s", key, toStr(value)); } map.put(key, value); } } return map; }

Target:
public Object perform(InvocationContext ctx) throws Throwable { Map<Object, Object> map = createMap(); for (Object key : keys) { CacheEntry entry = ctx.lookupEntry(key); if (entry == null) { if (trace) { log.tracef("Entry for key %s not found", key); } continue; } if (entry.isNull()) { if (trace) { log.tracef("Entry for key %s is null in current context", key); } map.put(key, null); continue; } if (entry.isRemoved()) { if (trace) { log.tracef("Entry for key %s has been deleted and is of type %s", key, entry.getClass().getSimpleName()); } map.put(key, null); continue; } if (returnEntries) { CacheEntry copy; if (ctx.isOriginLocal()) { copy = entryFactory.copy(entry); } else { copy = entry; } if (trace) { log.tracef("Found entry %s -> %s", key, entry); log.tracef("Returning copied entry %s", copy); } map.put(key, copy); } else { Object value = entry.getValue(); if (trace) { log.tracef("Found %s -> %s", key, toStr(value)); } map.put(key, value); } } return map; }
Source:
public void doScrape() throws Exception { MBeanServerConnection beanConn; JMXConnector jmxc = null; if (jmxUrl.isEmpty()) { beanConn = ManagementFactory.getPlatformMBeanServer(); } else { Map<String, Object> environment = new HashMap<String, Object>(); if (username != null && username.length() != 0 && password != null && password.length() != 0) { String[] credent = new String[] {username, password}; environment.put(javax.management.remote.JMXConnector.CREDENTIALS, credent); } if (ssl) { environment.put(Context.SECURITY_PROTOCOL, "ssl"); SslRMIClientSocketFactory clientSocketFactory = new SslRMIClientSocketFactory(); environment.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory); environment.put("com.sun.jndi.rmi.factory.socket", clientSocketFactory); } jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxUrl), environment); beanConn = jmxc.getMBeanServerConnection(); } try { Set<ObjectInstance> mBeanNames = new HashSet(); for (ObjectName name : whitelistObjectNames) { mBeanNames.addAll(beanConn.queryMBeans(name, null)); } for (ObjectName name : blacklistObjectNames) { mBeanNames.removeAll(beanConn.queryMBeans(name, null)); } for (ObjectInstance name : mBeanNames) { long start = System.nanoTime(); scrapeBean(beanConn, name.getObjectName()); logger.fine("TIME " + (System.nanoTime() - start) + " : " + name.getObjectName().toString()); } } finally { if (jmxc != null) { jmxc.close(); } } }

Target:
public void doScrape() throws Exception { MBeanServerConnection beanConn; JMXConnector jmxc = null; if (jmxUrl.isEmpty()) { beanConn = ManagementFactory.getPlatformMBeanServer(); } else { Map<String, Object> environment = new HashMap<String, Object>(); if (username != null && username.length() != 0 && password != null && password.length() != 0) { String[] credent = new String[] {username, password}; environment.put(javax.management.remote.JMXConnector.CREDENTIALS, credent); } if (ssl) { environment.put(Context.SECURITY_PROTOCOL, "ssl"); SslRMIClientSocketFactory clientSocketFactory = new SslRMIClientSocketFactory(); environment.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory); environment.put("com.sun.jndi.rmi.factory.socket", clientSocketFactory); } jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxUrl), environment); beanConn = jmxc.getMBeanServerConnection(); } try { Set<ObjectInstance> mBeanNames = new HashSet(); for (ObjectName name : whitelistObjectNames) { mBeanNames.addAll(beanConn.queryMBeans(name, null)); } for (ObjectName name : blacklistObjectNames) { mBeanNames.removeAll(beanConn.queryMBeans(name, null)); } for (ObjectInstance name : mBeanNames) { long start = System.nanoTime(); scrapeBean(beanConn, name.getObjectName()); logger.fine("TIME: " + (System.nanoTime() - start) + " ns for " + name.getObjectName().toString()); } } finally { if (jmxc != null) { jmxc.close(); } } }
Source:
private static ORidBag readRidbag(BytesContainer bytes) { byte configByte = OByteSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset++); boolean isEmbedded = (configByte & 1) != 0; UUID uuid = null; ORidBag ridbag = null; if (isEmbedded) { ridbag = new ORidBag(); int size = OVarIntSerializer.readAsInteger(bytes); ridbag.getDelegate().setSize(size); for (int i = 0; i < size; i++) { OIdentifiable record = readLinkOptimizedEmbedded(bytes); if (record == null) { String errorMessage = "Deserialized null object during ridbag deserialization"; OSerializationException exc = new OSerializationException(""); OLogManager.instance().error(ORecordSerializerBinaryV1.class, errorMessage, null); throw exc; } else ((OEmbeddedRidBag) ridbag.getDelegate()).addEntry(record); } } else { long fileId = OVarIntSerializer.readAsLong(bytes); long pageIndex = OVarIntSerializer.readAsLong(bytes); int pageOffset = OVarIntSerializer.readAsInteger(bytes); OVarIntSerializer.readAsInteger(bytes); OBonsaiCollectionPointer pointer = null; if (fileId != -1) pointer = new OBonsaiCollectionPointer(fileId, new OBonsaiBucketPointer(pageIndex, pageOffset)); Map<OIdentifiable, Change> changes = new HashMap<>(); int changesSize = OVarIntSerializer.readAsInteger(bytes); for (int i = 0; i < changesSize; i++) { OIdentifiable recId = readLinkOptimizedSBTree(bytes); Change change = deserializeChange(bytes); changes.put(recId, change); } ridbag = new ORidBag(pointer, changes, uuid); ridbag.getDelegate().setSize(-1); } return ridbag; }

Target:
private static ORidBag readRidbag(BytesContainer bytes) { byte configByte = OByteSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset++); boolean isEmbedded = (configByte & 1) != 0; UUID uuid = null; ORidBag ridbag = null; if (isEmbedded) { ridbag = new ORidBag(); int size = OVarIntSerializer.readAsInteger(bytes); ridbag.getDelegate().setSize(size); for (int i = 0; i < size; i++) { OIdentifiable record = readLinkOptimizedEmbedded(bytes); ((OEmbeddedRidBag) ridbag.getDelegate()).addEntry(record); } } else { long fileId = OVarIntSerializer.readAsLong(bytes); long pageIndex = OVarIntSerializer.readAsLong(bytes); int pageOffset = OVarIntSerializer.readAsInteger(bytes); OVarIntSerializer.readAsInteger(bytes); OBonsaiCollectionPointer pointer = null; if (fileId != -1) pointer = new OBonsaiCollectionPointer(fileId, new OBonsaiBucketPointer(pageIndex, pageOffset)); Map<OIdentifiable, Change> changes = new HashMap<>(); int changesSize = OVarIntSerializer.readAsInteger(bytes); for (int i = 0; i < changesSize; i++) { OIdentifiable recId = readLinkOptimizedSBTree(bytes); Change change = deserializeChange(bytes); changes.put(recId, change); } ridbag = new ORidBag(pointer, changes, uuid); ridbag.getDelegate().setSize(-1); } return ridbag; }
Source:
private void applyFactorsFilter(final StringBuilder sql, final String variableId, final String variableType, final boolean performLikeOperation) { final String observationUnitClause = VariableType.OBSERVATION_UNIT.name().equals(variableType) ? "nde.observation_unit_no" : null; final String filterClause = factorsFilterMap.get(variableId); final String finalId = variableId.replace("-", ""); final String matchClause = performLikeOperation ? " LIKE :" + finalId + "_text " : " IN (:" + finalId + "_values) "; if (filterClause != null || observationUnitClause != null) { sql.append(" AND ").append(observationUnitClause != null ? observationUnitClause : filterClause).append(matchClause); return; } if (VariableType.GERMPLASM_DESCRIPTOR.name().equals(variableType)) { final String stockMatchClause = performLikeOperation ? "sp.value LIKE :" + variableId + "_text " : " (cvt.name IN (:" + variableId + "_values) OR sp.value IN (:" + variableId + "_values ))"; sql.append(" AND EXISTS ( SELECT 1 FROM stockprop sp " + "LEFT JOIN cvterm cvt ON cvt.cvterm_id = sp.value " + "WHERE sp.stock_id = s.stock_id AND sp.type_id = :" + variableId + "_Id AND ").append(stockMatchClause).append(" )"); } }

Target:
private void applyFactorsFilter(final StringBuilder sql, final String variableId, final String variableType, final boolean performLikeOperation) { final String filterClause = factorsFilterMap.get(variableId); if (filterClause != null) { final String finalId = variableId.replace("-", ""); final String matchClause = performLikeOperation ? " LIKE :" + finalId + "_text " : " IN (:" + finalId + "_values) "; sql.append(" AND ").append(filterClause).append(matchClause); if (variableId.equalsIgnoreCase(String.valueOf(TermId.GID_ACTIVE_LOTS_COUNT.getId())) || variableId.equalsIgnoreCase(String.valueOf(TermId.GID_UNIT.getId()))) sql.append(") "); return; } if (VariableType.GERMPLASM_DESCRIPTOR.name().equals(variableType)) { final String stockMatchClause = performLikeOperation ? "sp.value LIKE :" + variableId + "_text " : " (cvt.name IN (:" + variableId + "_values) OR sp.value IN (:" + variableId + "_values ))"; sql.append(" AND EXISTS ( SELECT 1 FROM stockprop sp " + "LEFT JOIN cvterm cvt ON cvt.cvterm_id = sp.value " + "WHERE sp.stock_id = s.stock_id AND sp.type_id = :" + variableId + "_Id AND ").append(stockMatchClause).append(" )"); } }
Source:
public void shouldReturnAllSavedRules(){ List<SpamRule> expectedList = listOfRandomSpamRules(10); persistObjects(expectedList); List<SpamRule> actualList = dao.getAllRules(); assertReflectionEquals(expectedList, actualList); }

Target:
public void shouldReturnAllSavedRules() { List<SpamRule> expectedList = persistObjects(listOfRandomSpamRules(10)); List<SpamRule> actualList = dao.getAllRules(); assertEquals(actualList.size(), expectedList.size()); for (SpamRule expected : expectedList) { assertTrue(actualList.contains(expected)); } }
Source:
private GenContext serializeArguments(List<FormalArg> args, GenContext ctx) { if(isGeneric()) { ValueType type = this.genericStructuralType(); args.add(new FormalArg(GENERIC_PREFACE, type)); ctx = ctx.extend(GENERIC_PREFACE, new Variable(GENERIC_PREFACE), type); } for (NameBinding b : argNames) { String bName = b.getName(); Type t = b.getType(); ValueType type = null; if( isGeneric() && t instanceof UnresolvedType && ((UnresolvedType) t).getName().equals(this.genTypeName) ) { type = new NominalType(new Variable(GENERIC_PREFACE), GENERIC_MEMBER); } else { type = t.getILType(ctx); } FormalArg fa = new FormalArg(bName, type); args.add(fa); ctx = ctx.extend(bName, new Variable(bName), type); } return ctx; }

Target:
private GenContext serializeArguments(List<FormalArg> args, GenContext ctx) { if(isGeneric()) { for(String s : this.generics) { ValueType type = this.genericStructuralType(s); String genName = GENERIC_PREFIX + s; args.add(new FormalArg(genName, type)); ctx = new TypeGenContext(s, genName, ctx); ctx = ctx.extend(genName, new Variable(genName), type); } } for (NameBinding b : argNames) { String bName = b.getName(); Type t = b.getType(); ValueType type = t.getILType(ctx); FormalArg fa = new FormalArg(bName, type); args.add(fa); ctx = ctx.extend(bName, new Variable(bName), type); } return ctx; }
Source:
ByteBuffer encrypt(ByteBuffer toEncrypt, T key) throws GeneralSecurityException; default ByteBuf encrypt(ByteBuf toEncrypt, T key) throws GeneralSecurityException { ByteBuffer encrypted = encrypt(toEncrypt.nioBuffer(), key); ByteBuf result = ByteBufAllocator.DEFAULT.ioBuffer(encrypted.remaining()); result.writeBytes(encrypted); return result; }

Target:
ByteBuffer encrypt(ByteBuffer toEncrypt, T key) throws GeneralSecurityException; default ByteBuf encrypt(ByteBuf toEncrypt, T key) throws GeneralSecurityException { ByteBuffer encrypted = encrypt(toEncrypt.nioBuffer(), key); return Unpooled.wrappedBuffer(encrypted); }
Source:
public MetaData getMetaData(final MetaDataKey key) throws SomeException { DefaultMetaDataBuilder builder = new DefaultMetaDataBuilder(); return new DefaultMetaData(builder.build()); }

Target:
public MetaData getMetaData(final MetaDataKey key) throws SomeException { DefaultMetaDataBuilder builder = new DefaultMetaDataBuilder(); return null; }
Source:
private boolean validateNetworkAttachmentsFromRequest(List<? extends BusinessEntity<?>> newOrUpdateBusinessEntities) { SeparateNewAndModifiedInstances instances = new SeparateNewAndModifiedInstances(newOrUpdateBusinessEntities); List<String> validationMessages = new ArrayList<>(); validationMessages.addAll(callValidationOnAllItems(instances.getNewEntities(), CreateEntity.class, Default.class)); validationMessages.addAll(callValidationOnAllItems(instances.getUpdatedEntities(), UpdateEntity.class, Default.class)); getReturnValue().getCanDoActionMessages().addAll(validationMessages); return validationMessages.isEmpty(); }

Target:
private boolean validateNetworkAttachmentsFromRequest(List<? extends BusinessEntity<?>> newOrUpdateBusinessEntities) { SeparateNewAndModifiedInstances instances = new SeparateNewAndModifiedInstances(newOrUpdateBusinessEntities); List<String> validationMessages = new ArrayList<>(); validationMessages.addAll(callValidationOnAllItems(instances.getNewEntities(), CreateEntity.class, Default.class)); validationMessages.addAll(callValidationOnAllItems(instances.getUpdatedEntities(), UpdateEntity.class, Default.class)); return !getReturnValue().getCanDoActionMessages().addAll(validationMessages); }
Source:
private ExpressionResult executeExpressions(final Expression expression, final Class<? extends Annotation> annotationClass, Expression.EvaluationMode mode) { ExpressionResult result = expression.evaluate(mode); if (log.isTraceEnabled()) { String checkKey = expression.toString(); Long checkOccurrences = checkStats.getOrDefault(checkKey, 0L) + 1; checkStats.put(checkKey, checkOccurrences); } if (result == DEFERRED) { if (mode == Expression.EvaluationMode.USER_CHECKS_ONLY) { return DEFERRED; } if (isInlineOnlyCheck(annotationClass)) { result = expression.evaluate(Expression.EvaluationMode.ALL_CHECKS); if (result == FAIL) { ForbiddenAccessException e = new ForbiddenAccessException( getSimpleName(annotationClass), expression, Expression.EvaluationMode.ALL_CHECKS); if (log.isTraceEnabled()) { log.trace("{}", e.getLoggedMessage()); } throw e; } } else { commitCheckQueue.add(new QueuedCheck(expression, annotationClass)); } return DEFERRED; } if (result == FAIL) { ForbiddenAccessException e = new ForbiddenAccessException(getSimpleName(annotationClass), expression, mode); if (log.isTraceEnabled()) { log.trace("{}", e.getLoggedMessage()); } throw e; } return result; }

Target:
private ExpressionResult executeExpressions(final Expression expression, final Class<? extends Annotation> annotationClass, Expression.EvaluationMode mode) { ExpressionResult result = expression.evaluate(mode); if (log.isTraceEnabled()) { String checkKey = expression.toString(); Long checkOccurrences = checkStats.getOrDefault(checkKey, 0L) + 1; checkStats.put(checkKey, checkOccurrences); } if (result == DEFERRED) { if (mode == Expression.EvaluationMode.USER_CHECKS_ONLY) { return DEFERRED; } if (isInlineOnlyCheck(annotationClass)) { result = expression.evaluate(Expression.EvaluationMode.ALL_CHECKS); if (result == FAIL) { ForbiddenAccessException e = new ForbiddenAccessException( EntityDictionary.getSimpleName(annotationClass), expression, Expression.EvaluationMode.ALL_CHECKS); if (log.isTraceEnabled()) { log.trace("{}", e.getLoggedMessage()); } throw e; } } else { commitCheckQueue.add(new QueuedCheck(expression, annotationClass)); } return DEFERRED; } if (result == FAIL) { ForbiddenAccessException e = new ForbiddenAccessException( EntityDictionary.getSimpleName(annotationClass), expression, mode); if (log.isTraceEnabled()) { log.trace("{}", e.getLoggedMessage()); } throw e; } return result; }
Source:
protected void internalProcessHttpErrorResponse(HttpWebRequest httpWebResponse, Exception webException, TraceFlags responseHeadersTraceFlag, TraceFlags responseTraceFlag) throws Exception { EwsUtilities.EwsAssert(500 != httpWebResponse.getResponseCode(), "ExchangeServiceBase.InternalProcessHttpErrorResponse", "InternalProcessHttpErrorResponse does not handle 500 ISE errors, the caller is supposed to handle this."); this.processHttpResponseHeaders(responseHeadersTraceFlag, httpWebResponse); if (httpWebResponse.getResponseCode() == 456) { String location = httpWebResponse.getResponseContentType(); URI accountUnlockUrl = null; if (checkURIPath(location)) { accountUnlockUrl = new URI(location); } this.traceMessage(responseTraceFlag, String.format("Account is locked. Unlock URL is %s", accountUnlockUrl)); throw new AccountIsLockedException(String.format(Strings.AccountIsLocked, accountUnlockUrl), accountUnlockUrl, webException); } }

Target:
protected void internalProcessHttpErrorResponse(HttpWebRequest httpWebResponse, Exception webException, TraceFlags responseHeadersTraceFlag, TraceFlags responseTraceFlag) throws Exception { EwsUtilities.EwsAssert(500 != httpWebResponse.getResponseCode(), "ExchangeServiceBase.InternalProcessHttpErrorResponse", "InternalProcessHttpErrorResponse does not handle 500 ISE errors, the caller is supposed to handle this."); this.processHttpResponseHeaders(responseHeadersTraceFlag, httpWebResponse); if (httpWebResponse.getResponseCode() == 456) { String location = httpWebResponse.getResponseContentType(); URI accountUnlockUrl = null; if (checkURIPath(location)) { accountUnlockUrl = new URI(location); } final String message = String.format(Strings.AccountIsLocked, accountUnlockUrl); this.traceMessage(responseTraceFlag, message); throw new AccountIsLockedException(message, accountUnlockUrl, webException); } }
Source:
private void addPlugins(CucumberOptions options, List<String> args) { List<String> plugins = new ArrayList<String>(); plugins.addAll(asList(options.plugin())); for (String plugin : plugins) { args.add("--plugin"); args.add(plugin); if (PluginFactory.isPluginName(plugin)) { pluginSpecified = true; } } }

Target:
private void addPlugins(CucumberOptions options, List<String> args) { List<String> plugins = new ArrayList<>(); plugins.addAll(asList(options.plugin())); for (String plugin : plugins) { args.add("--plugin"); args.add(plugin); } }
Source:
private static void appendUserFiles(PythonEnvironment env, List<Path> userFileList) throws IOException { List<String> pythonPathList = new ArrayList<>(); Path tmpDirPath = new Path(env.tempDirectory); for (Path pythonFile : userFileList) { String sourceFileName = pythonFile.getName(); Path targetPath = new Path( tmpDirPath, String.join(File.separator, UUID.randomUUID().toString(), sourceFileName)); try { if (!pythonFile.getFileSystem().isDistributedFS()) { if (!pythonFile.getFileSystem().exists(pythonFile)) { LOG.error(pythonFile + " not exists, skipping..."); continue; } new File(targetPath.getParent().toString()).mkdir(); createSymbolicLinkForPyflinkLib( Paths.get(new File(pythonFile.getPath()).getAbsolutePath()), Paths.get(targetPath.toString())); } else { FileUtils.copy(pythonFile, targetPath, true); } } catch (Exception e) { LOG.error("Error occured when copying user python files, skipping...", e); continue; } if (Files.isRegularFile(Paths.get(targetPath.toString()).toRealPath()) && sourceFileName.endsWith(".py")) { pythonPathList.add(targetPath.getParent().toString()); } else { pythonPathList.add(targetPath.toString()); } } if (env.pythonPath != null && !env.pythonPath.isEmpty()) { pythonPathList.add(env.pythonPath); } env.pythonPath = String.join(File.pathSeparator, pythonPathList); }

Target:
private static void appendUserFiles(PythonEnvironment env, List<Path> userFileList) throws IOException { List<String> pythonPathList = new ArrayList<>(); Path tmpDirPath = new Path(env.tempDirectory); for (Path pythonFile : userFileList) { String sourceFileName = pythonFile.getName(); Path targetPath = new Path( tmpDirPath, String.join(File.separator, UUID.randomUUID().toString(), sourceFileName)); if (!pythonFile.getFileSystem().isDistributedFS()) { new File(targetPath.getParent().toString()).mkdir(); createSymbolicLinkForPyflinkLib( Paths.get(new File(pythonFile.getPath()).getAbsolutePath()), Paths.get(targetPath.toString())); } else { try { FileUtils.copy(pythonFile, targetPath, true); } catch (Exception e) { LOG.error("Error occured when copying user python files from DFS, skipping...", e); continue; } } if (Files.isRegularFile(Paths.get(targetPath.toString()).toRealPath()) && sourceFileName.endsWith(".py")) { pythonPathList.add(targetPath.getParent().toString()); } else { pythonPathList.add(targetPath.toString()); } } if (env.pythonPath != null && !env.pythonPath.isEmpty()) { pythonPathList.add(env.pythonPath); } env.pythonPath = String.join(File.pathSeparator, pythonPathList); }
Source:
private static boolean isSerdeSupported(Properties schema) { String serdeName = getDeserializerClassName(schema); if (!SUPPORTED_SERDES.contains(serdeName)) { return false; } return true; }

Target:
private static boolean isSerdeSupported(Properties schema) { String serdeName = getDeserializerClassName(schema); return SUPPORTED_SERDES.contains(serdeName); }
Source:
public ElasticsearchTableDescription getTable(String schemaName, String tableName) { requireNonNull(schemaName, "schemaName is null"); requireNonNull(tableName, "tableName is null"); ElasticsearchTableDescription table = tableDescriptions.get(new SchemaTableName(schemaName, tableName)); if (table == null) { return null; } if (table.getColumns().isPresent()) { return table; } List<ElasticsearchColumn> columns = buildColumns(table); ElasticsearchTableDescription result = new ElasticsearchTableDescription( table.getTableName(), table.getSchemaName(), table.getHost(), table.getPort(), table.getClusterName(), table.getIndex(), table.getIndexExactMatch(), table.getType(), Optional.of(columns)); return result; }

Target:
public ElasticsearchTableDescription getTable(String schemaName, String tableName) { requireNonNull(schemaName, "schemaName is null"); requireNonNull(tableName, "tableName is null"); ElasticsearchTableDescription table = tableDescriptions.get(new SchemaTableName(schemaName, tableName)); if (table == null) { return null; } if (table.getColumns().isPresent()) { return table; } return new ElasticsearchTableDescription( table.getTableName(), table.getSchemaName(), table.getHost(), table.getPort(), table.getClusterName(), table.getIndex(), table.getIndexExactMatch(), table.getType(), Optional.of(buildColumns(table))); }
Source:
public String getLabel() { return String.format("Replace Bundle's Execution Environment with %s", this.fRequiredEE); }

Target:
public String getLabel() { return NLS.bind(Messages.ReplaceExecEnvironment_Marker_Label, this.fRequiredEE); }
Source:
synchronized Long startTick(Span span) { return span.startTick; }

Target:
Long startTick(Span span) { synchronized (span) { return span.startTick; } }
Source:
public static boolean isUnix() { return (OperatingSystem.indexOf("nix") >= 0 || OperatingSystem.indexOf("nux") >= 0 || OperatingSystem.indexOf("aix") > 0 ); }

Target:
public static boolean isUnix() { return (Os.indexOf("nix") >= 0 || Os.indexOf("nux") >= 0 || Os.indexOf("aix") > 0 ); }
Source:
private void writeResult(String testName, String resultXml) throws IOException { String finalPath = getXmlFileName(testName); Writer fw = null; try { fw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(finalPath), StandardCharsets.UTF_8.displayName())); fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fw.write(resultXml); } finally { if (fw != null) { fw.close(); } } }

Target:
private void writeResult(String testName, String resultXml) throws IOException { String finalPath = getXmlFileName(testName); try (Writer fw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(finalPath), StandardCharsets.UTF_8))) { fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fw.write(resultXml); } }
Source:
public void convertsToJsonWhenContextAbsent() { final String pending = "Kragle is drying..."; MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.PENDING) .withTargetUrl(Optional.of(URL)) .withDescription(pending) .json().toString(), Matchers.equalTo("{\"state\":\"pending\",\"description\":\"Kragle is drying...\",\"target_url\":\"<LINK_0>\"}") ); }

Target:
public void convertsToJsonWhenContextAbsent() { final String pending = "Kragle is drying..."; MatcherAssert.assertThat( new Statuses.StatusCreate(Status.State.PENDING) .withTargetUrl(Optional.of(StatusesTest.URL)) .withDescription(pending) .json().toString(), Matchers.equalTo( Json.createObjectBuilder() .add(StatusesTest.STATE_PROP, "pending") .add(StatusesTest.DESCRIPTION_PROP, pending) .add(StatusesTest.TARGET_PROP, StatusesTest.URL) .build().toString() ) ); }
Source:
private static String extractToken(CloseableHttpResponse response) throws OAuthException, IOException { int responseCode = response.getStatusLine().getStatusCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent(), StandardCharsets.UTF_8)); String inputLine; StringBuilder stringBuilder = new StringBuilder(); while ((inputLine = reader.readLine()) != null) { stringBuilder.append(inputLine); } if (log.isDebugEnabled()) { log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString()); } if (!(responseCode == HttpStatus.SC_OK)) { throw new OAuthException("Error while accessing the Token URL. " + response.getStatusLine()); } JsonParser parser = new JsonParser(); JsonObject jsonResponse = (JsonObject) parser.parse(stringBuilder.toString()); if (jsonResponse.has(OAuthConstants.ACCESS_TOKEN)) { return jsonResponse.get(OAuthConstants.ACCESS_TOKEN).getAsString(); } throw new OAuthException("Missing key [access_token] in the response from the OAuth server"); }

Target:
private static String extractToken(CloseableHttpResponse response) throws OAuthException, IOException { int responseCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); Charset charset = ContentType.getOrDefault(entity).getCharset(); if (charset == null) { charset = StandardCharsets.UTF_8; } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset)); String inputLine; StringBuilder stringBuilder = new StringBuilder(); while ((inputLine = reader.readLine()) != null) { stringBuilder.append(inputLine); } if (log.isDebugEnabled()) { log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString()); } if (responseCode != HttpStatus.SC_OK) { throw new OAuthException("Error while accessing the Token URL. " + response.getStatusLine()); } JsonParser parser = new JsonParser(); JsonObject jsonResponse = (JsonObject) parser.parse(stringBuilder.toString()); if (jsonResponse.has(OAuthConstants.ACCESS_TOKEN)) { return jsonResponse.get(OAuthConstants.ACCESS_TOKEN).getAsString(); } throw new OAuthException("Missing key [access_token] in the response from the OAuth server"); }
Source:
public BlockFluix() { super( BlockFluix.class, Material.iron ); setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); }

Target:
public BlockFluix() { super( BlockFluix.class, Material.rock ); setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); }
Source:
private static void cleanCppCache(IProject project) { IPath projectSpecificWorkDir = project.getWorkingLocation(SonarLintCorePlugin.PLUGIN_ID); Path cppCacheDir = projectSpecificWorkDir.toFile().toPath().resolve("cfamily").resolve("pph"); if (Files.exists(cppCacheDir)) { SonarLintCorePlugin.getDefault().debug("Deleting cache: " + cppCacheDir.toString()); FileUtils.deleteDirectory(cppCacheDir); } }

Target:
private void cleanCppCache(IProject project) { IPath projectSpecificWorkDir = project.getWorkingLocation(SonarLintCorePlugin.PLUGIN_ID); Path cppCacheDir = projectSpecificWorkDir.toFile().toPath().resolve("cfamily").resolve("pph"); if (Files.exists(cppCacheDir)) { core.debug("Deleting cache: " + cppCacheDir.toString()); FileUtils.deleteDirectory(cppCacheDir); } }
Source:
public void testLookup() { scripts.addScript("", "utils"); scripts.addScript("", "jquery"); scripts.addScript("", "diff"); scripts.addScript("", "jquery-tablesorter"); assertEquals(4, scripts.size()); scripts.sort(); int prev = -1; for (Script s : scripts) { if (prev > s.getPriority()) { fail("The scripts must be sorted in ascending order by the priority, " + prev + " > " + s.getPriority()); } prev = s.getPriority(); } for (Entry<String, Script> s : Scripts.SCRIPTS.entrySet()) { if (!s.getKey().equals("utils") && !s.getKey().equals("jquery") && !s.getKey().equals("jquery-tablesorter") && !s.getKey().equals("diff")) { continue; } assertTrue(scripts.toHtml() + " must contain <script type=\"text/javascript\"" + " src=\"" + s.getValue().getScript() + "\"" + " data-priority=\"" + s.getValue().getPriority() + "\"></script>", scripts.toHtml() .contains("<script type=\"text/javascript\"" + " src=\"" + s.getValue().getScript() + "\"" + " data-priority=\"" + s.getValue().getPriority() + "\"></script>")); } }

Target:
public void testLookup() { scripts.addScript("", "utils"); scripts.addScript("", "jquery"); scripts.addScript("", "diff"); scripts.addScript("", "jquery-tablesorter"); assertEquals(4, scripts.size()); int prev = -1; for (Script s : scripts) { if (prev > s.getPriority()) { fail("The scripts must be sorted in ascending order by the priority, " + prev + " > " + s.getPriority()); } prev = s.getPriority(); } for (Entry<String, Script> s : Scripts.SCRIPTS.entrySet()) { if (!s.getKey().equals("utils") && !s.getKey().equals("jquery") && !s.getKey().equals("jquery-tablesorter") && !s.getKey().equals("diff")) { continue; } assertTrue(scripts.toHtml() + " must contain <script type=\"text/javascript\"" + " src=\"" + s.getValue().getScriptData() + "\"" + " data-priority=\"" + s.getValue().getPriority() + "\"></script>", scripts.toHtml() .contains("<script type=\"text/javascript\"" + " src=\"" + s.getValue().getScriptData() + "\"" + " data-priority=\"" + s.getValue().getPriority() + "\"></script>")); } }