text:
package com.fsck.k9;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;

import com.fsck.k9.Account.SortType;
import com.fsck.k9.activity.MessageCompose;
import com.fsck.k9.activity.UpgradeDatabases;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.SimpleMessagingListener;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.K9MailLib;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.internet.BinaryTempFileBody;
import com.fsck.k9.mail.ssl.LocalKeyStore;
import com.fsck.k9.mailstore.LocalStore;
import com.fsck.k9.power.DeviceIdleManager;
import com.fsck.k9.preferences.Storage;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.provider.UnreadWidgetProvider;
import com.fsck.k9.service.BootReceiver;
import com.fsck.k9.service.MailService;
import com.fsck.k9.service.ShutdownReceiver;
import com.fsck.k9.service.StorageGoneReceiver;
import com.fsck.k9.widget.list.MessageListWidgetProvider;
import timber.log.Timber;
import timber.log.Timber.DebugTree;

public class K9 extends Application {
    /**
     * Components that are interested in knowing when the K9 instance is
     * available and ready (Android invokes Application.onCreate() after other
     * components') should implement this interface and register using
     * {@link K9#registerApplicationAware(ApplicationAware)}.
     */
    public static interface ApplicationAware {
        /**
         * Called when the Application instance is available and ready.
         *
         * @param application
         *            The application instance. Never null.
         * @throws Exception
         */
        void initializeComponent(Application application);
    }

    public static Application app = null;
    public static File tempDirectory;
    public static final String LOG_TAG = "k9";

    /**
     * Name of the {@link SharedPreferences} file used to store the last known version of the
     * accounts' databases.
     *
     *

     * See {@link UpgradeDatabases} for a detailed explanation of the database upgrade process.
     *

     */
    private static final String DATABASE_VERSION_CACHE = "database_version_cache";

    /**
     * Key used to store the last known database version of the accounts' databases.
     *
     * @see #DATABASE_VERSION_CACHE
     */
    private static final String KEY_LAST_ACCOUNT_DATABASE_VERSION = "last_account_database_version";

    /**
     * Components that are interested in knowing when the K9 instance is
     * available and ready.
     *
     * @see ApplicationAware
     */
    private static final List<ApplicationAware> observers = new ArrayList<ApplicationAware>();

    /**
     * This will be {@code true} once the initialization is complete and {@link #notifyObservers()}
     * was called.
     * Afterwards calls to {@link #registerApplicationAware(com.fsck.k9.K9.ApplicationAware)} will
     * immediately call {@link com.fsck.k9.K9.ApplicationAware#initializeComponent(K9)} for the
     * supplied argument.
     */
    private static boolean sInitialized = false;

    public enum BACKGROUND_OPS {
        ALWAYS, NEVER, WHEN_CHECKED_AUTO_SYNC
    }

    private static String language = "";
    private static Theme theme = Theme.LIGHT;
    private static Theme messageViewTheme = Theme.USE_GLOBAL;
    private static Theme composerTheme = Theme.USE_GLOBAL;
    private static boolean useFixedMessageTheme = true;

    private static final FontSizes fontSizes = new FontSizes();

    private static BACKGROUND_OPS backgroundOps = BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC;
    /**
     * Some log messages can be sent to a file, so that the logs
     * can be read using unprivileged access (eg. Terminal Emulator)
     * on the phone, without adb.  Set to null to disable
     */
    public static final String logFile = null;
    //public static final String logFile = Environment.getExternalStorageDirectory() + "/k9mail/debug.log";

    /**
     * If this is enabled, various development settings will be enabled
     * It should NEVER be on for Market builds
     * Right now, it just governs strictmode
     **/
    public static boolean DEVELOPER_MODE = BuildConfig.DEVELOPER_MODE;

    /**
     * If this is enabled there will be additional logging information sent to
     * Log.d, including protocol dumps.
     * Controlled by Preferences at run-time
     */
    private static boolean DEBUG = false;

    /**
     * If this is enabled than logging that normally hides sensitive information
     * like passwords will show that information.
     */
    public static boolean DEBUG_SENSITIVE = false;

    /**
     * Can create messages containing stack traces that can be forwarded
     * to the development team.
     *
     * Feature is enabled when DEBUG == true
     */
    public static final String ERROR_FOLDER_NAME = "K9mail-errors";

    /**
     * A reference to the {@link SharedPreferences} used for caching the last known database
     * version.
     *
     * @see #checkCachedDatabaseVersion()
     * @see #setDatabasesUpToDate(boolean)
     */
    private static SharedPreferences sDatabaseVersionCache;

    private static boolean mAnimations = true;

    private static boolean mConfirmDelete = false;
    private static boolean mConfirmDiscardMessage = true;
    private static boolean mConfirmDeleteStarred = false;
    private static boolean mConfirmSpam = false;
    private static boolean mConfirmDeleteFromNotification = true;
    private static boolean mConfirmMarkAllRead = true;

    private static NotificationHideSubject sNotificationHideSubject = NotificationHideSubject.NEVER;

    /**
     * Controls when to hide the subject in the notification area.
     */
    public enum NotificationHideSubject {
        ALWAYS,
        WHEN_LOCKED,
        NEVER
    }

    private static NotificationQuickDelete sNotificationQuickDelete = NotificationQuickDelete.NEVER;

    /**
     * Controls behaviour of delete button in notifications.
     */
    public enum NotificationQuickDelete {
        ALWAYS,
        FOR_SINGLE_MSG,
        NEVER
    }

    private static LockScreenNotificationVisibility sLockScreenNotificationVisibility =
        LockScreenNotificationVisibility.MESSAGE_COUNT;

    public enum LockScreenNotificationVisibility {
        EVERYTHING,
        SENDERS,
        MESSAGE_COUNT,
        APP_NAME,
        NOTHING
    }

    /**
     * Controls when to use the message list split view.
     */
    public enum SplitViewMode {
        ALWAYS,
        NEVER,
        WHEN_IN_LANDSCAPE
    }

    private static boolean mMessageListCheckboxes = true;
    private static boolean mMessageListStars = true;
    private static int mMessageListPreviewLines = 2;

    private static boolean mShowCorrespondentNames = true;
    private static boolean mMessageListSenderAboveSubject = false;
    private static boolean mShowContactName = false;
    private static boolean mChangeContactNameColor = false;
    private static int mContactNameColor = 0xff00008f;
    private static boolean sShowContactPicture = true;
    private static boolean mMessageViewFixedWidthFont = false;
    private static boolean mMessageViewReturnToList = false;
    private static boolean mMessageViewShowNext = false;

    private static boolean mGesturesEnabled = true;
    private static boolean mUseVolumeKeysForNavigation = false;
    private static boolean mUseVolumeKeysForListNavigation = false;
    private static boolean mStartIntegratedInbox = false;
    private static boolean mMeasureAccounts = true;
    private static boolean mCountSearchMessages = true;
    private static boolean mHideSpecialAccounts = false;
    private static boolean mAutofitWidth;
    private static boolean mQuietTimeEnabled = false;
    private static boolean mNotificationDuringQuietTimeEnabled = true;
    private static String mQuietTimeStarts = null;
    private static String mQuietTimeEnds = null;
    private static String mAttachmentDefaultPath = "";
    private static boolean mWrapFolderNames = false;
    private static boolean mHideUserAgent = false;
    private static boolean mHideTimeZone = false;

    private static String sOpenPgpProvider = "";
    private static boolean sOpenPgpSupportSignOnly = false;

    private static SortType mSortType;
    private static Map<SortType, Boolean> mSortAscending = new HashMap<SortType, Boolean>();

    private static boolean sUseBackgroundAsUnreadIndicator = true;
    private static boolean sThreadedViewEnabled = true;
    private static SplitViewMode sSplitViewMode = SplitViewMode.NEVER;
    private static boolean sColorizeMissingContactPictures = true;

    private static boolean sMessageViewArchiveActionVisible = false;
    private static boolean sMessageViewDeleteActionVisible = true;
    private static boolean sMessageViewMoveActionVisible = false;
    private static boolean sMessageViewCopyActionVisible = false;
    private static boolean sMessageViewSpamActionVisible = false;

    private static int sPgpInlineDialogCounter;
    private static int sPgpSignOnlyDialogCounter;

    /**
     * @see #areDatabasesUpToDate()
     */
    private static boolean sDatabasesUpToDate = false;

    /**
     * For use when displaying that no folder is selected
     */
    public static final String FOLDER_NONE = "-NONE-";

    public static final String LOCAL_UID_PREFIX = "K9LOCAL:";

    public static final String REMOTE_UID_PREFIX = "K9REMOTE:";

    public static final String IDENTITY_HEADER = K9MailLib.IDENTITY_HEADER;

    /**
     * Specifies how many messages will be shown in a folder by default. This number is set
     * on each new folder and can be incremented with "Load more messages..." by the
     * VISIBLE_LIMIT_INCREMENT
     */
    public static final int DEFAULT_VISIBLE_LIMIT = 25;

    /**
     * The maximum size of an attachment we're willing to download (either View or Save)
     * Attachments that are base64 encoded (most) will be about 1.375x their actual size
     * so we should probably factor that in. A 5MB attachment will generally be around
     * 6.8MB downloaded but only 5MB saved.
     */
    public static final int MAX_ATTACHMENT_DOWNLOAD_SIZE = (128 * 1024 * 1024);

    /* How many times should K-9 try to deliver a message before giving up
     * until the app is killed and restarted
     */

    public static final int MAX_SEND_ATTEMPTS = 5;

    /**
     * Max time (in millis) the wake lock will be held for when background sync is happening
     */
    public static final int WAKE_LOCK_TIMEOUT = 600000;

    public static final int MANUAL_WAKE_LOCK_TIMEOUT = 120000;

    public static final int PUSH_WAKE_LOCK_TIMEOUT = K9MailLib.PUSH_WAKE_LOCK_TIMEOUT;

    public static final int MAIL_SERVICE_WAKE_LOCK_TIMEOUT = 60000;

    public static final int BOOT_RECEIVER_WAKE_LOCK_TIMEOUT = 60000;

    public static final String NO_OPENPGP_PROVIDER = "";

    public static class Intents {

        public static class EmailReceived {
            public static final String ACTION_EMAIL_RECEIVED = BuildConfig.APPLICATION_ID + ".intent.action.EMAIL_RECEIVED";
            public static final String ACTION_EMAIL_DELETED = BuildConfig.APPLICATION_ID + ".intent.action.EMAIL_DELETED";
            public static final String ACTION_REFRESH_OBSERVER = BuildConfig.APPLICATION_ID + ".intent.action.REFRESH_OBSERVER";
            public static final String EXTRA_ACCOUNT = BuildConfig.APPLICATION_ID + ".intent.extra.ACCOUNT";
            public static final String EXTRA_FOLDER = BuildConfig.APPLICATION_ID + ".intent.extra.FOLDER";
            public static final String EXTRA_SENT_DATE = BuildConfig.APPLICATION_ID + ".intent.extra.SENT_DATE";
            public static final String EXTRA_FROM = BuildConfig.APPLICATION_ID + ".intent.extra.FROM";
            public static final String EXTRA_TO = BuildConfig.APPLICATION_ID + ".intent.extra.TO";
            public static final String EXTRA_CC = BuildConfig.APPLICATION_ID + ".intent.extra.CC";
            public static final String EXTRA_BCC = BuildConfig.APPLICATION_ID + ".intent.extra.BCC";
            public static final String EXTRA_SUBJECT = BuildConfig.APPLICATION_ID + ".intent.extra.SUBJECT";
            public static final String EXTRA_FROM_SELF = BuildConfig.APPLICATION_ID + ".intent.extra.FROM_SELF";
        }

        public static class Share {
            /*
             * We don't want to use EmailReceived.EXTRA_FROM ("com.fsck.k9.intent.extra.FROM")
             * because of different semantics (String array vs. string with comma separated
             * email addresses)
             */
            public static final String EXTRA_FROM = BuildConfig.APPLICATION_ID + ".intent.extra.SENDER";
        }
    }

    /**
     * Called throughout the application when the number of accounts has changed. This method
     * enables or disables the Compose activity, the boot receiver and the service based on
     * whether any accounts are configured.
     */
    public static void setServicesEnabled(Context context) {
        Context appContext = context.getApplicationContext();
        int acctLength = Preferences.getPreferences(appContext).getAvailableAccounts().size();
        boolean enable = acctLength > 0;

        setServicesEnabled(appContext, enable, null);

        updateDeviceIdleReceiver(appContext, enable);
    }

    private static void updateDeviceIdleReceiver(Context context, boolean enable) {
        DeviceIdleManager deviceIdleManager = DeviceIdleManager.getInstance(context);
        if (enable) {
            deviceIdleManager.registerReceiver();
        } else {
            deviceIdleManager.unregisterReceiver();
        }
    }

    private static void setServicesEnabled(Context context, boolean enabled, Integer wakeLockId) {

        PackageManager pm = context.getPackageManager();

        if (!enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) ==
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            /*
             * If no accounts now exist but the service is still enabled we're about to disable it
             * so we'll reschedule to kill off any existing alarms.
             */
            MailService.actionReset(context, wakeLockId);
        }
        Class<?>[] classes = { MessageCompose.class, BootReceiver.class, MailService.class };

        for (Class<?> clazz : classes) {

            boolean alreadyEnabled = pm.getComponentEnabledSetting(new ComponentName(context, clazz)) ==
                                     PackageManager.COMPONENT_ENABLED_STATE_ENABLED;

            if (enabled != alreadyEnabled) {
                pm.setComponentEnabledSetting(
                    new ComponentName(context, clazz),
                    enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
            }
        }

        if (enabled && pm.getComponentEnabledSetting(new ComponentName(context, MailService.class)) ==
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            /*
             * And now if accounts do exist then we've just enabled the service and we want to
             * schedule alarms for the new accounts.
             */
            MailService.actionReset(context, wakeLockId);
        }

    }

    /**
     * Register BroadcastReceivers programmatically because doing it from manifest
     * would make K-9 auto-start. We don't want auto-start because the initialization
     * sequence isn't safe while some events occur (SD card unmount).
     */
    protected void registerReceivers() {
        final StorageGoneReceiver receiver = new StorageGoneReceiver();
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addDataScheme("file");

        final BlockingQueue<Handler> queue = new SynchronousQueue<Handler>();

        // starting a new thread to handle unmount events
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                try {
                    queue.put(new Handler());
                } catch (InterruptedException e) {
                    Timber.e(e);
                }
                Looper.loop();
            }

        }, "Unmount-thread").start();

        try {
            final Handler storageGoneHandler = queue.take();
            registerReceiver(receiver, filter, null, storageGoneHandler);
            Timber.i("Registered: unmount receiver");
        } catch (InterruptedException e) {
            Timber.e(e, "Unable to register unmount receiver");
        }

        registerReceiver(new ShutdownReceiver(), new IntentFilter(Intent.ACTION_SHUTDOWN));
        Timber.i("Registered: shutdown receiver");
    }

    public static void save(StorageEditor editor) {
        editor.putBoolean("enableDebugLogging", K9.DEBUG);
        editor.putBoolean("enableSensitiveLogging", K9.DEBUG_SENSITIVE);
        editor.putString("backgroundOperations", K9.backgroundOps.name());
        editor.putBoolean("animations", mAnimations);
        editor.putBoolean("gesturesEnabled", mGesturesEnabled);
        editor.putBoolean("useVolumeKeysForNavigation", mUseVolumeKeysForNavigation);
        editor.putBoolean("useVolumeKeysForListNavigation", mUseVolumeKeysForListNavigation);
        editor.putBoolean("autofitWidth", mAutofitWidth);
        editor.putBoolean("quietTimeEnabled", mQuietTimeEnabled);
        editor.putBoolean("notificationDuringQuietTimeEnabled", mNotificationDuringQuietTimeEnabled);
        editor.putString("quietTimeStarts", mQuietTimeStarts);
        editor.putString("quietTimeEnds", mQuietTimeEnds);

        editor.putBoolean("startIntegratedInbox", mStartIntegratedInbox);
        editor.putBoolean("measureAccounts", mMeasureAccounts);
        editor.putBoolean("countSearchMessages", mCountSearchMessages);
        editor.putBoolean("messageListSenderAboveSubject", mMessageListSenderAboveSubject);
        editor.putBoolean("hideSpecialAccounts", mHideSpecialAccounts);
        editor.putBoolean("messageListStars", mMessageListStars);
        editor.putInt("messageListPreviewLines", mMessageListPreviewLines);
        editor.putBoolean("messageListCheckboxes", mMessageListCheckboxes);
        editor.putBoolean("showCorrespondentNames", mShowCorrespondentNames);
        editor.putBoolean("showContactName", mShowContactName);
        editor.putBoolean("showContactPicture", sShowContactPicture);
        editor.putBoolean("changeRegisteredNameColor", mChangeContactNameColor);
        editor.putInt("registeredNameColor", mContactNameColor);
        editor.putBoolean("messageViewFixedWidthFont", mMessageViewFixedWidthFont);
        editor.putBoolean("messageViewReturnToList", mMessageViewReturnToList);
        editor.putBoolean("messageViewShowNext", mMessageViewShowNext);
        editor.putBoolean("wrapFolderNames", mWrapFolderNames);
        editor.putBoolean("hideUserAgent", mHideUserAgent);
        editor.putBoolean("hideTimeZone", mHideTimeZone);

        editor.putString("openPgpProvider", sOpenPgpProvider);
        editor.putBoolean("openPgpSupportSignOnly", sOpenPgpSupportSignOnly);

        editor.putString("language", language);
        editor.putInt("theme", theme.ordinal());
        editor.putInt("messageViewTheme", messageViewTheme.ordinal());
        editor.putInt("messageComposeTheme", composerTheme.ordinal());
        editor.putBoolean("fixedMessageViewTheme", useFixedMessageTheme);

        editor.putBoolean("confirmDelete", mConfirmDelete);
        editor.putBoolean("confirmDiscardMessage", mConfirmDiscardMessage);
        editor.putBoolean("confirmDeleteStarred", mConfirmDeleteStarred);
        editor.putBoolean("confirmSpam", mConfirmSpam);
        editor.putBoolean("confirmDeleteFromNotification", mConfirmDeleteFromNotification);
        editor.putBoolean("confirmMarkAllRead", mConfirmMarkAllRead);

        editor.putString("sortTypeEnum", mSortType.name());
        editor.putBoolean("sortAscending", mSortAscending.get(mSortType));

        editor.putString("notificationHideSubject", sNotificationHideSubject.toString());
        editor.putString("notificationQuickDelete", sNotificationQuickDelete.toString());
        editor.putString("lockScreenNotificationVisibility", sLockScreenNotificationVisibility.toString());

        editor.putString("attachmentdefaultpath", mAttachmentDefaultPath);
        editor.putBoolean("useBackgroundAsUnreadIndicator", sUseBackgroundAsUnreadIndicator);
        editor.putBoolean("threadedView", sThreadedViewEnabled);
        editor.putString("splitViewMode", sSplitViewMode.name());
        editor.putBoolean("colorizeMissingContactPictures", sColorizeMissingContactPictures);

        editor.putBoolean("messageViewArchiveActionVisible", sMessageViewArchiveActionVisible);
        editor.putBoolean("messageViewDeleteActionVisible", sMessageViewDeleteActionVisible);
        editor.putBoolean("messageViewMoveActionVisible", sMessageViewMoveActionVisible);
        editor.putBoolean("messageViewCopyActionVisible", sMessageViewCopyActionVisible);
        editor.putBoolean("messageViewSpamActionVisible", sMessageViewSpamActionVisible);

        editor.putInt("pgpInlineDialogCounter", sPgpInlineDialogCounter);
        editor.putInt("pgpSignOnlyDialogCounter", sPgpSignOnlyDialogCounter);

        fontSizes.save(editor);
    }

    @Override
    public void onCreate() {
        if (K9.DEVELOPER_MODE) {
            StrictMode.enableDefaults();
        }

        PRNGFixes.apply();

        super.onCreate();
        app = this;
        Globals.setContext(this);

        K9MailLib.setDebugStatus(new K9MailLib.DebugStatus() {
            @Override public boolean enabled() {
                return DEBUG;
            }

            @Override public boolean debugSensitive() {
                return DEBUG_SENSITIVE;
            }
        });

        checkCachedDatabaseVersion();

        Preferences prefs = Preferences.getPreferences(this);
        loadPrefs(prefs);

        /*
         * We have to give MimeMessage a temp directory because File.createTempFile(String, String)
         * doesn't work in Android and MimeMessage does not have access to a Context.
         */
        BinaryTempFileBody.setTempDirectory(getCacheDir());

        LocalKeyStore.setKeyStoreLocation(getDir("KeyStore", MODE_PRIVATE).toString());

        /*
         * Enable background sync of messages
         */

        setServicesEnabled(this);
        registerReceivers();

        MessagingController.getInstance(this).addListener(new SimpleMessagingListener() {
            private void broadcastIntent(String action, Account account, String folder, Message message) {
                Uri uri = Uri.parse("email://messages/" + account.getAccountNumber() + "/" + Uri.encode(folder) + "/" + Uri.encode(message.getUid()));
                Intent intent = new Intent(action, uri);
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_ACCOUNT, account.getDescription());
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_FOLDER, folder);
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_SENT_DATE, message.getSentDate());
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_FROM, Address.toString(message.getFrom()));
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_TO, Address.toString(message.getRecipients(Message.RecipientType.TO)));
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_CC, Address.toString(message.getRecipients(Message.RecipientType.CC)));
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_BCC, Address.toString(message.getRecipients(Message.RecipientType.BCC)));
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_SUBJECT, message.getSubject());
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_FROM_SELF, account.isAnIdentity(message.getFrom()));
                K9.this.sendBroadcast(intent);

                Timber.d("Broadcasted: action=%s account=%s folder=%s message uid=%s",
                        action,
                        account.getDescription(),
                        folder,
                        message.getUid());
            }

            private void updateUnreadWidget() {
                try {
                    UnreadWidgetProvider.updateUnreadCount(K9.this);
                } catch (Exception e) {
                    Timber.e(e, "Error while updating unread widget(s)");
                }
            }

            private void updateMailListWidget() {
                try {
                    MessageListWidgetProvider.triggerMessageListWidgetUpdate(K9.this);
                } catch (RuntimeException e) {
                    if (BuildConfig.DEBUG) {
                        throw e;
                    } else {
                        Timber.e(e, "Error while updating message list widget");
                    }
                }
            }

            @Override
            public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) {
                broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folder, message);
                updateUnreadWidget();
                updateMailListWidget();
            }

            @Override
            public void messageDeleted(Account account, String folder, Message message) {
                broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_DELETED, account, folder, message);
                updateUnreadWidget();
                updateMailListWidget();
            }

            @Override
            public void synchronizeMailboxNewMessage(Account account, String folder, Message message) {
                broadcastIntent(K9.Intents.EmailReceived.ACTION_EMAIL_RECEIVED, account, folder, message);
                updateUnreadWidget();
                updateMailListWidget();
            }

            @Override
            public void folderStatusChanged(Account account, String folderName,
                    int unreadMessageCount) {

                updateUnreadWidget();
                updateMailListWidget();

                // let observers know a change occurred
                Intent intent = new Intent(K9.Intents.EmailReceived.ACTION_REFRESH_OBSERVER, null);
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_ACCOUNT, account.getDescription());
                intent.putExtra(K9.Intents.EmailReceived.EXTRA_FOLDER, folderName);
                K9.this.sendBroadcast(intent);

            }

        });

        notifyObservers();
    }

    /**
     * Loads the last known database version of the accounts' databases from a
     * {@code SharedPreference}.
     *
     *

     * If the stored version matches {@link LocalStore#DB_VERSION} we know that the databases are
     * up to date.

     * Using {@code SharedPreferences} should be a lot faster than opening all SQLite databases to
     * get the current database version.
     *

     * See {@link UpgradeDatabases} for a detailed explanation of the database upgrade process.
     *

     *
     * @see #areDatabasesUpToDate()
     */
    public void checkCachedDatabaseVersion() {
        sDatabaseVersionCache = getSharedPreferences(DATABASE_VERSION_CACHE, MODE_PRIVATE);

        int cachedVersion = sDatabaseVersionCache.getInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, 0);

        if (cachedVersion >= LocalStore.DB_VERSION) {
            K9.setDatabasesUpToDate(false);
        }
    }

    /**
     * Load preferences into our statics.
     *
     * If you're adding a preference here, odds are you'll need to add it to
     * {@link com.fsck.k9.preferences.GlobalSettings}, too.
     *
     * @param prefs Preferences to load
     */
    public static void loadPrefs(Preferences prefs) {
        Storage storage = prefs.getStorage();
        setDebug(storage.getBoolean("enableDebugLogging", BuildConfig.DEVELOPER_MODE));
        DEBUG_SENSITIVE = storage.getBoolean("enableSensitiveLogging", false);
        mAnimations = storage.getBoolean("animations", true);
        mGesturesEnabled = storage.getBoolean("gesturesEnabled", false);
        mUseVolumeKeysForNavigation = storage.getBoolean("useVolumeKeysForNavigation", false);
        mUseVolumeKeysForListNavigation = storage.getBoolean("useVolumeKeysForListNavigation", false);
        mStartIntegratedInbox = storage.getBoolean("startIntegratedInbox", false);
        mMeasureAccounts = storage.getBoolean("measureAccounts", true);
        mCountSearchMessages = storage.getBoolean("countSearchMessages", true);
        mHideSpecialAccounts = storage.getBoolean("hideSpecialAccounts", false);
        mMessageListSenderAboveSubject = storage.getBoolean("messageListSenderAboveSubject", false);
        mMessageListCheckboxes = storage.getBoolean("messageListCheckboxes", false);
        mMessageListStars = storage.getBoolean("messageListStars", true);
        mMessageListPreviewLines = storage.getInt("messageListPreviewLines", 2);

        mAutofitWidth = storage.getBoolean("autofitWidth", true);

        mQuietTimeEnabled = storage.getBoolean("quietTimeEnabled", false);
        mNotificationDuringQuietTimeEnabled = storage.getBoolean("notificationDuringQuietTimeEnabled", true);
        mQuietTimeStarts = storage.getString("quietTimeStarts", "21:00");
        mQuietTimeEnds = storage.getString("quietTimeEnds", "7:00");

        mShowCorrespondentNames = storage.getBoolean("showCorrespondentNames", true);
        mShowContactName = storage.getBoolean("showContactName", false);
        sShowContactPicture = storage.getBoolean("showContactPicture", true);
        mChangeContactNameColor = storage.getBoolean("changeRegisteredNameColor", false);
        mContactNameColor = storage.getInt("registeredNameColor", 0xff00008f);
        mMessageViewFixedWidthFont = storage.getBoolean("messageViewFixedWidthFont", false);
        mMessageViewReturnToList = storage.getBoolean("messageViewReturnToList", false);
        mMessageViewShowNext = storage.getBoolean("messageViewShowNext", false);
        mWrapFolderNames = storage.getBoolean("wrapFolderNames", false);
        mHideUserAgent = storage.getBoolean("hideUserAgent", false);
        mHideTimeZone = storage.getBoolean("hideTimeZone", false);

        sOpenPgpProvider = storage.getString("openPgpProvider", NO_OPENPGP_PROVIDER);
        sOpenPgpSupportSignOnly = storage.getBoolean("openPgpSupportSignOnly", false);

        mConfirmDelete = storage.getBoolean("confirmDelete", false);
        mConfirmDiscardMessage = storage.getBoolean("confirmDiscardMessage", true);
        mConfirmDeleteStarred = storage.getBoolean("confirmDeleteStarred", false);
        mConfirmSpam = storage.getBoolean("confirmSpam", false);
        mConfirmDeleteFromNotification = storage.getBoolean("confirmDeleteFromNotification", true);
        mConfirmMarkAllRead = storage.getBoolean("confirmMarkAllRead", true);

        try {
            String value = storage.getString("sortTypeEnum", Account.DEFAULT_SORT_TYPE.name());
            mSortType = SortType.valueOf(value);
        } catch (Exception e) {
            mSortType = Account.DEFAULT_SORT_TYPE;
        }

        boolean sortAscending = storage.getBoolean("sortAscending", Account.DEFAULT_SORT_ASCENDING);
        mSortAscending.put(mSortType, sortAscending);

        String notificationHideSubject = storage.getString("notificationHideSubject", null);
        if (notificationHideSubject == null) {
            // If the "notificationHideSubject" setting couldn't be found, the app was probably
            // updated. Look for the old "keyguardPrivacy" setting and map it to the new enum.
            sNotificationHideSubject = (storage.getBoolean("keyguardPrivacy", false)) ?
                    NotificationHideSubject.WHEN_LOCKED : NotificationHideSubject.NEVER;
        } else {
            sNotificationHideSubject = NotificationHideSubject.valueOf(notificationHideSubject);
        }

        String notificationQuickDelete = storage.getString("notificationQuickDelete", null);
        if (notificationQuickDelete != null) {
            sNotificationQuickDelete = NotificationQuickDelete.valueOf(notificationQuickDelete);
        }

        String lockScreenNotificationVisibility = storage.getString("lockScreenNotificationVisibility", null);
        if(lockScreenNotificationVisibility != null) {
            sLockScreenNotificationVisibility = LockScreenNotificationVisibility.valueOf(lockScreenNotificationVisibility);
        }

        String splitViewMode = storage.getString("splitViewMode", null);
        if (splitViewMode != null) {
            sSplitViewMode = SplitViewMode.valueOf(splitViewMode);
        }

        mAttachmentDefaultPath = storage.getString("attachmentdefaultpath",
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
        sUseBackgroundAsUnreadIndicator = storage.getBoolean("useBackgroundAsUnreadIndicator", true);
        sThreadedViewEnabled = storage.getBoolean("threadedView", true);
        fontSizes.load(storage);

        try {
            setBackgroundOps(BACKGROUND_OPS.valueOf(storage.getString(
                    "backgroundOperations",
                    BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC.name())));
        } catch (Exception e) {
            setBackgroundOps(BACKGROUND_OPS.WHEN_CHECKED_AUTO_SYNC);
        }

        sColorizeMissingContactPictures = storage.getBoolean("colorizeMissingContactPictures", true);

        sMessageViewArchiveActionVisible = storage.getBoolean("messageViewArchiveActionVisible", false);
        sMessageViewDeleteActionVisible = storage.getBoolean("messageViewDeleteActionVisible", true);
        sMessageViewMoveActionVisible = storage.getBoolean("messageViewMoveActionVisible", false);
        sMessageViewCopyActionVisible = storage.getBoolean("messageViewCopyActionVisible", false);
        sMessageViewSpamActionVisible = storage.getBoolean("messageViewSpamActionVisible", false);

        sPgpInlineDialogCounter = storage.getInt("pgpInlineDialogCounter", 0);
        sPgpSignOnlyDialogCounter = storage.getInt("pgpSignOnlyDialogCounter", 0);

        K9.setK9Language(storage.getString("language", ""));

        int themeValue = storage.getInt("theme", Theme.LIGHT.ordinal());
        // We used to save the resource ID of the theme. So convert that to the new format if
        // necessary.
        if (themeValue == Theme.DARK.ordinal() || themeValue == android.R.style.Theme) {
            K9.setK9Theme(Theme.DARK);
        } else {
            K9.setK9Theme(Theme.LIGHT);
        }

        themeValue = storage.getInt("messageViewTheme", Theme.USE_GLOBAL.ordinal());
        K9.setK9MessageViewThemeSetting(Theme.values()[themeValue]);
        themeValue = storage.getInt("messageComposeTheme", Theme.USE_GLOBAL.ordinal());
        K9.setK9ComposerThemeSetting(Theme.values()[themeValue]);
        K9.setUseFixedMessageViewTheme(storage.getBoolean("fixedMessageViewTheme", true));
    }

    /**
     * since Android invokes Application.onCreate() only after invoking all
     * other components' onCreate(), here is a way to notify interested
     * component that the application is available and ready
     */
    protected void notifyObservers() {
        synchronized (observers) {
            for (final ApplicationAware aware : observers) {
                Timber.v("Initializing observer: %s", aware);

                try {
                    aware.initializeComponent(this);
                } catch (Exception e) {
                    Timber.w(e, "Failure when notifying %s", aware);
                }
            }

            sInitialized = true;
            observers.clear();
        }
    }

    /**
     * Register a component to be notified when the {@link K9} instance is ready.
     *
     * @param component
     *            Never null.
     */
    public static void registerApplicationAware(final ApplicationAware component) {
        synchronized (observers) {
            if (sInitialized) {
                component.initializeComponent(K9.app);
            } else if (!observers.contains(component)) {
                observers.add(component);
            }
        }
    }

    public static String getK9Language() {
        return language;
    }

    public static void setK9Language(String nlanguage) {
        language = nlanguage;
    }

    /**
     * Possible values for the different theme settings.
     *
     *
Important:
     * Do not change the order of the items! The ordinal value (position) is used when saving the
     * settings.

     */
    public enum Theme {
        LIGHT,
        DARK,
        USE_GLOBAL
    }

    public static int getK9ThemeResourceId(Theme themeId) {
        return (themeId == Theme.LIGHT) ? R.style.Theme_K9_Light : R.style.Theme_K9_Dark;
    }

    public static int getK9ThemeResourceId() {
        return getK9ThemeResourceId(theme);
    }

    public static Theme getK9MessageViewTheme() {
        return messageViewTheme == Theme.USE_GLOBAL ? theme : messageViewTheme;
    }

    public static Theme getK9MessageViewThemeSetting() {
        return messageViewTheme;
    }

    public static Theme getK9ComposerTheme() {
        return composerTheme == Theme.USE_GLOBAL ? theme : composerTheme;
    }

    public static Theme getK9ComposerThemeSetting() {
        return composerTheme;
    }

    public static Theme getK9Theme() {
        return theme;
    }

    public static void setK9Theme(Theme ntheme) {
        if (ntheme != Theme.USE_GLOBAL) {
            theme = ntheme;
        }
    }

    public static void setK9MessageViewThemeSetting(Theme nMessageViewTheme) {
        messageViewTheme = nMessageViewTheme;
    }

    public static boolean useFixedMessageViewTheme() {
        return useFixedMessageTheme;
    }

    public static void setK9ComposerThemeSetting(Theme compTheme) {
        composerTheme = compTheme;
    }

    public static void setUseFixedMessageViewTheme(boolean useFixed) {
        useFixedMessageTheme = useFixed;
        if (!useFixedMessageTheme && messageViewTheme == Theme.USE_GLOBAL) {
            messageViewTheme = theme;
        }
    }

    public static BACKGROUND_OPS getBackgroundOps() {
        return backgroundOps;
    }

    public static boolean setBackgroundOps(BACKGROUND_OPS backgroundOps) {
        BACKGROUND_OPS oldBackgroundOps = K9.backgroundOps;
        K9.backgroundOps = backgroundOps;
        return backgroundOps != oldBackgroundOps;
    }

    public static boolean setBackgroundOps(String nbackgroundOps) {
        return setBackgroundOps(BACKGROUND_OPS.valueOf(nbackgroundOps));
    }

    public static boolean gesturesEnabled() {
        return mGesturesEnabled;
    }

    public static void setGesturesEnabled(boolean gestures) {
        mGesturesEnabled = gestures;
    }

    public static boolean useVolumeKeysForNavigationEnabled() {
        return mUseVolumeKeysForNavigation;
    }

    public static void setUseVolumeKeysForNavigation(boolean volume) {
        mUseVolumeKeysForNavigation = volume;
    }

    public static boolean useVolumeKeysForListNavigationEnabled() {
        return mUseVolumeKeysForListNavigation;
    }

    public static void setUseVolumeKeysForListNavigation(boolean enabled) {
        mUseVolumeKeysForListNavigation = enabled;
    }

    public static boolean autofitWidth() {
        return mAutofitWidth;
    }

    public static void setAutofitWidth(boolean autofitWidth) {
        mAutofitWidth = autofitWidth;
    }

    public static boolean getQuietTimeEnabled() {
        return mQuietTimeEnabled;
    }

    public static void setQuietTimeEnabled(boolean quietTimeEnabled) {
        mQuietTimeEnabled = quietTimeEnabled;
    }

    public static boolean isNotificationDuringQuietTimeEnabled() {
        return mNotificationDuringQuietTimeEnabled;
    }

    public static void setNotificationDuringQuietTimeEnabled(boolean notificationDuringQuietTimeEnabled) {
        mNotificationDuringQuietTimeEnabled = notificationDuringQuietTimeEnabled;
    }

    public static String getQuietTimeStarts() {
        return mQuietTimeStarts;
    }

    public static void setQuietTimeStarts(String quietTimeStarts) {
        mQuietTimeStarts = quietTimeStarts;
    }

    public static String getQuietTimeEnds() {
        return mQuietTimeEnds;
    }

    public static void setQuietTimeEnds(String quietTimeEnds) {
        mQuietTimeEnds = quietTimeEnds;
    }

    public static boolean isQuietTime() {
        if (!mQuietTimeEnabled) {
            return false;
        }

        GregorianCalendar gregorianCalendar = new GregorianCalendar();

        Integer startHour = Integer.parseInt(mQuietTimeStarts.split(":")[0]);
        Integer startMinute = Integer.parseInt(mQuietTimeStarts.split(":")[1]);
        Integer endHour = Integer.parseInt(mQuietTimeEnds.split(":")[0]);
        Integer endMinute = Integer.parseInt(mQuietTimeEnds.split(":")[1]);

        Integer now = (gregorianCalendar.get(Calendar.HOUR) * 60) + gregorianCalendar.get(Calendar.MINUTE);
        Integer quietStarts = startHour * 60 + startMinute;
        Integer quietEnds =  endHour * 60 + endMinute;

        // If start and end times are the same, we're never quiet
        if (quietStarts.equals(quietEnds)) {
            return false;
        }

        // 21:00 - 05:00 means we want to be quiet if it's after 9 or before 5
        if (quietStarts > quietEnds) {
            // if it's 22:00 or 03:00 but not 8:00
            if (now >= quietStarts || now <= quietEnds) {
                return true;
            }
        }

        // 01:00 - 05:00
        else {

            // if it' 2:00 or 4:00 but not 8:00 or 0:00
            if (now >= quietStarts && now <= quietEnds) {
                return true;
            }
        }

        return false;
    }

    public static void setDebug(boolean debug) {
        K9.DEBUG = debug;
        updateLoggingStatus();
    }

    public static boolean isDebug() {
        return DEBUG;
    }

    public static boolean startIntegratedInbox() {
        return mStartIntegratedInbox;
    }

    public static void setStartIntegratedInbox(boolean startIntegratedInbox) {
        mStartIntegratedInbox = startIntegratedInbox;
    }

    public static boolean showAnimations() {
        return mAnimations;
    }

    public static void setAnimations(boolean animations) {
        mAnimations = animations;
    }

    public static int messageListPreviewLines() {
        return mMessageListPreviewLines;
    }

    public static void setMessageListPreviewLines(int lines) {
        mMessageListPreviewLines = lines;
    }

    public static boolean messageListCheckboxes() {
        return mMessageListCheckboxes;
    }

    public static void setMessageListCheckboxes(boolean checkboxes) {
        mMessageListCheckboxes = checkboxes;
    }

    public static boolean messageListStars() {
        return mMessageListStars;
    }

    public static void setMessageListStars(boolean stars) {
        mMessageListStars = stars;
    }

    public static boolean showCorrespondentNames() {
        return mShowCorrespondentNames;
    }

     public static boolean messageListSenderAboveSubject() {
         return mMessageListSenderAboveSubject;
     }

    public static void setMessageListSenderAboveSubject(boolean sender) {
         mMessageListSenderAboveSubject = sender;
    }
    public static void setShowCorrespondentNames(boolean showCorrespondentNames) {
        mShowCorrespondentNames = showCorrespondentNames;
    }

    public static boolean showContactName() {
        return mShowContactName;
    }

    public static void setShowContactName(boolean showContactName) {
        mShowContactName = showContactName;
    }

    public static boolean changeContactNameColor() {
        return mChangeContactNameColor;
    }

    public static void setChangeContactNameColor(boolean changeContactNameColor) {
        mChangeContactNameColor = changeContactNameColor;
    }

    public static int getContactNameColor() {
        return mContactNameColor;
    }

    public static void setContactNameColor(int contactNameColor) {
        mContactNameColor = contactNameColor;
    }

    public static boolean messageViewFixedWidthFont() {
        return mMessageViewFixedWidthFont;
    }

    public static void setMessageViewFixedWidthFont(boolean fixed) {
        mMessageViewFixedWidthFont = fixed;
    }

    public static boolean messageViewReturnToList() {
        return mMessageViewReturnToList;
    }

    public static void setMessageViewReturnToList(boolean messageViewReturnToList) {
        mMessageViewReturnToList = messageViewReturnToList;
    }

    public static boolean messageViewShowNext() {
        return mMessageViewShowNext;
    }

    public static void setMessageViewShowNext(boolean messageViewShowNext) {
        mMessageViewShowNext = messageViewShowNext;
    }

    public static FontSizes getFontSizes() {
        return fontSizes;
    }

    public static boolean measureAccounts() {
        return mMeasureAccounts;
    }

    public static void setMeasureAccounts(boolean measureAccounts) {
        mMeasureAccounts = measureAccounts;
    }

    public static boolean countSearchMessages() {
        return mCountSearchMessages;
    }

    public static void setCountSearchMessages(boolean countSearchMessages) {
        mCountSearchMessages = countSearchMessages;
    }

    public static boolean isHideSpecialAccounts() {
        return mHideSpecialAccounts;
    }

    public static void setHideSpecialAccounts(boolean hideSpecialAccounts) {
        mHideSpecialAccounts = hideSpecialAccounts;
    }

    public static boolean confirmDelete() {
        return mConfirmDelete;
    }

    public static void setConfirmDelete(final boolean confirm) {
        mConfirmDelete = confirm;
    }

    public static boolean confirmDeleteStarred() {
        return mConfirmDeleteStarred;
    }

    public static void setConfirmDeleteStarred(final boolean confirm) {
        mConfirmDeleteStarred = confirm;
    }

    public static boolean confirmSpam() {
        return mConfirmSpam;
    }

    public static boolean confirmDiscardMessage() {
        return mConfirmDiscardMessage;
    }

    public static void setConfirmSpam(final boolean confirm) {
        mConfirmSpam = confirm;
    }

    public static void setConfirmDiscardMessage(final boolean confirm) {
        mConfirmDiscardMessage = confirm;
    }

    public static boolean confirmDeleteFromNotification() {
        return mConfirmDeleteFromNotification;
    }

    public static void setConfirmDeleteFromNotification(final boolean confirm) {
        mConfirmDeleteFromNotification = confirm;
    }

    public static boolean confirmMarkAllRead() {
        return mConfirmMarkAllRead;
    }

    public static void setConfirmMarkAllRead(final boolean confirm) {
        mConfirmMarkAllRead = confirm;
    }

    public static NotificationHideSubject getNotificationHideSubject() {
        return sNotificationHideSubject;
    }

    public static void setNotificationHideSubject(final NotificationHideSubject mode) {
        sNotificationHideSubject = mode;
    }

    public static NotificationQuickDelete getNotificationQuickDeleteBehaviour() {
        return sNotificationQuickDelete;
    }

    public static void setNotificationQuickDeleteBehaviour(final NotificationQuickDelete mode) {
        sNotificationQuickDelete = mode;
    }

    public static LockScreenNotificationVisibility getLockScreenNotificationVisibility() {
        return sLockScreenNotificationVisibility;
    }

    public static void setLockScreenNotificationVisibility(final LockScreenNotificationVisibility visibility) {
        sLockScreenNotificationVisibility = visibility;
    }

    public static boolean wrapFolderNames() {
        return mWrapFolderNames;
    }
    public static void setWrapFolderNames(final boolean state) {
        mWrapFolderNames = state;
    }

    public static boolean hideUserAgent() {
        return mHideUserAgent;
    }
    public static void setHideUserAgent(final boolean state) {
        mHideUserAgent = state;
    }

    public static boolean hideTimeZone() {
        return mHideTimeZone;
    }
    public static void setHideTimeZone(final boolean state) {
        mHideTimeZone = state;
    }

    public static boolean isOpenPgpProviderConfigured() {
        return !NO_OPENPGP_PROVIDER.equals(sOpenPgpProvider);
    }

    public static String getOpenPgpProvider() {
        return sOpenPgpProvider;
    }

    public static void setOpenPgpProvider(String openPgpProvider) {
        sOpenPgpProvider = openPgpProvider;
    }

    public static boolean getOpenPgpSupportSignOnly() {
        return sOpenPgpSupportSignOnly;
    }

    public static void setOpenPgpSupportSignOnly(boolean supportSignOnly) {
        sOpenPgpSupportSignOnly = supportSignOnly;
    }

    public static String getAttachmentDefaultPath() {
        return mAttachmentDefaultPath;
    }

    public static void setAttachmentDefaultPath(String attachmentDefaultPath) {
        K9.mAttachmentDefaultPath = attachmentDefaultPath;
    }

    public static synchronized SortType getSortType() {
        return mSortType;
    }

    public static synchronized void setSortType(SortType sortType) {
        mSortType = sortType;
    }

    public static synchronized boolean isSortAscending(SortType sortType) {
        if (mSortAscending.get(sortType) == null) {
            mSortAscending.put(sortType, sortType.isDefaultAscending());
        }
        return mSortAscending.get(sortType);
    }

    public static synchronized void setSortAscending(SortType sortType, boolean sortAscending) {
        mSortAscending.put(sortType, sortAscending);
    }

    public static synchronized boolean useBackgroundAsUnreadIndicator() {
        return sUseBackgroundAsUnreadIndicator;
    }

    public static synchronized void setUseBackgroundAsUnreadIndicator(boolean enabled) {
        sUseBackgroundAsUnreadIndicator = enabled;
    }

    public static synchronized boolean isThreadedViewEnabled() {
        return sThreadedViewEnabled;
    }

    public static synchronized void setThreadedViewEnabled(boolean enable) {
        sThreadedViewEnabled = enable;
    }

    public static synchronized SplitViewMode getSplitViewMode() {
        return sSplitViewMode;
    }

    public static synchronized void setSplitViewMode(SplitViewMode mode) {
        sSplitViewMode = mode;
    }

    public static boolean showContactPicture() {
        return sShowContactPicture;
    }

    public static void setShowContactPicture(boolean show) {
        sShowContactPicture = show;
    }

    public static boolean isColorizeMissingContactPictures() {
        return sColorizeMissingContactPictures;
    }

    public static void setColorizeMissingContactPictures(boolean enabled) {
        sColorizeMissingContactPictures = enabled;
    }

    public static boolean isMessageViewArchiveActionVisible() {
        return sMessageViewArchiveActionVisible;
    }

    public static void setMessageViewArchiveActionVisible(boolean visible) {
        sMessageViewArchiveActionVisible = visible;
    }

    public static boolean isMessageViewDeleteActionVisible() {
        return sMessageViewDeleteActionVisible;
    }

    public static void setMessageViewDeleteActionVisible(boolean visible) {
        sMessageViewDeleteActionVisible = visible;
    }

    public static boolean isMessageViewMoveActionVisible() {
        return sMessageViewMoveActionVisible;
    }

    public static void setMessageViewMoveActionVisible(boolean visible) {
        sMessageViewMoveActionVisible = visible;
    }

    public static boolean isMessageViewCopyActionVisible() {
        return sMessageViewCopyActionVisible;
    }

    public static void setMessageViewCopyActionVisible(boolean visible) {
        sMessageViewCopyActionVisible = visible;
    }

    public static boolean isMessageViewSpamActionVisible() {
        return sMessageViewSpamActionVisible;
    }

    public static void setMessageViewSpamActionVisible(boolean visible) {
        sMessageViewSpamActionVisible = visible;
    }

    public static int getPgpInlineDialogCounter() {
        return sPgpInlineDialogCounter;
    }

    public static void setPgpInlineDialogCounter(int pgpInlineDialogCounter) {
        K9.sPgpInlineDialogCounter = pgpInlineDialogCounter;
    }

    public static int getPgpSignOnlyDialogCounter() {
        return sPgpSignOnlyDialogCounter;
    }

    public static void setPgpSignOnlyDialogCounter(int pgpSignOnlyDialogCounter) {
        K9.sPgpSignOnlyDialogCounter = pgpSignOnlyDialogCounter;
    }

    /**
     * Check if we already know whether all databases are using the current database schema.
     *
     *

     * This method is only used for optimizations. If it returns {@code true} we can be certain that
     * getting a {@link LocalStore} instance won't trigger a schema upgrade.
     *

     *
     * @return {@code true}, if we know that all databases are using the current database schema.
     *         {@code false}, otherwise.
     */
    public static synchronized boolean areDatabasesUpToDate() {
        return sDatabasesUpToDate;
    }

    /**
     * Remember that all account databases are using the most recent database schema.
     *
     * @param save
     *         Whether or not to write the current database version to the
     *         {@code SharedPreferences} {@link #DATABASE_VERSION_CACHE}.
     *
     * @see #areDatabasesUpToDate()
     */
    public static synchronized void setDatabasesUpToDate(boolean save) {
        sDatabasesUpToDate = true;

        if (save) {
            Editor editor = sDatabaseVersionCache.edit();
            editor.putInt(KEY_LAST_ACCOUNT_DATABASE_VERSION, LocalStore.DB_VERSION);
            editor.apply();
        }
    }

    private static void updateLoggingStatus() {
        Timber.uprootAll();
        boolean enableDebugLogging = BuildConfig.DEBUG || DEBUG;
        if (enableDebugLogging) {
            Timber.plant(new DebugTree());
        }
    }

    public static void saveSettingsAsync() {
        new AsyncTask<Void,Void,Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                Preferences prefs = Preferences.getPreferences(app);
                StorageEditor editor = prefs.getStorage().edit();
                save(editor);
                editor.commit();

                return null;
            }
        }.execute();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.ocdsoft.bacta.swg.server.game.script;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.ocdsoft.bacta.engine.conf.BactaConfiguration;
import com.ocdsoft.bacta.engine.io.FileSystemWatcher;
import com.ocdsoft.bacta.swg.conf.ConfigSections;
import com.ocdsoft.bacta.swg.server.game.object.ServerObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by crush on 6/6/2016.
 */
@Singleton
public final class ScriptService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScriptService.class);

    private final Map<String, ScriptReference> scriptReferences;
    private final FileSystemWatcher scriptWatcherService;
    private final Path scriptsPath;

    @Inject
    public ScriptService(final BactaConfiguration configuration) {
        this.scriptReferences = new ConcurrentHashMap<>();
        this.scriptsPath = Paths.get(System.getProperty("user.dir"), configuration.getString(ConfigSections.GAME_SERVER_SCRIPTS, "path"));
        this.scriptWatcherService = new FileSystemWatcher(scriptsPath, this::onScriptCreated, this::onScriptDeleted, this::onScriptModified);

        initialize();
    }

    /**
     * Attaches a script to the specified object.
     *
     * @param scriptName The script to attach.
     * @param object     The object to which to attach the script.
     */
    public void attachScript(final String scriptName, final ServerObject object) {
        //If the script failed to load, then do nothing. Load will output any errors.
        if (!containsScript(scriptName) && !loadScript(scriptName))
            return;

        ensureObjectAttachedScripts(object);

        //Set the script reference on the object.
        final Set<String> attachedScripts = object.getAttachedScripts();
        attachedScripts.add(scriptName);

        final ScriptReference scriptReference = scriptReferences.get(scriptName);
        scriptReference.attachObject(object);

        //TODO: See reference counting question in detachScript.
    }

    /**
     * Detaches a script from the specified object.
     *
     * @param scriptName The script to detach.
     * @param object     The object from which to detach the script.
     */
    public void detachScript(final String scriptName, final ServerObject object) {
        if (!containsScript(scriptName))
            return;

        final Set<String> attachedScripts = object.getAttachedScripts();

        if (attachedScripts == null) {
            LOGGER.warn("Attached scripts should not be null, but it is!");
        } else {
            attachedScripts.remove(scriptName);
        }

        final ScriptReference scriptReference = scriptReferences.get(scriptName);
        scriptReference.detachObject(object);

        //TODO: Do we want to reference count, and remove the reference from the map when its no longer being used?
    }

    /**
     * Checks if a specific script exists as a script reference.
     *
     * @param scriptName The script to check.
     * @return True if it exists, otherwise false.
     */
    public boolean containsScript(final String scriptName) {
        return scriptReferences.containsKey(scriptName);
    }

    private boolean loadScript(final String scriptName) {
        if (!validateScript(scriptName))
            return false;

        //The script is valid. All we need to do is create a new reference for it, and plug it into our map.
        LOGGER.debug("Loading script [{}]", scriptName);

        final ScriptReference scriptReference = new ScriptReference(scriptName);
        scriptReferences.put(scriptName, scriptReference);

        return true;
    }

    /**
     * Checks to see if a script is valid syntactically - can it run? Does it violate any custom rules we set?
     *
     * @param scriptName The name to the script.
     * @return True if it is valid. Otherwise, false.
     */
    private boolean validateScript(final String scriptName) {
        //TODO: Some kind of checking to make sure the script will actually run. Clojure lint integration?
        //If it can't run, then output some kind of error messages to the LOGGER explaining the problem with the script.

        return true;
    }

    private void ensureObjectAttachedScripts(final ServerObject object) {
        final Set<String> attachedScripts = object.getAttachedScripts();

        if (attachedScripts == null)
            object.setAttachedScripts(new HashSet<>());
    }

    private void initialize() {
        LOGGER.debug("Initializing script service.");

        //Monitor for changes to scripts.
        this.scriptWatcherService.start();

        //Should we validate all scripts now, or wait for them to be lazy loaded? I guess it depends on speed.
    }

    /**
     * When a script is created, we want to examine the script to see if it has any trigger bindings. If any trigger
     * bindings exist, then we wire those up. If any object has been created that had this script attached, it will
     * already exist in the {@link #scriptReferences} map. If it doesn't exist, then we need to register it there with
     * no attached objects. If it does exist, we don't need to do anything except wire up the reference.
     *
     * @param path The path to the newly created script.
     */
    private void onScriptCreated(final Path path) {
        LOGGER.debug("The script [{}] was created.", path.toString());
    }

    /**
     * When a script is deleted, we simply want to remove the reference to the clojure script, but leave the internal
     * {@link ScriptReference} because it may be recreated later, in which case we want it to be rebound.
     *
     * @param path The path to the script that was deleted.
     */
    private void onScriptDeleted(final Path path) {
        //When a script is deleted, we need to detach it from all objects that were attached to it so that they don't try
        //and call it.
        LOGGER.debug("The script [{}] was deleted.", path.toString());
    }

    /**
     * When a script is modified, it could simply mean that it was renamed, or it could've changed. Either way, we want
     * to update the {@link ScriptReference}.
     *
     * @param path The path to the script that was modified.
     */
    private void onScriptModified(final Path path) {
        LOGGER.debug("The script [{}] was modified.", path.toString());
    }
}


text:
        Phone Number : {{ patientPhoneNumber }}

          Alternative Phone Number : {{ alternativePhoneNumber }}

        Spouse Phone Number : {{ partnerPhoneNumber }}

          Next of Kin Phone Number : {{ nextofkinPhoneNumber }}

        Caregiver Name : {{ careGivername }}

          Relationship to Caregiver : {{ relationshipToCareGiver }}

          Caregiver Phone Number : {{ careGiverPhoneNumber }}


text:
<!DOCTYPE html>
<html lang="{{$language}}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="description" content="Customer Portal">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{Config::get("customer_portal.company_name")}}</title>
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/assets/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="/assets/css/vendor/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/js/vendor/sweetalert/dist/sweetalert.css">
    <link rel="stylesheet" href="/assets/css/global.css">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="/assets/js/html5shiv.min.js"></script>
    <script src="/assets/js/respond.min.js"></script>
    <![endif]-->
    <script src="/messages.js" type="text/javascript"></script>
    @yield('additionalCSS')
</head>


text:
<!DOCTYPE html>

<title>Dashboard Agente - OneLink</title>
	<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php
    	$this->load->view('common/common_header');
      $this->load->model('estado');
      $this->estado->recuperaEstado();
      $fecha = $this->session->userdata('fecha_ultimo_estado');;
      echo "";
    ?>
<?php
foreach($css_files as $file): ?>
	<link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<?php foreach($js_files as $file): ?>

<?php endforeach; ?>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              Toggle navigation

            </button>
            OneLink Agente Dashboard

                 <?php echo $this->session->userdata('nickname_usuario'); ?>

Usuario

<a href="<?php echo site_url('login_Controller/cerrarSesion'); ?>">Cerrar Sesión

Sus Estados

    <?php echo $output; ?>

    <?php
    $this->load->view('cambiarEstado');
    ?>

    <?php $this->load->view('common/common_footer'); ?>


text:
package net.jadecy.graph;

import java.util.Collection;
import java.util.Random;

import net.jadecy.graph.InterfaceVertex;
import net.jadecy.graph.InterfaceVertexCollProcessor;
import net.jadecy.graph.SccsComputer;
import net.jadecy.graph.GraphTestsUtilz.BallGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.ChainGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.CycleGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.InterfaceGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.TreeGraphGenerator;

public class SccsComputerPerf {

    /*
     * Not benching random graphs, because there it causes too much variations.
     */

    //--------------------------------------------------------------------------
    // CONFIGURATION
    //--------------------------------------------------------------------------

    private static final int NBR_OF_RUNS = 4;

    private static final int NBR_OF_CALLS = 10;

    private static final long SEED = 123456789L;

    //--------------------------------------------------------------------------
    // PRIVATE CLASSES
    //--------------------------------------------------------------------------

    private static class MySccVcp implements InterfaceVertexCollProcessor {
        int counter;
        @Override
        public void processCollBegin() {
        }
        @Override
        public void processCollVertex(InterfaceVertex vertex) {
        }
        @Override
        public boolean processCollEnd() {
            this.counter++;
            return false;
        }
    }

    //--------------------------------------------------------------------------
    // PUBLIC METHODS
    //--------------------------------------------------------------------------

    public static void main(String[] args) {
        newRun(args);
    }

    public static void newRun(String[] args) {
        new SccsComputerPerf().run(args);
    }

    public SccsComputerPerf() {
    }

    //--------------------------------------------------------------------------
    // PRIVATE METHODS
    //--------------------------------------------------------------------------

    private void run(String[] args) {
        System.out.println("--- " + SccsComputerPerf.class.getSimpleName() + "... ---");
        System.out.println("number of calls = " + NBR_OF_CALLS);

        this.bench_computeSccs_chain();

        this.bench_computeSccs_tree();

        this.bench_computeSccs_cycle();

        this.bench_computeSccs_ball();

        System.out.println("--- ..." + SccsComputerPerf.class.getSimpleName() + " ---");
    }

    /*
     * Chain.
     */

    private void bench_computeSccs_chain() {
        System.out.println();
        final Random random = new Random(SEED);
        for (int size : new int[]{1000, 10*1000}) {
            this.bench_computeSccs(new ChainGraphGenerator(random.nextLong(), size));
        }
    }

    /*
     * Tree.
     */

    private void bench_computeSccs_tree() {
        System.out.println();
        final Random random = new Random(SEED);
        for (int depth : new int[]{12}) {
            this.bench_computeSccs(new TreeGraphGenerator(random.nextLong(), depth));
        }
    }

    /*
     * Cycle.
     */

    private void bench_computeSccs_cycle() {
        System.out.println();
        final Random random = new Random(SEED);
        for (int size : new int[]{1000, 10*1000}) {
            this.bench_computeSccs(new CycleGraphGenerator(random.nextLong(), size));
        }
    }

    /*
     * Ball.
     */

    private void bench_computeSccs_ball() {
        System.out.println();
        final Random random = new Random(SEED);
        for (int size : new int[]{500, 1000}) {
            this.bench_computeSccs(new BallGraphGenerator(random.nextLong(), size));
        }
    }

    /*
     *
     */

    private void bench_computeSccs(InterfaceGraphGenerator gg) {
        System.out.println();

        /*
         *
         */

        final Collection<InterfaceVertex> graph = gg.newGraph();

        /*
         *
         */

        for (int k = 0; k < NBR_OF_RUNS; k++) {
            final MySccVcp processor = new MySccVcp();
            long a = System.nanoTime();
            for (int i = 0; i < NBR_OF_CALLS; i++) {
                processor.counter = 0;
                SccsComputer.computeSccs(
                        graph,
                        processor);
            }
            long b = System.nanoTime();
            System.out.println("SccsComputer.computeSccs(...), (" + gg + ") (count=" + processor.counter + "), took " + ((b-a)/1e6/1000) + " s");
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Overview (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Lucene 4.6.1 highlighter API

The highlight package contains classes to provide "keyword in context" features
  typically used to highlight search terms in the text of results pages.

See: Description

Packages

Package
Description

org.apache.lucene.search.highlight

The highlight package contains classes to provide "keyword in context" features
typically used to highlight search terms in the text of results pages.

org.apache.lucene.search.postingshighlight

Highlighter implementation that uses offsets from postings lists.

org.apache.lucene.search.vectorhighlight

This is an another highlighter implementation.

The highlight package contains classes to provide "keyword in context" features
  typically used to highlight search terms in the text of results pages.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

          Copyright © 2000-2014 Apache Software Foundation.  All Rights Reserved.


text:
/*
 * Changelog
 *
 *   05/02/2002 - First drop [HM]
 */

#include "tools.h"

int disks_found;
int parts_found;
int pv_disks_found;
int pv_parts_found;
int max_len;

static int _get_max_dev_name_len(struct dev_filter *filter)
{
	int len = 0;
	int maxlen = 0;
	struct dev_iter *iter;
	struct device *dev;

	if (!(iter = dev_iter_create(filter, 1))) {
		log_error("dev_iter_create failed");
		return 0;
	}

	/* Do scan */
	for (dev = dev_iter_get(iter); dev; dev = dev_iter_get(iter)) {
		len = strlen(dev_name(dev));
		if (len > maxlen)
			maxlen = len;
	}
	dev_iter_destroy(iter);

	return maxlen;
}

static void _count(struct device *dev, int *disks, int *parts)
{
	int c = dev_name(dev)[strlen(dev_name(dev)) - 1];

	if (!isdigit(c))
		(*disks)++;
	else
		(*parts)++;
}

static void _print(struct cmd_context *cmd, const struct device *dev,
		   uint64_t size, const char *what)
{
	log_print("%-*s [%15s] %s", max_len, dev_name(dev),
		  display_size(cmd, size), what ? : "");
}

static int _check_device(struct cmd_context *cmd, struct device *dev)
{
	char buffer;
	uint64_t size;

	if (!dev_open_readonly(dev)) {
		return 0;
	}
	if (!dev_read(dev, UINT64_C(0), (size_t) 1, &buffer)) {
		dev_close(dev);
		return 0;
	}
	if (!dev_get_size(dev, &size)) {
		log_error("Couldn't get size of \"%s\"", dev_name(dev));
	}
	_print(cmd, dev, size, NULL);
	_count(dev, &disks_found, &parts_found);
	if (!dev_close(dev)) {
		log_error("dev_close on \"%s\" failed", dev_name(dev));
		return 0;
	}
	return 1;
}

int lvmdiskscan(struct cmd_context *cmd, int argc __attribute__((unused)),
		char **argv __attribute__((unused)))
{
	uint64_t size;
	struct dev_iter *iter;
	struct device *dev;
	struct label *label;

	/* initialise these here to avoid problems with the lvm shell */
	disks_found = 0;
	parts_found = 0;
	pv_disks_found = 0;
	pv_parts_found = 0;

	if (arg_count(cmd, lvmpartition_ARG))
		log_warn("WARNING: only considering LVM devices");

	max_len = _get_max_dev_name_len(cmd->filter);

	if (!(iter = dev_iter_create(cmd->filter, 0))) {
		log_error("dev_iter_create failed");
		return ECMD_FAILED;
	}

	/* Do scan */
	for (dev = dev_iter_get(iter); dev; dev = dev_iter_get(iter)) {
		/* Try if it is a PV first */
		if ((label_read(dev, &label, UINT64_C(0)))) {
			if (!dev_get_size(dev, &size)) {
				log_error("Couldn't get size of \"%s\"",
					  dev_name(dev));
				continue;
			}
			_print(cmd, dev, size, "LVM physical volume");
			_count(dev, &pv_disks_found, &pv_parts_found);
			continue;
		}
		/* If user just wants PVs we are done */
		if (arg_count(cmd, lvmpartition_ARG))
			continue;

		/* What other device is it? */
		if (!_check_device(cmd, dev))
			continue;
	}
	dev_iter_destroy(iter);

	/* Display totals */
	if (!arg_count(cmd, lvmpartition_ARG)) {
		log_print("%d disk%s",
			  disks_found, disks_found == 1 ? "" : "s");
		log_print("%d partition%s",
			  parts_found, parts_found == 1 ? "" : "s");
	}
	log_print("%d LVM physical volume whole disk%s",
		  pv_disks_found, pv_disks_found == 1 ? "" : "s");
	log_print("%d LVM physical volume%s",
		  pv_parts_found, pv_parts_found == 1 ? "" : "s");

	return ECMD_PROCESSED;
}


text:
package org.apache.fluo.recipes.core.types;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.common.collect.Maps;
import org.apache.commons.collections.map.DefaultedMap;
import org.apache.fluo.api.client.AbstractSnapshotBase;
import org.apache.fluo.api.client.SnapshotBase;
import org.apache.fluo.api.client.scanner.ScannerBuilder;
import org.apache.fluo.api.data.Bytes;
import org.apache.fluo.api.data.Column;
import org.apache.fluo.api.data.RowColumn;
import org.apache.fluo.recipes.core.types.TypeLayer.Data;
import org.apache.fluo.recipes.core.types.TypeLayer.FamilyMethods;
import org.apache.fluo.recipes.core.types.TypeLayer.QualifierMethods;
import org.apache.fluo.recipes.core.types.TypeLayer.RowMethods;

// TODO need to refactor column to use Encoder

/**
 * A {@link SnapshotBase} that uses a {@link TypeLayer}
 *
 * @since 1.0.0
 */
public class TypedSnapshotBase extends AbstractSnapshotBase implements SnapshotBase {

  private SnapshotBase snapshot;
  private Encoder encoder;
  private TypeLayer tl;

  /**
   * @since 1.0.0
   */
  public class VisibilityMethods extends Value {

    VisibilityMethods(Data data) {
      super(data);
    }

    public Value vis(Bytes cv) {
      data.vis = cv;
      return new Value(data);
    }

    public Value vis(byte[] cv) {
      data.vis = Bytes.of(cv);
      return new Value(data);
    }

    public Value vis(ByteBuffer bb) {
      data.vis = Bytes.of(bb);
      return new Value(data);
    }

    public Value vis(String cv) {
      data.vis = Bytes.of(cv);
      return new Value(data);
    }
  }

  /**
   * @since 1.0.0
   */
  public class Value {
    private Bytes bytes;
    private boolean gotBytes = false;
    Data data;

    public Bytes getBytes() {
      if (!gotBytes) {
        try {
          bytes = snapshot.get(data.row, data.getCol());
          gotBytes = true;
        } catch (Exception e) {
          if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
          }
          throw new RuntimeException(e);
        }
      }

      return bytes;
    }

    private Value(Bytes bytes) {
      this.bytes = bytes;
      this.gotBytes = true;
    }

    private Value(Data data) {
      this.data = data;
      this.gotBytes = false;
    }

    public Integer toInteger() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeInteger(getBytes());
    }

    public int toInteger(int defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeInteger(getBytes());
    }

    public Long toLong() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeLong(getBytes());
    }

    public long toLong(long defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeLong(getBytes());
    }

    @Override
    public String toString() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeString(getBytes());
    }

    public String toString(String defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeString(getBytes());
    }

    public Float toFloat() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeFloat(getBytes());
    }

    public float toFloat(float defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeFloat(getBytes());
    }

    public Double toDouble() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeDouble(getBytes());
    }

    public double toDouble(double defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeDouble(getBytes());
    }

    public Boolean toBoolean() {
      if (getBytes() == null) {
        return null;
      }
      return encoder.decodeBoolean(getBytes());
    }

    public boolean toBoolean(boolean defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return encoder.decodeBoolean(getBytes());
    }

    public byte[] toBytes() {
      if (getBytes() == null) {
        return null;
      }
      return getBytes().toArray();
    }

    public byte[] toBytes(byte[] defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return getBytes().toArray();
    }

    public ByteBuffer toByteBuffer() {
      if (getBytes() == null) {
        return null;
      }
      return ByteBuffer.wrap(getBytes().toArray());
    }

    public ByteBuffer toByteBuffer(ByteBuffer defaultValue) {
      if (getBytes() == null) {
        return defaultValue;
      }
      return toByteBuffer();
    }

    @Override
    public int hashCode() {
      if (getBytes() == null) {
        return 0;
      }

      return getBytes().hashCode();
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof Value) {
        Value ov = (Value) o;
        if (getBytes() == null) {
          return ov.getBytes() == null;
        } else {
          return getBytes().equals(ov.getBytes());
        }
      }

      return false;
    }
  }

  /**
   * @since 1.0.0
   */
  public class ValueQualifierBuilder extends QualifierMethods<VisibilityMethods> {

    ValueQualifierBuilder(Data data) {
      tl.super(data);
    }

    @Override
    VisibilityMethods create(Data data) {
      return new VisibilityMethods(data);
    }
  }

  /**
   * @since 1.0.0
   */
  public class ValueFamilyMethods extends FamilyMethods<ValueQualifierBuilder, Value> {

    ValueFamilyMethods(Data data) {
      tl.super(data);
    }

    @Override
    ValueQualifierBuilder create1(Data data) {
      return new ValueQualifierBuilder(data);
    }

    @Override
    Value create2(Data data) {
      return new Value(data);
    }

    public Map<Column, Value> columns(Set<Column> columns) {
      try {
        return wrap(snapshot.get(data.row, columns));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    public Map<Column, Value> columns(Column... columns) {
      try {
        return wrap(snapshot.get(data.row, new HashSet<>(Arrays.asList(columns))));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }

  /**
   * @since 1.0.0
   */
  public class MapConverter {
    private Collection<Bytes> rows;
    private Set<Column> columns;

    public MapConverter(Collection<Bytes> rows, Set<Column> columns) {
      this.rows = rows;
      this.columns = columns;
    }

    private Map<Bytes, Map<Column, Bytes>> getInput() {
      try {
        return snapshot.get(rows, columns);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map wrap2(Map m) {
      return Collections
          .unmodifiableMap(DefaultedMap.decorate(m, new DefaultedMap(new Value((Bytes) null))));
    }

    @SuppressWarnings("unchecked")
    public Map<String, Map<Column, Value>> toStringMap() {
      Map<Bytes, Map<Column, Bytes>> in = getInput();
      Map<String, Map<Column, Value>> out = new HashMap<>();

      for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) {
        out.put(encoder.decodeString(rowEntry.getKey()), wrap(rowEntry.getValue()));
      }

      return wrap2(out);
    }

    @SuppressWarnings("unchecked")
    public Map<Long, Map<Column, Value>> toLongMap() {
      Map<Bytes, Map<Column, Bytes>> in = getInput();
      Map<Long, Map<Column, Value>> out = new HashMap<>();

      for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) {
        out.put(encoder.decodeLong(rowEntry.getKey()), wrap(rowEntry.getValue()));
      }

      return wrap2(out);
    }

    @SuppressWarnings("unchecked")
    public Map<Integer, Map<Column, Value>> toIntegerMap() {
      Map<Bytes, Map<Column, Bytes>> in = getInput();
      Map<Integer, Map<Column, Value>> out = new HashMap<>();

      for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) {
        out.put(encoder.decodeInteger(rowEntry.getKey()), wrap(rowEntry.getValue()));
      }

      return wrap2(out);
    }

    @SuppressWarnings("unchecked")
    public Map<Bytes, Map<Column, Value>> toBytesMap() {
      Map<Bytes, Map<Column, Bytes>> in = getInput();
      Map<Bytes, Map<Column, Value>> out = new HashMap<>();

      for (Entry<Bytes, Map<Column, Bytes>> rowEntry : in.entrySet()) {
        out.put(rowEntry.getKey(), wrap(rowEntry.getValue()));
      }

      return wrap2(out);
    }
  }

  /**
   * @since 1.0.0
   */
  public class ColumnsMethods {
    private Collection<Bytes> rows;

    public ColumnsMethods(Collection<Bytes> rows) {
      this.rows = rows;
    }

    public MapConverter columns(Set<Column> columns) {
      return new MapConverter(rows, columns);
    }

    public MapConverter columns(Column... columns) {
      return columns(new HashSet<>(Arrays.asList(columns)));
    }
  }

  /**
   * @since 1.0.0
   */
  public class ValueRowMethods extends RowMethods<ValueFamilyMethods> {

    ValueRowMethods() {
      tl.super();
    }

    @Override
    ValueFamilyMethods create(Data data) {
      return new ValueFamilyMethods(data);
    }

    public ColumnsMethods rows(Collection<Bytes> rows) {
      return new ColumnsMethods(rows);
    }

    public ColumnsMethods rows(Bytes... rows) {
      return new ColumnsMethods(Arrays.asList(rows));
    }

    public ColumnsMethods rowsString(String... rows) {
      return rowsString(Arrays.asList(rows));
    }

    public ColumnsMethods rowsString(Collection<String> rows) {
      ArrayList<Bytes> conv = new ArrayList<>();
      for (String row : rows) {
        conv.add(encoder.encode(row));
      }

      return rows(conv);
    }

    public ColumnsMethods rowsLong(Long... rows) {
      return rowsLong(Arrays.asList(rows));
    }

    public ColumnsMethods rowsLong(Collection<Long> rows) {
      ArrayList<Bytes> conv = new ArrayList<>();
      for (Long row : rows) {
        conv.add(encoder.encode(row));
      }

      return rows(conv);
    }

    public ColumnsMethods rowsInteger(Integer... rows) {
      return rowsInteger(Arrays.asList(rows));
    }

    public ColumnsMethods rowsInteger(Collection<Integer> rows) {
      ArrayList<Bytes> conv = new ArrayList<>();
      for (Integer row : rows) {
        conv.add(encoder.encode(row));
      }

      return rows(conv);
    }

    public ColumnsMethods rowsBytes(byte[]... rows) {
      return rowsBytes(Arrays.asList(rows));
    }

    public ColumnsMethods rowsBytes(Collection<byte[]> rows) {
      ArrayList<Bytes> conv = new ArrayList<>();
      for (byte[] row : rows) {
        conv.add(Bytes.of(row));
      }

      return rows(conv);
    }

    public ColumnsMethods rowsByteBuffers(ByteBuffer... rows) {
      return rowsByteBuffers(Arrays.asList(rows));
    }

    public ColumnsMethods rowsByteBuffers(Collection<ByteBuffer> rows) {
      ArrayList<Bytes> conv = new ArrayList<>();
      for (ByteBuffer row : rows) {
        conv.add(Bytes.of(row));
      }

      return rows(conv);
    }

  }

  TypedSnapshotBase(SnapshotBase snapshot, Encoder encoder, TypeLayer tl) {
    this.snapshot = snapshot;
    this.encoder = encoder;
    this.tl = tl;
  }

  @Override
  public Bytes get(Bytes row, Column column) {
    return snapshot.get(row, column);
  }

  @Override
  public Map<Column, Bytes> get(Bytes row, Set<Column> columns) {
    return snapshot.get(row, columns);
  }

  @Override
  public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) {
    return snapshot.get(rowColumns);
  }

  @Override
  public Map<Bytes, Map<Column, Bytes>> get(Collection<Bytes> rows, Set<Column> columns) {
    return snapshot.get(rows, columns);
  }

  public ValueRowMethods get() {
    return new ValueRowMethods();
  }

  @Override
  public ScannerBuilder scanner() {
    return snapshot.scanner();
  }

  @SuppressWarnings({"unchecked"})
  private Map<Column, Value> wrap(Map<Column, Bytes> map) {
    Map<Column, Value> ret = Maps.transformValues(map, Value::new);
    return Collections.unmodifiableMap(DefaultedMap.decorate(ret, new Value((Bytes) null)));
  }

  @Override
  public long getStartTimestamp() {
    return snapshot.getStartTimestamp();
  }

  @Override
  public String gets(CharSequence row, Column column) {
    return snapshot.gets(row, column);
  }

  @Override
  public Map<Column, String> gets(CharSequence row, Set<Column> columns) {
    return snapshot.gets(row, columns);
  }

  @Override
  public Map<String, Map<Column, String>> gets(Collection<? extends CharSequence> rows,
      Set<Column> columns) {
    return snapshot.gets(rows, columns);
  }

  @Override
  public Map<RowColumn, String> gets(Collection<RowColumn> rowColumns) {
    return snapshot.gets(rowColumns);
  }
}


text:
#include "config.h"

#include "TileMapLayerInfo.h"
#include "BitBuffer.h"

using namespace std;

template<class X, class Y>
static bool setReportChanged( X& a, const Y& b ) {
   if ( a != b ) {
      a = b;
      return true;
   } else {
      return false;
   }
}

TileMapLayerInfo::TileMapLayerInfo()
{
   m_id = MAX_UINT32;
   m_updatePeriod = 0;
   m_isOptional = false;

   // These will be overridden by the load method, but if an old
   // tmfd is loaded then they will used.
   m_transient = false;
   m_alwaysFetchStrings = true;
   m_visible = true;
   m_presentInTileMapFormatDesc = true;
   m_serverOverride = false;
}

void
TileMapLayerInfo::setIDAndName( uint32 id,
                                const MC2SimpleString& name )
{
   m_name = name;
   m_id   = id;
}

bool
TileMapLayerInfo::setVisible( bool visible )
{
   return setReportChanged( m_visible, visible );
}

bool
TileMapLayerInfo::setUpdatePeriodMinutes( uint32 period )
{
   return setReportChanged( m_updatePeriod, period );
}

bool
TileMapLayerInfo::setOptional( int optional )
{
   return setReportChanged( m_isOptional, optional );
}

bool
TileMapLayerInfo::setServerOverrideNumber( uint8 nbr )
{
   return setReportChanged( m_serverOverride, nbr );
}

bool
TileMapLayerInfo::setPresent( bool present )
{
   return setReportChanged( m_presentInTileMapFormatDesc, present );
}

int
TileMapLayerInfo::getSizeInDataBuffer() const
{
   return 4 + 4 + m_name.length() + 1 + 4 + 1 + 1 + 1 + 2;
}

int
TileMapLayerInfo::save( BitBuffer& buf ) const
{
   int length = 0;
   {
      // Create temporary buffer for easier skipping.
      BitBuffer buf2( buf.getCurrentOffsetAddress(),
                      getSizeInDataBuffer() );

      buf2.writeNextBALong( 0 ); // Length, fill in later
      int startPos = buf2.getCurrentOffset();

      buf2.writeNextBALong( m_id );
      buf2.writeNextString( m_name );
      buf2.writeNextBALong( m_updatePeriod );
      buf2.writeNextBits( m_transient,1 );
      buf2.writeNextBits( m_isOptional, 1 );
      buf2.writeNextBits( m_serverOverride, 8 );
      buf2.writeNextBits( m_presentInTileMapFormatDesc, 1 );
      buf2.writeNextBits( m_visible, 1 );
      buf2.writeNextBits( m_alwaysFetchStrings, 1 );
      buf2.writeNextBits( 3, 1 );
      buf2.alignToByte();

      length = buf2.getCurrentOffset() - startPos;
   }
   buf.writeNextBALong( length );
   buf.readPastBytes( length );

   return length + 4;
}

int
TileMapLayerInfo::load( BitBuffer& buf )
{
   int nbrBytes = buf.readNextBALong();
   {
      // Create temporary buffer for easier skipping.
      BitBuffer buf2( buf.getCurrentOffsetAddress(), nbrBytes );

      buf2.readNextBALong( m_id );
      buf2.readNextString( m_name );
      buf2.readNextBALong( m_updatePeriod );
      buf2.readNextBits( m_transient,1 );
      buf2.readNextBits( m_isOptional, 1 );
      buf2.readNextBits( m_serverOverride, 8 );
      buf2.readNextBits( m_presentInTileMapFormatDesc, 1 );
      buf2.readNextBits( m_visible, 1 );
      buf2.readNextBits( m_alwaysFetchStrings, 1 );
#ifdef ARCH_OS_WINDOWS_ACTIVEX
      m_alwaysFetchStrings = true;
#endif
      buf2.alignToByte();
   }
   buf.readPastBytes( nbrBytes );
   return nbrBytes + 4;
}

int
TileMapLayerInfoVector::getSizeInDataBuffer() const
{
   int sum = 4 + 4; // Length + version
   for ( const_iterator it = begin();
         it != end();
         ++it ) {
      sum += it->getSizeInDataBuffer();
   }
   return sum;
}

int
TileMapLayerInfoVector::save( BitBuffer& buf ) const
{
   buf.writeNextBALong( 0 ); // version
   buf.writeNextBALong( size() );
   for ( const_iterator it = begin();
         it != end();
         ++it ) {
      it->save( buf );
   }
   return getSizeInDataBuffer();
}

int
TileMapLayerInfoVector::load( BitBuffer& buf )
{
   clear();
   buf.readNextBALong(); // version
   int length = buf.readNextBALong();
   resize( length );
   for ( iterator it = begin();
         it != end();
         ++it ) {
      it->load( buf );
   }
   return getSizeInDataBuffer();
}

const TileMapLayerInfo*
TileMapLayerInfoVector::getLayerInfo( uint32 layerID ) const
{
   for ( const_iterator it = begin();
         it != end();
         ++it ) {
      if ( (*it).getID() == layerID ) {
         return &(*it);
      }
   }
   return NULL;
}

bool
TileMapLayerInfoVector::updateLayers( TileMapLayerInfoVector& clientVector,
                                      const set<int>& existinLayers )
{
   // The clientVector will be the target of this operation.
   // Afterwards the vector is copied.
   int changed = 0;

   // Add changes from the client vector to our settings.
   for( TileMapLayerInfoVector::iterator it = clientVector.begin();
        it != clientVector.end();
        ++it ) {
      TileMapLayerInfo* myInfo = NULL;
      // Find the info from the server.
      for ( TileMapLayerInfoVector::iterator jt = this->begin();
            jt != this->end();
            ++jt ) {
         if ( jt->getID() == it->getID() ) {
            myInfo = &(*jt);
            break;
         }
      }
      changed += it->setPresent( myInfo &&
                ( existinLayers.find( it->getID() ) != existinLayers.end() ) );
      if ( ! myInfo ) {
         continue;
      }
      // These are always correct from the server by definition
      changed += it->setOptional( myInfo->isOptional() );
      // Non-optional layers can not be turned off.
      if ( ! it->isOptional() ) {
         changed += it->setVisible( true );
      }
      if ( it->getServerOverrideNumber() !=
           myInfo->getServerOverrideNumber() ) {
         // Force the update into the vector.
         changed +=
            it->setUpdatePeriodMinutes( myInfo->getUpdatePeriodMinutes() );
         changed += it->setVisible( myInfo->isVisible() );
         // But only do it once.
         it->setServerOverrideNumber( myInfo->getServerOverrideNumber() );
      } else {
         // Keep the info that the client entered
      }
   }
   // Add layers to the vector that are not present yet.
   for ( iterator jt = begin();
         jt != end();
         ++jt ) {
      bool found = false;
      for ( iterator it = clientVector.begin();
            it != clientVector.end();
            ++it ) {
         if ( jt->getID() == it->getID() ) {
            found = true;
            break;
         }
      }
      if ( ! found ) {
         // Insert that into the client vector.
         ++changed;
         clientVector.push_back( *jt );
      }
   }

   // This vector will now be the same as the other one.
   *this = clientVector;

   return changed;
}

bool
TileMapLayerInfoVector::updateLayersToDisplay( set<int>& layerIDs ) const
{
   set<int> newLayers;
   for( const_iterator jt = begin();
        jt != end();
        ++jt ) {
      if ( jt->isVisible() && jt->isPresent() ) {
         newLayers.insert( jt->getID() );
      }
   }
   newLayers.swap( layerIDs );
   return newLayers != layerIDs;
}


text:
vagrant-disque
==============

Vagrantfiles for building different types of Disque clusters for testing and
development.

Single Node
-----------
```sh
cd 01_singleHost
vagrant up
```

Appears as port 7711 locally (with 17711 for clustering).
Upstart init script included.

You may want to increase the RAM in the Vagrantfile if needed.

Clustered Nodes
---------------
```sh
cd 02_basicCluster
vagrant up
```

Opens up port 7710-7713 locally (with 17710-17713 for the cluster bus). The
nodes are all speaking via the private network. The Disque build is cached
while building instances for faster bootstrap time.

Misc Settings
-------------
The MEMSIZE and CPUS variables in the Vagrantfiles do what you expect them to,
and change the configuration of the virtual machines.

NODECOUNT (only in the second example) sets the number of nodes in the cluster.
I have only tested this to 4, but I'm sure it will be fine if you set it to a
number that your system can support.

Disque Info
-----------
[Disque](https://github.com/antirez/disque)


text:
/**
 * Changes the values of getMode().test, getMode().localDev to false
 * and getMode().localDev to true.
 * @param {Object} babelTypes
 */
const {resolve, dirname} = require('path');

let shouldResolveDevelopmentMode = true;

// This plugin is not executed when AMP is building resources in isForTesting mode.
module.exports = function ({types: t}) {
  let getModeFound = false;
  return {
    pre() {
      const {isEsmBuild = true} = this.opts;
      // Only apply the development resolution when building module output.
      // This is due to the module output only applying to AMP Caches.
      shouldResolveDevelopmentMode = isEsmBuild;
    },
    visitor: {
      ImportDeclaration({node}, state) {
        const {specifiers, source} = node;
        if (!source.value.endsWith('/mode')) {
          return;
        }
        specifiers.forEach((specifier) => {
          if (specifier.imported && specifier.imported.name === 'getMode') {
            const filepath = resolve(
              dirname(state.file.opts.filename),
              source.value
            );
            if (filepath.endsWith('/amphtml/src/mode')) {
              getModeFound = true;
            }
          }
        });
      },
      MemberExpression(path) {
        if (!getModeFound) {
          return;
        }

        const {node} = path;
        const {object: obj, property} = node;
        const {callee} = obj;
        if (callee && callee.name === 'getMode') {
          if (property.name === 'test' || property.name === 'localDev') {
            path.replaceWith(t.booleanLiteral(false));
          }
          if (shouldResolveDevelopmentMode && property.name === 'development') {
            path.replaceWith(t.booleanLiteral(false));
          }
          if (property.name === 'minified') {
            path.replaceWith(t.booleanLiteral(true));
          }
        }
      },
    },
  };
};


text:
#include "ofMain.h"

#define SPEED_THRESHOLD 15

class TargetCursor {

public:
	TargetCursor();
	void draw();
	void update();
	void update(float, float, float, float);
	static ofPoint leftHand;
	static ofPoint rightHand;
	static float leftDistance;
	static float rightDistance;
    static ofSoundPlayer swipe[7];

private:

	vector<ofPoint*> leftCoordinates;
	vector<ofPoint*> rightCoordinates;
};


text:
describe('promise', function () {
  beforeEach(function () {
    jasmine.Ajax.install();
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('should provide succinct object to then', function (done) {
    var response;

    axios('/foo').then(function (r) {
      response = r;
    });

    getAjaxRequest().then(function (request) {
      request.respondWith({
        status: 200,
        responseText: '{"hello":"world"}'
      });

      setTimeout(function () {
        expect(typeof response).toEqual('object');
        expect(response.data.hello).toEqual('world');
        expect(response.status).toEqual(200);
        expect(response.headers['content-type']).toEqual('application/json');
        expect(response.config.url).toEqual('/foo');
        done();
      });
    });
  });

  it('should support all', function (done) {
    var fulfilled = false;

    axios.all([true, 123]).then(function () {
      fulfilled = true;
    });

    setTimeout(function () {
      expect(fulfilled).toEqual(true);
      done();
    }, 100);
  });

  it('should support spread', function (done) {
    var sum = 0;
    var fulfilled = false;
    var result;

    axios
      .all([123, 456])
      .then(axios.spread(function (a, b) {
        sum = a + b;
        fulfilled = true;
        return 'hello world';
      }))
      .then(function (res) {
        result = res;
      });

    setTimeout(function () {
      expect(fulfilled).toEqual(true);
      expect(sum).toEqual(123 + 456);
      expect(result).toEqual('hello world');
      done();
    }, 100);
  });
});