text:
package org.sleuthkit.autopsy.casemodule;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case.CaseType;
import org.sleuthkit.autopsy.core.UserPreferences;
import org.sleuthkit.autopsy.core.UserPreferencesException;
import org.sleuthkit.autopsy.coreutils.NetworkUtils;
import org.sleuthkit.datamodel.CaseDbConnectionInfo;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskData;

/**
 * Import a case from single-user to multi-user.
 *
 * DO NOT USE, NEEDS TO BE UPDATED
 */
public class SingleUserCaseConverter {

    private static final String MODULE_FOLDER = "ModuleOutput"; //NON-NLS
    private static final String AUTOPSY_DB_FILE = "autopsy.db"; //NON-NLS
    private static final String DOTAUT = CaseMetadata.getFileExtension(); //NON-NLS
    private static final String TIMELINE_FOLDER = "Timeline"; //NON-NLS
    private static final String TIMELINE_FILE = "events.db"; //NON-NLS
    private static final String POSTGRES_DEFAULT_DB_NAME = "postgres"; //NON-NLS
    private static final int MAX_DB_NAME_LENGTH = 63;

    public class ImportCaseData {

        private final Path imageInputFolder;
        private final Path caseInputFolder;
        private final Path imageOutputFolder;
        private final Path caseOutputFolder;
        private final String oldCaseName;
        private final String newCaseName;
        private final boolean copySourceImages;
        private final boolean deleteCase;
        private String postgreSQLDbName;
        private final String autFileName;
        private final String rawFolderName;
        private final CaseDbConnectionInfo db;

        public ImportCaseData(
                Path imageInput,
                Path caseInput,
                Path imageOutput,
                Path caseOutput,
                String oldCaseName,
                String newCaseName,
                String autFileName,
                String rawFolderName,
                boolean copySourceImages,
                boolean deleteCase) throws UserPreferencesException {

            this.imageInputFolder = imageInput;
            this.caseInputFolder = caseInput;
            this.imageOutputFolder = imageOutput;
            this.caseOutputFolder = caseOutput;
            this.oldCaseName = oldCaseName;
            this.newCaseName = newCaseName;
            this.autFileName = autFileName;
            this.rawFolderName = rawFolderName;
            this.copySourceImages = copySourceImages;
            this.deleteCase = deleteCase;
            this.db = UserPreferences.getDatabaseConnectionInfo();
        }

        public Path getCaseInputFolder() {
            return this.caseInputFolder;
        }

        public Path getCaseOutputFolder() {
            return this.caseOutputFolder;
        }

        Path getImageInputFolder() {
            return this.imageInputFolder;
        }

        Path getImageOutputFolder() {
            return this.imageOutputFolder;
        }

        String getOldCaseName() {
            return this.oldCaseName;
        }

        String getNewCaseName() {
            return this.newCaseName;
        }

        boolean getCopySourceImages() {
            return this.copySourceImages;
        }

        boolean getDeleteCase() {
            return this.deleteCase;
        }

        String getPostgreSQLDbName() {
            return this.postgreSQLDbName;
        }

        String getAutFileName() {
            return this.autFileName;
        }

        String getRawFolderName() {
            return this.rawFolderName;
        }

        CaseDbConnectionInfo getDb() {
            return this.db;
        }

        void setPostgreSQLDbName(String dbName) {
            this.postgreSQLDbName = dbName;
        }
    }

    /**
     * Handles the heavy lifting for importing a case from single-user to
     * multi-user. Creates new .aut file, moves folders to the right place,
     * imports the database, and updates paths within the database.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws java.lang.Exception
     */
    public static void importCase(ImportCaseData icd) throws Exception {

        Class.forName("org.postgresql.Driver"); //NON-NLS

        // Make sure there is a SQLite databse file
        Path oldDatabasePath = icd.getCaseInputFolder().resolve(AUTOPSY_DB_FILE);
        if (false == oldDatabasePath.toFile().exists()) {
            throw new Exception(NbBundle.getMessage(SingleUserCaseConverter.class, "SingleUserCaseConverter.BadDatabaseFileName")); //NON-NLS
        }

        // Read old xml config
        CaseMetadata oldCaseMetadata = new CaseMetadata(icd.getCaseInputFolder().resolve(icd.getAutFileName()));
        if (oldCaseMetadata.getCaseType() == CaseType.MULTI_USER_CASE) {
            throw new Exception(NbBundle.getMessage(SingleUserCaseConverter.class, "SingleUserCaseConverter.AlreadyMultiUser")); //NON-NLS
        }

        // Create sanitized names for PostgreSQL and Solr
        /*
         * RJC: Removed package access sanitizeCaseName method, so this is no
         * longer correct, but this whole class is currently out-of-date (out of
         * synch with case database schema) and probably belongs in the TSK
         * layer anyway, see JIRA-1984.
         */
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); //NON-NLS
        Date date = new Date();
        String dbName = icd.getNewCaseName() + "_" + dateFormat.format(date); //NON-NLS
        icd.setPostgreSQLDbName(dbName);

        // Copy items to new hostname folder structure
        copyResults(icd);

        // Convert from SQLite to PostgreSQL
        importDb(icd);

        // Update paths inside databse
        fixPaths(icd);

        // Copy images
        copyImages(icd);

        // Create new .aut file
        CaseMetadata newCaseMetadata = new CaseMetadata(CaseType.MULTI_USER_CASE,
                icd.getCaseOutputFolder().toString(),
                icd.getNewCaseName(),
                new CaseDetails(icd.getNewCaseName(),
                        oldCaseMetadata.getCaseNumber(),
                        oldCaseMetadata.getExaminer(),
                        oldCaseMetadata.getExaminerPhone(),
                        oldCaseMetadata.getExaminerEmail(),
                        oldCaseMetadata.getCaseNotes()));
        newCaseMetadata.setCaseDatabaseName(dbName);
        // Set created date. This calls writefile, no need to call it again
        newCaseMetadata.setCreatedDate(oldCaseMetadata.getCreatedDate());
        newCaseMetadata.setCreatedByVersion(oldCaseMetadata.getCreatedByVersion());

        // At this point the import has been finished successfully so we can delete the original case
        // (if requested). This *should* be fairly safe - at this point we know there was an autopsy file
        // and database in the given directory so the user shouldn't be able to accidently blow away
        // their C drive.
        if (icd.getDeleteCase()) {
            FileUtils.deleteDirectory(icd.getCaseInputFolder().toFile());
        }
    }

    /**
     * Figure out the input folder for images and return it.
     *
     * @param icd the Import Case Data for the current case
     *
     * @return the name of the proper Image input folder
     */
    private static File findInputFolder(ImportCaseData icd) {

        File thePath = icd.getImageInputFolder().resolve(icd.getOldCaseName()).toFile();
        if (thePath.isDirectory()) {
            /// we've found it
            return thePath;
        }
        thePath = icd.getImageInputFolder().resolve(icd.getRawFolderName()).toFile();
        if (thePath.isDirectory()) {
            /// we've found it
            return thePath;
        }
        return icd.getImageInputFolder().toFile();
    }

    /**
     * Copy all folders at the base level to the new scheme involving hostname.
     * Also take care of a few files such as logs, timeline database, etc.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws IOException
     */
    private static void copyResults(ImportCaseData icd) throws IOException {
        /// get hostname
        String hostName = NetworkUtils.getLocalHostName();

        Path destination;
        Path source = icd.getCaseInputFolder();
        if (source.toFile().exists()) {
            destination = icd.getCaseOutputFolder().resolve(hostName);
            FileUtils.copyDirectory(source.toFile(), destination.toFile());
        }

        source = icd.getCaseInputFolder().resolve(TIMELINE_FILE);
        if (source.toFile().exists()) {
            destination = Paths.get(icd.getCaseOutputFolder().toString(), hostName, MODULE_FOLDER, TIMELINE_FOLDER, TIMELINE_FILE);
            FileUtils.copyFile(source.toFile(), destination.toFile());
        }

        // Remove the single-user .aut file from the multi-user folder
        File oldAutopsyFile = Paths.get(icd.getCaseOutputFolder().toString(), hostName, icd.getOldCaseName() + DOTAUT).toFile();
        if (oldAutopsyFile.exists()) {
            oldAutopsyFile.delete();
        }

        // Remove the single-user database file from the multi-user folder
        File oldDatabaseFile = Paths.get(icd.getCaseOutputFolder().toString(), hostName, AUTOPSY_DB_FILE).toFile();
        if (oldDatabaseFile.exists()) {
            oldDatabaseFile.delete();
        }

        // Remove the single-user Timeline file from the multi-user folder
        File oldTimelineFile = Paths.get(icd.getCaseOutputFolder().toString(), hostName, TIMELINE_FILE).toFile();
        if (oldTimelineFile.exists()) {
            oldTimelineFile.delete();
        }
    }

    /**
     * Import the database from SQLite to PostgreSQL. Do not change any of the
     * data while loading it over. Fixing paths is done once the database is
     * completely imported.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws Exception
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    private static void importDb(ImportCaseData icd) throws SQLException, ClassNotFoundException, Exception {
        // deconflict the database name
        deconflictDatabaseName(icd);

        // Create a new database via SleuthkitCase
        SleuthkitCase newCase = SleuthkitCase.newCase(icd.getPostgreSQLDbName(), icd.getDb(), icd.getCaseOutputFolder().toString());
        newCase.close();

        /// Migrate from SQLite to PostgreSQL
        Class.forName("org.sqlite.JDBC"); //NON-NLS
        Connection sqliteConnection = getSQLiteConnection(icd);
        Connection postgreSQLConnection = getPostgreSQLConnection(icd);

        // blackboard_artifact_types
        Statement inputStatement = sqliteConnection.createStatement();
        ResultSet inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifact_types"); //NON-NLS
        Statement outputStatement;
        Statement numberingPK;
        long biggestPK = 0;

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                Statement check = postgreSQLConnection.createStatement();
                ResultSet checkResult = check.executeQuery("SELECT * FROM blackboard_artifact_types WHERE artifact_type_id=" + value + " AND type_name LIKE '" + inputResultSet.getString(2) + "' AND display_name LIKE '" + inputResultSet.getString(3) + "'"); //NON-NLS
                if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                    String sql = "INSERT INTO blackboard_artifact_types (artifact_type_id, type_name, display_name) VALUES (" //NON-NLS
                            + value + ", '"
                            + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "',"
                            + " ? )"; //NON-NLS
                    PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                    populateNullableString(pst, inputResultSet, 3, 1);
                    pst.executeUpdate();
                }
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE blackboard_artifact_types_artifact_type_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // blackboard_attribute_types
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_attribute_types"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                Statement check = postgreSQLConnection.createStatement();
                ResultSet checkResult = check.executeQuery("SELECT * FROM blackboard_attribute_types WHERE attribute_type_id=" + value + " AND type_name LIKE '" + inputResultSet.getString(2) + "' AND display_name LIKE '" + inputResultSet.getString(3) + "'"); //NON-NLS
                if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                    String sql = "INSERT INTO blackboard_attribute_types (attribute_type_id, type_name, display_name) VALUES (" //NON-NLS
                            + value + ", '"
                            + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "',"
                            + " ? )"; //NON-NLS

                    PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                    populateNullableString(pst, inputResultSet, 3, 1);
                    pst.executeUpdate();
                }
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE blackboard_attribute_types_attribute_type_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_objects
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_objects"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO tsk_objects (obj_id, par_obj_id, type) VALUES (" //NON-NLS
                        + value + ","
                        + getNullableLong(inputResultSet, 2) + ","
                        + inputResultSet.getInt(3) + ")"); //NON-NLS
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_objects_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_image_names, no primary key
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_image_names"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                outputStatement.executeUpdate("INSERT INTO tsk_image_names (obj_id, name, sequence) VALUES (" //NON-NLS
                        + inputResultSet.getLong(1) + ",'"
                        + inputResultSet.getString(2) + "',"
                        + inputResultSet.getInt(3) + ")"); //NON-NLS
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }

        // tsk_image_info
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_image_info"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_image_info (obj_id, type, ssize, tzone, size, md5, display_name) VALUES (" //NON-NLS
                        + value + ","
                        + getNullableInt(inputResultSet, 2) + ","
                        + getNullableInt(inputResultSet, 3) + ","
                        + " ? ,"
                        + getNullableLong(inputResultSet, 5) + ","
                        + " ? ,"
                        + " ? )"; //NON-NLS

                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 4, 1);
                populateNullableString(pst, inputResultSet, 6, 2);
                populateNullableString(pst, inputResultSet, 7, 3);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_image_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_fs_info
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_fs_info"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_fs_info (obj_id, img_offset, fs_type, block_size, block_count, root_inum, first_inum, last_inum, display_name) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getInt(3) + ","
                        + inputResultSet.getLong(4) + ","
                        + inputResultSet.getLong(5) + ","
                        + inputResultSet.getLong(6) + ","
                        + inputResultSet.getLong(7) + ","
                        + inputResultSet.getLong(8) + ","
                        + " ? )"; //NON-NLS

                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 9, 1);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_fs_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_files_path
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_path"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }

                // If the entry contains an encoding type, copy it. Otherwise use NONE.
                // The test on column count can be removed if we upgrade the database before conversion.
                int encoding = TskData.EncodingType.NONE.getType();
                ResultSetMetaData rsMetaData = inputResultSet.getMetaData();
                if (rsMetaData.getColumnCount() == 3) {
                    encoding = inputResultSet.getInt(3);
                }
                outputStatement.executeUpdate("INSERT INTO tsk_files_path (obj_id, path, encoding_type) VALUES (" //NON-NLS
                        + value + ", '"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "', "
                        + encoding + ")"); //NON-NLS
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_files_path_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_files
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_files (obj_id, fs_obj_id, attr_type, attr_id, name, meta_addr, meta_seq, type, has_layout, has_path, dir_type, meta_type, dir_flags, meta_flags, size, ctime, crtime, atime, mtime, mode, uid, gid, md5, known, parent_path) VALUES (" //NON-NLS
                        + value + ","
                        + getNullableLong(inputResultSet, 2) + ","
                        + getNullableInt(inputResultSet, 3) + ","
                        + getNullableInt(inputResultSet, 4) + ",'"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(5)) + "',"
                        + getNullableLong(inputResultSet, 6) + ","
                        + getNullableLong(inputResultSet, 7) + ","
                        + getNullableInt(inputResultSet, 8) + ","
                        + getNullableInt(inputResultSet, 9) + ","
                        + getNullableInt(inputResultSet, 10) + ","
                        + getNullableInt(inputResultSet, 11) + ","
                        + getNullableInt(inputResultSet, 12) + ","
                        + getNullableInt(inputResultSet, 13) + ","
                        + getNullableInt(inputResultSet, 14) + ","
                        + getNullableLong(inputResultSet, 15) + ","
                        + getNullableLong(inputResultSet, 16) + ","
                        + getNullableLong(inputResultSet, 17) + ","
                        + getNullableLong(inputResultSet, 18) + ","
                        + getNullableLong(inputResultSet, 19) + ","
                        + getNullableInt(inputResultSet, 20) + ","
                        + getNullableInt(inputResultSet, 21) + ","
                        + getNullableInt(inputResultSet, 22) + ","
                        + " ? ,"
                        + getNullableInt(inputResultSet, 24) + ","
                        + " ? )"; //NON-NLS

                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 23, 1);
                populateNullableString(pst, inputResultSet, 25, 2);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_files_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_file_layout, no primary key
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_file_layout"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                outputStatement.executeUpdate("INSERT INTO tsk_file_layout (obj_id, byte_start, byte_len, sequence) VALUES (" //NON-NLS
                        + inputResultSet.getLong(1) + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getLong(3) + ","
                        + inputResultSet.getInt(4) + ")"); //NON-NLS
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }

        // tsk_db_info, no primary key
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_db_info"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                Statement check = postgreSQLConnection.createStatement();
                ResultSet checkResult = check.executeQuery("SELECT * FROM tsk_db_info WHERE schema_ver=" + inputResultSet.getInt(1) + " AND tsk_ver=" + inputResultSet.getInt(2)); //NON-NLS
                if (!checkResult.isBeforeFirst()) { // only insert if it doesn't exist
                    outputStatement.executeUpdate("INSERT INTO tsk_db_info (schema_ver, tsk_ver) VALUES (" //NON-NLS
                            + getNullableInt(inputResultSet, 1) + ","
                            + getNullableInt(inputResultSet, 2) + ")"); //NON-NLS
                }
            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }

        // tag_names
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tag_names"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tag_names (tag_name_id, display_name, description, color) VALUES (" //NON-NLS
                        + value + ","
                        + " ? ,'"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(3)) + "','"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(4)) + "')"; //NON-NLS

                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 2, 1);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tag_names_tag_name_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // reports
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM reports"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO reports (report_id, path, crtime, src_module_name, report_name) VALUES (" //NON-NLS
                        + value + ", '"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(2)) + "',"
                        + inputResultSet.getInt(3) + ",'"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(4)) + "','"
                        + SleuthkitCase.escapeSingleQuotes(inputResultSet.getString(5)) + "')"); //NON-NLS

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE reports_report_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // blackboard_artifacts
        biggestPK = Long.MIN_VALUE; // This table uses very large negative primary key values, so start at Long.MIN_VALUE
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifacts"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO blackboard_artifacts (artifact_id, obj_id, artifact_type_id) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getLong(3) + ")"); //NON-NLS

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE blackboard_artifacts_artifact_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // blackboard_attributes, no primary key
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_attributes"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                String sql = "INSERT INTO blackboard_attributes (artifact_id, artifact_type_id, source, context, attribute_type_id, value_type, value_byte, value_text, value_int32, value_int64, value_double) VALUES (" //NON-NLS
                        + inputResultSet.getLong(1) + ","
                        + inputResultSet.getLong(2) + ","
                        + " ? ,"
                        + " ? ,"
                        + inputResultSet.getLong(5) + ","
                        + inputResultSet.getInt(6) + ","
                        + " ? ,"
                        + " ? ,"
                        + getNullableInt(inputResultSet, 9) + ","
                        + getNullableLong(inputResultSet, 10) + ","
                        + " ? )"; //NON-NLS
                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 3, 1);
                populateNullableString(pst, inputResultSet, 4, 2);
                populateNullableByteArray(pst, inputResultSet, 7, 3);
                populateNullableString(pst, inputResultSet, 8, 4);
                populateNullableNumeric(pst, inputResultSet, 11, 5);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }

        // tsk_vs_parts
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_vs_parts"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_vs_parts (obj_id, addr, start, length, descr, flags) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getLong(3) + ","
                        + inputResultSet.getLong(4) + ","
                        + " ? ,"
                        + inputResultSet.getInt(6) + ")"; //NON-NLS
                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 5, 1);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_vs_parts_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_vs_info
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_vs_info"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO tsk_vs_info (obj_id, vs_type, img_offset, block_size) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getInt(2) + ","
                        + inputResultSet.getLong(3) + ","
                        + inputResultSet.getLong(4) + ")"); //NON-NLS

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_vs_info_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_files_derived
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_derived"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_files_derived (obj_id, derived_id, rederive) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + " ? )"; //NON-NLS
                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 3, 1);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_files_derived_obj_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // tsk_files_derived_method
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_files_derived_method"); //NON-NLS

        while (inputResultSet.next()) {
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                String sql = "INSERT INTO tsk_files_derived_method (derived_id, tool_name, tool_version, other) VALUES (" //NON-NLS
                        + value + ", '"
                        + inputResultSet.getString(2) + "','"
                        + inputResultSet.getString(3) + "',"
                        + " ? )"; //NON-NLS
                PreparedStatement pst = postgreSQLConnection.prepareStatement(sql);
                populateNullableString(pst, inputResultSet, 4, 1);
                pst.executeUpdate();

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE tsk_files_derived_method_derived_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // content_tags
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM content_tags LEFT OUTER JOIN tsk_examiners ON content_tags.examiner_id = tsk_examiners.examiner_id"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO content_tags (tag_id, obj_id, tag_name_id, comment, begin_byte_offset, end_byte_offset, examiner_id) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getLong(3) + ",'"
                        + inputResultSet.getString(4) + "',"
                        + inputResultSet.getLong(5) + ","
                        + inputResultSet.getLong(6) + ","
                        + inputResultSet.getInt(7) + ")"); //NON-NLS

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE content_tags_tag_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        // blackboard_artifact_tags
        biggestPK = 0;
        inputStatement = sqliteConnection.createStatement();
        inputResultSet = inputStatement.executeQuery("SELECT * FROM blackboard_artifact_tags"); //NON-NLS

        while (inputResultSet.next()) {
            outputStatement = postgreSQLConnection.createStatement();
            try {
                long value = inputResultSet.getLong(1);
                if (value > biggestPK) {
                    biggestPK = value;
                }
                outputStatement.executeUpdate("INSERT INTO blackboard_artifact_tags (tag_id, artifact_id, tag_name_id, comment) VALUES (" //NON-NLS
                        + value + ","
                        + inputResultSet.getLong(2) + ","
                        + inputResultSet.getLong(3) + ",'"
                        + inputResultSet.getString(4) + "','"
                        + inputResultSet.getString(5) + "')"); //NON-NLS

            } catch (SQLException ex) {
                if (ex.getErrorCode() != 0) { // 0 if the entry already exists
                    throw new SQLException(ex);
                }
            }
        }
        numberingPK = postgreSQLConnection.createStatement();
        numberingPK.execute("ALTER SEQUENCE blackboard_artifact_tags_tag_id_seq RESTART WITH " + (biggestPK + 1)); //NON-NLS

        sqliteConnection.close();
        postgreSQLConnection.close();
    }

    /**
     * Checks that the database name is unique. If it is not, attempts to add
     * numbers to it until it is unique. Gives up if it goes through all
     * positive integers without finding a unique name.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws Exception
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    private static void deconflictDatabaseName(ImportCaseData icd) throws ClassNotFoundException, SQLException, Exception {

        Connection postgreSQLConnection = getPostgreSQLConnection(icd, POSTGRES_DEFAULT_DB_NAME);

        int number = 1;
        boolean unique = false;
        String sanitizedDbName = icd.getPostgreSQLDbName();
        if (sanitizedDbName.length() > MAX_DB_NAME_LENGTH) {
            sanitizedDbName = sanitizedDbName.substring(0, MAX_DB_NAME_LENGTH);
        }

        if (postgreSQLConnection != null) {
            while (unique == false) {
                Statement st = postgreSQLConnection.createStatement();
                ResultSet answer = st.executeQuery("SELECT datname FROM pg_catalog.pg_database WHERE LOWER(datname) LIKE LOWER('" + sanitizedDbName + "%')"); //NON-NLS

                if (!answer.next()) {
                    unique = true;
                } else {
                    // not unique. add numbers to db name.
                    if (number == Integer.MAX_VALUE) {
                        // oops. it never became unique. give up.
                        throw new Exception(NbBundle.getMessage(SingleUserCaseConverter.class, "SingleUserCaseConverter.NonUniqueDatabaseName")); //NON-NLS
                    }
                    sanitizedDbName = "db_" + Integer.toString(number) + "_" + icd.getPostgreSQLDbName(); //NON-NLS

                    // Chop full db name to 63 characters (max for PostgreSQL)
                    if (sanitizedDbName.length() > MAX_DB_NAME_LENGTH) {
                        sanitizedDbName = sanitizedDbName.substring(0, MAX_DB_NAME_LENGTH);
                    }
                    ++number;
                }
            }
            postgreSQLConnection.close();
        } else {
            // Could be caused by database credentials, using user accounts that
            // can not check if other databases exist, so allow it to continue
        }

        icd.setPostgreSQLDbName(sanitizedDbName);
    }

    /**
     * Get the images from the old case and stage them for the new case, if the
     * user chose to copy images over.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws IOException
     */
    private static void copyImages(ImportCaseData icd) throws Exception {
        if (icd.getCopySourceImages()) {
            File imageSource = findInputFolder(icd); // Find the folder for the input images
            File imageDestination = new File(icd.getImageOutputFolder().toString());

            // If we can find the input images, copy if needed.
            if (imageSource.exists()) {
                FileUtils.copyDirectory(imageSource, imageDestination);

            } else {
                throw new Exception(NbBundle.getMessage(SingleUserCaseConverter.class, "SingleUserCaseConverter.UnableToCopySourceImages")); //NON-NLS
            }
        }
    }

    /**
     * Fix up any paths in the database that refer to items that have moved.
     * Candidates include events.db, input images, reports, file paths, etc.
     *
     * @param icd the Import Case Data for the current case
     *
     * @throws Exception
     * @throws SQLExceptionException
     */
    private static void fixPaths(ImportCaseData icd) throws SQLException, Exception {
        /// Fix paths in reports, tsk_files_path, and tsk_image_names tables

        String input = icd.getImageInputFolder().toString();
        String output = icd.getImageOutputFolder().toString();

        Connection postgresqlConnection = getPostgreSQLConnection(icd);

        if (postgresqlConnection != null) {
            String hostName = NetworkUtils.getLocalHostName();

            // add hostname to reports
            Statement updateStatement = postgresqlConnection.createStatement();
            updateStatement.executeUpdate("UPDATE reports SET path=CONCAT('" + hostName + "/', path) WHERE path IS NOT NULL AND path != ''"); //NON-NLS

            // add hostname to tsk_files_path
            updateStatement = postgresqlConnection.createStatement();
            updateStatement.executeUpdate("UPDATE tsk_files_path SET path=CONCAT('" + hostName + "\\', path) WHERE path IS NOT NULL AND path != ''"); //NON-NLS

            String caseName = icd.getRawFolderName().toLowerCase();

            if (icd.getCopySourceImages()) {
                // update path for images
                Statement inputStatement = postgresqlConnection.createStatement();
                ResultSet inputResultSet = inputStatement.executeQuery("SELECT * FROM tsk_image_names"); //NON-NLS

                while (inputResultSet.next()) {
                    Path oldPath = Paths.get(inputResultSet.getString(2));

                    for (int x = 0; x < oldPath.getNameCount(); ++x) {
                        if (oldPath.getName(x).toString().toLowerCase().equals(caseName)) {
                            Path newPath = Paths.get(output, oldPath.subpath(x + 1, oldPath.getNameCount()).toString());
                            updateStatement = postgresqlConnection.createStatement();
                            updateStatement.executeUpdate("UPDATE tsk_image_names SET name='" + newPath.toString() + "' WHERE obj_id = " + inputResultSet.getInt(1)); //NON-NLS
                            break;
                        }
                    }
                }
            }
            postgresqlConnection.close();
        } else {
            throw new Exception(NbBundle.getMessage(SingleUserCaseConverter.class, "SingleUserCaseConverter.CanNotOpenDatabase")); //NON-NLS
        }
    }

    /**
     * Return an integer from the ResultSet converted to String or NULL, by
     * checking ResultSet.wasNull()
     *
     * @param rs    the ResultSet to work with
     * @param index the index into the ResultSet to work with
     *
     * @return the proper value, the integer, or NULL
     *
     * @throws SQLException
     */
    private static String getNullableInt(ResultSet rs, int index) throws SQLException {
        int value = rs.getInt(index);
        if (rs.wasNull()) {
            return "NULL"; //NON-NLS
        } else {
            return Integer.toString(value);
        }
    }

    /**
     * Return a long from the ResultSet converted to String or NULL, by checking
     * ResultSet.wasNull()
     *
     * @param rs    the ResultSet to work with
     * @param index the index into the ResultSet to work with
     *
     * @return the proper value, the long, or NULL
     *
     * @throws SQLException
     */
    private static String getNullableLong(ResultSet rs, int index) throws SQLException {
        long value = rs.getLong(index);
        if (rs.wasNull()) {
            return "NULL"; //NON-NLS
        } else {
            return Long.toString(value);
        }
    }

    /**
     * Place a NULL inside a prepared statement if needed, otherwise, place the
     * String that was in the ResultSet.
     *
     * @param pst     the prepared statement
     * @param rs      the ResultSet to work with
     * @param rsIndex index for the result set
     * @param psIndex index for the prepared statement
     *
     * @throws SQLException
     */
    private static void populateNullableString(PreparedStatement pst, ResultSet rs, int rsIndex, int psIndex) throws SQLException {
        String nullableString = rs.getString(rsIndex);
        if (rs.wasNull()) {
            pst.setNull(psIndex, java.sql.Types.NULL);
        } else {
            pst.setString(psIndex, SleuthkitCase.escapeSingleQuotes(nullableString));
        }
    }

    /**
     * Place a NULL inside a prepared statement if needed, otherwise, place the
     * byte array that was in the ResultSet.
     *
     * @param pst     the prepared statement
     * @param rs      the ResultSet to work with
     * @param rsIndex index for the result set
     * @param psIndex index for the prepared statement
     *
     * @throws SQLException
     */
    private static void populateNullableByteArray(PreparedStatement pst, ResultSet rs, int rsIndex, int psIndex) throws SQLException {
        byte[] nullableBytes = rs.getBytes(rsIndex);
        if (rs.wasNull()) {
            pst.setNull(psIndex, java.sql.Types.NULL);
        } else {
            pst.setBytes(psIndex, nullableBytes);
        }
    }

    /**
     * Place a NULL inside a prepared statement if needed, otherwise, place the
     * double that was in the ResultSet.
     *
     * @param pst     the prepared statement
     * @param rs      the ResultSet to work with
     * @param rsIndex index for the result set
     * @param psIndex index for the prepared statement
     *
     * @throws SQLException
     */
    private static void populateNullableNumeric(PreparedStatement pst, ResultSet rs, int rsIndex, int psIndex) throws SQLException {
        double nullableNumeric = rs.getDouble(rsIndex);
        if (rs.wasNull()) {
            pst.setNull(psIndex, java.sql.Types.NULL);
        } else {
            pst.setDouble(psIndex, nullableNumeric);
        }
    }

    /**
     * Open the PostgreSQL database
     *
     * @param icd Import Case Data holding connection credentials
     *
     * @return returns a Connection
     *
     * @throws SQLException if unable to open
     */
    private static Connection getPostgreSQLConnection(ImportCaseData icd) throws SQLException {
        return getPostgreSQLConnection(icd, icd.getPostgreSQLDbName());
    }

    /**
     * Open the PostgreSQL database
     *
     * @param icd    Import Case Data holding connection credentials
     * @param dbName the name of the database to open
     *
     * @return returns a Connection
     *
     * @throws SQLException if unable to open
     */
    private static Connection getPostgreSQLConnection(ImportCaseData icd, String dbName) throws SQLException {
        return DriverManager.getConnection("jdbc:postgresql://" //NON-NLS
                + icd.getDb().getHost() + ":"
                + icd.getDb().getPort() + "/"
                + dbName,
                icd.getDb().getUserName(),
                icd.getDb().getPassword()); //NON-NLS
    }

    /**
     * Open the SQLite database
     *
     * @param icd Import Case Data holding database path details
     *
     * @return returns a Connection
     *
     * @throws SQLException if unable to open
     */
    private static Connection getSQLiteConnection(ImportCaseData icd) throws SQLException {
        return DriverManager.getConnection("jdbc:sqlite:" + icd.getCaseInputFolder().resolve(AUTOPSY_DB_FILE).toString(), "", ""); //NON-NLS
    }

}


text:
// This file is automatically generated.

package adila.db;

/*
 * Foxconn Commtiva N700
 *
 * DEVICE: n700
 * MODEL: Commtiva-N700
 */
final class n700 {
    public static final String DATA = "Foxconn|Commtiva N700|";
}

redpajama_set_name: RedPajamaGithub


text:
shadow input

    <input id="light-before"></input>
    <test-shadow>
        <template shadowroot="open">

                <input id="shadow-input"></input>

        </template>
    </test-shadow>
    <input id="light-after"></input>

tabbable host

    <input id="light-before"></input>
    <test-shadow tabindex="0" id="tabbable-host">
        <template shadowroot="open">

                <input id="shadow-input"></input>

        </template>
    </test-shadow>
    <input id="light-after"></input>

light shadow and slots

    <input id="light-before"></input>
    <test-shadow>
        <template shadowroot="open">

                <slot name="before"></slot>
                <input id="shadow-input"></input>
                <slot name="after"></slot>
                <slot>
                    <input id="default-slot-input-overridden"></input>
                </slot>
                <slot name="default-content">
                    <input id="default-slot-input"></input>
                </slot>

        </template>
        <input id="light-slotter-before" slot="before"></input>
        <input id="light-slotter-after" slot="after"></input>
        <input id="light-slotter-default"></input>
    </test-shadow>
    <input id="light-after"></input>

light shadow tab index

    <input id="light-last"></input>
    <test-shadow>
        <template shadowroot="open">

                <input id="shadow-middle" tabindex="2"></input>
                <input id="shadow-last"></input>
                <input id="shadow-first" tabindex="1"></input>

        </template>
    </test-shadow>
    <input id="light-middle" tabindex="10"></input>
    <input id="light-first" tabindex="5"></input>

slots with tab index

    <test-shadow>
        <template shadowroot="open">
            <input id="shadow-3"></input>
            <slot name="slot-last"></slot>
            <slot name="slot-middle" tabindex="3"></slot>
            <slot name="slot-first" tabindex="1"></slot>
            <input id="shadow-2" tabindex="2"></input>
            <input id="shadow-1" tabindex="1"></input>
        </template>
        <input id="light-2" slot="slot-middle"></input>
        <input id="light-3" slot="slot-last"></input>
        <input id="light-1" slot="slot-first"></input>
    </test-shadow>

slots with tab index

    <test-shadow>
        <template shadowroot="open">
            <slot></slot>
            <input id="shadow-between" tabindex="2"></input>
            <slot name="first" tabindex="1"></slot>
        </template>
        <input id="light-6"></input>
        <input id="light-5" tabindex="2"></input>
        <input id="light-4" tabindex="1"></input>
        <input id="light-3" slot="first"></input>
        <input id="light-2" slot="first" tabindex="2"></input>
        <input id="light-1" slot="first" tabindex="1"></input>
    </test-shadow>

slot through multiple nested shadow roots

    <test-shadow>
        <template shadowroot="open">
            <input id="shadow-outter-before"></input>
            <test-shadow>
                <template shadowroot="open">
                    <input id="shadow-inner"></input>
                    <slot></slot>
                </template>
                <slot></slot>
            </test-shadow>
            <input id="shadow-outter-after"></input>
        </template>
        <input id="light-slotted-input"></input>
    </test-shadow>

different conditions for filtering elements

    <test-shadow>
        <template shadowroot="open">
            <input id="shadow-disabled" disabled></input>
            <input id="shadow-type-hidden" type="hidden"></input>
            <input id="shadow-visibility-hidden" style="visibility: hidden;"></input>
            <input id="shadow-display-hidden" style="display: none;"></input>

                un-opened details
                <input id="shadow-unopned-details-hidden"></input>

            <input id="shadow-radio-unchecked" type="radio" name="group-a"></input>
            <input id="shadow-radio-checked" type="radio" name="group-a" checked></input>
            <input id="shadow-negative-tabindex" tabindex="-1"></input>
        </template>
    </test-shadow>

closed shadow input

    <input id="light-before"></input>
    <test-shadow>
        <template shadowroot="closed">

                <input id="shadow-input"></input>
                <slot></slot>

        </template>
        <input id="light-slotted" tabindex="1"></input>
    </test-shadow>
    <input id="light-after"></input>

"display=none" slot (mode=closed)

    <test-shadow>
        <template shadowroot="closed">

                <slot></slot>

        </template>
        <input id="query-light-input-slotted"></input>
    </test-shadow>

table with tabbable scoped headers

            Athlete
            Swim
            Bike
            Run

            John
            7
            12
            10

            Lisa
            3
            15
            9

            Paul
            9
            8
            12


text:
This sample uses `VkEvent` and calls `vkSetEvent` and `vkCmdWaitEvents` to
synchronize between host and device, to pass RGBA data for rendering.


text:
/* This file was generated by SableCC's ObjectMacro. */

package org.sablecc.sablecc.codegeneration.java.macro;

public class MAnonymousAltType {

    MAnonymousAltType() {

    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append("    return Type.TAnonymous;");
        sb.append(System.getProperty("line.separator"));
        return sb.toString();
    }

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CarroFotoMigration extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('carro_foto', function (Blueprint $table) {
            $table->increments('id_carro_foto');
            $table->unsignedInteger('fk_carro');
            $table->string('nome_foto');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('carro_foto');
    }
}


text:
package kieker.tools.slastic.plugins.slasticImpl.model.executionEnvironment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import kieker.tools.slastic.metamodel.executionEnvironment.ExecutionContainer;

/**
 *
 * @author Andre van Hoorn
 */
public class ExecutionContainersAllocationManager implements IExecutionContainersAllocationManager {
	private static final Log LOG = LogFactory.getLog(ExecutionContainersAllocationManager.class);

	private final Map<Long, ExecutionContainer> allocatedContainersById = new HashMap<Long, ExecutionContainer>();
	private final List<ExecutionContainer> allocatedExecutionContainers;

	@SuppressWarnings("unused")
	private ExecutionContainersAllocationManager() {
		this.allocatedExecutionContainers = null;
	}

	public ExecutionContainersAllocationManager(final List<ExecutionContainer> allocatedExecutionContainers) {
		this.allocatedExecutionContainers = allocatedExecutionContainers;
		for (final ExecutionContainer container : allocatedExecutionContainers) {
			this.allocatedContainersById.put(container.getId(), container);
		}
	}

	@Override
	public boolean allocateExecutionContainer(final ExecutionContainer executionContainer) {
		final long executionContainerId = executionContainer.getId();
		if (this.allocatedContainersById.containsKey(executionContainerId)) {
			LOG.warn("Execution container with id " + executionContainerId + " already allocated");
			return false;
		}
		this.allocatedContainersById.put(executionContainerId, executionContainer);
		return this.allocatedExecutionContainers.add(executionContainer);
	}

	/**
	 * TODO: Currently, we do not remove the {@link ExecutionContainer} but mark
	 * it inactive {@link ExecutionContainer#isActive()}.
	 */
	@Override
	public boolean deallocateExecutionContainer(final ExecutionContainer executionContainer) {
		final long executionContainerId = executionContainer.getId();
		if (!this.allocatedContainersById.containsKey(executionContainerId)) {
			LOG.warn("Execution container with id " + executionContainerId + " not allocated");
			return false;
		}
		final ExecutionContainer removedContainer = this.allocatedContainersById.remove(executionContainerId);
		if (removedContainer != executionContainer) {
			final IllegalStateException ise =
					new IllegalStateException(
							"Unexpected element removed with id"
									+ executionContainerId + ". Expected: "
									+ executionContainer + " ; removed: "
									+ removedContainer);
			LOG.error("IllegalStateException: " + ise.getMessage(), ise);
			throw ise;
		}
		// return this.allocatedExecutionContainers.remove(executionContainer);
		return this.allocatedExecutionContainers.contains(executionContainer);
	}
}


text:
layout: default
title: Projects
---

Projects

    {% assign current_date = "now" | date: "%s" %}
    {% assign projects = site.projects | sort: 'date' | reverse %}
    {% for project in projects %}

{{ project.title }}

{{ project.subtitle }}

                        {% if project.date-from != "" %}
                            {{ project.date-from | date: "%b %Y"}} -
                        {% endif %}
                        {% assign project_date = project.date | date: "%s" %}
                        {% if project_date > current_date %}
                            Present
                        {% else %}
                            {{ project.date | date: "%b %Y"}}
                        {% endif %}

    {% endfor %}


text:
using System.Collections.Generic;

namespace IOC.V3.MovieFinder
{
    public interface IMovieFinder
    {
        List<Movie> FindAll();
    }
}


text:
#include "config.h"
#include "platform/fonts/win/FontFallbackWin.h"

#include "platform/fonts/FontCache.h"
#include "SkFontMgr.h"
#include "SkTypeface.h"
#include "wtf/HashMap.h"
#include "wtf/text/StringHash.h"
#include "wtf/text/WTFString.h"
#include <limits>
#include <unicode/locid.h>
#include <unicode/uchar.h>

namespace blink {

namespace {

static inline bool isFontPresent(const UChar* fontName, SkFontMgr* fontManager)
{
    String family = fontName;
    SkTypeface* typeface;
    if (FontCache::useDirectWrite())
        typeface = fontManager->matchFamilyStyle(family.utf8().data(), SkFontStyle());
    else
        typeface = fontManager->legacyCreateTypeface(family.utf8().data(), SkTypeface::kNormal);

    if (!typeface)
        return false;

    RefPtr<SkTypeface> tf = adoptRef(typeface);
    SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
    bool matchesRequestedFamily = false;
    SkTypeface::LocalizedString actualFamily;
    while (actualFamilies->next(&actualFamily)) {
        if (equalIgnoringCase(family, AtomicString::fromUTF8(actualFamily.fString.c_str()))) {
            matchesRequestedFamily = true;
            break;
        }
    }
    actualFamilies->unref();

    return matchesRequestedFamily;
}

// A simple mapping from UScriptCode to family name. This is a sparse array,
// which works well since the range of UScriptCode values is small.
typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];

void initializeScriptMonospaceFontMap(ScriptToFontMap& scriptFontMap, SkFontMgr* fontManager)
{
    struct FontMap {
        UScriptCode script;
        const UChar* family;
    };

    static const FontMap fontMap[] = {
        { USCRIPT_HEBREW, L"courier new" },
        { USCRIPT_ARABIC, L"courier new" },
    };

    for (size_t i = 0; i < WTF_ARRAY_LENGTH(fontMap); ++i)
        scriptFontMap[fontMap[i].script] = fontMap[i].family;
}

void initializeScriptFontMap(ScriptToFontMap& scriptFontMap, SkFontMgr* fontManager)
{
    struct FontMap {
        UScriptCode script;
        const UChar* family;
    };

    static const FontMap fontMap[] = {
        {USCRIPT_LATIN, L"times new roman"},
        {USCRIPT_GREEK, L"times new roman"},
        {USCRIPT_CYRILLIC, L"times new roman"},
        // FIXME: Consider trying new Vista fonts before XP fonts for CJK.
        // Some Vista users do want to use Vista cleartype CJK fonts. If we
        // did, the results of tests with CJK characters would have to be
        // regenerated for Vista.
        {USCRIPT_THAANA, L"mv boli"},
        {USCRIPT_MONGOLIAN, L"mongolian balti"},
        // For USCRIPT_COMMON, we map blocks to scripts when
        // that makes sense.
    };

    struct ScriptToFontFamilies {
        UScriptCode script;
        const UChar** families;
    };

    // Kartika on Vista or earlier lacks the support for Chillu
    // letters added to Unicode 5.1.
    // Try AnjaliOldLipi (a very widely used Malaylalam font with the full
    // Unicode 5.x support) before falling back to Kartika.
    static const UChar* malayalamFonts[] = {L"AnjaliOldLipi", L"Lohit Malayalam", L"Kartika", L"Rachana", L"Nirmala UI", 0};
    // Try Khmer OS before Vista fonts because 'Khmer OS' goes along better
    // with Latin and looks better/larger for the same size.
    static const UChar* khmerFonts[] = {L"Leelawadee UI", L"Khmer OS", L"MoolBoran", L"DaunPenh", L"Code2000", 0};
    // For the following 6 scripts, two or fonts are listed. The fonts in
    // the 1st slot are not available on Windows XP. To support these
    // scripts on XP, listed in the rest of slots are widely used
    // fonts.
    static const UChar* ethiopicFonts[] = {L"Nyala", L"Abyssinica SIL", L"Ethiopia Jiret", L"Visual Geez Unicode", L"GF Zemen Unicode", L"Ebrima", 0};
    static const UChar* oriyaFonts[] = {L"Kalinga", L"ori1Uni", L"Lohit Oriya", L"Nirmala UI", 0};
    static const UChar* laoFonts[] = {L"Leelawadee UI", L"DokChampa", L"Saysettha OT", L"Phetsarath OT", L"Code2000", 0};
    static const UChar* tibetanFonts[] = {L"Microsoft Himalaya", L"Jomolhari", L"Tibetan Machine Uni", 0};
    static const UChar* sinhalaFonts[] = {L"Iskoola Pota", L"AksharUnicode", L"Nirmala UI", 0};
    static const UChar* yiFonts[] = {L"Microsoft Yi Balti", L"Nuosu SIL", L"Code2000", 0};
    // http://www.bethmardutho.org/support/meltho/download/index.php
    static const UChar* syriacFonts[] = {L"Estrangelo Edessa", L"Estrangelo Nisibin", L"Code2000", 0};
    static const UChar* myanmarFonts[] = {L"Myanmar Text", L"Padauk", L"Parabaik", L"Myanmar3", L"Code2000", 0};
    static const UChar* gothicFonts[] = {L"Segoe UI Symbol", 0};
    static const UChar* hangulFonts[] = {L"gulim", L"Malgun Gothic", 0};
    static const UChar* devanagariFonts[] = {L"mangal", L"Nirmala UI", 0};
    static const UChar* gujaratiFonts[] = {L"shruti", L"Nirmala UI", 0};
    static const UChar* bengaliFonts[] = {L"vrinda", L"Nirmala UI", 0};
    static const UChar* teluguFonts[] = {L"gautami", L"Nirmala UI", 0};
    static const UChar* tamilFonts[] = {L"latha", L"Nirmala UI", 0};
    static const UChar* kannadaFonts[] = {L"tunga", L"Nirmala UI", 0};
    static const UChar* gurumukhiFonts[] = {L"raavi", L"Nirmala UI", 0};
    static const UChar* thaiFonts[] = {L"tahoma", L"Leelawadee UI", L"Leelawadee", 0};
    static const UChar* hebrewFonts[] = {L"david", L"Segoe UI", 0};
    static const UChar* arabicFonts[] = {L"tahoma", L"Segoe UI", 0};
    static const UChar* georgianFonts[] = {L"sylfaen", L"Segoe UI", 0};
    static const UChar* armenianFonts[] = {L"sylfaen", L"Segoe UI", 0};
    static const UChar* canadianAboriginalFonts[] = {L"euphemia", L"Gadugi", 0};
    static const UChar* cherokeeFonts[] = {L"plantagenet cherokee", L"Gadugi", 0};
    static const UChar* simplifiedHanFonts[] = {L"simsun", L"Microsoft YaHei", 0};
    static const UChar* traditionalHanFonts[] = {L"pmingliu", L"Microsoft JhengHei", 0};
    static const UChar* hiraganaFonts[] = {L"ms pgothic", L"Yu Gothic", L"Microsoft YaHei", 0};
    static const UChar* katakanaFonts[] = {L"ms pgothic", L"Yu Gothic", L"Microsoft YaHei", 0};
    static const UChar* katakanaOrHiraganaFonts[] = {L"ms pgothic", L"Yu Gothic", L"Microsoft YaHei", 0};

    static const ScriptToFontFamilies scriptToFontFamilies[] = {
        {USCRIPT_MALAYALAM, malayalamFonts},
        {USCRIPT_KHMER, khmerFonts},
        {USCRIPT_ETHIOPIC, ethiopicFonts},
        {USCRIPT_ORIYA, oriyaFonts},
        {USCRIPT_LAO, laoFonts},
        {USCRIPT_TIBETAN, tibetanFonts},
        {USCRIPT_SINHALA, sinhalaFonts},
        {USCRIPT_YI, yiFonts},
        {USCRIPT_SYRIAC, syriacFonts},
        {USCRIPT_MYANMAR, myanmarFonts},
        {USCRIPT_GOTHIC, gothicFonts},
        {USCRIPT_HANGUL, hangulFonts},
        {USCRIPT_DEVANAGARI, devanagariFonts},
        {USCRIPT_GUJARATI, gujaratiFonts},
        {USCRIPT_BENGALI, bengaliFonts},
        {USCRIPT_TELUGU, teluguFonts},
        {USCRIPT_TAMIL, tamilFonts},
        {USCRIPT_KANNADA, kannadaFonts},
        {USCRIPT_GURMUKHI, gurumukhiFonts},
        {USCRIPT_THAI, thaiFonts},
        {USCRIPT_HEBREW, hebrewFonts},
        {USCRIPT_ARABIC, arabicFonts},
        {USCRIPT_GEORGIAN, georgianFonts},
        {USCRIPT_ARMENIAN, armenianFonts},
        {USCRIPT_CANADIAN_ABORIGINAL, canadianAboriginalFonts},
        {USCRIPT_CHEROKEE, cherokeeFonts},
        {USCRIPT_SIMPLIFIED_HAN, simplifiedHanFonts},
        {USCRIPT_TRADITIONAL_HAN, traditionalHanFonts},
        {USCRIPT_HIRAGANA, hiraganaFonts},
        {USCRIPT_KATAKANA, katakanaFonts},
        {USCRIPT_KATAKANA_OR_HIRAGANA, katakanaOrHiraganaFonts},
    };

    for (size_t i = 0; i < WTF_ARRAY_LENGTH(fontMap); ++i)
        scriptFontMap[fontMap[i].script] = fontMap[i].family;

    // FIXME: Instead of scanning the hard-coded list, we have to
    // use EnumFont* to 'inspect' fonts to pick up fonts covering scripts
    // when it's possible (e.g. using OS/2 table). If we do that, this
    // had better be pulled out of here.
    for (size_t i = 0; i < WTF_ARRAY_LENGTH(scriptToFontFamilies); ++i) {
        UScriptCode script = scriptToFontFamilies[i].script;
        scriptFontMap[script] = 0;
        const UChar** familyPtr = scriptToFontFamilies[i].families;
        while (*familyPtr) {
            if (isFontPresent(*familyPtr, fontManager)) {
                scriptFontMap[script] = *familyPtr;
                break;
            }
            ++familyPtr;
        }
    }

    // Initialize the locale-dependent mapping.
    // Since Chrome synchronizes the ICU default locale with its UI locale,
    // this ICU locale tells the current UI locale of Chrome.
    icu::Locale locale = icu::Locale::getDefault();
    const UChar* localeFamily = 0;
    if (locale == icu::Locale::getJapanese()) {
        localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
    } else if (locale == icu::Locale::getKorean()) {
        localeFamily = scriptFontMap[USCRIPT_HANGUL];
    } else if (locale == icu::Locale::getTraditionalChinese()) {
        localeFamily = scriptFontMap[USCRIPT_TRADITIONAL_HAN];
    } else {
        // For other locales, use the simplified Chinese font for Han.
        localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
    }
    if (localeFamily)
        scriptFontMap[USCRIPT_HAN] = localeFamily;
}

// There are a lot of characters in USCRIPT_COMMON that can be covered
// by fonts for scripts closely related to them. See
// http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Script=Common:]
// FIXME: make this more efficient with a wider coverage
UScriptCode getScriptBasedOnUnicodeBlock(int ucs4)
{
    UBlockCode block = ublock_getCode(ucs4);
    switch (block) {
    case UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION:
        return USCRIPT_HAN;
    case UBLOCK_HIRAGANA:
    case UBLOCK_KATAKANA:
        return USCRIPT_HIRAGANA;
    case UBLOCK_ARABIC:
        return USCRIPT_ARABIC;
    case UBLOCK_THAI:
        return USCRIPT_THAI;
    case UBLOCK_GREEK:
        return USCRIPT_GREEK;
    case UBLOCK_DEVANAGARI:
        // For Danda and Double Danda (U+0964, U+0965), use a Devanagari
        // font for now although they're used by other scripts as well.
        // Without a context, we can't do any better.
        return USCRIPT_DEVANAGARI;
    case UBLOCK_ARMENIAN:
        return USCRIPT_ARMENIAN;
    case UBLOCK_GEORGIAN:
        return USCRIPT_GEORGIAN;
    case UBLOCK_KANNADA:
        return USCRIPT_KANNADA;
    case UBLOCK_GOTHIC:
        return USCRIPT_GOTHIC;
    default:
        return USCRIPT_COMMON;
    }
}

UScriptCode getScript(int ucs4)
{
    UErrorCode err = U_ZERO_ERROR;
    UScriptCode script = uscript_getScript(ucs4, &err);
    // If script is invalid, common or inherited or there's an error,
    // infer a script based on the unicode block of a character.
    if (script <= USCRIPT_INHERITED || U_FAILURE(err))
        script = getScriptBasedOnUnicodeBlock(ucs4);
    return script;
}

const UChar* getFontBasedOnUnicodeBlock(int ucs4, SkFontMgr* fontManager)
{
    static const UChar* emojiFonts[] = {L"Segoe UI Emoji", L"Segoe UI Symbol"};
    static const UChar* symbolFont = L"Segoe UI Symbol";
    const UChar* emojiFont = 0;
    static bool initialized = false;
    if (!initialized) {
        for (size_t i = 0; i < WTF_ARRAY_LENGTH(emojiFonts); i++) {
            if (isFontPresent(emojiFonts[i], fontManager)) {
                emojiFont = emojiFonts[i];
                break;
            }
        }
        initialized = true;
    }

    UBlockCode block = ublock_getCode(ucs4);
    switch (block) {
    case UBLOCK_EMOTICONS:
        return emojiFont;
    case UBLOCK_PLAYING_CARDS:
    case UBLOCK_MISCELLANEOUS_SYMBOLS:
    case UBLOCK_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS:
    case UBLOCK_TRANSPORT_AND_MAP_SYMBOLS:
    case UBLOCK_ALCHEMICAL_SYMBOLS:
    case UBLOCK_RUNIC:
    case UBLOCK_SUPPLEMENTAL_MATHEMATICAL_OPERATORS:
    case UBLOCK_DINGBATS:
        return symbolFont;
    default:
        return 0;
    };
}

} // namespace

// FIXME: this is font fallback code version 0.1
//  - Cover all the scripts
//  - Get the default font for each script/generic family from the
//    preference instead of hardcoding in the source.
//    (at least, read values from the registry for IE font settings).
//  - Support generic families (from FontDescription)
//  - If the default font for a script is not available,
//    try some more fonts known to support it. Finally, we can
//    use EnumFontFamilies or similar APIs to come up with a list of
//    fonts supporting the script and cache the result.
//  - Consider using UnicodeSet (or UnicodeMap) converted from
//    GLYPHSET (BMP) or directly read from truetype cmap tables to
//    keep track of which character is supported by which font
//  - Update script_font_cache in response to WM_FONTCHANGE

const UChar* getFontFamilyForScript(UScriptCode script,
    FontDescription::GenericFamilyType generic,
    SkFontMgr* fontManager)
{
    static ScriptToFontMap scriptFontMap;
    static ScriptToFontMap scriptMonospaceFontMap;
    static bool initialized = false;
    if (!initialized) {
        initializeScriptFontMap(scriptFontMap, fontManager);
        initializeScriptMonospaceFontMap(scriptMonospaceFontMap, fontManager);
        initialized = true;
    }
    if (script == USCRIPT_INVALID_CODE)
        return 0;
    ASSERT(script < USCRIPT_CODE_LIMIT);
    if (generic == FontDescription::MonospaceFamily && scriptMonospaceFontMap[script])
        return scriptMonospaceFontMap[script];
    return scriptFontMap[script];
}

// FIXME:
//  - Handle 'Inherited', 'Common' and 'Unknown'
//    (see http://www.unicode.org/reports/tr24/#Usage_Model )
//    For 'Inherited' and 'Common', perhaps we need to
//    accept another parameter indicating the previous family
//    and just return it.
//  - All the characters (or characters up to the point a single
//    font can cover) need to be taken into account
const UChar* getFallbackFamily(UChar32 character,
    FontDescription::GenericFamilyType generic,
    UScriptCode* scriptChecked,
    SkFontMgr* fontManager)
{
    ASSERT(character);
    ASSERT(fontManager);
    const UChar* family = getFontBasedOnUnicodeBlock(character, fontManager);
    if (family)
        return family;

    UScriptCode script = getScript(character);

    // For the full-width ASCII characters (U+FF00 - U+FF5E), use the font for
    // Han (determined in a locale-dependent way above). Full-width ASCII
    // characters are rather widely used in Japanese and Chinese documents and
    // they're fully covered by Chinese, Japanese and Korean fonts.
    if (0xFF00 < character && character < 0xFF5F)
        script = USCRIPT_HAN;

    if (script == USCRIPT_COMMON)
        script = getScriptBasedOnUnicodeBlock(character);

    family = getFontFamilyForScript(script, generic, fontManager);
    // Another lame work-around to cover non-BMP characters.
    // If the font family for script is not found or the character is
    // not in BMP (> U+FFFF), we resort to the hard-coded list of
    // fallback fonts for now.
    if (!family || character > 0xFFFF) {
        int plane = character >> 16;
        switch (plane) {
        case 1:
            family = L"code2001";
            break;
        case 2:
            // Use a Traditional Chinese ExtB font if in Traditional Chinese locale.
            // Otherwise, use a Simplified Chinese ExtB font. Windows Japanese
            // fonts do support a small subset of ExtB (that are included in JIS X 0213),
            // but its coverage is rather sparse.
            // Eventually, this should be controlled by lang/xml:lang.
            if (icu::Locale::getDefault() == icu::Locale::getTraditionalChinese())
                family = L"pmingliu-extb";
            else
                family = L"simsun-extb";
            break;
        default:
            family = L"lucida sans unicode";
        }
    }

    if (scriptChecked)
        *scriptChecked = script;
    return family;
}

} // namespace blink


text:
using System;
using System.Collections.Generic;

namespace Azure.ResourceManager.MachineLearningServices.Models
{
    /// <summary> The SweepJob. </summary>
    public partial class SweepJob : ComputeJobBase
    {
        /// <summary> Initializes a new instance of SweepJob. </summary>
        /// <param name="computeBinding"> Compute binding definition. </param>
        /// <param name="parameterSamplingConfiguration"> class for all hyperparameter sampling algorithms. </param>
        /// <param name="evaluationConfiguration"> . </param>
        /// <exception cref="ArgumentNullException"> <paramref name="computeBinding"/>, <paramref name="parameterSamplingConfiguration"/>, or <paramref name="evaluationConfiguration"/> is null. </exception>
        public SweepJob(ComputeBinding computeBinding, ParameterSamplingConfiguration parameterSamplingConfiguration, EvaluationConfiguration evaluationConfiguration) : base(computeBinding)
        {
            if (computeBinding == null)
            {
                throw new ArgumentNullException(nameof(computeBinding));
            }
            if (parameterSamplingConfiguration == null)
            {
                throw new ArgumentNullException(nameof(parameterSamplingConfiguration));
            }
            if (evaluationConfiguration == null)
            {
                throw new ArgumentNullException(nameof(evaluationConfiguration));
            }

            ParameterSamplingConfiguration = parameterSamplingConfiguration;
            EvaluationConfiguration = evaluationConfiguration;
            JobType = JobType.Sweep;
        }

        /// <summary> Initializes a new instance of SweepJob. </summary>
        /// <param name="jobType"> Specifies the type of job. </param>
        /// <param name="interactionEndpoints">
        /// Dictonary of endpoint URIs, keyed by enumerated job endpoints.
        ///
        /// For local jobs, a job endpoint will have a value of FileStreamObject.
        /// </param>
        /// <param name="description"> The asset description text. </param>
        /// <param name="tags"> Tag dictionary. Tags can be added, removed, and updated. </param>
        /// <param name="properties"> The asset property dictionary. </param>
        /// <param name="experimentName"> The name of the experiment the job belongs to. If not set, the job is placed in the "Default" experiment. </param>
        /// <param name="computeBinding"> Compute binding definition. </param>
        /// <param name="output"> . </param>
        /// <param name="status"> The status of a job. </param>
        /// <param name="parameterSamplingConfiguration"> class for all hyperparameter sampling algorithms. </param>
        /// <param name="terminationConfiguration"> . </param>
        /// <param name="evaluationConfiguration"> . </param>
        /// <param name="trialComponent"> . </param>
        internal SweepJob(JobType jobType, JobBaseInteractionEndpoints interactionEndpoints, string description, IDictionary<string, string> tags, IDictionary<string, string> properties, string experimentName, ComputeBinding computeBinding, JobOutput output, JobStatus? status, ParameterSamplingConfiguration parameterSamplingConfiguration, TerminationConfiguration terminationConfiguration, EvaluationConfiguration evaluationConfiguration, TrialComponent trialComponent) : base(jobType, interactionEndpoints, description, tags, properties, experimentName, computeBinding, output)
        {
            Status = status;
            ParameterSamplingConfiguration = parameterSamplingConfiguration;
            TerminationConfiguration = terminationConfiguration;
            EvaluationConfiguration = evaluationConfiguration;
            TrialComponent = trialComponent;
            JobType = jobType;
        }

        /// <summary> The status of a job. </summary>
        public JobStatus? Status { get; set; }
        /// <summary> class for all hyperparameter sampling algorithms. </summary>
        public ParameterSamplingConfiguration ParameterSamplingConfiguration { get; set; }
        public TerminationConfiguration TerminationConfiguration { get; set; }
        public EvaluationConfiguration EvaluationConfiguration { get; set; }
        public TrialComponent TrialComponent { get; set; }
    }
}


text:
@protocol ParticipantViewControllerDelegate
- (void)didItemCountChange:(NSUInteger)itemCount;
@end

@protocol ParticipantViewControllerEditDelegate
- (void)participantWasDeleted:(Participant *)participant;
- (void)openParticipantPopup:(Participant *)participant;
@end

@interface ParticipantViewController : CoreDataTableViewController {
}

@property (nonatomic, retain, readonly) Travel *travel;
@property (nonatomic, assign) id <ParticipantViewControllerDelegate> delegate;
@property (nonatomic, assign) id <ParticipantViewControllerEditDelegate> editDelegate;

- (void)updateTravelOpenOrClosed;
- (id)initWithTravel:(Travel *)travel;

@end


text:
var Cell = (function () {
    function Cell(x, y, ctx) {
        this.x = x;
        this.y = y;
        this.width = 40;
        this.height = 40;
        this.ctx = ctx;
        var strokewidth = 1;
        this.state = 1 /* Empty */;
        this.redraw();
        return (this);
    }
    Cell.prototype.setSailCell = function () {
        this.isSailCell = true;
    };

    Cell.prototype.clearSailCell = function () {
        this.isSailCell = false;
    };

    Cell.prototype.shot = function () {
        if (this.isSailCell) {
            this.state = 2 /* Hit */;
        } else {
            this.state = 3 /* Miss */;
        }

        //this.redraw();
        return this.isSailCell;
    };

    Cell.prototype.redraw = function () {
        switch (this.state) {
            case 1 /* Empty */:
                this.draw(false, "gray");
                break;
            case 2 /* Hit */:
                this.draw(true, "green");
                break;
            case 3 /* Miss */:
                this.draw(true, "black");
                break;
            case 5 /* Sunk */:
                break;
        }
    };

    Cell.prototype.changeState = function (state) {
        this.state = state;
    };

    Cell.prototype.highlight = function () {
        this.draw(true, "darkgray");
        return (this);
    };

    Cell.prototype.isPointInside = function (x, y) {
        return (x >= this.x && x <= this.x + this.width && y >= this.y && y <= this.y + this.height);
    };

    Cell.prototype.draw = function (opacity, fillStyle) {
        this.ctx.save();
        if (opacity) {
            this.ctx.globalAlpha = 0.8;
        }

        this.ctx.beginPath();
        this.ctx.fillStyle = fillStyle;
        this.ctx.strokeStyle = "skyblue";
        this.ctx.lineWidth = 1;
        this.ctx.rect(this.x, this.y, this.width, this.height);
        this.ctx.stroke();
        this.ctx.fill();
        this.ctx.restore();
    };
    return Cell;
})();
//# sourceMappingURL=cell.js.map


text:
// Code generated by informer-gen. DO NOT EDIT.

package v1alpha1

import (
	internalinterfaces "github.com/bytedance/fedlearner/deploy/kubernetes_operator/pkg/client/informers/externalversions/internalinterfaces"
)

// Interface provides access to all the informers in this group version.
type Interface interface {
	// FLApps returns a FLAppInformer.
	FLApps() FLAppInformer
}

type version struct {
	factory          internalinterfaces.SharedInformerFactory
	namespace        string
	tweakListOptions internalinterfaces.TweakListOptionsFunc
}

// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {
	return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions}
}

// FLApps returns a FLAppInformer.
func (v *version) FLApps() FLAppInformer {
	return &fLAppInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}


text:
package sample.filter;

import sample.servlet.LoginServlet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value="/*", filterName="authenticationFilter")
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        if (this.satisfiesToReject(req)) {
            this.redirectToLoginPage(req, (HttpServletResponse) response);
            return;
        }

        chain.doFilter(request, response);
    }

    private boolean satisfiesToReject(HttpServletRequest request) {
        return !this.permitsRequestedPath(request) && !this.isLoggedIn(request);
    }

    private boolean permitsRequestedPath(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        return LoginServlet.LOGIN_PATH.equals(servletPath) || servletPath.startsWith("/css");
    }

    private boolean isLoggedIn(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        return session.getAttribute(LoginServlet.SESSION_USER_KEY) != null;
    }

    private void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(request.getContextPath() + LoginServlet.LOGIN_PATH);
    }

    @Override public void init(FilterConfig filterConfig) throws ServletException {}
    @Override public void destroy() {}
}


text:
//
//  ViewController.m
//  ASasas
//
//  Created by BEVER on 16/7/15.
//  Copyright © 2016年 mac. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef void (^coverDidRomove)();
@interface SetingViewController : UIViewController

//** 遮盖按钮 */
@property (nonatomic, strong) UIButton *coverBtn;

@property (nonatomic, strong) coverDidRomove coverDidRomove;

@property (nonatomic, assign) BOOL isScale;

- (void)coverClick;

@end


text:
from .equity_pricing_loader import USEquityPricingLoader
from .crypto_pricing_loader import CryptoPricingLoader

__all__ = [
    'USEquityPricingLoader',
    'CryptoPricingLoader',
]


text:
package glusterfs

import (
	"encoding/json"
	"net/http"
)

// DbDump ... Creates a JSON output representing the state of DB
// This is the variant to be called via the API and running in the App
func (a *App) DbDump(w http.ResponseWriter, r *http.Request) {
	dump, err := dbDumpInternal(a.db)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Write msg
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	encoder := json.NewEncoder(w)
	encoder.SetIndent("", "    ")
	if err := encoder.Encode(dump); err != nil {
		panic(err)
	}
}

// DbCheck ... Checks the DB for inconsistencies.
// It returns a JSON summary of the check.
// This is the variant to be called via the API and running in the App
func (a *App) DbCheck(w http.ResponseWriter, r *http.Request) {
	checkResponse, err := dbCheckConsistency(a.db)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Write msg
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	encoder := json.NewEncoder(w)
	encoder.SetIndent("", "    ")
	if err := encoder.Encode(checkResponse); err != nil {
		panic(err)
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// 100/100
/// https://judge.softuni.bg/Contests/Practice/Index/835#1
/// </summary>
namespace _04._Anonymous_Cache
{
    class DataBase
    {
        public string DataSet { get; set; }
        public List<string> DataKey { get; set; }
        public List<long> DataSize { get; set; }
    }

    class AnonymousCache
    {
        static void Main()
        {
            List<DataBase> mainData = new List<DataBase>();
            List<string> cache = new List<string>();

            string input = string.Empty;

            while ((input = Console.ReadLine()) != "thetinggoesskrra")
            {
                string[] args = input.Split(new[] { ' ', '{', '}', '-','|', '>' }, StringSplitOptions.RemoveEmptyEntries);

                if (args.Length == 1)
                {
                    string dataSet = args[0];
                    if (!cache.Contains(dataSet))
                    {
                        cache.Add(dataSet);
                    }
                }
                else
                {
                    string dataKey = args[0];
                    long dataSize = long.Parse(args[1]);
                    string dataSet = args[2];

                    DataBase data = new DataBase()
                    {
                        DataKey=new List<string>(),
                        DataSet=dataSet,
                        DataSize=new List<long>()
                    };

                    if (!mainData.Any(x=>x.DataSet==dataSet))
                    {
                        mainData.Add(data);
                    }
                    var curr=mainData.Where(x=>x.DataSet==dataSet).First();
                    curr.DataKey.Add(dataKey);
                    curr.DataSize.Add(dataSize);
                }
            }

            foreach (var set in mainData.Where(x=>cache.Contains(x.DataSet)).OrderByDescending(x=>x.DataSize.Sum()))
            {
                Console.WriteLine($"Data Set: {set.DataSet}, Total Size: {set.DataSize.Sum()}");
                foreach (var item in set.DataKey)
                {
                    Console.Write("$.");
                    Console.WriteLine(string.Join("",item));
                }
                    return;
            }
        }
    }
}


text:
<?php

namespace Consigliere\Components\Providers;

use Illuminate\Support\ServiceProvider;

class BootstrapServiceProvider extends ServiceProvider
{
    /**
     * Booting the package.
     */
    public function boot()
    {
        $this->app['components']->boot();
    }

    /**
     * Register the provider.
     */
    public function register()
    {
        $this->app['components']->register();
    }
}


text:
log into a nodejs site using just an email address

## loading the code

    <script src="/email-login/lib/email-login.js"></script>

## example javascript usage (in browser)

    email_login = new EmailLogin("#id_of_place_to_prepend_email_login_form");
    // email_login.logged_in; // boolean
    // email_login.log_out(); // log user out

## on the server side (example code for nodejs)

    You should have a class which does something like this:

    class EmailAuthenticator
      constructor: ->
	@email_login_ctlr = new EmailLoginController()
	@email_login_ctlr.userNo_sessNo_regex = @userNo_sessNo_regex
	@verification_handler = @email_login_ctlr.verification_handler
	@verification_handler_async = @email_login_ctlr.verification_handler_async
	@join_handler = @email_login_ctlr.join_handler
	@session_middleware = @email_login_ctlr.session_middleware
	@email_login_ctlr.environment = app.settings.env
	@email_login_ctlr.server_uri = cli.base_url + "/"
	console.log("server_uri:", @email_login_ctlr.server_uri)
	@email_login_ctlr.from = "do-not-reply@your-domain.com"

      entwine: ->
	@email_login_ctlr.delegate_to(@)

      userNo_sessNo_regex: /sess\:([0-9A-Za-z]{1,20})\_([0-9A-Za-z]{1,20})/

      get_real_verification_token: =>
      get_latest_verification_token_for_person_uri: =>
      record_verification_of_person_uri_from_ip_using_token: =>
      is_verification_already_used: =>
      get_next_session_token_for: (person_uri) =>
	console.log "get_next_session_token_for() person_uri:",person_uri
	create_session(person_uri)
      user_middleware: (req, res, next) =>
	query =
	  username: cli.run_as
	if req.signedCookies
	  if req.signedCookies.auth
	    query =
	      email: req.signedCookies.auth.person_uri.replace("mailto:", "")
	user = findUserBy(query)
	if user?
	  if not user.account_key?
	    user.account_key = user.username
	  req.user = user
	next()

    GET /email-login/login
      this should trigger the sending of email with a link like:
        http://example.com/email-login/verfiy/user@site.com/SINGLE_USE_TOKEN

    GET /email-login/verify/:email/:verification
      this should set a signed cookie and redir to root:
        res.cookie("auth", {email: email, token: token}, {signed: true})
        res.redirect("/")

## Developing

  It is generally handy to develop `email-login` within the context of something
  that uses it.  This is how I do it:

    cd REPOS/email-login
    npm install               # just once of course
    cd ../MyParentProject     # the client project
    npm install               # once all the node_modules are installed
    npm uninstall email-login # uninstall this one so...
    npm link ../email-login   # it can be 'linked' per https://docs.npmjs.com/cli/link

  Then I make changes to both the parent project and `email-login` while running:

    cd REPOS/email-login
    grunt watch            # run this to keep email-login built

  When changes have been made and commited, then do one of the following:

    grunt release        # equivalent to ...
    grunt release:patch  # trivial or bug fixes

    grunt release:minor  # new features

    grunt release:major  # breaking changes