text:
package org.jivesoftware;

import org.jivesoftware.launcher.Startup;
import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatFrame;
import org.jivesoftware.spark.ui.RawPacketSender;
import org.jivesoftware.spark.util.*;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.alerts.InputTextAreaDialog;
import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettings;
import org.jivesoftware.sparkimpl.plugin.layout.LayoutSettingsManager;
import org.jivesoftware.sparkimpl.plugin.manager.Enterprise;
import org.jivesoftware.sparkimpl.settings.JiveInfo;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import org.jivesoftware.sparkimpl.updater.CheckUpdates;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.TimerTask;

/**
 * The MainWindow class acts as both the DockableHolder and the proxy
 * to the Workspace in Spark.
 *
 * @version 1.0, 03/12/14
 */
public final class MainWindow extends ChatFrame implements ActionListener {
	private static final long serialVersionUID = -6062104959613603510L;

	private final Set<MainWindowListener> listeners = new HashSet<>();

    private final JMenu connectMenu = new JMenu();
    private final JMenu contactsMenu = new JMenu();
    private final JMenu actionsMenu = new JMenu();
    private final JMenu pluginsMenu = new JMenu();
    private final JMenu helpMenu = new JMenu();

    private JMenuItem preferenceMenuItem;
    private JCheckBoxMenuItem alwaysOnTopItem;

    private final JMenuItem menuAbout = new JMenuItem(SparkRes.getImageIcon(SparkRes.INFORMATION_IMAGE));
    private final JMenuItem sparkforumItem = new JMenuItem();

    private final JMenuBar mainWindowBar = new JMenuBar();

    private boolean focused;

    private JToolBar topToolbar = new JToolBar();

    private JSplitPane splitPane;

    private JEditorPane aboutBoxPane;

    private static MainWindow singleton;
    private static final Object LOCK = new Object();

    /**
     * Returns the singleton instance of MainWindow,
     * creating it if necessary.
     *

     *
     * @return the singleton instance of MainWindow
     */
    public static MainWindow getInstance() {
        // Synchronize on LOCK to ensure that we don't end up creating
        // two singletons.

        synchronized (LOCK) {
            if (null == singleton) {
            	MainWindow controller = new MainWindow(Default.getString(Default.APPLICATION_NAME), SparkManager.getApplicationImage());
            	singleton = controller;
            }
        }
        return singleton;
    }

    /**
     * Constructs the UI for the MainWindow. The MainWindow UI is the container for the
     * entire Spark application.
     *
     * @param title the title of the frame.
     * @param icon  the icon used in the frame.
     */
    private MainWindow(String title, ImageIcon icon) {

        // Initialize and dock the menus
        buildMenu();

        // Add Workspace Container
        getContentPane().setLayout(new BorderLayout());

        LayoutSettings settings = LayoutSettingsManager.getLayoutSettings();
        if (settings.getMainWindowX() == 0 && settings.getMainWindowY() == 0) {
            // Use default settings.
            setSize(300, 500);
            GraphicUtils.centerWindowOnScreen(this);
        }
        else {
            setBounds(settings.getMainWindowX(), settings.getMainWindowY(), settings.getMainWindowWidth(), settings.getMainWindowHeight());
        }

        // Add menubar
        this.setJMenuBar(mainWindowBar);
        this.getContentPane().add(topToolbar, BorderLayout.NORTH);

        setTitle(title);
        setIconImage(icon.getImage());

        // Setup WindowListener to be the proxy to the actual window listener
        // which cannot normally be used outside of the Window component because
        // of protected access.
        addWindowListener(new WindowAdapter() {

            /**
             * This event fires when the window has become active.
             *
             * @param e WindowEvent is not used.
             */
            public void windowActivated(WindowEvent e) {
                fireWindowActivated();
            }

            /**
             * Invoked when a window is de-activated.
             */
            public void windowDeactivated(WindowEvent e) {
            }

            /**
             * This event fires whenever a user minimizes the window
             * from the toolbar.
             *
             * @param e WindowEvent is not used.
             */
            public void windowIconified(WindowEvent e) {
            }

            /**
             * This event fires when the application is closing.
             * This allows Plugins to do any persistence or other
             * work before exiting.
             *
             * @param e WindowEvent is never used.
             */
            public void windowClosing(WindowEvent e) {
                saveLayout();
                setVisible(false);
            }
        });

        this.addWindowFocusListener(new MainWindowFocusListener());
    }

    /**
     * Adds a MainWindow listener to {@link MainWindow}. The
     * listener will be called when either the MainWindow has been minimized, maximized,
     * or is shutting down.
     *
     * @param listener the MainWindowListener to register
     */
    public void addMainWindowListener(MainWindowListener listener) {
        listeners.add(listener);
    }

    /**
     * Removes the specified {@link MainWindowListener}.
     *
     * @param listener the MainWindowListener to remove.
     */
    public void removeMainWindowListener(MainWindowListener listener) {
        listeners.remove(listener);
    }

    /**
     * Notifies all {@link MainWindowListener}s that the MainWindow
     * has been activated.
     */
    private void fireWindowActivated()
    {
        for ( MainWindowListener listener : listeners )
        {
            try
            {
                listener.mainWindowActivated();
            }
            catch ( Exception e )
            {
                Log.error( "A MainWindowListener (" + listener + ") threw an exception while processing a 'activated' event.", e );
            }
        }

        if (Spark.isMac()) {
            setJMenuBar(mainWindowBar);
        }
    }

    /**
     * Notifies all {@link MainWindowListener}s that the MainWindow
     * is shutting down.
     */
    private void fireWindowShutdown()
    {
        for ( MainWindowListener listener : listeners )
        {
            try
            {
                listener.shutdown();
            }
            catch ( Exception e )
            {
                Log.error( "A MainWindowListener (" + listener + ") threw an exception while processing a 'shutdown' event.", e );
            }
        }
    }

    /**
     * Invokes the Preferences Dialog.
     *
     * @param e the ActionEvent
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(preferenceMenuItem)) {
            SparkManager.getPreferenceManager().showPreferences();
        }
    }

    /**
     * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and
     * setting the Agent to be offline.
     */
    public void shutdown() {
        final XMPPConnection con = SparkManager.getConnection();

        if (con.isConnected()) {
            // Send disconnect.
            ((AbstractXMPPConnection)con).disconnect();
        }

        // Notify all MainWindowListeners
        try {
            fireWindowShutdown();
        }
        catch (Exception ex) {
            Log.error(ex);
        }
        // Close application.
        System.exit(1);

    }

    /**
     * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and
     * setting the Agent to be offline.
     *
     * @param sendStatus true if Spark should send a presence with a status message.
     */
    public void logout(boolean sendStatus) {
        final XMPPConnection con = SparkManager.getConnection();
        String status = null;

        if (con.isConnected() && sendStatus) {
            final InputTextAreaDialog inputTextDialog = new InputTextAreaDialog();
            status = inputTextDialog.getInput(Res.getString("title.status.message"), Res.getString("message.current.status"),
                SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24), this);
        }

        if (status != null || !sendStatus)
        {
	        // Notify all MainWindowListeners
	        try {
	            // Set auto-login to false;
	            SettingsManager.getLocalPreferences().setAutoLogin(false);
	            SettingsManager.saveSettings();

	            fireWindowShutdown();
	            setVisible(false);
	        }
	        finally {
	            closeConnectionAndInvoke(status);
	        }
        }
    }

    /**
     * Closes the current connection and restarts Spark.
     *
     * @param reason the reason for logging out. This can be if user gave no reason.
     */
    public void closeConnectionAndInvoke(String reason) {
        final XMPPConnection con = SparkManager.getConnection();
        if (con.isConnected()) {
            if (reason != null) {
                Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
                try
                {
                    ((AbstractXMPPConnection)con).disconnect(byePresence);
                }
                catch ( SmackException.NotConnectedException e )
                {
                    Log.error( "Unable to sign out with presence.", e);
                    ((AbstractXMPPConnection)con).disconnect();
                }
            }
            else {
                ((AbstractXMPPConnection)con).disconnect();
            }
        }
        if (!restartApplicationWithScript()) {
            restartApplicationWithJava();
        }
    }

    private File getLibDirectory() throws IOException {
        File jarFile;
        try{
            jarFile = new File(Startup.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        } catch(Exception e) {
            Log.error("Cannot get jar file containing the startup class", e);
            return null;
        }
        if ( !jarFile.getName().endsWith(".jar") ) {
            Log.error("The startup class is not packaged in a jar file");
            return null;
        }
        File libDir = jarFile.getParentFile();
        return libDir;
    }

    private String getClasspath() throws IOException {
        File libDir = getLibDirectory();
        String libPath = libDir.getCanonicalPath();
        String[] files = libDir.list();
        StringBuilder classpath = new StringBuilder();
        for (String file : files) {
            if (file.endsWith(".jar")) {
                classpath.append(libPath + File.separatorChar + file + File.pathSeparatorChar);
            }
        }
        return classpath.toString();
    }

    private String getCommandPath() throws IOException{
        return getLibDirectory().getParentFile().getCanonicalPath();
    }

    public boolean restartApplicationWithScript() {
        String command = null;
        try {
            if (Spark.isWindows()) {
                String sparkExe = getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME) + ".exe";
                if (!new File(sparkExe).exists()) {
                    Log.warning("Client EXE file does not exist");
                    return false;
                }
                String starterExe = getCommandPath() + File.separator + "starter.exe";
                if (!new File(starterExe).exists()) {
                    Log.warning("Starter EXE file does not exist");
                    return false;
                }
                command = starterExe + " \"" + sparkExe + "\"";
            } else if (Spark.isLinux()) {
                command = getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME);
                if (!new File(command).exists()) {
                    Log.warning("Client startup script does not exist");
                    return false;
                }
            } else if (Spark.isMac()) {
                command = "open -a " + Default.getString(Default.SHORT_NAME);
            }

            Runtime.getRuntime().exec(command);
            System.exit(0);
            return true;
        } catch (Exception e) {
            Log.error("Error trying to restart application with script", e);
            return false;
        }
    }

    public boolean restartApplicationWithJava() {
        String javaBin = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java";
        try {
            String toExec[] = new String[] {
                    javaBin, "-cp", getClasspath(), "org.jivesoftware.launcher.Startup"};
            Runtime.getRuntime().exec(toExec);
        } catch (Exception e) {
            Log.error("Error trying to restart application with java", e);
            return false;
        }
        System.exit(0);
        return true;
    }

    /**
     * Setup the Main Toolbar with File, Tools and Help.
     */
    private void buildMenu() {

        // setup file menu
        final JMenuItem exitMenuItem = new JMenuItem();

        // Setup ResourceUtils
        ResourceUtils.resButton(connectMenu, "&" + Res.getString("menuitem.connect"));
        ResourceUtils.resButton(contactsMenu, Res.getString("menuitem.contacts"));
        ResourceUtils.resButton(actionsMenu, Res.getString("menuitem.actions"));
        ResourceUtils.resButton(exitMenuItem, Res.getString("menuitem.exit"));
        ResourceUtils.resButton(pluginsMenu, Res.getString("menuitem.plugins"));

        exitMenuItem.setIcon(null);

        mainWindowBar.add(connectMenu);
        mainWindowBar.add(contactsMenu);
        mainWindowBar.add(actionsMenu);
        //mainWindowBar.add(pluginsMenu);
        mainWindowBar.add(helpMenu);

        preferenceMenuItem = new JMenuItem(SparkRes.getImageIcon(SparkRes.PREFERENCES_IMAGE));
        preferenceMenuItem.setText(Res.getString("title.spark.preferences"));
        preferenceMenuItem.addActionListener(this);

        // Show the "Preferences" menu item ONLY in Maintenance Mode or when DISABLE_PREFERENCES_MENU_ITEM = false and Client Control allows it.
        File myMaintFile = new File(Default.getString(Default.MAINT_FILESPEC));

        final boolean maintMode = (myMaintFile.exists() && !myMaintFile.isDirectory());
        final boolean prefsAllowed = (!Default.getBoolean("DISABLE_PREFERENCES_MENU_ITEM") && Enterprise.containsFeature(Enterprise.PREFERENCES_MENU_FEATURE));

        if (maintMode || prefsAllowed) connectMenu.add(preferenceMenuItem);

        alwaysOnTopItem = new JCheckBoxMenuItem();
        ResourceUtils.resButton(alwaysOnTopItem, Res.getString("menuitem.always.on.top"));
        alwaysOnTopItem.addActionListener( actionEvent -> {
        	SettingsManager.getLocalPreferences().setMainWindowAlwaysOnTop(alwaysOnTopItem.isSelected());
        	MainWindow.getInstance().setAlwaysOnTop(alwaysOnTopItem.isSelected());
        } );

        alwaysOnTopItem.setSelected(SettingsManager.getLocalPreferences().isMainWindowAlwaysOnTop());
        this.setAlwaysOnTop(SettingsManager.getLocalPreferences().isMainWindowAlwaysOnTop());

        connectMenu.add(alwaysOnTopItem);

        // Set up the Logout and Exit menus...
        if (!Default.getBoolean("DISABLE_EXIT") && Enterprise.containsFeature(Enterprise.LOGOUT_EXIT_FEATURE)) {
        	connectMenu.addSeparator();
        	if(!Default.getBoolean("HIDE_SAVE_PASSWORD_AND_AUTOLOGIN") && SettingsManager.getLocalPreferences().getPswdAutologin()) {
        		JMenuItem logoutMenuItem = new JMenuItem();
        		ResourceUtils.resButton(logoutMenuItem, Res.getString("menuitem.logout.no.status"));
        		logoutMenuItem.addActionListener( e -> logout(false) );

        		JMenuItem logoutWithStatus = new JMenuItem();
        		ResourceUtils.resButton(logoutWithStatus, Res.getString("menuitem.logout.with.status"));
        		logoutWithStatus.addActionListener( e -> logout(true) );

        		connectMenu.add(logoutMenuItem);
        		connectMenu.add(logoutWithStatus);
        		connectMenu.addSeparator();
        	}
        	connectMenu.add(exitMenuItem);
        }

        JMenuItem updateMenu= new JMenuItem("", SparkRes.getImageIcon(SparkRes.DOWNLOAD_16x16));
        ResourceUtils.resButton(updateMenu, Res.getString("menuitem.check.for.updates"));
        updateMenu.addActionListener( e -> checkForUpdates(true) );

        // Add Error Dialog Viewer
        final Action viewErrors = new AbstractAction() {
			private static final long serialVersionUID = -420926784631340112L;

			public void actionPerformed(ActionEvent e) {
                File logDir = new File(Spark.getLogDirectory(), "errors.log");
                if (!logDir.exists()) {
                	UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
                    JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "No error logs found.", "Error Log", JOptionPane.INFORMATION_MESSAGE);
                }
                else {
                    showErrorLog();
                }
            }
        };

        viewErrors.putValue(Action.NAME, Res.getString("menuitem.view.logs"));

        final Action viewHelpGuideAction = new AbstractAction() {

            	final String url = Default.getString(Default.HELP_USER_GUIDE);
			private static final long serialVersionUID = 2680369963282231348L;

			public void actionPerformed(ActionEvent actionEvent) {
                try {

                    BrowserLauncher.openURL(url);
                }
                catch (Exception e) {
                    Log.error("Unable to load online help.", e);
                }
            }
        };

        if (!Default.getBoolean("HELP_USER_GUIDE_DISABLED") && Enterprise.containsFeature(Enterprise.HELP_USERGUIDE_FEATURE)) {
        	viewHelpGuideAction.putValue(Action.NAME,
        			Res.getString("menuitem.user.guide"));
        	viewHelpGuideAction.putValue(Action.SMALL_ICON,
        			SparkRes.getImageIcon(SparkRes.SMALL_QUESTION));
        	helpMenu.add(viewHelpGuideAction);
        }

        if (!Default.getBoolean("HELP_FORUM_DISABLED") && Enterprise.containsFeature(Enterprise.HELP_FORUMS_FEATURE)) helpMenu.add(sparkforumItem);

	// Build Help Menu
	if (!Default.getBoolean("DISABLE_UPDATES") && Enterprise.containsFeature(Enterprise.UPDATES_FEATURE)) helpMenu.add(updateMenu);

	helpMenu.addSeparator();
	helpMenu.add(viewErrors);
	helpMenu.add(menuAbout);

	// ResourceUtils - Adds mnemonics
	ResourceUtils.resButton(preferenceMenuItem, Res.getString("menuitem.preferences"));
	ResourceUtils.resButton(helpMenu, Res.getString("menuitem.help"));
	ResourceUtils.resButton(menuAbout, Res.getString("menuitem.about"));

	if (Default.getString("HELP_FORUM_TEXT").length() > 0) {
	    ResourceUtils.resButton(sparkforumItem, Default.getString("HELP_FORUM_TEXT"));
	} else {
	    ResourceUtils.resButton(sparkforumItem, Res.getString("menuitem.online.help"));
	}
        // Register shutdown with the exit menu.
	exitMenuItem.addActionListener(new AbstractAction() {
	    private static final long serialVersionUID = -2301236575241532698L;

	    public void actionPerformed(ActionEvent e) {
		shutdown();
	    }
	});

	sparkforumItem.addActionListener(new AbstractAction() {
	    private static final long serialVersionUID = -1423433460333010339L;

	    final String url = Default.getString("HELP_FORUM");

	    public void actionPerformed(ActionEvent e) {
		try {
		    BrowserLauncher.openURL(url);
		} catch (Exception browserException) {
		    Log.error("Error launching browser:", browserException);
		}
	    }
	});

        // Show About Box
	menuAbout.addActionListener(new AbstractAction() {
	    private static final long serialVersionUID = -7173666373051354502L;

	    public void actionPerformed(ActionEvent e) {
		showAboutBox();
	    }
	});

	if (!Default.getBoolean("DISABLE_UPDATES") && Enterprise.containsFeature(Enterprise.UPDATES_FEATURE)) {
		// Execute spark update checker after one minute.
		final TimerTask task = new SwingTimerTask() {
			public void doRun() {
				checkForUpdates(false);
			}
		};

		TaskEngine.getInstance().schedule(task, 60000);
	}

	if(SettingsManager.getLocalPreferences().isDebuggerEnabled())
	{
	    JMenuItem rawPackets = new JMenuItem(SparkRes.getImageIcon(SparkRes.TRAY_IMAGE));
	    rawPackets.setText("Send Packets");
	    rawPackets.addActionListener( e -> new RawPacketSender() );

	    connectMenu.add(rawPackets,2);
	}

    }

    /**
     * Returns the JMenuBar for the MainWindow. You would call this if you
     * wished to add or remove menu items to the main menubar. (File | Tools | Help)
     *
     * @return the Jive Talker Main Window MenuBar
     */
    public JMenuBar getMenu() {
        return mainWindowBar;
    }

    /**
     * Returns the Menu in the JMenuBar by it's name. For example:

     *

     * JMenu toolsMenu = getMenuByName("Tools");
     *

     *

     *
     * @param name the name of the Menu.
     * @return the JMenu item with the requested name.
     */
    public JMenu getMenuByName(String name) {
        for (int i = 0; i < getMenu().getMenuCount(); i++) {
            JMenu menu = getMenu().getMenu(i);
            if (menu.getText().equals(name)) {
                return menu;
            }
        }
        return null;
    }

    /**
     * Returns true if the Spark window is in focus.
     *
     * @return true if the Spark window is in focus.
     */
    public boolean isInFocus() {
        return focused;
    }

    private class MainWindowFocusListener implements WindowFocusListener {

        public void windowGainedFocus(WindowEvent e) {
            focused = true;
        }

        public void windowLostFocus(WindowEvent e) {
            focused = false;
        }
    }

    /**
     * Return the top toolbar in the Main Window to allow for customization.
     *
     * @return the MainWindows top toolbar.
     */
    public JToolBar getTopToolBar() {
        return topToolbar;
    }

    /**
     * Checks for the latest update on the server.
     *
     * @param forced true if you want to bypass the normal checking security.
     */
    private void checkForUpdates(final boolean forced) {
        final CheckUpdates updater = new CheckUpdates();
        try {
            final SwingWorker updateThread = new SwingWorker() {
                public Object construct() {
                    try {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException e) {
                        Log.error(e);
                    }
                    return "ok";
                }

                public void finished() {
                    try {
                        updater.checkForUpdate(forced);
                    }
                    catch (Exception e) {
                        Log.error("There was an error while checking for a new update.", e);
                    }
                }
            };

            updateThread.start();

        }
        catch (Exception e) {
            Log.warning("Error updating.", e);
        }
    }

    /**
     * Sets About Box Pane for Spark.
     */
    private void setAboutBoxPane() {

        // Get values from default.properties file
        final String APPLICATION_INFO1 = Default.getString(Default.APPLICATION_INFO1);
        final String APPLICATION_INFO2 = Default.getString(Default.APPLICATION_INFO2);
        final String APPLICATION_INFO3 = Default.getString(Default.APPLICATION_INFO3);
        final String APPLICATION_LICENSE_LINK = Default.getString(Default.APPLICATION_LICENSE_LINK);
        final String APPLICATION_LICENSE_LINK_TXT = Default.getString(Default.APPLICATION_LICENSE_LINK_TXT);
        final String APPLICATION_INFO4 = Default.getString(Default.APPLICATION_INFO4);
        final String APPLICATION_LINK = Default.getString(Default.APPLICATION_LINK);
        final String APPLICATION_LINK_TXT = Default.getString(Default.APPLICATION_LINK_TXT);
        final boolean DISPLAY_DEV_INFO = Default.getBoolean(Default.DISPLAY_DEV_INFO);
        final String SMACK_VERSION = Default.getString(Default.SMACK_VERSION);
        final String JAVA_VERSION = Default.getString(Default.JAVA_VERSION);

        // Construct About Box text
        StringBuilder aboutBoxText = new StringBuilder();
        aboutBoxText.append(
            Default.getString(Default.APPLICATION_NAME) + " " + JiveInfo.getVersion());

        // Add APPLICATION_INFO1 if not empty
        if (!("".equals(APPLICATION_INFO1))) {
            aboutBoxText.append(
                "
"
                + APPLICATION_INFO1);
        }

        // Add APPLICATION_INFO2 if not empty
        if (!( "".equals(APPLICATION_INFO2))) {
            aboutBoxText.append(
                "
"
                + APPLICATION_INFO2);
        }

        // Add APPLICATION_INFO3 if not empty
        if (!("".equals(APPLICATION_INFO3))) {
            aboutBoxText.append(
                "
"
                + APPLICATION_INFO3);
        }

        // Add APPLICATION_LICENSE_LINK if not empty
        if (!( "".equals(APPLICATION_LICENSE_LINK))) {
            aboutBoxText.append(
                "
"
                + "" + APPLICATION_LICENSE_LINK_TXT + "");
        }

        // Add APPLICATION_LINK if not empty
        if (!( "".equals(APPLICATION_LINK))) {
            aboutBoxText.append(
                "
"
                + "" + APPLICATION_LINK_TXT + "");
        }

        // Add APPLICATION_INFO4 if not empty
        if (!( "".equals(APPLICATION_INFO4))) {
            aboutBoxText.append(
                "
"
                + APPLICATION_INFO4);
        }

        if (DISPLAY_DEV_INFO) {
            // Add Smack Version # if is empty
            if ("".equals(SMACK_VERSION)) {
                aboutBoxText.append(
                    "
"
                    + "Smack Version: " + SmackConfiguration.getVersion());
            }

            // Add Java JRE Version if is empty
            if ("".equals(JAVA_VERSION)) {
                aboutBoxText.append(
                    "
"
                    + "JRE Version: " + System.getProperty("java.version"));
            }
        }

        // copy window style
        JPanel p = new JPanel();
        Font font = p.getFont();

        // create some css from the JPanel's font
        String style = ( "font-family:" + font.getFamily() + ";" ) +
                "font-weight:" + ( font.isBold() ? "bold" : "normal" ) + ";" +
                "font-size:" + font.getSize() + "pt;";

        // assemble html
        JEditorPane ep = new JEditorPane("text/html", ( "" + aboutBoxText.toString() + "" ) );

        // handle link events
        ep.addHyperlinkListener( e -> {
            // if a link is clicked, and it is the APPLICATION_LICENSE_LINK, then load that page
            if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)
                    && e.getURL().toString().equalsIgnoreCase(Default.getString(Default.APPLICATION_LICENSE_LINK))) {
                try {

                    BrowserLauncher.openURL(Default.getString(Default.APPLICATION_LICENSE_LINK));

                } catch (Exception f) {
                    Log.error("There was an error loading the URL", f);
                }

            // else if a link is clicked, and it is the APPLICATION_LINK, then load that page
            } else if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)
                    && e.getURL().toString().equalsIgnoreCase(Default.getString(Default.APPLICATION_LINK))) {
                try {

                    BrowserLauncher.openURL(Default.getString(Default.APPLICATION_LINK));

                } catch (Exception f) {
                    Log.error("There was an error loading the URL", f);
                }
            }

        } );
        ep.setEditable(false);
        ep.setBackground(p.getBackground());
        this.aboutBoxPane = ep;

    }

    /**
     * Returns About Box Pane.
     * @return JEditorPane About Box
     */
    private JEditorPane getAboutBoxPane() {
        if (null == this.aboutBoxPane) {
            setAboutBoxPane();
        }
        return this.aboutBoxPane;
    }

    /**
     * Displays the About Box for Spark.
     */
    private static void showAboutBox() {
    	UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
        JOptionPane.showMessageDialog(SparkManager.getMainWindow(), SparkManager.getMainWindow().getAboutBoxPane(),
            Res.getString("title.about"), JOptionPane.INFORMATION_MESSAGE, SparkRes.getImageIcon(SparkRes.MAIN_IMAGE));
    }

    /**
     * Displays the Spark error log.
     */
    private void showErrorLog() {
        final File logDir = new File(Spark.getLogDirectory(), "errors.log");

        // Read file and show
        final String errorLogs = URLFileSystem.getContents(logDir);

        final JFrame frame = new JFrame(Res.getString("title.client.logs"));
        frame.setLayout(new BorderLayout());
        frame.setIconImage(SparkManager.getApplicationImage().getImage());

        final JTextPane pane = new JTextPane();
        pane.setBackground(Color.white);
        pane.setFont(new Font("Dialog", Font.PLAIN, 12));
        pane.setEditable(false);
        pane.setText(errorLogs);

        frame.add(new JScrollPane(pane), BorderLayout.CENTER);

        final JButton copyButton = new JButton(Res.getString("button.copy.to.clipboard"));
        frame.add(copyButton, BorderLayout.SOUTH);

        copyButton.addActionListener( e -> {
            SparkManager.setClipboard(errorLogs);
            copyButton.setEnabled(false);
        } );

        frame.pack();
        frame.setSize(600, 400);

        GraphicUtils.centerWindowOnScreen(frame);
        frame.setVisible(true);
    }

    /**
     * Saves the layout on closing of the main window.
     */
    public void saveLayout() {
        try {
            LayoutSettings settings = LayoutSettingsManager.getLayoutSettings();
            settings.setMainWindowHeight(getHeight());
            settings.setMainWindowWidth(getWidth());
            settings.setMainWindowX(getX());
            settings.setMainWindowY(getY());
            LayoutSettingsManager.saveLayoutSettings();
        }
        catch (Exception e) {
            // Don't let this cause a real problem shutting down.
        }
    }

    /**
     * Return true if the MainWindow is docked.
     *
     * @return true if the window is docked.
     */
    public boolean isDocked() {
        LocalPreferences preferences = SettingsManager.getLocalPreferences();
        return preferences.isDockingEnabled();
    }

    /**
     * Returns the inner split pane.
     *
     * @return the split pane.
     */
    public JSplitPane getSplitPane() {
        // create the split pane only if required.
        if (splitPane == null) {
            splitPane = new JSplitPane();
        }
        return this.splitPane;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Enumeration and Flag Types: GObject Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="GObject Reference Manual">
<link rel="up" href="rn01.html" title="API Reference">
<link rel="prev" href="gobject-The-Base-Object-Type.html" title="GObject">
<link rel="next" href="gobject-Boxed-Types.html" title="Boxed Types">
<meta name="generator" content="GTK-Doc V1.24 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

Top  |
                  Description

Enumeration and Flag Types

Enumeration and Flag Types — Enumeration and flags types

Functions

<colgroup>
<col width="150px" class="functions_return">
<col class="functions_name">
</colgroup>

#define

G_ENUM_CLASS_TYPE()

#define

G_ENUM_CLASS_TYPE_NAME()

#define

G_TYPE_IS_ENUM()

#define

G_ENUM_CLASS()

#define

G_IS_ENUM_CLASS()

#define

G_TYPE_IS_FLAGS()

#define

G_FLAGS_CLASS()

#define

G_IS_FLAGS_CLASS()

#define

G_FLAGS_CLASS_TYPE()

#define

G_FLAGS_CLASS_TYPE_NAME()

GEnumValue *

g_enum_get_value ()

GEnumValue *

g_enum_get_value_by_name ()

GEnumValue *

g_enum_get_value_by_nick ()

GFlagsValue *

g_flags_get_first_value ()

GFlagsValue *

g_flags_get_value_by_name ()

GFlagsValue *

g_flags_get_value_by_nick ()

GType

g_enum_register_static ()

GType

g_flags_register_static ()

void

g_enum_complete_type_info ()

void

g_flags_complete_type_info ()

Types and Values

<colgroup>
<col width="150px" class="name">
<col class="description">
</colgroup>

struct
GEnumClass

struct
GFlagsClass

struct
GEnumValue

struct
GFlagsValue

Includes

#include <glib-object.h>

Description

The GLib type system provides fundamental types for enumeration and
flags types. (Flags types are like enumerations, but allow their
values to be combined by bitwise or). A registered enumeration or
flags type associates a name and a nickname with each allowed
value, and the methods g_enum_get_value_by_name(),
g_enum_get_value_by_nick(), g_flags_get_value_by_name() and
g_flags_get_value_by_nick() can look up values by their name or
nickname.  When an enumeration or flags type is registered with the
GLib type system, it can be used as value type for object
properties, using g_param_spec_enum() or g_param_spec_flags().

GObject ships with a utility called glib-mkenums,
that can construct suitable type registration functions from C enumeration
definitions.

Example of how to get a string representation of an enum value:

1
2
3
4
5
6
7
8
9

GEnumClass *enum_class;
GEnumValue *enum_value;

enum_class = g_type_class_ref (MAMAN_TYPE_MY_ENUM);
enum_value = g_enum_get_value (enum_class, MAMAN_MY_ENUM_FOO);

g_print ("Name: %s\n", enum_value->value_name);

g_type_class_unref (enum_class);

Functions

G_ENUM_CLASS_TYPE()

#define G_ENUM_CLASS_TYPE(class)       (G_TYPE_FROM_CLASS (class))

Get the type identifier from a given GEnumClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GEnumClass

Returns

 the GType

G_ENUM_CLASS_TYPE_NAME()

#define G_ENUM_CLASS_TYPE_NAME(class)  (g_type_name (G_ENUM_CLASS_TYPE (class)))

Get the static type name from a given GEnumClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GEnumClass

Returns

 the type name.

G_TYPE_IS_ENUM()

#define G_TYPE_IS_ENUM(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_ENUM)

Checks whether type
 "is a" G_TYPE_ENUM.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

type

a GType ID.

Returns

 TRUE if type
"is a" G_TYPE_ENUM.

G_ENUM_CLASS()

#define G_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_ENUM, GEnumClass))

Casts a derived GEnumClass structure into a GEnumClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a valid GEnumClass

G_IS_ENUM_CLASS()

#define G_IS_ENUM_CLASS(class)	       (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_ENUM))

Checks whether class
 "is a" valid GEnumClass structure of type G_TYPE_ENUM
or derived.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GEnumClass

G_TYPE_IS_FLAGS()

#define G_TYPE_IS_FLAGS(type)	       (G_TYPE_FUNDAMENTAL (type) == G_TYPE_FLAGS)

Checks whether type
 "is a" G_TYPE_FLAGS.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

type

a GType ID.

Returns

 TRUE if type
"is a" G_TYPE_FLAGS.

G_FLAGS_CLASS()

#define G_FLAGS_CLASS(class)	       (G_TYPE_CHECK_CLASS_CAST ((class), G_TYPE_FLAGS, GFlagsClass))

Casts a derived GFlagsClass structure into a GFlagsClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a valid GFlagsClass

G_IS_FLAGS_CLASS()

#define G_IS_FLAGS_CLASS(class)        (G_TYPE_CHECK_CLASS_TYPE ((class), G_TYPE_FLAGS))

Checks whether class
 "is a" valid GFlagsClass structure of type G_TYPE_FLAGS
or derived.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GFlagsClass

G_FLAGS_CLASS_TYPE()

#define G_FLAGS_CLASS_TYPE(class)      (G_TYPE_FROM_CLASS (class))

Get the type identifier from a given GFlagsClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GFlagsClass

Returns

 the GType

G_FLAGS_CLASS_TYPE_NAME()

#define G_FLAGS_CLASS_TYPE_NAME(class) (g_type_name (G_FLAGS_CLASS_TYPE (class)))

Get the static type name from a given GFlagsClass structure.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

class

a GFlagsClass

Returns

 the type name.

g_enum_get_value ()

GEnumValue *
g_enum_get_value (GEnumClass *enum_class,
                  gint value);

Returns the GEnumValue for a value.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

enum_class

a GEnumClass

value

the value to look up

Returns

 the GEnumValue for value
, or NULL
if value
is not a member of the enumeration.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_enum_get_value_by_name ()

GEnumValue *
g_enum_get_value_by_name (GEnumClass *enum_class,
                          const gchar *name);

Looks up a GEnumValue by name.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

enum_class

a GEnumClass

name

the name to look up

Returns

 the GEnumValue with name name
,
or NULL if the enumeration doesn't have a member
with that name.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_enum_get_value_by_nick ()

GEnumValue *
g_enum_get_value_by_nick (GEnumClass *enum_class,
                          const gchar *nick);

Looks up a GEnumValue by nickname.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

enum_class

a GEnumClass

nick

the nickname to look up

Returns

 the GEnumValue with nickname nick
,
or NULL if the enumeration doesn't have a member
with that nickname.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_flags_get_first_value ()

GFlagsValue *
g_flags_get_first_value (GFlagsClass *flags_class,
                         guint value);

Returns the first GFlagsValue which is set in value
.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

flags_class

a GFlagsClass

value

the value

Returns

 the first GFlagsValue which is set in
value
, or NULL if none is set.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_flags_get_value_by_name ()

GFlagsValue *
g_flags_get_value_by_name (GFlagsClass *flags_class,
                           const gchar *name);

Looks up a GFlagsValue by name.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

flags_class

a GFlagsClass

name

the name to look up

Returns

 the GFlagsValue with name name
,
or NULL if there is no flag with that name.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_flags_get_value_by_nick ()

GFlagsValue *
g_flags_get_value_by_nick (GFlagsClass *flags_class,
                           const gchar *nick);

Looks up a GFlagsValue by nickname.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

flags_class

a GFlagsClass

nick

the nickname to look up

Returns

 the GFlagsValue with nickname nick
,
or NULL if there is no flag with that nickname.

[<acronym title="Don't free data after the code is done.">transfer none</acronym>]

g_enum_register_static ()

GType
g_enum_register_static (const gchar *name,
                        const GEnumValue *const_static_values);

Registers a new static enumeration type with the name name
.

It is normally more convenient to let glib-mkenums,
generate a my_enum_get_type() function from a usual C enumeration
definition  than to write one yourself using g_enum_register_static().

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

name

A nul-terminated string used as the name of the new type.

const_static_values

An array of GEnumValue structs for the possible
enumeration values. The array is terminated by a struct with all
members being 0. GObject keeps a reference to the data, so it cannot
be stack-allocated.

Returns

 The new type identifier.

g_flags_register_static ()

GType
g_flags_register_static (const gchar *name,
                         const GFlagsValue *const_static_values);

Registers a new static flags type with the name name
.

It is normally more convenient to let glib-mkenums
generate a my_flags_get_type() function from a usual C enumeration
definition than to write one yourself using g_flags_register_static().

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

name

A nul-terminated string used as the name of the new type.

const_static_values

An array of GFlagsValue structs for the possible
flags values. The array is terminated by a struct with all members being 0.
GObject keeps a reference to the data, so it cannot be stack-allocated.

Returns

 The new type identifier.

g_enum_complete_type_info ()

void
g_enum_complete_type_info (GType g_enum_type,
                           GTypeInfo *info,
                           const GEnumValue *const_values);

This function is meant to be called from the complete_type_info
function of a GTypePlugin implementation, as in the following
example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

static void
my_enum_complete_type_info (GTypePlugin     *plugin,
                            GType            g_type,
                            GTypeInfo       *info,
                            GTypeValueTable *value_table)
{
  static const GEnumValue values[] = {
    { MY_ENUM_FOO, "MY_ENUM_FOO", "foo" },
    { MY_ENUM_BAR, "MY_ENUM_BAR", "bar" },
    { 0, NULL, NULL }
  };

  g_enum_complete_type_info (type, info, values);
}

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

g_enum_type

the type identifier of the type being completed

info

 the GTypeInfo struct to be filled in.

[<acronym title="Out parameter, where caller must allocate storage.">out callee-allocates</acronym>]

const_values

An array of GEnumValue structs for the possible
enumeration values. The array is terminated by a struct with all
members being 0.

g_flags_complete_type_info ()

void
g_flags_complete_type_info (GType g_flags_type,
                            GTypeInfo *info,
                            const GFlagsValue *const_values);

This function is meant to be called from the complete_type_info()
function of a GTypePlugin implementation, see the example for
g_enum_complete_type_info() above.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

g_flags_type

the type identifier of the type being completed

info

 the GTypeInfo struct to be filled in.

[<acronym title="Out parameter, where caller must allocate storage.">out callee-allocates</acronym>]

const_values

An array of GFlagsValue structs for the possible
enumeration values. The array is terminated by a struct with all
members being 0.

Types and Values

struct GEnumClass

struct GEnumClass {
  GTypeClass  g_type_class;

  gint	      minimum;
  gint	      maximum;
  guint	      n_values;
  GEnumValue *values;
};

The class of an enumeration type holds information about its
possible values.

Members

<colgroup>
<col width="300px" class="struct_members_name">
<col class="struct_members_description">
<col width="200px" class="struct_members_annotations">
</colgroup>

GTypeClass g_type_class;

the parent class

gint minimum;

the smallest possible value.

gint maximum;

the largest possible value.

guint n_values;

the number of possible values.

GEnumValue *values;

an array of GEnumValue structs describing the
individual values.

struct GFlagsClass

struct GFlagsClass {
  GTypeClass   g_type_class;

  guint	       mask;
  guint	       n_values;
  GFlagsValue *values;
};

The class of a flags type holds information about its
possible values.

Members

<colgroup>
<col width="300px" class="struct_members_name">
<col class="struct_members_description">
<col width="200px" class="struct_members_annotations">
</colgroup>

GTypeClass g_type_class;

the parent class

guint mask;

a mask covering all possible values.

guint n_values;

the number of possible values.

GFlagsValue *values;

an array of GFlagsValue structs describing the
individual values.

struct GEnumValue

struct GEnumValue {
  gint	 value;
  const gchar *value_name;
  const gchar *value_nick;
};

A structure which contains a single enum value, its name, and its
nickname.

Members

<colgroup>
<col width="300px" class="struct_members_name">
<col class="struct_members_description">
<col width="200px" class="struct_members_annotations">
</colgroup>

gint value;

the enum value

const gchar *value_name;

the name of the value

const gchar *value_nick;

the nickname of the value

struct GFlagsValue

struct GFlagsValue {
  guint	 value;
  const gchar *value_name;
  const gchar *value_nick;
};

A structure which contains a single flags value, its name, and its
nickname.

Members

<colgroup>
<col width="300px" class="struct_members_name">
<col class="struct_members_description">
<col width="200px" class="struct_members_annotations">
</colgroup>

guint value;

the flags value

const gchar *value_name;

the name of the value

const gchar *value_nick;

the nickname of the value

See Also

GParamSpecEnum, GParamSpecFlags, g_param_spec_enum(),
g_param_spec_flags()

Generated by GTK-Doc V1.24


text:
(function(){module.exports = require('./includes');

})();


text: extern void mobai(unsigned char i);


text:
require "spec_helper"
describe Auth0::Api::V2::Clients do
  before :all do
    dummy_instance = DummyClass.new
    dummy_instance.extend(Auth0::Api::V2::Clients)
    @instance = dummy_instance
  end
  context ".clients" do
    it {expect(@instance).to respond_to(:clients)}
    it {expect(@instance).to respond_to(:get_clients)}
    it "is expected to send get request to /api/v2/clients/" do
      expect(@instance).to receive(:get).with("/api/v2/clients", {})
      expect{@instance.clients}.not_to raise_error
    end
    it "is expected to send get request to /api/v2/clients?fields=name&exclude_fields=false" do
      expect(@instance).to receive(:get).with("/api/v2/clients",{exclude_fields: false, fields: [:name]})
      expect{@instance.clients({exclude_fields: false, fields: [:name]})}.not_to raise_error
    end
  end
  context ".client" do
    it {expect(@instance).to respond_to(:client)}
    it "is expected to send get request to /api/v2/clients/1" do
      expect(@instance).to receive(:get).with("/api/v2/clients/1", {})
      expect{@instance.client(1)}.not_to raise_error
    end
    it "is expected to send get request to /api/v2/clients?fields=name&exclude_fields=false" do
      expect(@instance).to receive(:get).with("/api/v2/clients/1",{exclude_fields: false, fields: [:name]})
      expect{@instance.client(1,{exclude_fields: false, fields: [:name]})}.not_to raise_error
    end
  end

  context ".create_client" do
    it {expect(@instance).to respond_to(:create_client)}
    it "is expected to send post to /api/v2/clients" do
      expect(@instance).to receive(:post).with("/api/v2/clients",{name: "name", opt: "opt"})
      expect{@instance.create_client("name", {name: "/name1", opt: "opt"})}.not_to raise_error
    end
  end
  context ".delete_client" do
    it {expect(@instance).to respond_to(:delete_client)}
    it "is expected to send delete to /api/v2/clients/1" do
      expect(@instance).to receive(:delete).with("/api/v2/clients/1")
      expect{@instance.delete_client("1")}.not_to raise_error
    end
  end

  context ".patch_client" do
    it {expect(@instance).to respond_to(:patch_client)}
    it "is expected to send patch to /api/v2/clients/1" do
      expect(@instance).to receive(:patch).with("/api/v2/clients/1", {fields: "fields"})
      expect{@instance.patch_client("1", {fields: "fields"})}.not_to raise_error
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using proconappAdmin.Models;
using proconappWrapper.DataObjects;

namespace proconappAdmin.Controllers
{
    /// <summary>
    /// 競技結果管理画面のコントローラ
    /// </summary>
    [Authorize]
    public class GamesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Games
        public ActionResult Index(int count = 20, int page = 0)
        {
            ViewBag.Count = count;
            ViewBag.Page = page;
            ViewBag.MaxPage = (db.Games.Count() - 1) / count;
            return View(db.Games
                .OrderByDescending(item=>item._id)
                .Skip(count * page)
                .Take(count)
                .ToList());
        }

        // GET: Games/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Game game = db.Games.Find(id);
            if (game == null)
            {
                return HttpNotFound();
            }
            return View(game);
        }

        // GET: Games/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Game game = db.Games.Find(id);
            if (game == null)
            {
                return HttpNotFound();
            }
            return View(game);
        }

        // POST: Games/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [AccessFilterAttribute]
        public ActionResult DeleteConfirmed(int id)
        {
            Game game = db.Games.Find(id);
            db.Games.Remove(game);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


text:
package com.evolveum.midpoint.prism.lex;

import com.evolveum.midpoint.prism.lex.json.JsonLexicalProcessor;
import com.evolveum.midpoint.prism.util.PrismTestUtil;

public class TestJsonParser extends AbstractJsonLexicalProcessorTest {

	@Override
	protected String getSubdirName() {
		return "json";
	}

	@Override
	protected String getFilenameSuffix() {
		return "json";
	}

	@Override
	protected JsonLexicalProcessor createParser() {
		return new JsonLexicalProcessor(PrismTestUtil.getSchemaRegistry());
	}

	@Override
	protected String getWhenItemSerialized() {
		return "\"when\" : \"2012-02-24T10:48:52.000Z\"";
	}
}


text:
<?php

class DropoutCollection extends BaseDropoutCollection
{
	public static function getBySchool($sid){
		$peer_object = new Dropout();
		return self::getCollection($peer_object, $peer_object->getSelectQuery() . " WHERE school_id=\"$sid\"" );
	}

	public static function getYearsSupported(){
		$db = self::fetchDB();
		$Select = "SELECT DISTINCT year from dropout ORDER by year asc;";
		$stmt = $db->prepare($Select);
		$stmt->execute();
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		return $result;
	}

	public static function getDropoutsByYear($year){
		$query = "select c.lat,c.lng,year, AVG(nine2twelve) as n2t, AVG(seven2twelve) as s2t, i.name, i.county from dropout d inner join institute i on i.school_id = d.school_id inner join county c on c.name = i.county where year=$year group by i.county,year";
		$db = self::fetchDB();
		$stmt = $db->prepare($query);
		$stmt->execute();
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		return $result;
	}
}


text:
TODO authentication

TODO service mesh?

### 9.5. Split API into two microservices

Builds take time, upgrades are tedious for the full codebase, different parts of the software too tightly coupled, reusability of services, ...

(NOTE: For more complex microservice setups you may need: 16. api gateway, 17. service mesh)

### 9.6. Alternative technologies

---

**Next:** [10. Production setup](10-production-setup.md)


text:
var lastDate ="";
var loadedLayers = [];

L.Playback = L.Playback || {};

L.Playback.Util = L.Class.extend({
  statics: {

    DateStr: function(time) {
      return new Date(time).toDateString();
    },

    TimeStr: function(time) {
      var d = new Date(time);
      var h = d.getHours();
      var m = d.getMinutes();
      var s = d.getSeconds();
      var tms = time / 1000;
      var dec = (tms - Math.floor(tms)).toFixed(2).slice(1);
      var mer = 'AM';
      if (h > 11) {
        h %= 12;
        mer = 'PM';
      }
      if (h === 0) h = 12;
      if (m < 10) m = '0' + m;
      if (s < 10) s = '0' + s;
      return h + ':' + m + ':' + s + dec + ' ' + mer;
    },

    ParseGPX: function(gpx) {
      var geojson = {
        type: 'Feature',
        geometry: {
          type: 'MultiPoint',
          coordinates: []
        },
        properties: {
          time: [],
          speed: [],
          altitude: []
        },
        bbox: []
      };
      var xml = $.parseXML(gpx);
      var pts = $(xml).find('trkpt');
      for(var i=0, len=pts.length; i<len; i++){
        var p = pts[i];
        var lat = parseFloat(p.getAttribute('lat'));
        var lng = parseFloat(p.getAttribute('lon'));
        var timeStr = $(p).find('time').text();
        var eleStr = $(p).find('ele').text();
        var t = new Date(timeStr).getTime();
        var ele = parseFloat(eleStr);

        var coords = geojson.geometry.coordinates;
        var props = geojson.properties;
        var time = props.time;
        var altitude = geojson.properties.altitude;

        coords.push([lng,lat]);
        time.push(t);
        altitude.push(ele);
      }
      return geojson;
    }
  }

});

L.Playback = L.Playback || {};

L.Playback.MoveableMarker = L.Marker.extend({
    initialize: function (startLatLng, options, feature) {
        var marker_options = options.marker || {};

        if (jQuery.isFunction(marker_options)){
            marker_options = marker_options(feature);
        }

        L.Marker.prototype.initialize.call(this, startLatLng, marker_options);

        this.popupContent = '';

        if (marker_options.getPopup){
            this.popupContent = marker_options.getPopup(feature);
        }

        this.bindPopup(this.getPopupContent() + startLatLng.toString());
    },

    getPopupContent: function(){
        if (this.popupContent != ''){
            return '' + this.popupContent + '
'
        }

        return '';
    },

    move: function (latLng, transitionTime) {
        // Only if CSS3 transitions are supported
        if (L.DomUtil.TRANSITION) {
            if (this._icon) {
                this._icon.style[L.DomUtil.TRANSITION] = 'all ' + transitionTime + 'ms linear';
                if (this._popup && this._popup._wrapper)
                    this._popup._wrapper.style[L.DomUtil.TRANSITION] = 'all ' + transitionTime + 'ms linear';
            }
            if (this._shadow) {
                this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + transitionTime + 'ms linear';
            }
        }
        this.setLatLng(latLng);
        if (this._popup){
            this._popup.setContent(this.getPopupContent() + this._latlng.toString());
        }
    }
});

L.Playback = L.Playback || {};

L.Playback.Track = L.Class.extend({

        initialize : function (geoJSON, options) {
            options = options || {};
            var tickLen = options.tickLen || 250;

            this._geoJSON = geoJSON;
            this._tickLen = tickLen;
            this._ticks = [];
            this._marker = null;

            var sampleTimes = geoJSON.properties.time;
            var samples = geoJSON.geometry.coordinates;
            var currSample = samples[0];
            var nextSample = samples[1];
            var t = currSampleTime = sampleTimes[0]; // t is used to iterate through tick times
            var nextSampleTime = sampleTimes[1];
            var tmod = t % tickLen; // ms past a tick time
            var rem,
            ratio;

            // handle edge case of only one t sample
            if (sampleTimes.length === 1) {
                if (tmod !== 0)
                    t += tickLen - tmod;
                this._ticks[t] = samples[0];
                this._startTime = t;
                this._endTime = t;
                return;
            }

            // interpolate first tick if t not a tick time
            if (tmod !== 0) {
                rem = tickLen - tmod;
                ratio = rem / (nextSampleTime - currSampleTime);
                t += rem;
                this._ticks[t] = this._interpolatePoint(currSample, nextSample, ratio);
            } else {
                this._ticks[t] = currSample;
            }

            this._startTime = t;
            t += tickLen;
            while (t < nextSampleTime) {
                ratio = (t - currSampleTime) / (nextSampleTime - currSampleTime);
                this._ticks[t] = this._interpolatePoint(currSample, nextSample, ratio);
                t += tickLen;
            }

            // iterating through the rest of the samples
            for (var i = 1, len = samples.length; i < len; i++) {
                currSample = samples[i];
                nextSample = samples[i + 1];
                t = currSampleTime = sampleTimes[i];
                nextSampleTime = sampleTimes[i + 1];

                tmod = t % tickLen;
                if (tmod != 0 && nextSampleTime) {
                    rem = tickLen - tmod;
                    ratio = rem / (nextSampleTime - currSampleTime);
                    t += rem;
                    this._ticks[t] = this._interpolatePoint(currSample, nextSample, ratio);
                } else {
                    this._ticks[t] = currSample;
                }

                t += tickLen;
                while (t < nextSampleTime) {
                    ratio = (t - currSampleTime) / (nextSampleTime - currSampleTime);

                    if (nextSampleTime - currSampleTime > options.maxInterpolationTime){
                        this._ticks[t] = currSample;
                    }
                    else {
                        this._ticks[t] = this._interpolatePoint(currSample, nextSample, ratio);
                    }

                    t += tickLen;
                }
            }

            // the last t in the while would be past bounds
            this._endTime = t - tickLen;
            this._lastTick = this._ticks[this._endTime];

        },

        _interpolatePoint : function (start, end, ratio) {
            try {
                var delta = [end[0] - start[0], end[1] - start[1]];
                var offset = [delta[0] * ratio, delta[1] * ratio];
                return [start[0] + offset[0], start[1] + offset[1]];
            } catch (e) {
                console.log('err: cant interpolate a point');
                console.log(['start', start]);
                console.log(['end', end]);
                console.log(['ratio', ratio]);
            }
        },

        getFirstTick : function () {
            return this._ticks[this._startTime];
        },

        getLastTick : function () {
            return this._ticks[this._endTime];
        },

        getStartTime : function () {
            return this._startTime;
        },

        getEndTime : function () {
            return this._endTime;
        },

        getTickMultiPoint : function () {
            var t = this.getStartTime();
            var endT = this.getEndTime();
            var coordinates = [];
            var time = [];
            while (t <= endT) {
                time.push(t);
                coordinates.push(this.tick(t));
                t += this._tickLen;
            }

            return {
                type : 'Feature',
                geometry : {
                    type : 'MultiPoint',
                    coordinates : coordinates
                },
                properties : {
                    time : time
                }
            };
        },

        tick : function (timestamp) {
            if (timestamp > this._endTime)
                timestamp = this._endTime;
            if (timestamp < this._startTime)
                timestamp = this._startTime;
            return this._ticks[timestamp];
        },

        setMarker : function(timestamp, options){
            var lngLat = null;

            // if time stamp is not set, then get first tick
            if (timestamp){
                lngLat = this.tick(timestamp);
            }
            else {
                lngLat = this.getFirstTick();
            }

            if (lngLat){
                var latLng = new L.LatLng(lngLat[1], lngLat[0]);
                this._marker = new L.Playback.MoveableMarker(latLng, options, this._geoJSON);
            }

            return this._marker;
        },

        moveMarker : function(latLng, transitionTime){
            if (this._marker){
                this._marker.move(latLng, transitionTime);
            }
        },

        getMarker : function(){
            return this._marker;
        }

    });
L.Playback = L.Playback || {};

L.Playback.TrackController = L.Class.extend({

    initialize : function (map, tracks, options) {
        this.options = options || {};

        this._map = map;

        this._tracks = [];

        // initialize tick points
        this.setTracks(tracks);
    },

    clearTracks: function(){
        while (this._tracks.length > 0){
            var track = this._tracks.pop();
            var marker = track.getMarker();

            if (marker){
                this._map.removeLayer(marker);
            }
        }
    },

    setTracks : function (tracks){
        // reset current tracks
        this.clearTracks();

        this.addTracks(tracks);
    },

    addTracks : function (tracks) {
        // return if nothing is set
        if (!tracks){
            return;
        }

        if (tracks instanceof Array) {
            for (var i = 0, len = tracks.length; i < len; i++) {
                this.addTrack(tracks[i]);
            }
        } else {
            this.addTrack(tracks);
        }
    },

    // add single track
    addTrack : function (track, timestamp) {
        // return if nothing is set
        if (!track){
            return;
        }

        var marker = track.setMarker(timestamp, this.options);

        if (marker){
            marker.addTo(this._map);

            this._tracks.push(track);
        }
    },

    tock : function (timestamp, transitionTime) {
        for (var i = 0, len = this._tracks.length; i < len; i++) {
            var lngLat = this._tracks[i].tick(timestamp);
            var latLng = new L.LatLng(lngLat[1], lngLat[0]);
            this._tracks[i].moveMarker(latLng, transitionTime);
        }
    },

    getStartTime : function () {
        var earliestTime = 0;

        if (this._tracks.length > 0){
            earliestTime = this._tracks[0].getStartTime();
            for (var i = 1, len = this._tracks.length; i < len; i++) {
                var t = this._tracks[i].getStartTime();
                if (t < earliestTime)
                    earliestTime = t;
            }
        }

        return earliestTime;
    },

    getEndTime : function () {
        var latestTime = 0;

        if (this._tracks.length > 0){
            latestTime = this._tracks[0].getEndTime();
            for (var i = 1, len = this._tracks.length; i < len; i++) {
                var t = this._tracks[i].getEndTime();
                if (t > latestTime)
                    latestTime = t;
            }
        }

        return latestTime;
    },

    getTracks : function () {
        return this._tracks;
    }
});
L.Playback = L.Playback || {};

L.Playback.Clock = L.Class.extend({

  initialize: function (trackController, callback, options) {
    this._trackController = trackController;
    this._callbacksArry = [];
    if (callback) this.addCallback(callback);
    L.setOptions(this, options);
    this._speed = this.options.speed;
    this._tickLen = this.options.tickLen;
    this._cursor = trackController.getStartTime();
    this._transitionTime = 0.000000000000001; //this._tickLen / this._speed;
  },

  _tick: function (self) {
    if (self._cursor > self._trackController.getEndTime()) {
      clearInterval(self._intervalID);
      return;
    }
    self._trackController.tock(self._cursor, self._transitionTime);
    self._callbacks(self._cursor);
    self._cursor += self._tickLen;
  },

  _callbacks: function(cursor) {
    var arry = this._callbacksArry;
    for(var i=0, len=arry.length; i<len; i++){
      arry[i](cursor);
    }
  },

  addCallback: function(fn) {
    this._callbacksArry.push(fn);
  },

  start: function () {
    if (this._intervalID) return;
    this._intervalID = window.setInterval(
      this._tick,
      this._transitionTime,
      this);
  },

  stop: function () {
    if (!this._intervalID) return;
    clearInterval(this._intervalID);
    this._intervalID = null;
  },

  getSpeed: function() {
    return this._speed;
  },

  isPlaying: function() {
    return this._intervalID ? true : false;
  },

  setSpeed: function (speed) {
    this._speed = speed;
    this._transitionTime = 0.000000000000001; //this._tickLen / speed;
    if (this._intervalID) {
      this.stop();
      this.start();
    }
  },

  setCursor: function (ms) {
    var time = parseInt(ms);
    if (!time) return;
    var mod = time % this._tickLen;
    if (mod !== 0) {
      time += this._tickLen - mod;
    }
    this._cursor = time;
    this._trackController.tock(this._cursor, 0);
    this._callbacks(this._cursor);
  },

  getTime: function() {
    return this._cursor;
  },

  getStartTime: function() {
    return this._trackController.getStartTime();
  },

  getEndTime: function() {
    return this._trackController.getEndTime();
  },

  getTickLen: function() {
    return this._tickLen;
  }

});

// Simply shows all of the track points as circles.
// TODO: Associate circle color with the marker color.

L.Playback = L.Playback || {};

L.Playback.TracksLayer = L.Class.extend({
    initialize : function (map, options) {
        var layer_options = options.layer || {};

        if (jQuery.isFunction(layer_options)){
            layer_options = layer_options(feature);
        }

        if (!layer_options.pointToLayer){
            layer_options.pointToLayer = function (featureData, latlng) {
                return new L.CircleMarker(latlng, { radius : 5 });
            }
        }

        this.layer = new L.GeoJSON(null, layer_options);
/*
        var overlayControl = {
            'GPS Tracks' : this.layer
        };

        L.control.layers(null, overlayControl, {
            collapsed : false
        }).addTo(map);

        */
    },

    // clear all geoJSON layers
    clearLayer : function(){
        for (var i in this.layer._layers){
            this.layer.removeLayer(this.layer._layers[i]);
        }
    },

    // add new geoJSON layer
    addLayer : function(geoJSON){
        this.layer.addData(geoJSON);
    }
});
L.Playback = L.Playback || {};

L.Playback.DateControl = L.Control.extend({
    options : {
        position : 'bottomleft'
    },

    initialize : function (playback) {
        this.playback = playback;
    },

    onAdd : function (map) {
        this._container = L.DomUtil.create('div', '');

        var self = this;
        var playback = this.playback;
        var time = playback.getTime();

        var datetime = L.DomUtil.create('div', 'datetimeControl', this._container);

        // date time
        this._date = L.DomUtil.create('input', 'datetimeValue', datetime);
       // this._time = L.DomUtil.create('p', '', datetime);

      //  this._date = L.DomUtil.create('input', 'slider', this._container);
        this._date.type = 'number';
        this._date.min = -10000;
        this._date.max = 2000;
        this._date.value = new Date(time).getFullYear();

       //     this._date.innerHTML = new Date(time).getFullYear();//L.Playback.Util.DateStr(time);

     //   this._time.innerHTML = L.Playback.Util.TimeStr(time);

       // console.debug("!!datetime, time",datetime, time)

        // setup callback
        playback.addCallback(function (ms) {
         //   console.debug(ms,L.Playback.Util.DateStr(ms));
            var newDate = new Date(ms).getFullYear();

            if (lastDate != newDate){

                //TODO: text, g supposed to be empty _
            //    $("text").empty()
            //    $("g").empty()
                currLabel = 0;
                isNewDate = true;
                console.log("year changed from",lastDate,"to",newDate);

                /*

                 var sortRuler = [];
                 var sortCul = [];
                 var sortRel = [];

                 var total = 0;
                 var rulerPops = {}
                 var culPops = {}
                 var relPops = {}
                 var mainRelPops = {}

                 for (var key in y1500) {
                     total +=  y1500[key][4]

                     if (isNaN(rulerPops[y1500[key][0]])){
                        rulerPops[y1500[key][0]] = y1500[key][4];
                     } else {
                        rulerPops[y1500[key][0]] += y1500[key][4];
                     }

                     if (isNaN(culPops[y1500[key][1]])){
                        culPops[y1500[key][1]] = y1500[key][4];
                     } else {
                        culPops[y1500[key][1]] += y1500[key][4];
                     }

                     if (isNaN(relPops[y1500[key][2]])){
                        relPops[y1500[key][2]] = y1500[key][4];
                     } else {
                        relPops[y1500[key][2]] += y1500[key][4];
                     }
                 }

                 sortRuler = [];
                 sortCul = [];
                 sortRel = [];

                 for (var key in rulerPops)
                    sortRuler.push([key, rulerPops[key]])
                 for (var key in culPops)
                    sortCul.push([key, culPops[key]])
                 for (var key in relPops)
                    sortRel.push([key, relPops[key]])

                 sortRuler.sort(function(b, a) {return a[1] - b[1]})
                 sortCul.sort(function(b, a) {return a[1] - b[1]})
                 sortRel.sort(function(b, a) {return a[1] - b[1]})

                 */

                if(loadedLayers.indexOf(newDate) == -1){
                    staticLayerThis.createDataLayer({"displayOnLoad":false,"name":newDate.toString(),"id":newDate,"remoteData":{}})
                    loadedLayers.push(newDate)
                }

                if($("#year_"+lastDate).length != 0)
                    $("#year_"+lastDate).find(".layer-toggle")[0].click()
                if($("#year_"+newDate).length != 0)
                    $("#year_"+newDate).find(".layer-toggle")[0].click()
                lastDate = newDate;

                self._date.value = (newDate.toString().indexOf("-") === -1) ? newDate : newDate; //newDate.toString().substr(1) + " BC"; // L.Playback.Util.DateStr(1369786384250);
                //hideAllUnchecked();

                if  ($(".datetimeValue").hasClass('leaflet-clickable')){
                if(true) { //$(".datetimeValue")[0].innerHTML.substring(0,1) != "-"){
                    newObject.properties.description = "chronasYear"+$(".datetimeValue")[0].value;
                }
                else{
                    newObject.properties.description = "chronasYear"+$(".datetimeValue")[0].value.substr(1)+"_BC";
                }
                L.DomEvent.on($(".datetimeValue")[0], 'click', newObject._onMouseClick, newObject);
                }

                if($("#chronasWiki").hasClass("wikiYear")){

                    $("#chronasWiki")[0].setAttribute("src",newObject.properties.description.replace("chronasYear","http://en.wikipedia.org/wiki/")+"?printable=yes")
                }

                //$("#browse_data_toggle_4").find(".layer-toggle")[0].click()
            }

     //       self._time.innerHTML = L.Playback.Util.TimeStr(ms);
        });

        if (!L.Browser.touch) {
            L.DomEvent.disableClickPropagation(this._container);
            L.DomEvent.on(this._container, 'mousewheel', L.DomEvent.stopPropagation);
            L.DomEvent.on(this._container, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
        } else {
            L.DomEvent.on(this._container, 'click', L.DomEvent.stopPropagation);
        }

        return this._container;
    }
});

L.Playback.PlayControl = L.Control.extend({
    options : {
        position : 'bottomright'
    },

    initialize : function (playback) {
        this.playback = playback;
    },

    onAdd : function (map) {
        this._container = L.DomUtil.create('div', 'leaflet-control-layers leaflet-control-layers-expanded');

        var self = this;
        var playback = this.playback;
        playback.setSpeed(100000000000000000);

        var playControl = L.DomUtil.create('div', 'playControl', this._container);

        this._button = L.DomUtil.create('button', '', playControl);
        this._button.innerHTML = 'Play';

        var stop = L.DomEvent.stopPropagation;

        L.DomEvent
        .on(this._button, 'click', stop)
        .on(this._button, 'mousedown', stop)
        .on(this._button, 'dblclick', stop)
        .on(this._button, 'click', L.DomEvent.preventDefault)
        .on(this._button, 'click', play, this);

        function play(){
            if (playback.isPlaying()){
                playback.stop();
                self._button.innerHTML = 'Play';
            }
            else {
                playback.start();
                self._button.innerHTML = 'Stop';
            }
        }

        return this._container;
    }
});

L.Playback.SliderControl = L.Control.extend({
    options : {
        position : 'bottomleft'
    },

    initialize : function (playback) {
        this.playback = playback;
    },

    onAdd : function (map) {

        this._container = L.DomUtil.create('div', 'leaflet-control-layers leaflet-control-layers-expanded');

        var self = this;
        var playback = this.playback;

        // slider
        this._slider = L.DomUtil.create('input', 'slider', this._container);
        this._slider.type = 'range';
        this._slider.min = playback.getStartTime();
        this._slider.max = playback.getEndTime();
        this._slider.value = playback.getTime();

        var stop = L.DomEvent.stopPropagation;

        L.DomEvent
        .on(this._slider, 'click', stop)
        .on(this._slider, 'mousedown', stop)
        .on(this._slider, 'dblclick', stop)
        .on(this._slider, 'click', L.DomEvent.preventDefault)
        //.on(this._slider, 'mousemove', L.DomEvent.preventDefault)
        .on(this._slider, 'change', onSliderChange, this)
        .on(this._slider, 'mousemove', onSliderChange, this);

        function onSliderChange(e) {
            var val = Number(e.target.value);
            playback.setCursor(val);
        }

        playback.addCallback(function (ms) {
            self._slider.value = ms;
        });

        map.on('playback:add_tracks', function(){

            self._slider.min = playback.getStartTime();
            self._slider.max = playback.getEndTime();
            self._slider.value = playback.getTime();
        });

        return this._container;
    }
});

L.Playback = L.Playback.Clock.extend({
        statics : {
            MoveableMarker : L.Playback.MoveableMarker,
            Track : L.Playback.Track,
            TrackController : L.Playback.TrackController,
            Clock : L.Playback.Clock,
            Util : L.Playback.Util,

            TracksLayer : L.Playback.TracksLayer,
            PlayControl : L.Playback.PlayControl,
            DateControl : L.Playback.DateControl,
            SliderControl : L.Playback.SliderControl
        },

        options : {
            tickLen: 250,
            speed: 1,
            maxInterpolationTime: 5*60*1000, // 5 minutes

            tracksLayer : true,

            playControl: false,
            dateControl: false,
            sliderControl: false,

            // options
            layer: {
                // pointToLayer(featureData, latlng)
            },

            marker : {
                // getPopup(feature)
            }
        },

        initialize : function (map, geoJSON, callback, options) {
            L.setOptions(this, options);

            this._map = map;
            this._trackController = new L.Playback.TrackController(map, null, this.options);
            L.Playback.Clock.prototype.initialize.call(this, this._trackController, callback, this.options);

            if (this.options.tracksLayer) {
                this._tracksLayer = new L.Playback.TracksLayer(map, options);
            }

            this.setData(geoJSON);

            if (this.options.playControl) {
                this.playControl = new L.Playback.PlayControl(this);
                this.playControl.addTo(map);
            }

            if (this.options.sliderControl) {
                this.sliderControl = new L.Playback.SliderControl(this);
                this.sliderControl.addTo(map);
            }

            if (this.options.dateControl) {
                this.dateControl = new L.Playback.DateControl(this);
                this.dateControl.addTo(map);
            }

        },

        clearData : function(){
            this._trackController.clearTracks();

            if (this._tracksLayer){
                this._tracksLayer.clearLayer();
            }
        },

        setData : function (geoJSON) {
            this.clearData();

            this.addData(geoJSON, this.getTime());

            this.setCursor(this.getStartTime());
        },

        // bad implementation
        addData : function (geoJSON, ms) {
            if (!geoJSON){
                return;
            }

            if (geoJSON instanceof Array) {
                for (var i = 0, len = geoJSON.length; i < len; i++) {
                    this._trackController.addTrack(new L.Playback.Track(geoJSON[i], this.options), ms);
                }
            } else {
                this._trackController.addTrack(new L.Playback.Track(geoJSON, this.options), ms);
            }

            this._map.fire('playback:set:data');

            if (this.options.tracksLayer) {
                this._tracksLayer.addLayer(geoJSON);
            }
        }
    });

L.Map.addInitHook(function () {
    if (this.options.playback) {
        this.playback = new L.Playback(this);
    }
});

L.playback = function (map, geoJSON, callback, options) {
    return new L.Playback(map, geoJSON, callback, options);
};


text:
static NSString *const kPXApiEndPointUrl = @"http://playerxtracker.herokuapp.com/v1.1/";
static NSString *const kPXGetUserPredictionsUrl = @"http://gistats.herokuapp.com/getUserPredictions/%@/%@";

static NSInteger kPXDynamicUpdateInterval = 1.0f * 60;
static NSInteger kPXCacheUpdateInterval = 1.0f * 65 * 5;
static NSInteger kPXRequestUserPredictionsInterval = 60;
static NSString *const kPXLockboxUUDIDKey = @"uudid";
static NSString *const kPXLevelKeyStore = @"userLevel";
static NSString *const kPXTriggerDateKeyStore = @"triggerDate";
static NSString *const kPXRewardAlreadyShownToday = @"rewardAlreadyShown";
static NSString *const kPXRewardLastSyncDate = @"lastSyncDate";
static char *const kPXFileQueueLockerName = "PXEventBufferQueue";
static NSString *const kPXCacheFileName = @"PXTrackerCache.data";

static const BOOL kPXLogsEnabled = YES;
static NSString *const kPXLogsTag = @"[PXSDK] ";

static inline void PXLog(NSString *format, ...) {
    if (kPXLogsEnabled) {
        va_list argList;
        va_start(argList, format);
        NSString *string = [kPXLogsTag stringByAppendingString:format];
        NSLogv(string, argList);
        va_end(argList);
    }
}

#endif


text:
/** Defines utilities used by the Dataflow SDK. **/
package com.google.cloud.dataflow.sdk.util;


text:
<?php namespace App\Providers;

use Illuminate\Bus\Dispatcher;
use Illuminate\Support\ServiceProvider;

class BusServiceProvider extends ServiceProvider {

	/**
	 * Bootstrap any application services.
	 *
	 * @param  \Illuminate\Bus\Dispatcher  $dispatcher
	 * @return void
	 */
	public function boot(Dispatcher $dispatcher)
	{
		$dispatcher->mapUsing(function($command)
		{
			return Dispatcher::simpleMapping(
				$command, 'App\Commands', 'App\Handlers\Commands'
			);
		});
	}

	/**
	 * Register any application services.
	 *
	 * @return void
	 */
	public function register()
	{
		//
	}

	public function invitation()
	{
		//
	}
}


text: A HIDShortItemParserTest is a test class for testing the behavior of HIDShortItemParser


text:
<?php
// This file generated by Propel 1.6.8 convert-conf target
// from XML runtime conf file M:\My Programs\kreader\runtime-conf.xml
$conf = array (
  'datasources' =>
  array (
    'kreader' =>
    array (
      'adapter' => 'mysql',
      'connection' =>
      array (
        'dsn' => 'mysql:host=localhost;dbname=kreader',
        'user' => 'username',
        'password' => 'password',
      ),
    ),
    'default' => 'kreader',
  ),
  'generator_version' => '1.6.8',
);
$conf['classmap'] = include(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classmap-kreader-conf.php');
return $conf;


text:
package org.zmlx.hg4idea.execution;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Nadya Zabrodina
 */
public class HgDeleteModifyPromptHandler implements HgPromptHandler {

  private static final Logger LOG = Logger.getInstance("#org.zmlx.hg4idea.execution.HgDeleteModifyPromptHandler");

  private static final Pattern LOCAL_DELETE_REMOTE_MODIFIED_CONFLICT_MESSAGE_PATTERN = Pattern.compile(
    "remote\\schanged(.+)which\\slocal\\sdeleted\\s.+");
  private static final Pattern REMOTE_DELETE_LOCAL_MODIFIED_CONFLICT_MESSAGE_PATTERN = Pattern.compile(
    "\\slocal\\schanged(.+)which\\sremote\\sdeleted\\s.+");

  public HgPromptChoice promptUser(@NotNull final String message,
                                   @NotNull final HgPromptChoice[] choices,
                                   @NotNull final HgPromptChoice defaultChoice) {

    Matcher localDelMatcher = LOCAL_DELETE_REMOTE_MODIFIED_CONFLICT_MESSAGE_PATTERN.matcher(message);
    Matcher localModifyMatcher = REMOTE_DELETE_LOCAL_MODIFIED_CONFLICT_MESSAGE_PATTERN.matcher(message);
    String filename;
    final String modifiedMessage;
    if (localDelMatcher.matches()) {
      filename = localDelMatcher.group(1);
      modifiedMessage =
        "File " + filename + " is deleted locally, but modified remotely. Do you want to keep the modified version or remove the file?";
    }
    else if (localModifyMatcher.matches()) {
      filename = localModifyMatcher.group(1);
      modifiedMessage =
        "File " + filename + " is deleted remotely, but modified locally. Do you want to keep the modified version or remove the file?";
    }
    else {
      modifiedMessage = message;
    }
    final int[] chosen = new int[]{-1};
    try {
      EventQueue.invokeAndWait
        (new Runnable() {
          public void run() {
            String[] choicePresentationArray = new String[choices.length];
            for (int i = 0; i < choices.length; ++i) {
              choicePresentationArray[i] = choices[i].toString();
            }
            chosen[0] = Messages
              .showDialog(modifiedMessage, "Delete-Modify Conflict",
                          choicePresentationArray, defaultChoice.getChosenIndex(),
                          Messages.getQuestionIcon());
          }
        });
    }
    catch (InterruptedException e) {
      LOG.error(e);
      return defaultChoice;
    }
    catch (InvocationTargetException e) {
      LOG.error(e);
      return defaultChoice;
    }
    return chosen[0] >= 0 ? choices[chosen[0]] : HgPromptChoice.ABORT;
  }

  public boolean shouldHandle(@Nullable String message) {
    if (message == null) {
      return false;
    }
    Matcher localDelMatcher = LOCAL_DELETE_REMOTE_MODIFIED_CONFLICT_MESSAGE_PATTERN.matcher(message);
    Matcher localModifyMatcher = REMOTE_DELETE_LOCAL_MODIFIED_CONFLICT_MESSAGE_PATTERN.matcher(message);
    if (localDelMatcher.matches() || localModifyMatcher.matches()) {
      return true;
    }
    return false;
  }
}


text:
package org.wso2.siddhi.core.partition.executor;

import org.wso2.siddhi.core.event.AtomicEvent;
import org.wso2.siddhi.core.executor.expression.ExpressionExecutor;

public class VariablePartitionExecutor implements PartitionExecutor {

    private ExpressionExecutor expressionExecutor;

    public VariablePartitionExecutor(ExpressionExecutor expressionExecutor) {
        this.expressionExecutor = expressionExecutor;
    }

    public String execute(AtomicEvent event) {
        return expressionExecutor.execute(event).toString();
    }

}


text:
pub struct Foo;

pub trait Bar {}

impl Bar for Foo {}

pub struct DoesNotImplementTrait;

pub struct ImplementsWrongTraitConditionally<T> {
    _marker: std::marker::PhantomData<T>,
}

impl Bar for ImplementsWrongTraitConditionally<isize> {}