text:
package org.apache.batik.apps.svgbrowser;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.LookAndFeel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.batik.ext.swing.GridBagConstants;
import org.apache.batik.ext.swing.JGridBagPanel;
import org.apache.batik.util.Platform;
import org.apache.batik.util.PreferenceManager;
import org.apache.batik.util.gui.CSSMediaPanel;
import org.apache.batik.util.gui.LanguageDialog;

/**
 * Dialog that displays user preferences.
 *
 * @author Vincent Hardy
 * @version $Id: PreferenceDialog.java 498740 2007-01-22 18:35:57Z dvholten $
 */
public class PreferenceDialog extends JDialog
    implements GridBagConstants {

    /**
     * The return value if 'OK' is chosen.
     */
    public static final int OK_OPTION = 0;

    /**
     * The return value if 'Cancel' is chosen.
     */
    public static final int CANCEL_OPTION = 1;

    //////////////////////////////////////////////////////////////
    // GUI Resources Keys
    //////////////////////////////////////////////////////////////

    public static final String PREFERENCE_KEY_TITLE_PREFIX
        = "PreferenceDialog.title.";

    public static final String PREFERENCE_KEY_TITLE_DIALOG
        = "PreferenceDialog.title.dialog";

    public static final String PREFERENCE_KEY_LABEL_RENDERING_OPTIONS
        = "PreferenceDialog.label.rendering.options";

    public static final String PREFERENCE_KEY_LABEL_ANIMATION_RATE_LIMITING
        = "PreferenceDialog.label.animation.rate.limiting";

    public static final String PREFERENCE_KEY_LABEL_OTHER_OPTIONS
        = "PreferenceDialog.label.other.options";

    public static final String PREFERENCE_KEY_LABEL_ENABLE_DOUBLE_BUFFERING
        = "PreferenceDialog.label.enable.double.buffering";

    public static final String PREFERENCE_KEY_LABEL_SHOW_RENDERING
        = "PreferenceDialog.label.show.rendering";

    public static final String PREFERENCE_KEY_LABEL_AUTO_ADJUST_WINDOW
        = "PreferenceDialog.label.auto.adjust.window";

    public static final String PREFERENCE_KEY_LABEL_SELECTION_XOR_MODE
        = "PreferenceDialog.label.selection.xor.mode";

    public static final String PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_CPU
        = "PreferenceDialog.label.animation.limit.cpu";

    public static final String PREFERENCE_KEY_LABEL_PERCENT
        = "PreferenceDialog.label.percent";

    public static final String PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_FPS
        = "PreferenceDialog.label.animation.limit.fps";

    public static final String PREFERENCE_KEY_LABEL_FPS
        = "PreferenceDialog.label.fps";

    public static final String PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_UNLIMITED
        = "PreferenceDialog.label.animation.limit.unlimited";

    public static final String PREFERENCE_KEY_LABEL_SHOW_DEBUG_TRACE
        = "PreferenceDialog.label.show.debug.trace";

    public static final String PREFERENCE_KEY_LABEL_IS_XML_PARSER_VALIDATING
        = "PreferenceDialog.label.is.xml.parser.validating";

    public static final String PREFERENCE_KEY_LABEL_GRANT_SCRIPTS_ACCESS_TO
        = "PreferenceDialog.label.grant.scripts.access.to";

    public static final String PREFERENCE_KEY_LABEL_LOAD_SCRIPTS
        = "PreferenceDialog.label.load.scripts";

    public static final String PREFERENCE_KEY_LABEL_ALLOWED_SCRIPT_ORIGIN
        = "PreferenceDialog.label.allowed.script.origin";

    public static final String PREFERENCE_KEY_LABEL_ALLOWED_RESOURCE_ORIGIN
        = "PreferenceDialog.label.allowed.resource.origin";

    public static final String PREFERENCE_KEY_LABEL_ENFORCE_SECURE_SCRIPTING
        = "PreferenceDialog.label.enforce.secure.scripting";

    public static final String PREFERENCE_KEY_LABEL_FILE_SYSTEM
        = "PreferenceDialog.label.file.system";

    public static final String PREFERENCE_KEY_LABEL_ALL_NETWORK
        = "PreferenceDialog.label.all.network";

    public static final String PREFERENCE_KEY_LABEL_JAVA_JAR_FILES
        = "PreferenceDialog.label.java.jar.files";

    public static final String PREFERENCE_KEY_LABEL_ECMASCRIPT
        = "PreferenceDialog.label.ecmascript";

    public static final String PREFERENCE_KEY_LABEL_ORIGIN_ANY
        = "PreferenceDialog.label.origin.any";

    public static final String PREFERENCE_KEY_LABEL_ORIGIN_DOCUMENT
        = "PreferenceDialog.label.origin.document";

    public static final String PREFERENCE_KEY_LABEL_ORIGIN_EMBEDDED
        = "PreferenceDialog.label.origin.embedded";

    public static final String PREFERENCE_KEY_LABEL_ORIGIN_NONE
        = "PreferenceDialog.label.origin.none";

    public static final String PREFERENCE_KEY_LABEL_USER_STYLESHEET
        = "PreferenceDialog.label.user.stylesheet";

    public static final String PREFERENCE_KEY_LABEL_CSS_MEDIA_TYPES
        = "PreferenceDialog.label.css.media.types";

    public static final String PREFERENCE_KEY_LABEL_ENABLE_USER_STYLESHEET
        = "PreferenceDialog.label.enable.user.stylesheet";

    public static final String PREFERENCE_KEY_LABEL_BROWSE
        = "PreferenceDialog.label.browse";

    public static final String PREFERENCE_KEY_LABEL_ADD
        = "PreferenceDialog.label.add";

    public static final String PREFERENCE_KEY_LABEL_REMOVE
        = "PreferenceDialog.label.remove";

    public static final String PREFERENCE_KEY_LABEL_CLEAR
        = "PreferenceDialog.label.clear";

    public static final String PREFERENCE_KEY_LABEL_HTTP_PROXY
        = "PreferenceDialog.label.http.proxy";

    public static final String PREFERENCE_KEY_LABEL_HOST
        = "PreferenceDialog.label.host";

    public static final String PREFERENCE_KEY_LABEL_PORT
        = "PreferenceDialog.label.port";

    public static final String PREFERENCE_KEY_LABEL_COLON
        = "PreferenceDialog.label.colon";

    public static final String PREFERENCE_KEY_BROWSE_TITLE
        = "PreferenceDialog.BrowseWindow.title";

    //////////////////////////////////////////////////////////////
    // Following are the preference keys used in the
    // PreferenceManager model.
    //////////////////////////////////////////////////////////////

    public static final String PREFERENCE_KEY_LANGUAGES
        = "preference.key.languages";

    public static final String PREFERENCE_KEY_IS_XML_PARSER_VALIDATING
        = "preference.key.is.xml.parser.validating";

    public static final String PREFERENCE_KEY_USER_STYLESHEET
        = "preference.key.user.stylesheet";

    public static final String PREFERENCE_KEY_USER_STYLESHEET_ENABLED
        = "preference.key.user.stylesheet.enabled";

    public static final String PREFERENCE_KEY_SHOW_RENDERING
        = "preference.key.show.rendering";

    public static final String PREFERENCE_KEY_AUTO_ADJUST_WINDOW
        = "preference.key.auto.adjust.window";

    public static final String PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING
        = "preference.key.enable.double.buffering";

    public static final String PREFERENCE_KEY_SHOW_DEBUG_TRACE
        = "preference.key.show.debug.trace";

    public static final String PREFERENCE_KEY_SELECTION_XOR_MODE
        = "preference.key.selection.xor.mode";

    public static final String PREFERENCE_KEY_PROXY_HOST
        = "preference.key.proxy.host";

    public static final String PREFERENCE_KEY_CSS_MEDIA
        = "preference.key.cssmedia";

    public static final String PREFERENCE_KEY_DEFAULT_FONT_FAMILY
        = "preference.key.default.font.family";

    public static final String PREFERENCE_KEY_PROXY_PORT
        = "preference.key.proxy.port";

    public static final String PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING
        = "preference.key.enforce.secure.scripting";

    public static final String PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS
        = "preference.key.grant.script.file.access";

    public static final String PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS
        = "preference.key.grant.script.network.access";

    public static final String PREFERENCE_KEY_LOAD_ECMASCRIPT
        = "preference.key.load.ecmascript";

    public static final String PREFERENCE_KEY_LOAD_JAVA
        = "preference.key.load.java.script";

    public static final String PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN
        = "preference.key.allowed.script.origin";

    public static final String PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN
        = "preference.key.allowed.external.resource.origin";

    public static final String PREFERENCE_KEY_ANIMATION_RATE_LIMITING_MODE
        = "preference.key.animation.rate.limiting.mode";

    public static final String PREFERENCE_KEY_ANIMATION_RATE_LIMITING_CPU
        = "preference.key.animation.rate.limiting.cpu";

    public static final String PREFERENCE_KEY_ANIMATION_RATE_LIMITING_FPS
        = "preference.key.animation.rate.limiting.fps";

    public static final String LABEL_OK
        = "PreferenceDialog.label.ok";

    public static final String LABEL_CANCEL
        = "PreferenceDialog.label.cancel";

    /**
     * <tt>PreferenceManager</tt> used to store and retrieve
     * preferences
     */
    protected PreferenceManager model;

    /**
     * The configuration panel that holds each of the configuration pages.
     */
    protected JConfigurationPanel configurationPanel;

    protected JCheckBox userStylesheetEnabled;
    protected JLabel userStylesheetLabel;
    protected JTextField userStylesheet;
    protected JButton userStylesheetBrowse;
    protected JCheckBox showRendering;
    protected JCheckBox autoAdjustWindow;
    protected JCheckBox enableDoubleBuffering;
    protected JCheckBox showDebugTrace;
    protected JCheckBox selectionXorMode;
    protected JCheckBox isXMLParserValidating;
    protected JRadioButton animationLimitUnlimited;
    protected JRadioButton animationLimitCPU;
    protected JRadioButton animationLimitFPS;
    protected JLabel animationLimitCPULabel;
    protected JLabel animationLimitFPSLabel;
    protected JTextField animationLimitCPUAmount;
    protected JTextField animationLimitFPSAmount;
    protected JCheckBox enforceSecureScripting;
    protected JCheckBox grantScriptFileAccess;
    protected JCheckBox grantScriptNetworkAccess;
    protected JCheckBox loadJava;
    protected JCheckBox loadEcmascript;
    protected JComboBox allowedScriptOrigin;
    protected JComboBox allowedResourceOrigin;
    protected JList mediaList;
    protected JButton mediaListRemoveButton;
    protected JButton mediaListClearButton;
    protected JTextField host;
    protected JTextField port;
    protected LanguageDialog.Panel languagePanel;
    protected DefaultListModel mediaListModel = new DefaultListModel();

    /**
     * Code indicating whether the dialog was okayed or cancelled.
     */
    protected int returnCode;

    /**
     * Returns whether the current LAF is Metal Steel.
     */
    protected static boolean isMetalSteel() {
        if (!UIManager.getLookAndFeel().getName().equals("Metal")) {
            return false;
        }
        try {
            LookAndFeel laf = UIManager.getLookAndFeel();
            laf.getClass().getMethod("getCurrentTheme", new Class[0]);
            return false;
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * Creates a new PreferenceDialog with the given model.
     */
    public PreferenceDialog(Frame owner, PreferenceManager model) {
        super(owner, true);

        if (model == null) {
            throw new IllegalArgumentException();
        }

        this.model = model;
        buildGUI();
        initializeGUI();
        pack();

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (Platform.isOSX) {
                    savePreferences();
                }
            }
        });
    }

    /**
     * Returns the preference manager used by this dialog.
     */
    public PreferenceManager getPreferenceManager() {
        return model;
    }

    /**
     * Initializes the GUI components with the values from the model.
     */
    protected void initializeGUI() {
        boolean b;
        float f;
        int i;
        String s;

        // General options
        enableDoubleBuffering.setSelected
            (model.getBoolean(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING));
        showRendering.setSelected
            (model.getBoolean(PREFERENCE_KEY_SHOW_RENDERING));
        autoAdjustWindow.setSelected
            (model.getBoolean(PREFERENCE_KEY_AUTO_ADJUST_WINDOW));
        selectionXorMode.setSelected
            (model.getBoolean(PREFERENCE_KEY_SELECTION_XOR_MODE));

        switch (model.getInteger(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_MODE)) {
            case 0: // unlimited
                animationLimitUnlimited.setSelected(true);
                break;
            case 2: // fps
                animationLimitFPS.setSelected(true);
                break;
            // case 1: // %cpu
            default:
                animationLimitCPU.setSelected(true);
                break;
        }
        f = model.getFloat(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_CPU);
        if (f <= 0f || f > 100f) {
            f = 85f;
        } else {
            f *= 100;
        }
        if (((int) f) == f) {
            animationLimitCPUAmount.setText(Integer.toString((int) f));
        } else {
            animationLimitCPUAmount.setText(Float.toString(f));
        }
        f = model.getFloat(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_FPS);
        if (f <= 0f) {
            f = 10f;
        }
        if (((int) f) == f) {
            animationLimitFPSAmount.setText(Integer.toString((int) f));
        } else {
            animationLimitFPSAmount.setText(Float.toString(f));
        }

        showDebugTrace.setSelected
            (model.getBoolean(PREFERENCE_KEY_SHOW_DEBUG_TRACE));
        isXMLParserValidating.setSelected
            (model.getBoolean(PREFERENCE_KEY_IS_XML_PARSER_VALIDATING));

        // Security options
        enforceSecureScripting.setSelected
            (model.getBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING));
        grantScriptFileAccess.setSelected
            (model.getBoolean(PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS));
        grantScriptNetworkAccess.setSelected
            (model.getBoolean(PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS));
        loadJava.setSelected
            (model.getBoolean(PREFERENCE_KEY_LOAD_JAVA));
        loadEcmascript.setSelected
            (model.getBoolean(PREFERENCE_KEY_LOAD_ECMASCRIPT));

        i = model.getInteger(PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN);
        switch (i) {
            case ResourceOrigin.ANY:
                allowedScriptOrigin.setSelectedIndex(0);
                break;
            case ResourceOrigin.DOCUMENT:
                allowedScriptOrigin.setSelectedIndex(1);
                break;
            case ResourceOrigin.EMBEDED:
                allowedScriptOrigin.setSelectedIndex(2);
                break;
            default:
                allowedScriptOrigin.setSelectedIndex(3);
                break;
        }

        i = model.getInteger(PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN);
        switch (i) {
            case ResourceOrigin.ANY:
                allowedResourceOrigin.setSelectedIndex(0);
                break;
            case ResourceOrigin.DOCUMENT:
                allowedResourceOrigin.setSelectedIndex(1);
                break;
            case ResourceOrigin.EMBEDED:
                allowedResourceOrigin.setSelectedIndex(2);
                break;
            default:
                allowedResourceOrigin.setSelectedIndex(3);
                break;
        }

        // Language options
        languagePanel.setLanguages(model.getString(PREFERENCE_KEY_LANGUAGES));

        // Stylesheet options
        s = model.getString(PREFERENCE_KEY_CSS_MEDIA);
        mediaListModel.removeAllElements();
        StringTokenizer st = new StringTokenizer(s, " ");
        while (st.hasMoreTokens()) {
            mediaListModel.addElement(st.nextToken());
        }

        userStylesheet.setText(model.getString(PREFERENCE_KEY_USER_STYLESHEET));
        b = model.getBoolean(PREFERENCE_KEY_USER_STYLESHEET_ENABLED);
        userStylesheetEnabled.setSelected(b);

        // Network options
        host.setText(model.getString(PREFERENCE_KEY_PROXY_HOST));
        port.setText(model.getString(PREFERENCE_KEY_PROXY_PORT));

        // Set some components disabled initially
        b = enableDoubleBuffering.isSelected();
        showRendering.setEnabled(b);

        b = animationLimitCPU.isSelected();
        animationLimitCPUAmount.setEnabled(b);
        animationLimitCPULabel.setEnabled(b);

        b = animationLimitFPS.isSelected();
        animationLimitFPSAmount.setEnabled(b);
        animationLimitFPSLabel.setEnabled(b);

        b = enforceSecureScripting.isSelected();
        grantScriptFileAccess.setEnabled(b);
        grantScriptNetworkAccess.setEnabled(b);

        b = userStylesheetEnabled.isSelected();
        userStylesheetLabel.setEnabled(b);
        userStylesheet.setEnabled(b);
        userStylesheetBrowse.setEnabled(b);

        mediaListRemoveButton.setEnabled(!mediaList.isSelectionEmpty());
        mediaListClearButton.setEnabled(!mediaListModel.isEmpty());
    }

    /**
     * Stores the current settings in the PreferenceManager model.
     */
    protected void savePreferences() {
        model.setString(PREFERENCE_KEY_LANGUAGES,
                        languagePanel.getLanguages());
        model.setString(PREFERENCE_KEY_USER_STYLESHEET,
                        userStylesheet.getText());
        model.setBoolean(PREFERENCE_KEY_USER_STYLESHEET_ENABLED,
                         userStylesheetEnabled.isSelected());
        model.setBoolean(PREFERENCE_KEY_SHOW_RENDERING,
                         showRendering.isSelected());
        model.setBoolean(PREFERENCE_KEY_AUTO_ADJUST_WINDOW,
                         autoAdjustWindow.isSelected());
        model.setBoolean(PREFERENCE_KEY_ENABLE_DOUBLE_BUFFERING,
                         enableDoubleBuffering.isSelected());
        model.setBoolean(PREFERENCE_KEY_SHOW_DEBUG_TRACE,
                         showDebugTrace.isSelected());
        model.setBoolean(PREFERENCE_KEY_SELECTION_XOR_MODE,
                         selectionXorMode.isSelected());
        model.setBoolean(PREFERENCE_KEY_IS_XML_PARSER_VALIDATING,
                         isXMLParserValidating.isSelected());
        model.setBoolean(PREFERENCE_KEY_ENFORCE_SECURE_SCRIPTING,
                         enforceSecureScripting.isSelected());
        model.setBoolean(PREFERENCE_KEY_GRANT_SCRIPT_FILE_ACCESS,
                         grantScriptFileAccess.isSelected());
        model.setBoolean(PREFERENCE_KEY_GRANT_SCRIPT_NETWORK_ACCESS,
                         grantScriptNetworkAccess.isSelected());
        model.setBoolean(PREFERENCE_KEY_LOAD_JAVA,
                         loadJava.isSelected());
        model.setBoolean(PREFERENCE_KEY_LOAD_ECMASCRIPT,
                         loadEcmascript.isSelected());
        int i;
        switch (allowedScriptOrigin.getSelectedIndex()) {
            case 0:
                i = ResourceOrigin.ANY;
                break;
            case 1:
                i = ResourceOrigin.DOCUMENT;
                break;
            case 2:
                i = ResourceOrigin.EMBEDED;
                break;
            // case 3:
            default:
                i = ResourceOrigin.NONE;
                break;
        }
        model.setInteger(PREFERENCE_KEY_ALLOWED_SCRIPT_ORIGIN, i);
        switch (allowedResourceOrigin.getSelectedIndex()) {
            case 0:
                i = ResourceOrigin.ANY;
                break;
            case 1:
                i = ResourceOrigin.DOCUMENT;
                break;
            case 2:
                i = ResourceOrigin.EMBEDED;
                break;
            // case 3:
            default:
                i = ResourceOrigin.NONE;
                break;
        }
        model.setInteger(PREFERENCE_KEY_ALLOWED_EXTERNAL_RESOURCE_ORIGIN, i);
        i = 1;
        if (animationLimitFPS.isSelected()) {
            i = 2;
        } else if (animationLimitUnlimited.isSelected()) {
            i = 0;
        }
        model.setInteger(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_MODE, i);
        float f;
        try {
            f = Float.parseFloat(animationLimitCPUAmount.getText()) / 100;
            if (f <= 0f || f >= 1.0f) {
                f = 0.85f;
            }
        } catch (NumberFormatException e) {
            f = 0.85f;
        }
        model.setFloat(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_CPU, f);
        try {
            f = Float.parseFloat(animationLimitFPSAmount.getText());
            if (f <= 0) {
                f = 15f;
            }
        } catch (NumberFormatException e) {
            f = 15f;
        }
        model.setFloat(PREFERENCE_KEY_ANIMATION_RATE_LIMITING_FPS, f);
        model.setString(PREFERENCE_KEY_PROXY_HOST,
                        host.getText());
        model.setString(PREFERENCE_KEY_PROXY_PORT,
                        port.getText());
        StringBuffer sb = new StringBuffer();
        Enumeration e = mediaListModel.elements();
        while (e.hasMoreElements()) {
            sb.append((String) e.nextElement());
            sb.append(' ');
        }
        model.setString(PREFERENCE_KEY_CSS_MEDIA, sb.toString());
    }

    /**
     * Builds the UI for this dialog.
     */
    protected void buildGUI() {
        JPanel panel = new JPanel(new BorderLayout());

        configurationPanel = new JConfigurationPanel();
        addConfigPanel("general", buildGeneralPanel());
        addConfigPanel("security", buildSecurityPanel());
        addConfigPanel("language", buildLanguagePanel());
        addConfigPanel("stylesheet", buildStylesheetPanel());
        addConfigPanel("network", buildNetworkPanel());

        panel.add(configurationPanel);

        if (!Platform.isOSX) {
            setTitle(Resources.getString(PREFERENCE_KEY_TITLE_DIALOG));
            panel.add(buildButtonsPanel(), BorderLayout.SOUTH);
        }
        setResizable(false);

        getContentPane().add(panel);
    }

    /**
     * Adds a panel to the configuration panel.
     */
    protected void addConfigPanel(String id, JPanel c) {
        String name = Resources.getString(PREFERENCE_KEY_TITLE_PREFIX + id);
        ImageIcon icon1 =
            new ImageIcon(PreferenceDialog.class.getResource
                              ("resources/icon-" + id + ".png"));
        ImageIcon icon2 =
            new ImageIcon(PreferenceDialog.class.getResource
                              ("resources/icon-" + id + "-dark.png"));
        configurationPanel.addPanel(name, icon1, icon2, c);
    }

    /**
     * Creates the OK/Cancel button panel.
     */
    protected JPanel buildButtonsPanel() {
        JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton okButton = new JButton(Resources.getString(LABEL_OK));
        JButton cancelButton = new JButton(Resources.getString(LABEL_CANCEL));
        p.add(okButton);
        p.add(cancelButton);

        okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    returnCode = OK_OPTION;
                    savePreferences();
                    dispose();
                }
            });

        cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    returnCode = CANCEL_OPTION;
                    dispose();
                }
            });

        addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_ESCAPE:
                            returnCode = CANCEL_OPTION;
                            break;
                        case KeyEvent.VK_ENTER:
                            returnCode = OK_OPTION;
                            break;
                        default:
                            return;
                    }
                    setVisible(false);
                    dispose();
                }
            });

        return p;
    }

    /**
     * Builds the General panel.
     */
    protected JPanel buildGeneralPanel() {
        JGridBagPanel.InsetsManager im = new JGridBagPanel.InsetsManager() {
            protected Insets i1 = new Insets(5, 5, 0, 0);
            protected Insets i2 = new Insets(5, 0, 0, 0);
            protected Insets i3 = new Insets(0, 5, 0, 0);
            protected Insets i4 = new Insets(0, 0, 0, 0);

            public Insets getInsets(int x, int y) {
                if (y == 4 || y == 9) {
                    return x == 0 ? i2 : i1;
                }
                return x == 0 ? i4 : i3;
            }
        };

        JGridBagPanel p = new JGridBagPanel(im);
        p.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));

        JLabel renderingLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_RENDERING_OPTIONS));
        enableDoubleBuffering = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_ENABLE_DOUBLE_BUFFERING));
        enableDoubleBuffering.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                showRendering.setEnabled(enableDoubleBuffering.isSelected());
            }
        });
        showRendering = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_SHOW_RENDERING));
        Insets in = showRendering.getMargin();
        showRendering.setMargin(new Insets(in.top, in.left + 24, in.bottom, in.right));
        selectionXorMode = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_SELECTION_XOR_MODE));
        autoAdjustWindow = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_AUTO_ADJUST_WINDOW));
        JLabel animLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_ANIMATION_RATE_LIMITING));
        animationLimitCPU = new JRadioButton(Resources.getString(PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_CPU));
        JPanel cpuPanel = new JPanel();
        cpuPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 3, 0));
        cpuPanel.setBorder(BorderFactory.createEmptyBorder(0, 24, 0, 0));
        animationLimitCPUAmount = new JTextField();
        animationLimitCPUAmount.setPreferredSize(new Dimension(40, 20));
        cpuPanel.add(animationLimitCPUAmount);
        animationLimitCPULabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_PERCENT));
        cpuPanel.add(animationLimitCPULabel);
        animationLimitFPS = new JRadioButton(Resources.getString(PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_FPS));
        JPanel fpsPanel = new JPanel();
        fpsPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 3, 0));
        fpsPanel.setBorder(BorderFactory.createEmptyBorder(0, 24, 0, 0));
        animationLimitFPSAmount = new JTextField();
        animationLimitFPSAmount.setPreferredSize(new Dimension(40, 20));
        fpsPanel.add(animationLimitFPSAmount);
        animationLimitFPSLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_FPS));
        fpsPanel.add(animationLimitFPSLabel);
        animationLimitUnlimited = new JRadioButton(Resources.getString(PREFERENCE_KEY_LABEL_ANIMATION_LIMIT_UNLIMITED));
        ButtonGroup g = new ButtonGroup();
        g.add(animationLimitCPU);
        g.add(animationLimitFPS);
        g.add(animationLimitUnlimited);
        ActionListener l = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                boolean b = animationLimitCPU.isSelected();
                animationLimitCPUAmount.setEnabled(b);
                animationLimitCPULabel.setEnabled(b);
                b = animationLimitFPS.isSelected();
                animationLimitFPSAmount.setEnabled(b);
                animationLimitFPSLabel.setEnabled(b);
            }
        };
        animationLimitCPU.addActionListener(l);
        animationLimitFPS.addActionListener(l);
        animationLimitUnlimited.addActionListener(l);
        JLabel otherLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_OTHER_OPTIONS));
        showDebugTrace = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_SHOW_DEBUG_TRACE));
        isXMLParserValidating = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_IS_XML_PARSER_VALIDATING));

        p.add(renderingLabel,          0, 0, 1, 1, EAST, NONE, 0, 0);
        p.add(enableDoubleBuffering,   1, 0, 1, 1, WEST, NONE, 0, 0);
        p.add(showRendering,           1, 1, 1, 1, WEST, NONE, 0, 0);
        p.add(autoAdjustWindow,        1, 2, 1, 1, WEST, NONE, 0, 0);
        p.add(selectionXorMode,        1, 3, 1, 1, WEST, NONE, 0, 0);
        p.add(animLabel,               0, 4, 1, 1, EAST, NONE, 0, 0);
        p.add(animationLimitCPU,       1, 4, 1, 1, WEST, NONE, 0, 0);
        p.add(cpuPanel,                1, 5, 1, 1, WEST, NONE, 0, 0);
        p.add(animationLimitFPS,       1, 6, 1, 1, WEST, NONE, 0, 0);
        p.add(fpsPanel,                1, 7, 1, 1, WEST, NONE, 0, 0);
        p.add(animationLimitUnlimited, 1, 8, 1, 1, WEST, NONE, 0, 0);
        p.add(otherLabel,              0, 9, 1, 1, EAST, NONE, 0, 0);
        p.add(showDebugTrace,          1, 9, 1, 1, WEST, NONE, 0, 0);
        p.add(isXMLParserValidating,   1,10, 1, 1, WEST, NONE, 0, 0);

        return p;
    }

    /**
     * Builds the Security panel.
     */
    protected JPanel buildSecurityPanel() {
        JGridBagPanel.InsetsManager im = new JGridBagPanel.InsetsManager() {
            protected Insets i1 = new Insets(5, 5, 0, 0);
            protected Insets i2 = new Insets(5, 0, 0, 0);
            protected Insets i3 = new Insets(0, 5, 0, 0);
            protected Insets i4 = new Insets(0, 0, 0, 0);

            public Insets getInsets(int x, int y) {
                if (y == 1 || y == 3 || y == 5 || y == 6) {
                    return x == 0 ? i2 : i1;
                }
                return x == 0 ? i4 : i3;
            }
        };

        JGridBagPanel p = new JGridBagPanel(im);
        p.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));

        enforceSecureScripting = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_ENFORCE_SECURE_SCRIPTING));
        enforceSecureScripting.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                boolean b = enforceSecureScripting.isSelected();
                grantScriptFileAccess.setEnabled(b);
                grantScriptNetworkAccess.setEnabled(b);
            }
        });

        JLabel grantScript = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_GRANT_SCRIPTS_ACCESS_TO));
        grantScript.setVerticalAlignment(SwingConstants.TOP);
        grantScript.setOpaque(true);
        grantScriptFileAccess = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_FILE_SYSTEM));
        grantScriptNetworkAccess = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_ALL_NETWORK));

        JLabel loadScripts = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_LOAD_SCRIPTS));
        loadScripts.setVerticalAlignment(SwingConstants.TOP);
        loadJava = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_JAVA_JAR_FILES));
        loadEcmascript = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_ECMASCRIPT));

        String[] origins = {
            Resources.getString(PREFERENCE_KEY_LABEL_ORIGIN_ANY),
            Resources.getString(PREFERENCE_KEY_LABEL_ORIGIN_DOCUMENT),
            Resources.getString(PREFERENCE_KEY_LABEL_ORIGIN_EMBEDDED),
            Resources.getString(PREFERENCE_KEY_LABEL_ORIGIN_NONE)
        };
        JLabel scriptOriginLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_ALLOWED_SCRIPT_ORIGIN));
        allowedScriptOrigin = new JComboBox(origins);
        JLabel resourceOriginLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_ALLOWED_RESOURCE_ORIGIN));
        allowedResourceOrigin = new JComboBox(origins);

        p.add(enforceSecureScripting,   1, 0, 1, 1, WEST, NONE, 1, 0);
        p.add(grantScript,              0, 1, 1, 1, EAST, NONE, 1, 0);
        p.add(grantScriptFileAccess,    1, 1, 1, 1, WEST, NONE, 1, 0);
        p.add(grantScriptNetworkAccess, 1, 2, 1, 1, WEST, NONE, 1, 0);
        p.add(loadScripts,              0, 3, 1, 1, EAST, NONE, 1, 0);
        p.add(loadJava,                 1, 3, 1, 1, WEST, NONE, 1, 0);
        p.add(loadEcmascript,           1, 4, 1, 1, WEST, NONE, 1, 0);
        p.add(scriptOriginLabel,        0, 5, 1, 1, EAST, NONE, 1, 0);
        p.add(allowedScriptOrigin,      1, 5, 1, 1, WEST, NONE, 1, 0);
        p.add(resourceOriginLabel,      0, 6, 1, 1, EAST, NONE, 1, 0);
        p.add(allowedResourceOrigin,    1, 6, 1, 1, WEST, NONE, 1, 0);

        return p;
    }

    /**
     * Builds the Language panel.
     */
    protected JPanel buildLanguagePanel() {
        JPanel p = new JPanel();
        p.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));
        languagePanel = new LanguageDialog.Panel();
        languagePanel.setBorder(BorderFactory.createEmptyBorder());
        Color c = UIManager.getColor("Window.background");
        languagePanel.getComponent(0).setBackground(c);
        languagePanel.getComponent(1).setBackground(c);
        p.add(languagePanel);
        return p;
    }

    /**
     * Builds the Stylesheet panel.
     */
    protected JPanel buildStylesheetPanel() {
        JGridBagPanel.InsetsManager im = new JGridBagPanel.InsetsManager() {
            protected Insets i1 = new Insets(5, 5, 0, 0);
            protected Insets i2 = new Insets(5, 0, 0, 0);
            protected Insets i3 = new Insets(0, 5, 0, 0);
            protected Insets i4 = new Insets(0, 0, 0, 0);

            public Insets getInsets(int x, int y) {
                if (y >= 1 && y <= 5) {
                    return x == 0 ? i2 : i1;
                }
                return x == 0 ? i4 : i3;
            }
        };

        JGridBagPanel p = new JGridBagPanel(im);
        p.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));

        userStylesheetEnabled = new JCheckBox(Resources.getString(PREFERENCE_KEY_LABEL_ENABLE_USER_STYLESHEET));
        userStylesheetEnabled.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                boolean b = userStylesheetEnabled.isSelected();
                userStylesheetLabel.setEnabled(b);
                userStylesheet.setEnabled(b);
                userStylesheetBrowse.setEnabled(b);
            }
        });

        userStylesheetLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_USER_STYLESHEET));
        userStylesheet = new JTextField();
        userStylesheetBrowse = new JButton(Resources.getString(PREFERENCE_KEY_LABEL_BROWSE));
        userStylesheetBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File f = null;
                if (Platform.isOSX) {
                    FileDialog fileDialog =
                        new FileDialog
                            ((Frame) getOwner(),
                             Resources.getString(PREFERENCE_KEY_BROWSE_TITLE));
                    fileDialog.setVisible(true);
                    String filename = fileDialog.getFile();
                    if (filename != null) {
                        String dirname = fileDialog.getDirectory();
                        f = new File(dirname, filename);
                    }
                } else {
                    JFileChooser fileChooser = new JFileChooser(new File("."));
                    fileChooser.setDialogTitle
                        (Resources.getString(PREFERENCE_KEY_BROWSE_TITLE));
                    fileChooser.setFileHidingEnabled(false);

                    int choice =
                    fileChooser.showOpenDialog(PreferenceDialog.this);
                    if (choice == JFileChooser.APPROVE_OPTION) {
                        f = fileChooser.getSelectedFile();
                    }
                }
                if (f != null) {
                    try {
                        userStylesheet.setText(f.getCanonicalPath());
                    } catch (IOException ex) {
                    }
                }
            }
        });

        JLabel mediaLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_CSS_MEDIA_TYPES));
        mediaLabel.setVerticalAlignment(SwingConstants.TOP);
        mediaList = new JList();
        mediaList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        mediaList.setModel(mediaListModel);
        mediaList.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                updateMediaListButtons();
            }
        });
        mediaListModel.addListDataListener(new ListDataListener() {
            public void contentsChanged(ListDataEvent e) {
                updateMediaListButtons();
            }
            public void intervalAdded(ListDataEvent e) {
                updateMediaListButtons();
            }
            public void intervalRemoved(ListDataEvent e) {
                updateMediaListButtons();
            }
        });
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBorder(BorderFactory.createLoweredBevelBorder());
        scrollPane.getViewport().add(mediaList);

        JButton addButton = new JButton(Resources.getString(PREFERENCE_KEY_LABEL_ADD));
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CSSMediaPanel.AddMediumDialog dialog =
                    new CSSMediaPanel.AddMediumDialog(PreferenceDialog.this);
                dialog.pack();
                dialog.setVisible(true);

                if (dialog.getReturnCode() ==
                            CSSMediaPanel.AddMediumDialog.CANCEL_OPTION
                        || dialog.getMedium() == null) {
                    return;
                }

                String medium = dialog.getMedium().trim();
                if (medium.length() == 0 || mediaListModel.contains(medium)) {
                    return;
                }

                for (int i = 0;
                        i < mediaListModel.size() && medium != null;
                        ++i) {
                    String s = (String) mediaListModel.getElementAt(i);
                    int c = medium.compareTo(s);
                    if (c == 0) {
                        medium = null;
                    } else if (c < 0) {
                        mediaListModel.insertElementAt(medium, i);
                        medium = null;
                    }
                }
                if (medium != null) {
                    mediaListModel.addElement(medium);
                }
            }
        });

        mediaListRemoveButton = new JButton(Resources.getString(PREFERENCE_KEY_LABEL_REMOVE));
        mediaListRemoveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int index = mediaList.getSelectedIndex();
                mediaList.clearSelection();
                if (index >= 0) {
                    mediaListModel.removeElementAt(index);
                }
            }
        });

        mediaListClearButton = new JButton(Resources.getString(PREFERENCE_KEY_LABEL_CLEAR));
        mediaListClearButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mediaList.clearSelection();
                mediaListModel.removeAllElements();
            }
        });

        p.add(userStylesheetEnabled, 1, 0, 2, 1, WEST, NONE, 0, 0);
        p.add(userStylesheetLabel,   0, 1, 1, 1, EAST, NONE, 0, 0);
        p.add(userStylesheet,        1, 1, 1, 1, WEST, HORIZONTAL, 1, 0);
        p.add(userStylesheetBrowse,  2, 1, 1, 1, WEST, HORIZONTAL, 0, 0);
        p.add(mediaLabel,            0, 2, 1, 1, EAST, VERTICAL, 0, 0);
        p.add(scrollPane,            1, 2, 1, 4, WEST, BOTH, 1, 1);
        p.add(new JPanel(),          2, 2, 1, 1, WEST, BOTH, 0, 1);
        p.add(addButton,             2, 3, 1, 1, SOUTHWEST, HORIZONTAL, 0, 0);
        p.add(mediaListRemoveButton, 2, 4, 1, 1, SOUTHWEST, HORIZONTAL, 0, 0);
        p.add(mediaListClearButton,  2, 5, 1, 1, SOUTHWEST, HORIZONTAL, 0, 0);

        return p;
    }

    /**
     * Updates the disabled state of the buttons next to the media type list.
     */
    protected void updateMediaListButtons() {
        mediaListRemoveButton.setEnabled(!mediaList.isSelectionEmpty());
        mediaListClearButton.setEnabled(!mediaListModel.isEmpty());
    }

    /**
     * Builds the Network panel.
     */
    protected JPanel buildNetworkPanel() {
        JGridBagPanel p = new JGridBagPanel();
        p.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));

        JLabel proxyLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_HTTP_PROXY));
        JLabel hostLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_HOST));
        JLabel portLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_PORT));
        JLabel colonLabel = new JLabel(Resources.getString(PREFERENCE_KEY_LABEL_COLON));
        Font f = hostLabel.getFont();
        float size = f.getSize2D() * 0.85f;
        f = f.deriveFont(size);
        hostLabel.setFont(f);
        portLabel.setFont(f);
        host = new JTextField();
        host.setPreferredSize(new Dimension(200, 20));
        port = new JTextField();
        port.setPreferredSize(new Dimension(40, 20));

        p.add(proxyLabel, 0, 0, 1, 1, EAST, NONE, 0, 0);
        p.add(host,       1, 0, 1, 1, WEST, HORIZONTAL, 0, 0);
        p.add(colonLabel, 2, 0, 1, 1, WEST, NONE, 0, 0);
        p.add(port,       3, 0, 1, 1, WEST, HORIZONTAL, 0, 0);
        p.add(hostLabel,  1, 1, 1, 1, WEST, NONE, 0, 0);
        p.add(portLabel,  3, 1, 1, 1, WEST, NONE, 0, 0);

        return p;
    }

    /**
     * Shows the dialog.
     */
    public int showDialog() {
        if (Platform.isOSX) {
            // No OK/Cancel buttons in OS X, so always save the options.
            returnCode = OK_OPTION;
        } else {
            // Default to Cancel on other platforms, if the window is closed
            // without clicking one of the buttons.
            returnCode = CANCEL_OPTION;
        }
        pack();
        setVisible(true);
        return returnCode;
    }

    /**
     * A paged panel for configuration windows.
     */
    protected class JConfigurationPanel extends JPanel {

        /**
         * The toolbar that allows selection between the pages.
         */
        protected JToolBar toolbar;

        /**
         * The panel that holds the configuration pages.
         */
        protected JPanel panel;

        /**
         * The layout manager for the configuration pages.
         */
        protected CardLayout layout;

        /**
         * The button group for the configuration page buttons.
         */
        protected ButtonGroup group;

        /**
         * The currently selected page.
         */
        protected int page = -1;

        /**
         * Creates a new JConfigurationPanel.
         */
        public JConfigurationPanel() {
            toolbar = new JToolBar();
            toolbar.setFloatable(false);
            toolbar.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
            toolbar.add(new JToolBar.Separator(new Dimension(8, 8)));
            if (Platform.isOSX || isMetalSteel()) {
                toolbar.setBackground(new Color(0xf8, 0xf8, 0xf8));
            }
            toolbar.setOpaque(true);
            panel = new JPanel();
            layout = Platform.isOSX ? new ResizingCardLayout() : new CardLayout();
            group = new ButtonGroup();
            setLayout(new BorderLayout());
            panel.setLayout(layout);
            add(toolbar, BorderLayout.NORTH);
            add(panel);
        }

        /**
         * Adds a panel to this configuration panel.
         * @param text the text to use on the toolbar button
         * @param icon the icon to use on the toolbar button
         * @param icon2 the icon to use on the toolbar button when the mouse
         *              button is held down
         * @param p the configuration panel page
         */
        public void addPanel(String text, Icon icon, Icon icon2, JPanel p) {
            JToggleButton button = new JToggleButton(text, icon);
            button.setVerticalTextPosition(AbstractButton.BOTTOM);
            button.setHorizontalTextPosition(AbstractButton.CENTER);
            button.setContentAreaFilled(false);
            try {
                // JDK 1.4+
                // button.setIconTextGap(0);
                AbstractButton.class.getMethod
                    ("setIconTextGap", new Class[] { Integer.TYPE })
                    .invoke(button, new Object[] { new Integer(0) });
            } catch (Exception ex) {
            }
            button.setPressedIcon(icon2);
            group.add(button);
            toolbar.add(button);
            toolbar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray));
            button.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    JToggleButton b = (JToggleButton) e.getSource();
                    switch (e.getStateChange()) {
                        case ItemEvent.SELECTED:
                            select(b);
                            break;
                        case ItemEvent.DESELECTED:
                            unselect(b);
                            break;
                    }
                }
            });
            if (panel.getComponentCount() == 0) {
                button.setSelected(true);
                page = 0;
            } else {
                unselect(button);
            }
            panel.add(p, text.intern());
        }

        /**
         * Returns the index of the given configuration page.
         */
        protected int getComponentIndex(Component c) {
            Container p = c.getParent();
            int count = p.getComponentCount();
            for (int i = 0; i < count; i++) {
                if (p.getComponent(i) == c) {
                    return i;
                }
            }
            return -1;
        }

        /**
         * Updates the style of the given button to indicate that it is
         * selected.
         */
        protected void select(JToggleButton b) {
            b.setOpaque(true);
            b.setBackground
                (Platform.isOSX ? new Color(0xd8, 0xd8, 0xd8)
                       : UIManager.getColor("List.selectionBackground"));
            b.setForeground(UIManager.getColor("List.selectionForeground"));
            b.setBorder(BorderFactory.createCompoundBorder
                            (BorderFactory.createMatteBorder
                                 (0, 1, 0, 1, new Color(160, 160, 160)),
                             BorderFactory.createEmptyBorder(4, 3, 4, 3)));
            layout.show(panel, b.getText().intern());
            page = getComponentIndex(b) - 1;
            if (Platform.isOSX) {
                PreferenceDialog.this.setTitle(b.getText());
            }
            PreferenceDialog.this.pack();
            panel.grabFocus();
        }

        /**
         * Updates the style of the given button to indicate that it is
         * unselected.
         */
        protected void unselect(JToggleButton b) {
            b.setOpaque(false);
            b.setBackground(null);
            b.setForeground(UIManager.getColor("Button.foreground"));
            b.setBorder(BorderFactory.createEmptyBorder(5, 4, 5, 4));
        }

        /**
         * A CardLayout that returns a preferred height based on the currently
         * displayed component.
         */
        protected class ResizingCardLayout extends CardLayout {

            /**
             * Creates a new ResizingCardLayout.
             */
            public ResizingCardLayout() {
                super(0, 0);
            }

            public Dimension preferredLayoutSize(Container parent) {
                Dimension d = super.preferredLayoutSize(parent);
                if (page != -1) {
                    Dimension cur = panel.getComponent(page).getPreferredSize();
                    d = new Dimension((int) d.getWidth(),
                                      (int) cur.getHeight());
                }
                return d;
            }
        }
    }
}


text:
Algorithms
----------

  * **Algorithm:** a sequence of unambiguous instructions for solving a problem
                   in a finite amount of time
  * **Computational complexity:** how economical an algorithm is with *time and
                                  space*
  * **Time complexity:** indicates how fast an algorithm runs
  * **Space complexity:** indicates how much memory an algorithm needs

Things that can impact algorithm run time:

  * Input size (number of inputs)
  * Data type (e.g. integers vs. strings)

In many algorithms, certain inputs can make the algorithm take very long to
return, maybe have to check each individual input value, while others can be
almost instant. The former we call **worst-case complexity**, and the latter
**best-case complexity**. Averaging all the times for each possible input gives
us the **average-case complexity**.

  * **Complexity of a problem:** the *worst-case complexity* of the most
                                 efficient algorithm which solves the problem

When considering the complexity of a problem, we always use the worst-case
value.

### Measuring time

**Basic operation:** the operation in an algorithm contributing the most to
                     total running time

Algorithms **aren't measured in terms of time**, since that would be entirely
dependent on the host computer's speed. Instead, we look at the *number of
operations*. However, this can be demanding to do.

It's sufficient to identify just the operation that contributes most to the
running time: the **basic operation**.

### Order of growth

**Order of growth:** what factor execution time increases when the size of the
                     input is increased

We shouldn't need to know any more, but the book goes into some simple algebra,
proving why doubling the input size of the *natural numbers sum algorithm*
quadruples the execution time. The algorithm is `(n/2)(n + 1)`, so the basic
operation is `(n/2)^2`. We can find the factor change by doing
`time(2n)/time(n)`, and you'll get a `(2n)^2/(n)^2` -> bla bla --> `4/1`.

In the proof, the factor `1/2` was cancelled out. For that reason, they are
ignored in the order of growth. So in this case, the order of growth is
*quadratic*: this is denoted by **O(n^(2))**.

### Big O notation

  * **O(g):** *"big O of g"*, represents the class of functions that grow no
              faster than g
  * **Order of complexity:** the big O complexity of a problem

e.g. an algorithm that grows at rate n^2 cannot belong to the class O(n),
because it grows faster than that.

#### Orders of complexity rankings

**EXAM QUESTION:** You could be asked to rank some given algorithms in terms of
their complexity. Here's the order they go in from least complex to most:

  * O(n^(0)) *{= O(0)}*
  * O(log n)
  * O(n) *(linear time)*
  * O(n log n)
  * O(n^(2)) *(polynomial time)*
  * O(n^(3))
  * ...
  * O(2^(n)) *(exponential time)*
  * O(3^(n))
  * ...
  * O(n!) *(factorial time)*

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web.Mvc;
using MvcRouteTester.Common;

namespace MvcRouteTester.Fluent
{
	public class ExpressionReader
	{
		public RouteValues Read<TController>(Expression<Func<TController, object>> action)
		{
			return Read(typeof(TController), UnwrapAction(action));
		}

		public RouteValues Read<TController>(Expression<Func<TController, Task<ActionResult>>> action)
		{
			return Read(typeof(TController), UnwrapAction(action));
		}

        public RouteValues Read<TController>(Expression<Func<TController, Task<JsonResult>>> action)
        {
            return Read(typeof(TController), UnwrapAction(action));
        }

		public RouteValues Read<TController>(Expression<Func<TController, ActionResult>> action)
		{
			return Read(typeof(TController), UnwrapAction(action));
		}

		public RouteValues Read<TController>(Expression<Action<TController>> action)
		{
			return Read(typeof(TController), UnwrapAction(action));
		}

		private static MethodCallExpression UnwrapAction<TController>(Expression<Action<TController>> action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}

			return UnwrapExpression(action.Body);
		}

		private static MethodCallExpression UnwrapAction<TController, TResult>(Expression<Func<TController, TResult>> action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}

			return UnwrapExpression(action.Body);
		}

		private static MethodCallExpression UnwrapExpression(Expression expression)
		{
			var methodCallExpression = expression as MethodCallExpression;
			if (methodCallExpression != null)
			{
				return methodCallExpression;
			}

			var unaryExpression = expression as UnaryExpression;
			if (unaryExpression != null)
			{
				return UnwrapExpression(unaryExpression.Operand);
			}

			throw new ApplicationException("No way to unwrap a " + expression.GetType().FullName);
		}

		private RouteValues Read(Type controllerType, MethodCallExpression methodCall)
		{
			var values = new RouteValues();
			values.Controller = ControllerName(controllerType);
			values.Action = ActionName(methodCall);
			values.Area = AreaName(controllerType);

			values.AddRange(ReadParameters(methodCall));

			return values;
		}

		private string ControllerName(Type controllertype)
		{
			const int SuffixLength = 10;
			var controllerName = controllertype.Name;
			if ((controllerName.Length > SuffixLength) && controllerName.EndsWith("Controller"))
			{
				controllerName = controllerName.Substring(0, controllerName.Length - SuffixLength);
			}

			return controllerName;
		}

		private string AreaName(Type controllerType)
		{
			var routeAreaAttributes = controllerType.GetCustomAttributes(typeof(RouteAreaAttribute), true);
			if (routeAreaAttributes.Length > 0)
			{
				var routeArea = (RouteAreaAttribute)(routeAreaAttributes[0]);
				return routeArea.AreaName;
			}

			var nameSpace = controllerType.Namespace;
			if (nameSpace == null)
			{
				return string.Empty;
			}

			const string AreasStartSearchString = "Areas.";
			var areasIndexOf = nameSpace.IndexOf(AreasStartSearchString, StringComparison.Ordinal);
			if (areasIndexOf < 0)
			{
				return string.Empty;
			}

			var areaStart = areasIndexOf + AreasStartSearchString.Length;
			var areaString = nameSpace.Substring(areaStart);
			if (areaString.Contains("."))
			{
				areaString = areaString.Remove(areaString.IndexOf(".", StringComparison.Ordinal));
			}
			return areaString;
		}

		private string ActionName(MethodCallExpression methodCall)
		{
			// Look for System.Web.Mvc ActionName attribute
			var attributes = methodCall.Method.GetCustomAttributes(typeof(System.Web.Mvc.ActionNameAttribute), true);

			if (attributes.Length > 0)
			{
				return ((ActionNameAttribute)attributes[0]).Name;
			}

			// Look for System.Web.Http ActionName attribute
			attributes = methodCall.Method.GetCustomAttributes(typeof(System.Web.Http.ActionNameAttribute), true);

			if (attributes.Length > 0)
			{
				return ((System.Web.Http.ActionNameAttribute)attributes[0]).Name;
			}

			// Otherwise, just use the method name
			return methodCall.Method.Name;
		}

		private IList<RouteValue> ReadParameters(MethodCallExpression methodCall)
		{
			var values = new List<RouteValue>();

			var attributeRecogniser = new AttributeRecogniser();
			var propertyReader = new PropertyReader();

			var parameters = methodCall.Method.GetParameters();
			var arguments = methodCall.Arguments;

			for (int i = 0; i < parameters.Length; i++)
			{
				var param = parameters[i];
				var expectedValue = GetExpectedValue(arguments[i]);
				var isFromBody = attributeRecogniser.IsFromBody(param);
				var routeValueOrigin = isFromBody ? RouteValueOrigin.Body : RouteValueOrigin.Unknown;
				if (expectedValue != null || !isFromBody)
				{
					if (propertyReader.IsSimpleType(param.ParameterType))
					{
						var resultValue = new RouteValue(param.Name, expectedValue, routeValueOrigin);
						values.Add(resultValue);
					}
					else
					{
						var objectFieldValues = propertyReader.PropertiesList(expectedValue, routeValueOrigin)
							.Where(x => x.Value != null);
						values.AddRange(objectFieldValues);
					}
				}
			}

			return values;
		}

		private static object GetExpectedValue(Expression argumentExpression)
		{
			switch (argumentExpression.NodeType)
			{
				case ExpressionType.Constant:
					return ((ConstantExpression)argumentExpression).Value;

				case ExpressionType.MemberAccess:
				case ExpressionType.Convert:
				case ExpressionType.MemberInit:
					return Expression.Lambda(argumentExpression).Compile().DynamicInvoke();

				default:
					return null;
			}
		}
	}
}


text:
require 'spec_helper'
require 'application_helper'
require 'console_helper'
require 'logging_helper'

shared_context 'component_helper' do
  include_context 'application_helper'
  include_context 'console_helper'
  include_context 'logging_helper'

  let(:component) { described_class.new context }

  let(:context) do |example|
    { app_dir:        app_dir,
      java_home:      example.metadata[:java_home],
      java_opts:      example.metadata[:java_opts],
      common_paths:   example.metadata[:common_paths],
      license_ids:    example.metadata[:license_ids],
      configuration:  example.metadata[:configuration],
      jvm_type:       example.metadata[:jvm_type],
      vcap_application: example.metadata[:vcap_application_context],
      vcap_services:  example.metadata[:vcap_services_context] }
  end

  let(:uri) { 'test-uri' }
  let(:version) { '0.0.0' }

end


text:
import logging
from docpie.error import DocpieError, UnknownOptionExit, AmbiguousPrefixExit

logger = logging.getLogger('docpie.tokens')

class Token(list):
    _brackets = {'(': ')', '[': ']'}  # , '{': '}', '<': '>'}

    def next(self):
        return self.pop(0) if self else None

    def current(self):
        return self[0] if self else None

    def check_ellipsis_and_drop(self):
        if self and self[0] == '...':
            self.pop(0)
            return True
        return False

    def till_end_bracket(self, start):
        # start bracket should not in self
        end = self._brackets[start]
        count = dict.fromkeys(self._brackets, 0)
        count[start] = 1
        element = []
        while self:
            this = self.pop(0)
            for each_start, each_end in self._brackets.items():
                count[each_start] += (this == each_start)
                count[each_start] -= (this == each_end)
            if this == end and all(x == 0 for x in count.values()):
                if any(x < 0 for x in count.values()):
                    raise DocpieError("brackets not in pair")
                return element
            element.append(this)
        else:
            raise DocpieError("brackets not in pair")

class Argv(list):

    def __init__(self, argv, auto2dashes,
                 stdopt, attachopt, attachvalue, known={}):

        super(Argv, self).__init__(argv)
        self.auto_dashes = auto2dashes
        self.dashes = False
        # when this is on, only --option can try to match.
        self.option_only = False
        self.stdopt = stdopt
        self.attachopt = attachopt
        self.attachvalue = attachvalue
        self.error = None
        self.known = known

    def formal(self, options_first):
        names = self.known
        result = []
        skip = 0
        for index, each in enumerate(self):
            if skip:
                skip -= 1
                continue
            # first command/argument
            if (options_first and
                    (each in ('-', '--') or not each.startswith('-'))):
                result.extend((each, '--'))  # add '--' after it
                result.extend(self[index + 1:])
                break

            if each == '--' and self.auto_dashes:
                result.extend(self[index:])
                break

            if each == '-':
                result.append(each)
                continue

            expect_args = 0

            # this won't work when -abc, and it actually means -a -b -c,
            # but -b, -c is not defined
            if each.startswith('-') and not each.startswith('--'):
                if self.stdopt:
                    this_opt = each[:2]
                else:
                    this_opt = each

                if this_opt not in names:
                    self.error = UnknownOptionExit(
                        'Unknown option: %s.' % this_opt,
                        option=this_opt,
                        inside=each,
                    )
                    result.extend(self[index:])
                    break

                result.append(each)

                expect_args = names[this_opt]
                if this_opt != each:
                    expect_args = 0

            elif not each.startswith('--'):
                result.append(each)
                continue
            else:
                option, equal, value = each.partition('=')
                if option in names:
                    result.append(each)
                    if equal:
                        expect_args = 0
                    else:
                        expect_args = names[option]
                else:
                    possible = list(
                        filter(lambda x: x.startswith(option), names))
                    if not possible:
                        self.error = UnknownOptionExit(
                            'Unknown option: %s.' % option,
                            option=option,
                            inside=each,
                        )
                        result.extend(self[index:])
                        break
                        # Don't raise. It may be --help
                        # and the developer didn't announce in
                        # either Usage or Options
                        # logger.info('not found this argv %s', each)
                        # result.append(each)
                    elif len(possible) == 1:
                        replace = ''.join((possible[0], equal, value))
                        logger.debug('expand %s -> %s', each, replace)
                        result.append(replace)
                    else:
                        self.error = AmbiguousPrefixExit(
                            '%s is not a unique prefix: %s?' %
                            (option, ', '.join(possible)),
                            prefix=option,
                            ambiguous=possible
                        )
                        result.extend(self[index:])
                        break

            if expect_args:
                total_rest = self[index + 1:]
                if len(total_rest) < expect_args:
                    to_append = total_rest
                else:
                    to_append = total_rest[:expect_args]

                skip = len(to_append)
                result.extend(to_append)

        logger.debug('%s -> %s', self, result)
        self[:] = result
        return None

    def current(self, offset=0):
        return self[offset] if len(self) > offset else None

    def insert(self, index, object, from_=None):
        if self.auto_dashes and '--' in self:
            dashes_index = self.index('--')
        else:
            dashes_index = float('inf')

        fine = True
        if (object != '-' and
                object.startswith('-') and
                not object.startswith('--')):
            if self.stdopt:
                flag = object[:2]
            else:
                flag = object
            fine = (flag in self.known)
            logger.debug('%s has flag %s, is known: %s', object, flag, fine)

        if (index <= dashes_index and fine or
                index > dashes_index or
                fine):
            logger.debug('insert %s into %s at %s', object, self, index)
            return super(Argv, self).insert(index, object)

        logger.debug('%s not in %s', flag, self.known)
        # self.error = 'Unknown option: %s.' % flag
        raise UnknownOptionExit('Unknown option: %s.' % flag,
                                option=flag,
                                inside=from_ or flag)

    def break_for_option(self, names):
        auto_dashes = self.auto_dashes
        stdopt = self.stdopt
        attachvalue = self.attachvalue
        for index, option in enumerate(self):
            if option == '--' and auto_dashes:
                return None, None, 0, option
            for name in names:
                if option.startswith(name):
                    value = None
                    self.pop(index)
                    # `-flag=sth` -> `-flag =sth`
                    if not stdopt:
                        _, _, value = option.partition(name)
                        if not value:
                            value = None

                    # `-flag` -> `-f lag`
                    # `--flag=sth` -> `--flag sth`
                    # `--flag=` -> `--flag ""`
                    # `-f` -> `-f None`
                    # `--flag-ext` -> `--flag -ext` -> not matched
                    # `--flag` -> `--flag None`
                    elif attachvalue:
                        _, _, value = option.partition(name)
                        if name.startswith('--'):
                            if value.startswith('='):
                                value = value[1:]
                            elif value:
                                return None, None, 0, None
                            else:
                                value = None
                        elif not value:
                            value = None

                    logger.debug('find %s, attached %s, index %s of %s',
                                 name, value, index, self)
                    return name, value, index, option

        return None, None, 0, None

    def next(self, offset=0):
        return self.pop(offset) if len(self) > offset else None

    def check_dash(self):
        if not self:
            return
        if self[0] == '--':
            self.dashes = True

    def clone(self):
        result = Argv(self, self.auto_dashes,
                      self.stdopt, self.attachopt, self.attachvalue)
        result.dashes = self.dashes
        result.option_only = self.option_only
        result.error = self.error
        result.known = self.known
        return result

    def restore(self, ins):
        self[:] = ins
        self.dashes = ins.dashes
        self.option_only = ins.option_only
        self.error = ins.error

    def status(self):
        # return len(self)
        return list(self)

    def dump_value(self):
        return list(self), self.dashes, self.option_only

    def load_value(self, value):
        self[:], self.dashes, self.option_only = value


text:
// for uGUI(from 4.6)
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5)

using System; // require keep for Windows Universal App
using UnityEngine;
using UnityEngine.EventSystems;

namespace UniRx.Triggers
{
    [DisallowMultipleComponent]
    public class ObservableBeginDragTrigger : ObservableTriggerBase, IEventSystemHandler, IBeginDragHandler
    {
        Subject<PointerEventData> onBeginDrag;

        void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
        {
            if (onBeginDrag != null) onBeginDrag.OnNext(eventData);
        }

        public IObservable<PointerEventData> OnBeginDragAsObservable()
        {
            return onBeginDrag ?? (onBeginDrag = new Subject<PointerEventData>());
        }

        protected override void RaiseOnCompletedOnDestroy()
        {
            if (onBeginDrag != null)
            {
                onBeginDrag.OnCompleted();
            }
        }
    }
}

#endif


text:
package org.gbif.nub.lookup;

import org.gbif.nub.utils.Constants;

import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.analysis.core.LowerCaseFilter;

public class ScientificNameAnalyzer extends Analyzer {

  public static final int BUFFER_SIZE = 1024;

  public ScientificNameAnalyzer() {
  }

  @Override
  protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
    KeywordTokenizer source = new KeywordTokenizer(reader, BUFFER_SIZE);

    TokenStream result = new LowerCaseFilter(Constants.LUCENE_VERSION, source);
    result = new ScientificNameSoundAlikeFilter(result);

    return new TokenStreamComponents(source, result);
  }

}


text:
package storage

import (
	"errors"
	"workshop/blog"
)

// Add is a method to add new blog entries into storage
func (storage *Storage) Add(entry blog.Entry) int {

	storage.items = append(storage.items, entry)

	return len(storage.items)
}

// GetLength is a method to get storage size
func (storage *Storage) GetLength() int {

	return len(storage.items)
}

// Update is a method to update blog entry
func (storage *Storage) Update(id int, entry blog.Entry) (bool, error) {

	if len(storage.items) == 0 || len(storage.items) < id || id == 0 {
		return false, errors.New("No record found")
	}

	storage.items[id-1] = entry

	return true, nil
}

// GetByID is a method which will return item by it's ID
func (storage *Storage) GetByID(id int) (blog.Entry, error) {

	if len(storage.items) == 0 || len(storage.items) < id || id == 0 {

		return blog.Entry{}, errors.New("No record found")
	}

	return storage.items[id-1], nil
}

// GetAll is a method which will return all storage items
func (storage *Storage) GetAll() []blog.Entry {

	return storage.items
}


text:
#include "CAPI_HSWDisplay.h"
#include "CAPI_HMDState.h"
#include "../Kernel/OVR_Log.h"
#include "../Kernel/OVR_String.h"
#include "Textures/healthAndSafety.tga.h" // TGA file as a C array declaration.
#include <stdlib.h>

//-------------------------------------------------------------------------------------
// ***** HSWDISPLAY_DEBUGGING
//
// Defined as 0 or 1. Enables debugging features of this module.

#if !defined(HSWDISPLAY_DEBUGGING)
    #if defined(AUTHOR_PPEDRIANA)
        #define HSWDISPLAY_DEBUGGING 1
    #else
        #define HSWDISPLAY_DEBUGGING 0
    #endif
#endif

#if HSWDISPLAY_DEBUGGING
    OVR_DISABLE_ALL_MSVC_WARNINGS()
    #include <winsock2.h>
    #include <Windows.h>
    OVR_RESTORE_ALL_MSVC_WARNINGS()
#endif

OVR_DISABLE_MSVC_WARNING(4996) // "This function or variable may be unsafe..."

//-------------------------------------------------------------------------------------
// ***** HSWDISPLAY_DEFAULT_ENABLED
//
// Defined as 0 or 1. 1 is default. If 0 then by default HSWDisplay is disabled.
// Developers can set it to 0 to disable HSW display.
//
#define HSWDISPLAY_DEFAULT_ENABLED 0

#if !defined(HSWDISPLAY_DEFAULT_ENABLED)
    #define HSWDISPLAY_DEFAULT_ENABLED 1
#endif

//-------------------------------------------------------------------------------------
// ***** Experimental C API functions
//

extern "C"
{
    OVR_EXPORT void ovrhmd_EnableHSWDisplaySDKRender(ovrHmd hmd, ovrBool enabled)
    {
        OVR::CAPI::HMDState* pHMDState = (OVR::CAPI::HMDState*)hmd->Handle;

	    if (pHMDState)
	    {
            OVR::CAPI::HSWDisplay* pHSWDisplay = pHMDState->pHSWDisplay;

            if(pHSWDisplay)
                pHSWDisplay->EnableRender((enabled == 0) ? false : true);
        }
    }
}

//-------------------------------------------------------------------------------------
// ***** HSWDisplay implementation
//

namespace OVR { namespace CAPI {

static const time_t HSWDisplayTimeNever = (time_t)0; // Constant which denotes the time of "never", as in the display has never been shown yet.

#define HSWDISPLAY_POLL_INTERVAL            0.400 // Seconds between polling for whether the display should be shown.
#define OVR_KEY_HSWDISPLAYLASTDISPLAYEDTIME "HASWLastDisplayedTime"

#if defined(OVR_BUILD_DEBUG)
    #define HSWDISPLAY_FIRST_DISMISSAL_TIME    4     // Earliest time in seconds until the user can dismiss the display.
    #define HSWDISPLAY_REGULAR_DISMISSAL_TIME  2
#else
    #define HSWDISPLAY_FIRST_DISMISSAL_TIME   15
    #define HSWDISPLAY_REGULAR_DISMISSAL_TIME  6
#endif

HSWDisplay::HSWDisplay(ovrRenderAPIType renderAPIType, ovrHmd hmd, const HMDRenderState& hmdRenderState)
  : Enabled(HSWDISPLAY_DEFAULT_ENABLED ? true : false),
    Displayed(false),
    SDKRendered(false),
    DismissRequested(false),
    RenderEnabled(true),
    UnloadGraphicsRequested(false),
    StartTime(0.0),
    DismissibleTime(0.0),
    LastPollTime(0.0),
    HMD(hmd),
    HMDMounted(false),
    HMDNewlyMounted(false),
    RenderAPIType(renderAPIType),
    RenderState(hmdRenderState),
    LastProfileName(),
    LastHSWTime(0)
{
}

HSWDisplay::~HSWDisplay()
{
    // To consider: assert that we are already shut down.
    HSWDisplay::Shutdown();
}

void HSWDisplay::Enable(bool enable)
{
    Enabled = enable;

#if HSWDISPLAY_DEFAULT_ENABLED == 0
    Enabled = false;
#endif

    if(!enable && Displayed) // If it's visible but should not be...
        Dismiss();
}

void HSWDisplay::EnableRender(bool enable)
{
    RenderEnabled = enable;
}

void HSWDisplay::Display()
{
    HSWDISPLAY_LOG(("[HSWDisplay] Display()"));

    DisplayInternal();

    HMDNewlyMounted = false;
    Displayed = true;
    SDKRendered = RenderEnabled;
    StartTime = ovr_GetTimeInSeconds();

    const time_t lastDisplayedTime = HSWDisplay::GetCurrentProfileLastHSWTime();
    DismissibleTime = StartTime + ((lastDisplayedTime == HSWDisplayTimeNever) ? HSWDISPLAY_FIRST_DISMISSAL_TIME : HSWDISPLAY_REGULAR_DISMISSAL_TIME);

    SetCurrentProfileLastHSWTime(time(NULL));
}

bool HSWDisplay::IsDisplayViewable() const
{
    // This function is called IsDisplayViewable, but currently it refers only to whether the
    // HMD is mounted on the user's head.

    return HMDMounted;
}

bool HSWDisplay::Dismiss()
{
    #if HSWDISPLAY_DEBUGGING && defined(OVR_OS_WIN32)
        if(GetKeyState(VK_SCROLL) & 0x0001) // If the scroll lock key is toggled on...
            return false;                   // Make it so that the display doesn't dismiss, so we can debug this.
    #endif

    // If dismissal is not requested yet, mark it as such.
    bool newlyRequested = false;

    if(!DismissRequested)
    {
        DismissRequested = true;
        newlyRequested = true;
    }

    // If displayed and time has elapsed, do the dismissal.
    OVR_ASSERT(DismissibleTime <= (ovr_GetTimeInSeconds() + HSWDISPLAY_FIRST_DISMISSAL_TIME)); // Make sure the dismissal time is sane.
    if (Displayed && (ovr_GetTimeInSeconds() >= DismissibleTime))
    {
        DismissInternal();
        Displayed = false;
        DismissRequested = false;
        SDKRendered = false;
        return true;
    }

    if(newlyRequested)
        { HSWDISPLAY_LOG(("[HSWDisplay] Dismiss(): Not permitted yet. Queued for timeout in %.1f seconds.", DismissibleTime - ovr_GetTimeInSeconds())); }

    return false; // Cannot dismiss yet.
}

bool HSWDisplay::TickState(ovrHSWDisplayState *hswDisplayState, bool graphicsContext)
{
    bool newlyDisplayed = false;
    const double currentTime = ovr_GetTimeInSeconds();

    // See if we need to be currently displayed. By design we automatically display but don't automatically dismiss.
    if (Displayed)
    {
        if (DismissRequested) // If dismiss was previously requested, see if it can be executed.
            Dismiss();

        if (Displayed) // If not already dismissed above...
        {
            // We currently have the debug behavior that we permit dismiss very soon after launch.
            #if defined(OVR_BUILD_DEBUG)
                if(currentTime >= (StartTime + 2))
                {
                    DismissibleTime = StartTime;
                    //Dismiss();
                }
            #endif
        }

        if (Displayed) // If not already dismissed above...
        {
            const ovrTrackingState ts = ((OVR::CAPI::HMDState*)HMD->Handle)->PredictedTrackingState(currentTime);

            if (ts.StatusFlags & ovrStatus_OrientationTracked) // If the Accelerometer data is valid...
            {
				const OVR::Vector3f v(ts.HeadPose.LinearAcceleration.x, ts.HeadPose.LinearAcceleration.y, ts.HeadPose.LinearAcceleration.z);

                const float minTapMagnitude = 350.0f; // Empirically determined by some testing.

                if (v.LengthSq() > minTapMagnitude)
                    Dismiss(); // This will do nothing if the display is not present.
            }
        }
    }
    else if (Enabled && (currentTime >= (LastPollTime + HSWDISPLAY_POLL_INTERVAL)))
    {
        LastPollTime = currentTime;

        // We need to display if any of the following are true:
        //     - The application is just started in Event Mode while the HMD is mounted (warning display would be viewable) and this app was not spawned from a launcher.
        //     - The current user has never seen the display yet while the HMD is mounted (warning display would be viewable).
        //     - The HMD is newly mounted (or the warning display is otherwise newly viewable).
        //     - The warning display hasn't shown in 24 hours (need to verify this as a requirement).
        // Event Mode refers to when the app is being run in a public demo event such as a trade show.

        OVR::CAPI::HMDState* pHMDState = (OVR::CAPI::HMDState*)HMD->Handle;

        if(pHMDState)
        {
            const time_t lastDisplayedTime = HSWDisplay::GetCurrentProfileLastHSWTime();

            // We currently unilaterally set HMDMounted to true because we don't yet have the ability to detect this. To do: Implement this when possible.
            const bool previouslyMounted = HMDMounted;
            HMDMounted = true;
            HMDNewlyMounted = (!previouslyMounted && HMDMounted); // We set this back to false in the Display function or if the HMD is unmounted before then.

            if((lastDisplayedTime == HSWDisplayTimeNever) || HMDNewlyMounted)
            {
                if(IsDisplayViewable()) // If the HMD is mounted and otherwise being viewed by the user...
                {
                    Display();
                    newlyDisplayed = true;
                }
            }
        }
    }
    else if(graphicsContext && UnloadGraphicsRequested)
    {
        UnloadGraphics();
        UnloadGraphicsRequested = false;
    }

    if(hswDisplayState)
        GetState(hswDisplayState);

    return newlyDisplayed;
}

void HSWDisplay::GetState(ovrHSWDisplayState *hswDisplayState) const
{
    // Return the state to the caller.
    OVR_ASSERT(hswDisplayState != NULL);
    if(hswDisplayState)
    {
        hswDisplayState->Displayed = Displayed;
        hswDisplayState->StartTime = StartTime;
        hswDisplayState->DismissibleTime = DismissibleTime;
    }
}

void HSWDisplay::Render(ovrEyeType eye, const ovrTexture* eyeTexture)
{
    SDKRendered = true;
    RenderInternal(eye, eyeTexture);
}

// Persist the HSW settings on the server, since it needs to be synchronized across all applications.
// Note that the profile manager singleton cannot be used for this task because it overwrites the global
// settings for which the rift config tool is supposed to be authoritative.  That also would step on the
// settings generated by other rift apps.  The server settings, however, are synchronized for all apps
// and so are appropriate for this task.
static String getHSWTimeKey(const char* userName)
{
    String keyName = "server:";
    keyName += OVR_KEY_HSWDISPLAYLASTDISPLAYEDTIME;
    keyName += ":";
    if (userName)
    {
        keyName += userName;
    }
    return keyName;
}

// Returns HSWDisplayTimeNever (0) if there is no profile or this is the first time we are seeing this profile.
time_t HSWDisplay::GetCurrentProfileLastHSWTime() const
{
    // We store the timeout value in HMDState's pProfile.
    HMDState* pHMDState = (HMDState*)HMD->Handle;

    if (pHMDState)
    {
        const char* profileName = pHMDState->pProfile ? pHMDState->pProfile->GetValue(OVR_KEY_USER) : NULL;

        if (profileName)
        {
            if (LastProfileName == profileName)
            {
                return LastHSWTime;
            }

            LastProfileName = profileName;
            String timeKey = getHSWTimeKey(profileName);
            int lastTime = pHMDState->getIntValue(timeKey.ToCStr(), (int)HSWDisplayTimeNever);

            LastHSWTime = lastTime;
            return lastTime;
        }
    }

    return HSWDisplayTimeNever;
}

void HSWDisplay::SetCurrentProfileLastHSWTime(time_t t)
{
    // The timeout value is stored in HMDState's pProfile.
    HMDState* pHMDState = (HMDState*)HMD->Handle;

    if (pHMDState)
    {
        const char* profileName = pHMDState->pProfile ? pHMDState->pProfile->GetValue(OVR_KEY_USER) : NULL;

        if (profileName)
        {
            LastProfileName = profileName;
            LastHSWTime = (int)t;

            String timeKey = getHSWTimeKey(profileName);
            pHMDState->setIntValue(timeKey.ToCStr(), (int)t);
        }
    }
}

// Generates an appropriate stereo ortho projection matrix.
void HSWDisplay::GetOrthoProjection(const HMDRenderState& RenderState, Matrix4f OrthoProjection[2])
{
    Matrix4f perspectiveProjection[2];
    perspectiveProjection[0] = ovrMatrix4f_Projection(RenderState.EyeRenderDesc[0].Fov, 0.01f, 10000.f, true);
    perspectiveProjection[1] = ovrMatrix4f_Projection(RenderState.EyeRenderDesc[1].Fov, 0.01f, 10000.f, true);

    const float    orthoDistance = HSWDISPLAY_DISTANCE; // This is meters from the camera (viewer) that we place the ortho plane.
    const Vector2f orthoScale0   = Vector2f(1.f) / Vector2f(RenderState.EyeRenderDesc[0].PixelsPerTanAngleAtCenter);
    const Vector2f orthoScale1   = Vector2f(1.f) / Vector2f(RenderState.EyeRenderDesc[1].PixelsPerTanAngleAtCenter);

    OrthoProjection[0] = ovrMatrix4f_OrthoSubProjection(perspectiveProjection[0], orthoScale0, orthoDistance, RenderState.EyeRenderDesc[0].HmdToEyeViewOffset.x);
    OrthoProjection[1] = ovrMatrix4f_OrthoSubProjection(perspectiveProjection[1], orthoScale1, orthoDistance, RenderState.EyeRenderDesc[1].HmdToEyeViewOffset.x);
}

const uint8_t* HSWDisplay::GetDefaultTexture(size_t& TextureSize)
{
    TextureSize = sizeof(healthAndSafety_tga);
    return healthAndSafety_tga;
}

}} // namespace OVR::CAPI

//-------------------------------------------------------------------------------------
// ***** HSWDisplay factory
//

#if defined (OVR_OS_WIN32)
    #define OVR_D3D_VERSION 9
    #include "D3D9/CAPI_D3D9_HSWDisplay.h"
    #undef  OVR_D3D_VERSION

    #define OVR_D3D_VERSION 10
    #include "D3D1X/CAPI_D3D10_HSWDisplay.h"
    #undef  OVR_D3D_VERSION

    #define OVR_D3D_VERSION 11
    #include "D3D1X/CAPI_D3D11_HSWDisplay.h"
    #undef  OVR_D3D_VERSION
#endif

#include "GL/CAPI_GL_HSWDisplay.h"

OVR::CAPI::HSWDisplay* OVR::CAPI::HSWDisplay::Factory(ovrRenderAPIType apiType, ovrHmd hmd, const OVR::CAPI::HMDRenderState& renderState)
{
    OVR::CAPI::HSWDisplay* pHSWDisplay = NULL;

    switch (apiType)
    {
        case ovrRenderAPI_None:
            pHSWDisplay = new OVR::CAPI::HSWDisplay(apiType, hmd, renderState);
            break;

        case ovrRenderAPI_OpenGL:
            pHSWDisplay = new OVR::CAPI::GL::HSWDisplay(apiType, hmd, renderState);
            break;

    #if defined(OVR_OS_WIN32)
        case ovrRenderAPI_D3D9:
            pHSWDisplay = new OVR::CAPI::D3D9::HSWDisplay(apiType, hmd, renderState);
            break;

        case ovrRenderAPI_D3D10:
            pHSWDisplay = new OVR::CAPI::D3D10::HSWDisplay(apiType, hmd, renderState);
            break;

        case ovrRenderAPI_D3D11:
            pHSWDisplay = new OVR::CAPI::D3D11::HSWDisplay(apiType, hmd, renderState);
            break;
    #else
        case ovrRenderAPI_D3D9:
        case ovrRenderAPI_D3D10:
        case ovrRenderAPI_D3D11: // Fall through
    #endif

        // Handle unsupported cases.
        case ovrRenderAPI_Android_GLES:
        case ovrRenderAPI_Count: // This is not actually a type.
        default:
            break;
    }

    return pHSWDisplay;
}


text:
import { DEFAULT_PREVIEWS_STATE } from '../state'
import { SPEC_LOOKUPS_SET } from '../action'
import { SPECS_PAGE_REQUEST } from '../action/home'

const initialState = { ...DEFAULT_PREVIEWS_STATE }

export default function previewReducer(state = initialState, action) {
  switch (action.type) {
    case SPECS_PAGE_REQUEST:
      const specId = action.payload
      let offset = 0
      const limit = 6

      if (specId) {
        let pageNumber = Number(specId)
        if (Number.isNaN(pageNumber)) {
          pageNumber = 0
        }
        offset = pageNumber * limit
      }

      return {
        ...state,
        limit,
        offset
      }
    case SPEC_LOOKUPS_SET:
      const previews = action.payload || []
      return {
        ...state,
        byId: previews.reduce(
          (memo, preview) => ({
            ...memo,
            [preview.id]: preview
          }),
          {}
        ),
        allIds: previews.map((preview) => preview.id)
      }
    default:
      return state
  }
}


text:
"use strict";
const vscode_debugadapter_1 = require('vscode-debugadapter');
let sendEvent;
function reportEvent(name, data) {
    // https://github.com/Microsoft/vscode-debugadapter-node/pull/77
    const event = new vscode_debugadapter_1.OutputEvent(name, 'telemetry');
    event.body.data = data;
    if (sendEvent)
        sendEvent(event);
}
exports.reportEvent = reportEvent;
function setupEventHandler(_sendEvent) {
    sendEvent = _sendEvent;
}
exports.setupEventHandler = setupEventHandler;

//# sourceMappingURL=telemetry.js.map


text:
require 'spec_helper'
require 'shared_examples_param_validation'

describe 'kafka::broker', type: :class do
  let :facts do
    {
      osfamily: 'Debian',
      os: { family: 'Debian' },
      operatingsystem: 'Ubuntu',
      operatingsystemrelease: '14.04',
      lsbdistcodename: 'trusty',
      architecture: 'amd64',
      service_provider: 'upstart'
    }
  end
  let :common_params do
    {
      config: {
        'zookeeper.connect' => 'localhost:2181'
      }
    }
  end

  let :params do
    common_params
  end

  it { is_expected.to contain_class('kafka::broker::install').that_comes_before('Class[kafka::broker::config]') }
  it { is_expected.to contain_class('kafka::broker::config').that_comes_before('Class[kafka::broker::service]') }
  it { is_expected.to contain_class('kafka::broker::service').that_comes_before('Class[kafka::broker]') }
  it { is_expected.to contain_class('kafka::broker') }

  context 'on Debian' do
    describe 'kafka::broker::install' do
      context 'defaults' do
        it { is_expected.to contain_class('kafka') }
      end
    end

    describe 'kafka::broker::config' do
      context 'defaults' do
        it { is_expected.to contain_file('/opt/kafka/config/server.properties') }
      end
    end

    describe 'kafka::broker::service' do
      context 'service_install false' do
        let :params do
          common_params.merge(service_install: false)
        end

        it { is_expected.not_to contain_file('/etc/init.d/kafka') }

        it { is_expected.not_to contain_service('kafka') }
      end
      context 'defaults' do
        it { is_expected.to contain_file('/etc/init.d/kafka') }

        it { is_expected.to contain_service('kafka') }
      end
    end
  end

  context 'on Centos' do
    let :facts do
      {
        osfamily: 'RedHat',
        os: { family: 'RedHat' },
        operatingsystem: 'CentOS',
        operatingsystemrelease: '7',
        operatingsystemmajrelease: '7',
        architecture: 'amd64',
        path: '/usr/local/sbin',
        service_provider: 'systemd'
      }
    end

    describe 'kafka::broker::install' do
      context 'defaults' do
        it { is_expected.to contain_class('kafka') }
      end
    end

    describe 'kafka::broker::config' do
      context 'defaults' do
        it { is_expected.to contain_file('/opt/kafka/config/server.properties') }
      end
    end

    describe 'kafka::broker::service' do
      context 'service_install false' do
        let :params do
          common_params.merge(service_install: false)
        end

        it { is_expected.not_to contain_file('/etc/systemd/system/kafka.service') }

        it { is_expected.not_to contain_service('kafka') }
      end

      context 'defaults' do
        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').that_notifies('Exec[systemctl-daemon-reload]') }
        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^After=network\.target syslog\.target$} }
        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^Wants=network\.target syslog\.target$} }
        it { is_expected.not_to contain_file('/etc/systemd/system/kafka.service').with_content %r{^LimitNOFILE=} }
        it { is_expected.not_to contain_file('/etc/systemd/system/kafka.service').with_content %r{^LimitCORE=} }

        it do
          is_expected.to contain_file('/etc/init.d/kafka').with(
            ensure: 'absent'
          )
        end

        it { is_expected.to contain_exec('systemctl-daemon-reload').that_comes_before('Service[kafka]') }

        it { is_expected.to contain_service('kafka') }
      end

      context 'limit_nofile set' do
        let :params do
          {
            limit_nofile: '65536'
          }
        end

        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^LimitNOFILE=65536$} }
      end

      context 'limit_core set' do
        let :params do
          {
            limit_core: 'infinity'
          }
        end

        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^LimitCORE=infinity$} }
      end

      context 'service_requires set' do
        let :params do
          {
            service_requires: ['dummy.target']
          }
        end

        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^After=dummy\.target$} }
        it { is_expected.to contain_file('/etc/systemd/system/kafka.service').with_content %r{^Wants=dummy\.target$} }
      end
    end
  end

  it_validates_parameter 'mirror_url'
end


text:
package webworks.io;

import java.util.Hashtable;
import java.util.Vector;

import net.rim.device.api.script.Scriptable;
import net.rim.device.api.script.ScriptableFunction;

public class FunctionUpload extends ScriptableFunction {

	public static final String NAME = "upload";

	private ScriptableFunction _successCallback = null;
	private ScriptableFunction _errorCallback = null;

	private int[] _transports = null;

	public FunctionUpload(int[] transports) {
		_transports = transports;
	}

	public Object invoke(Object thiz, Object[] args) throws Exception {
		Logger.info("Upload invoked...");

		if (args.length == 1) {
			Hashtable headers = null;
			Hashtable params = null;

			long timeout = 30000;

			Logger.info("Getting options...");

			Scriptable config = (Scriptable) args[0];

			Logger.info("Setting core options...");

			String url = (String) config.getField("url");
			String filePath = (String) config.getField("file");
			String fileKey = (String) config.getField("fileKey");
			String mimeType = (String) config.getField("mimeType");
			Object cTimeout = config.getField("timeout");

			Logger.info("Getting headers and params...");

			Object sHeaders = config.getField("headers");
			Object sParams = config.getField("params");

			if (mimeType.equals(UNDEFINED)) {
				mimeType = null;
			}

			if (!cTimeout.equals(UNDEFINED)) {
				timeout = ((Integer) cTimeout).intValue();
			}

			Logger.info("Setting headers and extra params...");

			try {
				headers = objectToHashtable(sHeaders);
				params = objectToHashtable(sParams);
			} catch(Throwable e) {
				Logger.error("Error setting custom params and headers..." + e.getMessage());
			}

			_successCallback = (ScriptableFunction) config.getField("success");
			_errorCallback = (ScriptableFunction) config.getField("error");

			Logger.info("Beginning upload...");

			new UploadRunnable(url, fileKey, params, filePath, mimeType, timeout, headers, _transports, _successCallback, _errorCallback);
		}
		return UNDEFINED;
	}

	private Hashtable objectToHashtable(Object obj) throws Exception
	{
		Hashtable ht = null;

		if (!obj.equals(UNDEFINED) && obj != null) {
			Scriptable s = (Scriptable) obj;

			Vector v = new Vector();
			s.enumerateFields(v);

			int count = v.size();
			Logger.log("Object Keys: " + String.valueOf(v.size()));

			if (count > 0) {
				ht = new Hashtable();
				String fieldName;

				for (int i=0; i<count; i++) {
					fieldName = (String) v.elementAt(i);
					ht.put(fieldName, s.getField(fieldName));
				}
			}
		}
		return ht;
	}

}


text:
layout: base
title:  'Statistics of Reflex in UD_Afrikaans'
udver: '2'
---

## Treebank Statistics: UD_Afrikaans: Features: `Reflex`

This feature is universal.
It occurs with 1 different values: `Yes`.

37 tokens (0%) have a non-empty value of `Reflex`.
10 types (0%) occur at least once with a non-empty value of `Reflex`.
10 lemmas (0%) occur at least once with a non-empty value of `Reflex`.
The feature is used with 1 part-of-speech tags: <tt>PRON</tt> (37; 0% instances).

### `PRON`

37 <tt>PRON</tt> tokens (1% of all `PRON` tokens) have a non-empty value of `Reflex`.

The most frequent other feature values with which `PRON` and `Reflex` co-occurred: <tt>Case</tt><tt>=EMPTY</tt> (37; 100%), <tt>Poss</tt><tt>=EMPTY</tt> (37; 100%), <tt>PronType</tt><tt>=Prs</tt> (37; 100%), <tt>Number</tt><tt>=Plur</tt> (22; 59%), <tt>Person</tt><tt>=1</tt> (19; 51%).

`PRON` tokens may have the following values of `Reflex`:

* `Yes` (37; 100% of non-empty `Reflex`): onsself self ons hulle hom haarself homself hulself jouself myself
* `EMPTY` (3681): ons wat dit jy hulle jou enige ek sy daar

`Reflex` seems to be **lexical feature** of `PRON`. 100% lemmas (10) occur only with one value of `Reflex`.


text:
from google.cloud import appengine_admin_v1

def sample_update_version():
    # Create a client
    client = appengine_admin_v1.VersionsClient()

    # Initialize request argument(s)
    request = appengine_admin_v1.UpdateVersionRequest(
    )

    # Make the request
    operation = client.update_version(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

# [END appengine_v1_generated_Versions_UpdateVersion_sync]


text:
/*! @file
    @brief RefOS sharing library.

    Helper ring buffer library which can be used to implement sharing. For details on how sharing
    is done on RefOS, please refer to the protocol documentation. Uses a standard ringbuffer
    implementation.

    Assumes that the sharing has already been set up, and mapped into windows on both processes.
*/

#ifndef _REFOS_SHARE_H_
#define _REFOS_SHARE_H_

#include <stddef.h>

#include "refos.h"

/*! @brief Read from a shared buffer.
    @param dest Buffer in which to store the read data. (output, no ownership)
    @param len Maximum length of the destination buffer.
    @param bufVaddr The shared ringbuffer address. (input, no ownership)
    @param bufSize The shared ringbuffer size.
    @param start Handle to the associated start address (input, output, no ownership)
    @param bytesRead The number of bytes that has been successfully read from the shared buffer.
                     (output, no ownership)
    @return 0 if success, -1 otherwise.
 */
int refos_share_read(char *dest, size_t len, char *bufVaddr, size_t bufSize,
        unsigned int *start, unsigned int *bytesRead);

/*! @brief Write to a shared buffer.
    @param src Buffer containing content to write. (input, no ownership)
    @param len Length of the content source.
    @param bufVaddr The shared ringbuffer address. (input, no ownership)
    @param bufSize The shared ringbuffer size.
    @param end Handle to the associated end address (input, output, no ownership)
    @return 0 if success, -1 otherwise.
 */
int refos_share_write(char *src, size_t len, char *bufVaddr, size_t bufSize,
        unsigned int *end);

#endif /* _REFOS_SHARE_H_ */