text:
package com.horical.appnote;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.horical.appnote.Background.MediaService;
import com.horical.appnote.BaseActivity.BaseActivity;
import com.horical.appnote.DTO.CalendarObject;
import com.horical.appnote.DTO.FileDTO.FileData;
import com.horical.appnote.DTO.NoteDTO.NoteData;
import com.horical.appnote.DTO.NoteDTO.NoteReminder;
import com.horical.appnote.DTO.NoteDTO.NoteSummary;
import com.horical.appnote.Interfaces.EditNoteListener;
import com.horical.appnote.LocalStorage.ApplicationSharedData;
import com.horical.appnote.LocalStorage.DAO.NoteDataDAO;
import com.horical.appnote.LocalStorage.DAO.NoteReminderDAO;
import com.horical.appnote.LocalStorage.DataConstant;
import com.horical.appnote.Fragments.BaseFragment;
import com.horical.appnote.Fragments.CalendarFragment;
import com.horical.appnote.Fragments.ForgotAccountFragment;
import com.horical.appnote.Fragments.ListNotesFragment;
import com.horical.appnote.Fragments.LoginFragment;
import com.horical.appnote.Fragments.NewNoteFragment;
import com.horical.appnote.Fragments.SettingFragment;
import com.horical.appnote.Fragments.SignUpFragment;
import com.horical.appnote.Fragments.FilesManagerFragment;
import com.horical.appnote.Fragments.ViewAccountFragment;
import com.horical.appnote.Fragments.ViewNoteFragment;
import com.horical.appnote.Fragments.ViewReminderFragment;
import com.horical.appnote.Interfaces.MainInterface;
import com.horical.appnote.Interfaces.NoteDataLine;
import com.horical.appnote.MyView.Item.BaseItem;
import com.horical.appnote.MyView.Item.ItemNormal;
import com.horical.appnote.MyView.Item.ItemNormalWithNotification;
import com.horical.appnote.MyView.MyAdapter.SideMenuAdapter;
import com.horical.appnote.MyView.RoundImageView;
import com.horical.appnote.ServerStorage.Callback.DeleteFileCallback;
import com.horical.appnote.ServerStorage.Callback.DeleteNoteCallback;
import com.horical.appnote.ServerStorage.Callback.DownloadDataCallback;
import com.horical.appnote.ServerStorage.Callback.DownloadFileCallback;
import com.horical.appnote.ServerStorage.Callback.NoteCallback;
import com.horical.appnote.ServerStorage.Callback.UploadFileCallback;
import com.horical.appnote.ServerStorage.FileRoute;
import com.horical.appnote.ServerStorage.NoteRoute;
import com.horical.appnote.ServerStorage.Param.UploadFileParam;
import com.horical.appnote.ServerStorage.Param.UploadNoteParam;
import com.horical.appnote.ServerStorage.Response.FileResponse;
import com.horical.appnote.ServerStorage.Response.NoteResponse;
import com.horical.appnote.Supports.CalendarUtils;
import com.horical.appnote.Supports.FileUtils;
import com.horical.appnote.Supports.LanguageUtils;
import com.horical.appnote.Supports.MediaUtils;
import com.horical.appnote.Supports.SupportUtils;
import com.parse.ParseException;
import com.parse.ParseFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends BaseActivity implements MainInterface, BaseActivity.ActivityAction,
        LoginFragment.LoginListener, SignUpFragment.SignUpListener, ImageButton.OnClickListener {

    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;

    private DrawerLayout mMainLayout;
    private LinearLayout mActionBar;
    private LinearLayout mSideMenuArea;
    private TextView mTitleHeader, mInternetConnection;

    private RoundImageView mRoundImageView;

    private ArrayList<BaseItem> mSideMenuResource;
    private SideMenuAdapter mSideMenuAdapter;

    private String mFragmentName = "";

    private Bundle mBundle;

    private NoteDataDAO mNoteDataDAO;
    private NoteReminderDAO mNoteReminderDAO;

    private ArrayList<NoteData> mListNoteData;
    private ArrayList<NoteReminder> mListReminders;

    private ArrayList<FileData> mListImageFile;
    private ArrayList<FileData> mListVideoFile;
    private ArrayList<FileData> mListAudioFile;

    private ImageButton mButtonSearchNote, mButtonOptionMenu, mSyncButton;
    private AlertDialog mDialog;

    private Intent mReminderService;

    private TextView mTvAppTitle;
    private LinearLayout mProgressbarLayout;

    private int mNumberOfFile = 0;

    private int mCurrentUploadedFiles = 0;
    private int mCurrentSavedNote = 0;

    private ProgressBar mSyncProgress;
    private TextView mLogView;

    private boolean mInternetAvailability;

    private EditNoteListener mEditNoteListener;

    private boolean mListImagesIsReloading, mListVideosIsReloading, mListAudiosIsReloading;

    private enum SameFragmentProperty {
        SameCurrent, Exists, NotExists
    }

    public interface SyncDataCallback {
        void onSyncSuccess(String message);
        void onSyncFail(String message);
    }

    @SuppressLint("CommitTransaction")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MediaUtils.setActivity(this);
        ApplicationSharedData.initResource(this);
        LanguageUtils.setContext(this);

        mNoteDataDAO = new NoteDataDAO(this);
        this.reloadListNote();

        mReminderService = new Intent(MainActivity.this, MediaService.class);

        AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
        mBuilder.setNegativeButton("Got it", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setPositiveButton("Later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        mDialog = mBuilder.create();

        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < mListReminders.size(); i++) {
                    final NoteReminder noteReminder = mListReminders.get(i);
                    if (noteReminder.readyToRemind() == 0) {
                        final int pos = i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mDialog.setTitle(noteReminder.getContent());
                                mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialogInterface) {
                                        stopMedia();
                                        ViewReminderFragment fragment = (ViewReminderFragment) mFragmentManager.
                                                findFragmentByTag(BaseFragment.ViewReminderFragment);
                                        if (fragment != null) {
                                            fragment.refreshListReminder();
                                        }
                                        mListReminders.remove(pos);
                                    }
                                });
                                mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialogInterface) {
                                        Toast.makeText(MainActivity.this, "Later", Toast.LENGTH_SHORT).show();
                                        stopMedia();
                                    }
                                });
                                if (MainActivity.this.hasWindowFocus()) {
                                    mDialog.show();
                                }
                            }
                        });
                        startMedia(noteReminder.getVoice());
                    }
                }
            }
        }, 5, 5, TimeUnit.SECONDS);

        mBundle = new Bundle();

        //set up Main fragment
        mFragmentManager = getFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        if (ApplicationSharedData.getUser().equals("")) {
            mFragmentName = BaseFragment.LoginFragment;
            LoginFragment loginFragment = new LoginFragment();
            loginFragment.setListener(this);
            mFragmentTransaction.add(R.id.fragmentsContainer, loginFragment, mFragmentName);
        } else {
            mFragmentName = BaseFragment.ListNotesFragment;
            ListNotesFragment listNotesFragment = new ListNotesFragment();
            mFragmentTransaction.add(R.id.fragmentsContainer, listNotesFragment, mFragmentName);
        }
        mFragmentTransaction.addToBackStack(null);
        mFragmentTransaction.commit();

        //Get neccessary view
        mMainLayout = (DrawerLayout) findViewById(R.id.MainLayout);
        mActionBar = (LinearLayout) findViewById(R.id.ActionBar);
        mSideMenuArea = (LinearLayout) findViewById(R.id.areaSideMenu);
        ListView mSideMenu = (ListView) findViewById(R.id.sideMenu);
        mTitleHeader = (TextView) findViewById(R.id.TitleHeader);
        mButtonSearchNote = (ImageButton) findViewById(R.id.buttonSearch);
        mButtonSearchNote.setOnClickListener(this);
        mButtonOptionMenu = (ImageButton) findViewById(R.id.buttonOptionMenu);
        mButtonOptionMenu.setOnClickListener(this);
        mSyncButton = (ImageButton) findViewById(R.id.buttonSyncToServer);
        mSyncButton.setOnClickListener(this);
        mInternetConnection = (TextView) findViewById(R.id.tvInternet);
        mRoundImageView = (RoundImageView) findViewById(R.id.imageAvatar);
        mRoundImageView.setOnClickListener(this);
        mTvAppTitle = (TextView) findViewById(R.id.tvAppTitle);
        mSyncProgress = (ProgressBar) findViewById(R.id.SyncBar);
        mProgressbarLayout = (LinearLayout) findViewById(R.id.ProgressBarArea);
        mProgressbarLayout.setOnClickListener(this);
        mLogView = (TextView) findViewById(R.id.LogView);
        mLogView.setText(LanguageUtils.getSyncTitleString());
        TextView mMainProcess = (TextView) findViewById(R.id.tvMainProcess);
        mMainProcess.setText(LanguageUtils.getProcessingString());

        this.checkAvatar();

        //Set up resource for side menu
        ArrayList<String> menuStringResource = new ArrayList<>();
        Collections.addAll(menuStringResource, LanguageUtils.getSideMenu());
        menuStringResource.add("Last sync: " + (new Date()).toString());
        mSideMenuResource = new ArrayList<>();
        initSideMenu(menuStringResource);
        mSideMenuAdapter = new SideMenuAdapter(MainActivity.this, 0, mSideMenuResource);
        mSideMenu.setAdapter(mSideMenuAdapter);

        //set up for navigation button to control fragments
        findViewById(R.id.buttonNavigation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListFragments.size() <= 0) mMainLayout.openDrawer(mSideMenuArea);
                else Back();
            }
        });

        //set up for menu to control fragments
        mSideMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String title = mSideMenuAdapter.getStringAt(i);
                if (title.equals(LanguageUtils.getNewNoteString())) {
                    NewFragment(BaseFragment.NewNoteFragment);
                }
                if (title.equals(LanguageUtils.getListNotesString())) {
                    NewFragment(BaseFragment.ListNotesFragment);
                }
                if (title.equals(LanguageUtils.getCalendarString())) {
                    NewFragment(BaseFragment.CalendarFragment);
                }
                if (title.equals(LanguageUtils.getFileManagerString())) {
                    NewFragment(BaseFragment.FileManagerFragment);
                }
                if (title.equals(LanguageUtils.getSettingString())) {
                    NewFragment(BaseFragment.SettingsFragment);
                }
                mMainLayout.closeDrawer(mSideMenuArea);
            }
        });

        mNoteReminderDAO = new NoteReminderDAO(this);
        this.reloadListReminder();

        this.reloadListFile(DataConstant.TYPE_IMAGE);
        this.reloadListFile(DataConstant.TYPE_VIDEOCLIP);
        this.reloadListFile(DataConstant.TYPE_VOICE);

        this.updateInternetStatus();

        this.updateUI();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onStart() {
        super.onStart();
        getWindow().setStatusBarColor(Color.parseColor("#075c52"));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonSearch:
                switch (mFragmentName) {
                    case BaseFragment.FileManagerFragment:
                        FilesManagerFragment listFileFragment = (FilesManagerFragment) mFragmentManager.findFragmentByTag(mFragmentName);
                        listFileFragment.toggleSearchBar();
                        break;

                    case BaseFragment.ListNotesFragment:
                        ListNotesFragment listNotesFragment = (ListNotesFragment) mFragmentManager.findFragmentByTag(mFragmentName);
                        listNotesFragment.toggleSearchBar();
                        break;
                    default:
                        break;
                }
                return;
            case R.id.ProgressBarArea:
                showLoadingEffect(false, "");
                return;
            case R.id.buttonSyncToServer:
                if (mInternetAvailability) {
                    this.syncData(new SyncDataCallback() {
                        @Override
                        public void onSyncSuccess(String message) {
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                            showLoadingEffect(false, "");
                        }

                        @Override
                        public void onSyncFail(String message) {
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                            showLoadingEffect(false, "");
                        }
                    }, true);
                } else {
                    Toast.makeText(MainActivity.this, "You are in offline!", Toast.LENGTH_SHORT).show();
                }
                return;
            case R.id.buttonOptionMenu:
                PopupMenu popupMenu = new PopupMenu(this, mButtonOptionMenu);
                popupMenu.getMenuInflater().inflate(LanguageUtils.getMainMenuRes(), popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.itemAboutUs:
                                break;
                            case R.id.itemHome:
                                NewFragment(BaseFragment.ListNotesFragment);
                                break;
                            case R.id.itemLogOut:
                                if (mInternetAvailability) {
                                    onLogout();
                                } else {
                                    Toast.makeText(MainActivity.this, LanguageUtils.getInternetOfflineString(), Toast.LENGTH_SHORT).show();
                                }
                                break;
                            case R.id.itemViewAccount:
                                NewFragment(BaseFragment.ViewAccountFragment);
                                break;
                        }
                        return false;
                    }
                });
                popupMenu.show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.stopMedia();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_activity_en, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (mListFragments.size() <= 0) {
            finish();
        } else {
            Back();
            if (mListFragments.size() <= 0) {
                Toast.makeText(this, LanguageUtils.getNotifyPressAgainString(), Toast.LENGTH_SHORT).show();
            }

            if (mEditNoteListener != null && ApplicationSharedData.isAutoSave()) {
                mEditNoteListener.saveNote(false);
            }
        }
    }

    /*implement BaseActivity.ActivityAction*/
    @Override
    public void NewFragment(String fragment_id) {
        this.showLoadingEffect(false, "");
        SameFragmentProperty mCheckSameStatus = checkSameFragment(fragment_id);
        if (mCheckSameStatus == SameFragmentProperty.SameCurrent) {
            Toast.makeText(getApplicationContext(), LanguageUtils.getNotifySameScreenString(), Toast.LENGTH_SHORT).show();
        } else {
            BaseFragment fragment;
            if (mFragmentManager.findFragmentByTag(mFragmentName) != null) {
                mListFragments.push(mFragmentName);
            } else {
                mListFragments.clear();
            }

            mFragmentTransaction = mFragmentManager.beginTransaction();
            mFragmentName = fragment_id;
            switch (fragment_id) {
                case BaseFragment.NewNoteFragment:
                    fragment = new NewNoteFragment();
                    mBundle = new Bundle();
                    mBundle.putBoolean("isCreate", true);
                    fragment.setArguments(mBundle);
                    this.updateSideMenuUI(LanguageUtils.getNewNoteString());
                    mEditNoteListener = (NewNoteFragment) fragment;
                    break;

                case BaseFragment.UpdateNoteFragment:
                    fragment = new NewNoteFragment();
                    mFragmentName = BaseFragment.NewNoteFragment;
                    mBundle.putBoolean("isCreate", false);
                    fragment.setArguments(mBundle);
                    this.updateSideMenuUI(LanguageUtils.getNewNoteString());
                    mEditNoteListener = (NewNoteFragment) fragment;
                    break;

                case BaseFragment.ListNotesFragment:
                    fragment = new ListNotesFragment();
                    mListFragments.clear();
                    this.updateSideMenuUI(LanguageUtils.getListNotesString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.ViewNoteFragment:
                    fragment = new ViewNoteFragment();
                    fragment.setArguments(mBundle);
                    this.updateSideMenuUI(LanguageUtils.getListNotesString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.CalendarFragment:
                    fragment = new CalendarFragment();
                    ((CalendarFragment) fragment).setCallback(this);
                    this.updateSideMenuUI(LanguageUtils.getCalendarString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.ViewReminderFragment:
                    fragment = new ViewReminderFragment();
                    fragment.setArguments(mBundle);
                    this.updateSideMenuUI(LanguageUtils.getCalendarString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.FileManagerFragment:
                    fragment = new FilesManagerFragment();
                    this.updateSideMenuUI(LanguageUtils.getFileManagerString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.SettingsFragment:
                    fragment = new SettingFragment();
                    this.updateSideMenuUI(LanguageUtils.getSettingString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.SignUpFragment:
                    fragment = new SignUpFragment();
                    ((SignUpFragment) fragment).setListener(this);
                    mEditNoteListener = null;
                    break;

                case BaseFragment.ForgotAccountFragment:
                    fragment = new ForgotAccountFragment();
                    mEditNoteListener = null;
                    break;

                case BaseFragment.ViewAccountFragment:
                    fragment = new ViewAccountFragment();
                    this.updateSideMenuUI(LanguageUtils.getSettingString());
                    mEditNoteListener = null;
                    break;

                case BaseFragment.LoginFragment:
                    fragment = new LoginFragment();
                    ((LoginFragment) fragment).setListener(this);
                    mEditNoteListener = null;
                    break;

                default:
                    mFragmentTransaction.commit();
                    return;
            }
            fragment.setMainListener(this);

            //if fragment is existed
            if (mCheckSameStatus == SameFragmentProperty.Exists && !fragment_id.equals(BaseFragment.ListNotesFragment)) {
                //get the old one
                getExistsFragment(mFragmentName);

                //begin update back stack
                Stack<String> stack = new Stack<>();
                String key;
                while (mListFragments.size() > 1) {
                    key = mListFragments.pop();
                    if (key.contains(mFragmentName)) break;
                    else stack.push(key);
                }

                while (!stack.isEmpty()) {
                    mListFragments.push(stack.pop());
                }
                //end update back stack

            } else {
                fragment.setFragmentName(mFragmentName);
                mFragmentTransaction.replace(R.id.fragmentsContainer, fragment, fragment.getFragmentName());
                mFragmentTransaction.addToBackStack(null);
            }
            if (mListFragments.size() >= 1 && !mFragmentName.contains(BaseFragment.ListNotesFragment)) {
                ((ImageButton) findViewById(R.id.buttonNavigation)).setImageResource(R.drawable.ic_arrow_back_white_24dp);
            } else {
                ((ImageButton) findViewById(R.id.buttonNavigation)).setImageResource(R.drawable.ic_menu_white_24dp);
            }
            mFragmentTransaction.commit();
        }

        this.updateUI();
    }

    @Override
    public void Back() {
        if (mListFragments.size() >= 1) {
            mFragmentName = mListFragments.pop();
            getExistsFragment(mFragmentName);
            mFragmentTransaction.commit();
        }
        if (mListFragments.size() == 0) {
            ((ImageButton) findViewById(R.id.buttonNavigation)).setImageResource(R.drawable.ic_menu_white_24dp);
        }
        switch (mFragmentName) {
            case BaseFragment.NewNoteFragment:
            case BaseFragment.UpdateNoteFragment:
                this.updateSideMenuUI(LanguageUtils.getNewNoteString());
                break;
            case BaseFragment.ListNotesFragment:
            case BaseFragment.ViewNoteFragment:
                this.updateSideMenuUI(LanguageUtils.getListNotesString());
                break;
            case BaseFragment.CalendarFragment:
            case BaseFragment.ViewReminderFragment:
                this.updateSideMenuUI(LanguageUtils.getCalendarString());
                break;
            case BaseFragment.FileManagerFragment:
                this.updateSideMenuUI(LanguageUtils.getFileManagerString());
                break;
            case BaseFragment.SettingsFragment:
                this.updateSideMenuUI(LanguageUtils.getSettingString());
                break;
        }
        this.updateUI();
    }

    /*MainActivity member method*/
    //set up data resource for side menu
    private void stopMedia() {
        if (MediaService.isRunning()) {
            stopService(mReminderService);
            MediaService.setRunning(false);
        }
    }

    private void startMedia(String audio) {
        if (!MediaService.isRunning()) {
            MediaService.setAudioName(audio);
            startService(mReminderService);
            MediaService.setRunning(true);
        }
    }

    private void getAllNotesFromServer() {
        //TODO get all notes from parse.com
        NoteRoute request = new NoteRoute();
        request.getAllNotes(new DownloadDataCallback<NoteData>() {
            @Override
            public void onDownloadSuccess(final ArrayList<NoteData> data) {
                if (data != null && !data.isEmpty()) {
                    for (NoteData noteData : data) {
                        for (NoteData note : mListNoteData) {
                            if (note.toString().equals(noteData.toString())) {
                                return;
                            }
                        }
                        NoteDataDAO dao = new NoteDataDAO(MainActivity.this);
                        dao.setNoteData(noteData);
                        dao.insertNote(new NewNoteFragment.CreateNoteCallback() {
                            @Override
                            public void onSuccess(String message) {
                                mCurrentSavedNote++;
                                if (mCurrentSavedNote == data.size()) {
                                    Toast.makeText(MainActivity.this, LanguageUtils.getNotifySyncSuccessString(), Toast.LENGTH_SHORT).show();
                                    reloadListNote();
                                    if (mFragmentName.equals(BaseFragment.ListNotesFragment)) {
                                        ListNotesFragment fragment = (ListNotesFragment) mFragmentManager.findFragmentByTag(mFragmentName);
                                        if (fragment != null) {
                                            fragment.reLoadListNote();
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFailure(String message) {

                            }
                        });
                    }
                } else {
                    Toast.makeText(MainActivity.this, LanguageUtils.getNotifyDownloadFailString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(NoteResponse response) {

            }
        });
        reloadListNote();
        NewFragment(BaseFragment.ListNotesFragment);
    }

    private void syncData(final SyncDataCallback callback, final boolean showMessage) {
        if (showMessage) {
            Toast.makeText(this, LanguageUtils.getNotifyLimitString(), Toast.LENGTH_LONG).show();
        }
        FileRoute fileRequest = new FileRoute();
        showLoadingEffect(true, LanguageUtils.getProcessingString());
        fileRequest.deleteAllFiles(new DeleteFileCallback() {
            @Override
            public void onSuccess(FileResponse response) {
                NoteRoute noteRequest = new NoteRoute();
                noteRequest.deleteAllNotes(new DeleteNoteCallback() {
                    @Override
                    public void onSuccess(NoteResponse response) {
                        uploadData(callback, showMessage);
                    }

                    @Override
                    public void onFail(ParseException e) {
                        if (showMessage) {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                        showLoadingEffect(false, "");
                    }
                });
            }

            @Override
            public void onFail(ParseException e) {
                if (showMessage) {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                showLoadingEffect(false, "");
            }
        });
    }

    private void uploadData(final SyncDataCallback callback, final boolean showMessage) {

        final HashMap<String, String> listFiles = new HashMap<>();

        for (FileData data : mListImageFile) {
            listFiles.put(data.getFilePath(), DataConstant.TYPE_IMAGE);
        }
        for (FileData data : mListVideoFile) {
            listFiles.put(data.getFilePath(), DataConstant.TYPE_VIDEOCLIP);
        }
        for (FileData data : mListAudioFile) {
            listFiles.put(data.getFilePath(), DataConstant.TYPE_VOICE);
        }

        if (mListNoteData.isEmpty()) {
            callback.onSyncSuccess(LanguageUtils.getNotifyNothingUploadString());
            return;
        }

        FileRoute request = new FileRoute();
        final int all_files = ((mListImageFile != null) ? mListImageFile.size() : 0) +
                ((mListVideoFile != null) ? mListVideoFile.size() : 0) +
                ((mListAudioFile != null) ? mListAudioFile.size() : 0);
        if (all_files == 0) {
            NoteRoute note_request = new NoteRoute();
            for (NoteData noteData : mListNoteData) {
                if (noteData.getNoteData() != null && !noteData.getNoteData().isEmpty()) {
                    UploadNoteParam uploadNoteParam = new UploadNoteParam();
                    uploadNoteParam.userId = ApplicationSharedData.getUserID();
                    uploadNoteParam.id = String.valueOf(noteData.getNoteSummary().getID());
                    uploadNoteParam.content = noteData.createJSON();

                    note_request.uploadNote(uploadNoteParam, new NoteCallback() {
                        @Override
                        public void onSuccess(NoteResponse response) {
                            callback.onSyncSuccess(response.message);
                            showLoadingEffect(false, "");
                        }

                        @Override
                        public void onFail(ParseException e) {
                            callback.onSyncFail(e.getMessage());
                            showLoadingEffect(false, "");
                        }
                    });
                }
            }
        } else {
            for (Map.Entry<String, String> entry : listFiles.entrySet()) {
                UploadFileParam param = new UploadFileParam();
                param.type = entry.getValue();
                param.name = SupportUtils.getNameFromPath(entry.getKey());
                param.path = entry.getKey();
                request.uploadFile(param, new UploadFileCallback() {
                    @Override
                    public void onSuccess(FileResponse response) {
                        mCurrentUploadedFiles++;
                        if (mCurrentUploadedFiles == all_files) {
                            NoteRoute request = new NoteRoute();
                            for (NoteData noteData : mListNoteData) {
                                if (noteData.getNoteData() != null && !noteData.getNoteData().isEmpty()) {
                                    UploadNoteParam uploadNoteParam = new UploadNoteParam();
                                    uploadNoteParam.userId = ApplicationSharedData.getUserID();
                                    uploadNoteParam.id = String.valueOf(noteData.getNoteSummary().getID());
                                    uploadNoteParam.content = noteData.createJSON();

                                    request.uploadNote(uploadNoteParam, new NoteCallback() {
                                        @Override
                                        public void onSuccess(NoteResponse response) {
                                            callback.onSyncSuccess(response.message);
                                            showLoadingEffect(false, "");
                                        }

                                        @Override
                                        public void onFail(ParseException e) {
                                            callback.onSyncFail(e.getMessage());
                                            showLoadingEffect(false, "");
                                        }
                                    });
                                }
                            }

                            mCurrentUploadedFiles = 0;
                        }
                    }

                    @Override
                    public void onFail(ParseException e) {
                        if (showMessage) {
                            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                        showLoadingEffect(false, "");
                    }
                });
            }
        }
    }

    private void deleteAllNoteInDatabase(final SyncDataCallback callback) {
        int real = 0, deleted = 0;
        NoteDataDAO noteDataDAO = new NoteDataDAO(MainActivity.this);
        for (NoteData noteData : mListNoteData) {
            if (noteData.getNoteData() != null && !noteData.getNoteData().isEmpty()) {
                real++;
                if (noteDataDAO.deleteNote(noteData.getNoteSummary().getID())) {
                    deleted++;
                }
            }
        }
        if (deleted == real) {
            callback.onSyncSuccess(LanguageUtils.getNotifyCompletedString());
        } else {
            callback.onSyncFail(LanguageUtils.getNotifyFailedString());
        }
    }

    private void initSideMenu(ArrayList<String> dataSource) {
        for (String data : dataSource) {
            if (data.equals(LanguageUtils.getNewNoteString()) ||
                    data.equals(LanguageUtils.getListNotesString()) ||
                    data.equals(LanguageUtils.getSettingString())) {

                ItemNormal itemNormal = new ItemNormal();
                itemNormal.setNameOfItem(data);
                itemNormal.setItemName(data);
                itemNormal.setFocused(false);
                if (data.equals(LanguageUtils.getNewNoteString())) {
                    itemNormal.setIllustrateImage(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_add_black_24dp));
                    itemNormal.setBitmapIllustrateImageFocus(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_add_green_24dp));
                } else {
                    if (data.equals(LanguageUtils.getListNotesString())) {
                        itemNormal.setFocused(true);
                        itemNormal.setIllustrateImage(
                                SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_list_black_24dp));
                        itemNormal.setBitmapIllustrateImageFocus(
                                SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_list_green_24dp));
                    } else {
                        itemNormal.setIllustrateImage(
                                SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_settings_black_24dp));
                        itemNormal.setBitmapIllustrateImageFocus(
                                SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_settings_green_24dp));
                    }
                }
                mSideMenuResource.add(itemNormal);
            }

            if (data.equals(LanguageUtils.getCalendarString()) || data.equals(LanguageUtils.getFileManagerString())) {
                ItemNormalWithNotification itemNotification = new ItemNormalWithNotification();
                itemNotification.setNameOfItem(data);
                itemNotification.setItemName(data);
                itemNotification.setFocused(false);
                if (data.equals(LanguageUtils.getCalendarString())) {
                    itemNotification.setIllustrateImage(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_event_note_black_24dp));
                    itemNotification.setBitmapIllustrateImageFocus(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_event_note_green_24dp));
                } else {
                    itemNotification.setIllustrateImage(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_folder_black_24dp));
                    itemNotification.setBitmapIllustrateImageFocus(
                            SupportUtils.getBitmapResource(MainActivity.this, R.drawable.ic_folder_green_24dp));
                }
                mSideMenuResource.add(itemNotification);
            }
        }
    }

    public void sortListFile(String type) {
        switch (type) {
            case DataConstant.TYPE_VOICE:
                for (int i = 0; i < mListAudioFile.size() - 1; i++)
                    for (int j = i + 1; j < mListAudioFile.size(); j++) {
                        if (mListAudioFile.get(i).compare(mListAudioFile.get(j)) == 1) {
                            Collections.swap(mListAudioFile, i, j);
                        }
                    }
                break;
            case DataConstant.TYPE_IMAGE:
                for (int i = 0; i < mListImageFile.size() - 1; i++)
                    for (int j = i + 1; j < mListImageFile.size(); j++) {
                        if (mListImageFile.get(i).compare(mListImageFile.get(j)) == 1) {
                            Collections.swap(mListImageFile, i, j);
                        }
                    }
                break;
            case DataConstant.TYPE_VIDEOCLIP:
                for (int i = 0; i < mListVideoFile.size() - 1; i++)
                    for (int j = i + 1; j < mListVideoFile.size(); j++) {
                        if (mListVideoFile.get(i).compare(mListVideoFile.get(j)) == 1) {
                            Collections.swap(mListVideoFile, i, j);
                        }
                    }
                break;
        }
    }

    //check if current fragment is the same with the on replacing fragment
    private SameFragmentProperty checkSameFragment(String fragment_id) {
        String searchObject;
        searchObject = fragment_id;
        if (mFragmentName.contains(searchObject)) return SameFragmentProperty.SameCurrent;
        for (String name : mListFragments) {
            if (name.contains(searchObject))
                return SameFragmentProperty.Exists;
        }
        return SameFragmentProperty.NotExists;
    }

    private void getExistsFragment(String name) {
        if (mFragmentManager.findFragmentByTag(name) != null) {
            mFragmentTransaction = mFragmentManager.beginTransaction();
            mFragmentTransaction.replace(R.id.fragmentsContainer, mFragmentManager.findFragmentByTag(name));
        }
    }

    private void updateSideMenuUI(String item_name) {
        for (BaseItem item : mSideMenuResource) {
            if (item.getNameOfItem().contains(item_name)) {
                item.setFocused(true);
            } else {
                item.setFocused(false);
            }
        }
        mSideMenuAdapter.notifyDataSetChanged();
    }

    private void checkAvatar() {
        String[] avatars = FileUtils.getListFile("Avatar");
        if (avatars != null && avatars.length > 0) {
            Bitmap bitmap = BitmapFactory.decodeFile(avatars[0]);
            if (bitmap != null) {
                mRoundImageView.setImageBitmap(bitmap);
            }
        }
    }

    private void updateUI() {
        switch (mFragmentName) {
            case BaseFragment.CalendarFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getCalendarString());
                break;
            case BaseFragment.ViewAccountFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getAccountString());
                break;
            case BaseFragment.ForgotAccountFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                mActionBar.setVisibility(View.GONE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getAccountString());
                break;
            case BaseFragment.FileManagerFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.VISIBLE);
                mTvAppTitle.setText(LanguageUtils.getFileString());
                break;
            case BaseFragment.ListNotesFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.VISIBLE);
                mTvAppTitle.setText(getResources().getString(R.string.app_name));
                break;
            case BaseFragment.LoginFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                mActionBar.setVisibility(View.GONE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getAccountString());
                break;
            case BaseFragment.NewNoteFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.GONE);
                mButtonSearchNote.setVisibility(View.GONE);
                break;
            case BaseFragment.SettingsFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getSettingString());
                break;
            case BaseFragment.SignUpFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                mActionBar.setVisibility(View.GONE);
                mButtonSearchNote.setVisibility(View.GONE);
                break;
            case BaseFragment.ViewNoteFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.GONE);
                mButtonSearchNote.setVisibility(View.GONE);
                return;
            case BaseFragment.ViewReminderFragment:
                mMainLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mActionBar.setVisibility(View.VISIBLE);
                mButtonSearchNote.setVisibility(View.GONE);
                mTvAppTitle.setText(LanguageUtils.getCalendarString());
                break;
        }
        this.mTitleHeader.setText(ApplicationSharedData.getDisplayname());
    }

    /*CallbackInterface*/
    @Override
    public void ChangeFragment(String fragmentCaller, String fragmentDestination) {
        NewFragment(fragmentDestination);
    }

    @Override
    public void PassNoteSummary(NoteSummary noteSummary) {
        mBundle = new Bundle();
        mBundle.putSerializable("NoteSummary", noteSummary);
        NewFragment(BaseFragment.ViewNoteFragment);
    }

    @Override
    public void PassEditInfo(NoteData noteData) {
        mBundle = new Bundle();
        mBundle.putSerializable("NoteData", noteData);
        NewFragment(BaseFragment.UpdateNoteFragment);
    }

    @Override
    public void CalendarItemClicked(CalendarObject calendarObject) {
        mBundle = new Bundle();
        mBundle.putInt("day", calendarObject.getDay());
        mBundle.putInt("month", calendarObject.getMonth());
        mBundle.putInt("year", calendarObject.getYear());
        this.NewFragment(BaseFragment.ViewReminderFragment);
    }

    @Override
    public void PlayMedia(String path) {
        mBundle = new Bundle();
        mBundle.putString("MediaPath", path);
        Intent intentPlayMedia = new Intent(MainActivity.this, MediaPlayerActivity.class);
        intentPlayMedia.putExtra("MediaInfor", mBundle);
        startActivity(intentPlayMedia);
    }

    @Override
    public ArrayList<NoteData> getAllNotes() {
        if (mListNoteData == null || mListNoteData.isEmpty()) {
            this.reloadListNote();
        }
        return mListNoteData;
    }

    @Override
    public void showLoadingEffect(boolean flag, String message) {
        if (flag) {
            mSyncButton.setVisibility(View.GONE);
            mProgressbarLayout.setVisibility(View.VISIBLE);
            mSyncProgress.setVisibility(View.VISIBLE);
            mLogView.setText(message);
        } else {
            mSyncButton.setVisibility(View.VISIBLE);
            mProgressbarLayout.setVisibility(View.GONE);
            mSyncProgress.setVisibility(View.GONE);
            mLogView.setText(LanguageUtils.getSyncTitleString());
        }
    }

    @Override
    public void restartApplication() {
        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage( getBaseContext().getPackageName() );
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }

    @Override
    public NoteData getRecentNote() {
        if (mListNoteData.isEmpty() || mListNoteData == null) {
            return null;
        }
        return mListNoteData.get(1);
    }

    @Override
    public void reloadListNote() {
        mListNoteData = new ArrayList<>();
        if (mNoteDataDAO != null) {
            ArrayList<NoteSummary> listNoteSummary = mNoteDataDAO.loadListNote();
            String mTimeStamp = null;
            if (mListNoteData == null) {
                mListNoteData = new ArrayList<>();
            } else {
                mListNoteData.clear();
            }

            for (int i = 0; i < listNoteSummary.size() - 1; i++)
                for (int j = i + 1; j < listNoteSummary.size(); j++) {
                    if (CalendarUtils.compareDate(listNoteSummary.get(i).getCreatedAt(), listNoteSummary.get(j).getCreatedAt()) < 0) {
                        Collections.swap(listNoteSummary, i, j);
                    }
                }

            for (NoteSummary noteSummary : listNoteSummary) {
                if (mTimeStamp == null ||
                        !mTimeStamp.equals(CalendarUtils.checkTimeStamp(CalendarUtils.getDateFromString(noteSummary.getCreatedAt())))) {
                    mListNoteData.add(new NoteData(noteSummary, null));
                    mTimeStamp = CalendarUtils.checkTimeStamp(CalendarUtils.getDateFromString(noteSummary.getCreatedAt()));
                }
                ArrayList<NoteDataLine> listNoteContent = mNoteDataDAO.loadNoteDetails(noteSummary.getID());
                mListNoteData.add(new NoteData(noteSummary, listNoteContent));
            }
        }
    }

    @Override
    public ArrayList<FileData> getAllFiles(String type) {
        switch (type) {
            case DataConstant.TYPE_IMAGE:
                if (mListImageFile == null) {
                    mListImageFile = new ArrayList<>();
                }
                return mListImageFile;
            case DataConstant.TYPE_VIDEOCLIP:
                if (mListVideoFile == null) {
                    mListVideoFile = new ArrayList<>();
                }
                return mListVideoFile;
            case DataConstant.TYPE_VOICE:
                if (mListAudioFile == null) {
                    mListAudioFile = new ArrayList<>();
                }
                return mListAudioFile;
        }
        return null;
    }

    @Override
    public void reloadListFile(final String type) {
        final String[] files = FileUtils.getListFile(type);
        if (mListImageFile == null) {
            mListImageFile = new ArrayList<>();
        } else {
            mListImageFile.clear();
        }
        if (mListVideoFile == null) {
            mListVideoFile = new ArrayList<>();
        } else {
            mListVideoFile.clear();
        }
        if (mListAudioFile == null) {
            mListAudioFile = new ArrayList<>();
        } else {
            mListAudioFile.clear();
        }

        mNumberOfFile = 0;

        switch (type) {
            case DataConstant.TYPE_IMAGE:
                mListImagesIsReloading = true;
                break;
            case DataConstant.TYPE_VIDEOCLIP:
                mListVideosIsReloading = true;
                break;
            case DataConstant.TYPE_VOICE:
                mListAudiosIsReloading = true;
                break;
        }

        if (files != null && files.length > 0) {
            AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    switch (type) {
                        case DataConstant.TYPE_IMAGE:
                            for (String file : files) {
                                mListImageFile.add(new FileData(SupportUtils.getNameFromPath(file),
                                        SupportUtils.checkFileSize(file), file, type));
                                mNumberOfFile++;
                            }
                            break;
                        case DataConstant.TYPE_VIDEOCLIP:
                            for (String file : files) {
                                mListVideoFile.add(new FileData(SupportUtils.getNameFromPath(file),
                                        SupportUtils.MilliSecToTime(SupportUtils.getDuration(Uri.parse(file), MainActivity.this)) + "",
                                        file, type));
                                mNumberOfFile++;
                            }
                            break;
                        case DataConstant.TYPE_VOICE:
                            for (String file : files) {
                                mListAudioFile.add(new FileData(SupportUtils.getNameFromPath(file),
                                        SupportUtils.MilliSecToTime(SupportUtils.getDuration(Uri.parse(file), MainActivity.this)) + "",
                                        file, type));
                                mNumberOfFile++;
                            }
                            break;
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    for (BaseItem baseItem : mSideMenuResource) {
                        if (baseItem.getNameOfItem().contains(LanguageUtils.getFileManagerString())) {
                            ItemNormalWithNotification notification = (ItemNormalWithNotification) baseItem;
                            notification.setNotification(String.valueOf(mNumberOfFile));
                        }
                    }
                    mSideMenuAdapter.notifyDataSetChanged();

                    switch (type) {
                        case DataConstant.TYPE_IMAGE:
                            mListImagesIsReloading = false;
                            break;
                        case DataConstant.TYPE_VIDEOCLIP:
                            mListVideosIsReloading = false;
                            break;
                        case DataConstant.TYPE_VOICE:
                            mListAudiosIsReloading = false;
                            break;
                    }
                    sortListFile(type);
                }
            };
            asyncTask.execute();
        } else {
            for (BaseItem baseItem : mSideMenuResource) {
                if (baseItem.getNameOfItem().contains(LanguageUtils.getFileManagerString())) {
                    ItemNormalWithNotification notification = (ItemNormalWithNotification) baseItem;
                    notification.setNotification(String.valueOf(mNumberOfFile));
                }
            }
            mSideMenuAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onLogout() {
        syncData(new SyncDataCallback() {
            @Override
            public void onSyncSuccess(String message) {
                deleteAllNoteInDatabase(new SyncDataCallback() {
                    @Override
                    public void onSyncSuccess(String message) {
                        if (ApplicationSharedData.clearSession()) {
                            NewFragment(BaseFragment.LoginFragment);
                            mListFragments.clear();
                        }
                    }

                    @Override
                    public void onSyncFail(String message) {
                        if (ApplicationSharedData.clearSession()) {
                            NewFragment(BaseFragment.LoginFragment);
                            mListFragments.clear();
                        }
                    }
                });
            }

            @Override
            public void onSyncFail(String message) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }, false);
    }

    @Override
    public boolean checkInternetAvailable() {
        return mInternetAvailability;
    }

    private void updateInternetStatus() {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                mInternetAvailability = checkInternetAvailibility();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mInternetConnection.setText(
                                (mInternetAvailability)?LanguageUtils.getInternetOnlineString():LanguageUtils.getInternetOfflineString());
                        LoginFragment fragment = (LoginFragment) mFragmentManager.findFragmentByTag(BaseFragment.LoginFragment);
                        if (fragment != null) {
                            fragment.setInternetSignal(mInternetAvailability);
                        }
                    }
                });
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void reloadListReminder() {
        mListReminders = mNoteReminderDAO.getAllReminders();
        int mNumberOfReminders = 0;
        for (NoteReminder reminder : mListReminders) {
            if (CalendarUtils.checkToday(reminder.getTimeComplete())) {
                mNumberOfReminders++;
            }
        }
        if (mFragmentName.contains(BaseFragment.ViewReminderFragment)) {
            ViewReminderFragment fragment = (ViewReminderFragment) mFragmentManager.findFragmentByTag(mFragmentName);
            fragment.refreshListReminder();
        }
        for (BaseItem baseItem : mSideMenuResource) {
            if (baseItem.getNameOfItem().contains(LanguageUtils.getCalendarString())) {
                ItemNormalWithNotification notification = (ItemNormalWithNotification) baseItem;
                notification.setNotification(String.valueOf(mNumberOfReminders));
                mSideMenuAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public boolean isReloadingFiles() {
        return mListImagesIsReloading && mListVideosIsReloading && mListAudiosIsReloading;
    }

    /*implement LoginFragment.LoginListner*/
    @Override
    public void onLoginSuccess(String username, String email, String id, String displayname, ParseFile avatar) {
        if (ApplicationSharedData.saveSession(username, email, id, displayname, "")) {
            Log.d("Log", "Session's stored successfully!");
        }

        if (avatar != null) {
            try {
                FileUtils.writeFile("Avatar", avatar.getData(), "UserAvatar");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        this.checkAvatar();
        FileRoute request = new FileRoute();
        request.getAllFileFromServer(new DownloadFileCallback() {
            @Override
            public void onSuccess(FileResponse response) {
                reloadListFile(DataConstant.TYPE_IMAGE);
                reloadListFile(DataConstant.TYPE_VIDEOCLIP);
                reloadListFile(DataConstant.TYPE_VOICE);
                Toast.makeText(MainActivity.this, response.message, Toast.LENGTH_SHORT).show();

                reloadListReminder();

                if (mNoteDataDAO.loadListNote().isEmpty()) {
                    getAllNotesFromServer();
                } else {
                    reloadListNote();
                    NewFragment(BaseFragment.ListNotesFragment);
                }
                updateUI();
            }

            @Override
            public void onFail(ParseException e) {
                Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        updateUI();
    }

    @Override
    public void onForgotPassword() {

    }

    @Override
    public void onSignUp() {
        this.NewFragment(BaseFragment.SignUpFragment);
    }

    /*implement SignUpFragment.SignUpListener*/
    @Override
    public void onSignUpSuccess(String username, String email, String id, String displayname, ParseFile avatar) {
        this.onLoginSuccess(username, email, id, displayname, avatar);
    }
}


text:
<?php

namespace	cs;
use			h,
			PHPMailer;

class Mail extends PHPMailer {
	use Singleton;

	/**
	 * Setting base mail sending parameters according to system configuration
	 */
	function construct () {
		$Config			= Config::instance();
		if ($Config->core['smtp']) {
			$this->IsSMTP();
			$this->Host			= $Config->core['smtp_host'];
			$this->Port			= $Config->core['smtp_port'] ?: $Config->core['smtp_secure'] ? 465 : 25;
			$this->SMTPSecure	= $Config->core['smtp_secure'];
			if ($Config->core['smtp_auth']) {
				$this->SMTPAuth	= true;
				$this->Username	= $Config->core['smtp_user'];
				$this->Password	= $Config->core['smtp_password'];
			}
		}
		$this->From		= $Config->core['mail_from'];
		$this->FromName	= get_core_ml_text('mail_from_name');
		$this->CharSet	= 'utf-8';
		$this->IsHTML();
	}
	/**
	 * @param string	$body
	 * @param string	$signature
	 *
	 * @return string
	 */
	protected function body_normalization ($body, $signature) {
		if (strpos($body, '<!doctype') === 0 && strpos($body, '<body') !== false) {
			$body	= "<!doctype html>\n$body";
		}
		if (strpos($body, '<html') === false) {
			if (substr($body, 0, 5) != '<body') {
				$body = h::body($body.$signature);
			} else {
				$body = str_replace('', "$signature", $body);
			}
			$body = h::html(
				h::{'head meta'}([
					'content'		=> 'text/html; charset=utf-8',
					'http-equiv'	=> 'Content-Type'
				]).
				$body
			);
		} else {
			$body = str_replace('', "$signature", $body);
		}
		return $body;
	}
	/**
	 * Sending of email
	 *
	 * @param array|string|string[]			$email			if emails without names - string (may be several emails separated by comma) or
	 * 														1-dimensional array(email)

	 * 														else - 2-dimensional array(email, name) must be given
	 * @param string						$subject		Mail subject
	 * @param string						$body			html body
	 * @param string|null					$body_text		plain text body
	 * @param array|null|string				$attachments	1- or 2-dimensional array of array(path, name) or simply string
	 * 														with path to the file in file system
	 * @param array|null|string|string[]	$reply_to		Similar to $email
	 * @param bool|string					$signature		true - add system signature

	 * 														false - without signature

	 * 														string - custom signature
	 * @return bool
	 */
	function send_to ($email, $subject, $body, $body_text = null, $attachments = null, $reply_to = null, $signature = true) {
		if (empty($email) || empty($subject) || empty($body)) {
			return false;
		}
		if (is_array($email)) {
			if (count($email) == 2) {
				$this->AddAddress($email[0], $email[1]);
			} else {
				foreach ($email as $m) {
					if (is_array($m)) {
						$this->AddAddress($m[0], $m[1]);
					} else {
						$this->AddAddress($m);
					}
				}
			}
		} else {
			$email	= _trim(explode(',', $email));
			foreach ($email as $e) {
				$this->AddAddress($e);
			}
			unset($e, $email);
		}
		$this->Subject = $subject;
		if ($signature === true) {
			if ($signature = get_core_ml_text('mail_signature')) {
				$signature = "$this->LE-- $this->LE.$signature";
			}
		} elseif ($signature) {
			$signature = "$this->LE-- $this->LE".xap($signature, true);
		} else {
			$signature = '';
		}
		$this->Body = $this->body_normalization($body, $signature);
		if ($body_text) {
			$this->AltBody = $body_text.strip_tags($signature);
		}
		if (is_array($attachments)) {
			if (count($attachments) == 2) {
				$this->AddStringAttachment($attachments[0], $attachments[1]);
			} else {
				foreach ($attachments as $a) {
					if (is_array($a)) {
						$this->AddStringAttachment($a[0], $a[1]);
					} else {
						$this->AddStringAttachment($a, pathinfo($a, PATHINFO_FILENAME));
					}
				}
			}
		} elseif (is_string($attachments)) {
			$this->AddStringAttachment($attachments, pathinfo($attachments, PATHINFO_FILENAME));
		}
		if (is_array($reply_to)) {
			if (count($reply_to) == 2) {
				$this->AddReplyTo($reply_to[0], $reply_to[1]);
			} else {
				foreach ($reply_to as $r) {
					if (is_array($r)) {
						$this->AddReplyTo($r[0], $r[1]);
					} else {
						$this->AddReplyTo($r);
					}
				}
			}
		} elseif (is_string($reply_to)) {
			$this->AddReplyTo($reply_to);
		}
		$result = $this->Send();
		$this->ClearAddresses();
		$this->ClearAttachments();
		$this->ClearReplyTos();
		return $result;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sling.distribution.trigger.impl;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.scheduler.Scheduler;
import org.apache.sling.distribution.DistributionRequestType;
import org.apache.sling.distribution.component.impl.DistributionComponentConstants;
import org.apache.sling.distribution.trigger.DistributionRequestHandler;
import org.apache.sling.distribution.trigger.DistributionTrigger;
import org.apache.sling.distribution.trigger.DistributionTriggerException;
import org.apache.sling.jcr.api.SlingRepository;
import org.osgi.framework.BundleContext;

import javax.annotation.Nonnull;
import java.util.Map;

@Component(metatype = true,
        label = "Apache Sling Distribution Trigger - Scheduled Triggers Factory",
        configurationFactory = true,
        specVersion = "1.1",
        policy = ConfigurationPolicy.REQUIRE
)
@Service(DistributionTrigger.class)
public class ScheduledDistributionTriggerFactory implements DistributionTrigger {

    @Property(label = "Name", description = "The name of the trigger.")
    public static final String NAME = DistributionComponentConstants.PN_NAME;

    /**
     * scheduled trigger action property
     */
    @Property(label = "Distribution Type", description = "The type of the distribution request produced by this trigger.")
    public static final String ACTION = "action";

    /**
     * scheduled trigger path property
     */
    @Property(label = "Distributed Path", description = "The path to be distributed periodically.")
    public static final String PATH = "path";

    /**
     * scheduled trigger seconds property
     */
    @Property(label = "Interval in Seconds", description = "The number of seconds between executions")
    public static final String SECONDS = "seconds";

    ScheduledDistributionTrigger trigger;

    @Reference
    private SlingRepository repository;

    @Reference
    private Scheduler scheduler;

    @Activate
    public void activate(BundleContext bundleContext, Map<String, Object> config) {
        String action = PropertiesUtil.toString(config.get(ACTION), DistributionRequestType.PULL.name());
        String path = PropertiesUtil.toString(config.get(PATH), null);
        int interval = PropertiesUtil.toInteger(config.get(SECONDS), 30);

        trigger =  new ScheduledDistributionTrigger(action, path, interval, scheduler);
    }

    @Deactivate
    public void deactivate() {
       trigger.disable();
    }

    public void register(@Nonnull DistributionRequestHandler requestHandler) throws DistributionTriggerException {
        trigger.register(requestHandler);
    }

    public void unregister(@Nonnull DistributionRequestHandler requestHandler) throws DistributionTriggerException {
        trigger.unregister(requestHandler);
    }
}


text:
{-# LANGUAGE QuasiQuotes #-}

module TestDocumentParser (parseExpensesFileSpec) where

import Data.Either (isLeft, isRight)

import qualified Data.Time.Calendar.Compat     as DT

import Data.String.Interpolate (i)
import Data.String.Interpolate.Util (unindent)

import Test.Hspec (Spec, context, describe, expectationFailure, it, shouldBe, shouldSatisfy)

import Test.Hspec.Megaparsec
  ( err
  , elabel
  , shouldSucceedOn
  , utoks
  )

import Text.Megaparsec (parse)

import qualified Data.Expenses.Parse.Megaparsec.Document as PED
import qualified Data.Expenses.Parse.Megaparsec.Types as PT
import qualified Data.Expenses.Types as ET
import Data.Expenses.Parse.Megaparsec.Document (modelFromAst)

goodExpensesDoc :: String
goodExpensesDoc =
  unindent [i|
    2016-01-01 MON
    Spent 1 on stuff

    TUE
    Spent 2 on thing
  |]

goodExpensesDocWithCmts :: String
goodExpensesDocWithCmts =
  unindent [i|
    # Comment
    2016-01-01 MON
    Spent 1 on stuff

    # Comment
    TUE
    Spent 2 on thing
    # Comment
  |]

goodExpensesDocWithUsing :: String
goodExpensesDocWithUsing =
  unindent [i|
    Using VND as the default currency

    2016-01-01 MON
    Spent 10k on stuff
  |]

badExpensesDoc :: String
badExpensesDoc =
  unindent [i|
    2016-01-01 MON
    Spent 1 on stuff
    Sent 1.5 on stuff

    TUE
    Spent 2 on thing
  |]

badExpensesDocWithMultipleTypos :: String
badExpensesDocWithMultipleTypos =
  unindent [i|
    2016-01-01 MON
    Spent 1 on stuff
    Sent 1.5 on stuff

    TUE
    spent 2 on thing
  |]

badExpensesDocTypoLastLine :: String
badExpensesDocTypoLastLine =
  unindent [i|
    2016-01-01 MON
    Spent 1 on stuff
    Sent 1.5 on stuff|]

parseExpensesFileSpec :: Spec
parseExpensesFileSpec =
  describe "Data.Expenses.Parse.Megaparsec.ExpensesDoc" $ do
    describe "parseExpensesFile" $ do
      context "should successfully parse well-formed doc" $ do
        let shouldSuccessfullyParseDocument p d = do
              parse p "" `shouldSucceedOn` d
              let rawResult = parse p "" d
              case rawResult of
                Left _ -> expectationFailure "parser shouldn't fail"
                Right (PT.AST rawLines) -> rawLines `shouldSatisfy` all isRight
        it "simple document" $
          docParser `shouldSuccessfullyParseDocument` goodExpensesDoc
        it "document with comments" $
          docParser `shouldSuccessfullyParseDocument` goodExpensesDocWithCmts
        it "document with Using directive" $
          docParser `shouldSuccessfullyParseDocument` goodExpensesDocWithUsing

      context "recovers parsing malformed doc" $ do
        let shouldRecoverWithAtLeastOneError p d = do
              parse p "" `shouldSucceedOn` d
              let rawResult = parse p "" d
              case rawResult of
                Left _ -> expectationFailure "parser shouldn't fail"
                Right (PT.AST rawLines) -> rawLines `shouldSatisfy` any isLeft
        it "malformed with simple typo" $
          docParser `shouldRecoverWithAtLeastOneError` badExpensesDoc
        it "malformed typo on last line (no EOL)" $
          docParser `shouldRecoverWithAtLeastOneError` badExpensesDocTypoLastLine

      -- XXX: need to update these to assert that the Lefts of the
      -- raw result are as asserted!
      describe "parse error for 1x error (typo 'Sent')" $
        it "should show unexpected \"Sent\", expected \"Spent\" or \"Received\"" $ do
          let rawResult = parse docParser "" badExpensesDoc

          case rawResult of
            Left _ -> expectationFailure "parser shouldn't fail"
            Right ast ->
              case modelFromAst ast of
                Left errors ->
                  errors
                    `shouldBe`
                      [ err 32    -- row 4, col 1
                        -- Extra space b/c 'Using' parser not as strict as directives
                        (utoks "Sent" <>
                         elabel "Date directive" <>
                         elabel "Expense directive" <>
                         elabel "Using directive")
                      ]
                Right _ ->
                  expectationFailure "should have recovered from an error"

      describe "parse error for 2x error (typos: 'Sent', 'spent')" $
        it "should show unexpected \"Sent\" and \"spent\", expected \"Spent\" or \"Received\"" $ do
          let rawResult = parse docParser "" badExpensesDocWithMultipleTypos

          case rawResult of
            Left _ -> expectationFailure "parser shouldn't fail"
            Right ast ->
              case modelFromAst ast of
                Left errors ->
                  errors
                    `shouldBe`
                      [ err 32    -- row 4, col 1
                        -- Extra space b/c 'Using' parser not as strict as directives
                        (utoks "Sent" <>
                         elabel "Date directive" <>
                         elabel "Expense directive" <>
                         elabel "Using directive")
                      , err 55    -- row 7, col 1
                        (utoks "spent" <>
                         elabel "Date directive" <>
                         elabel "Expense directive" <>
                         elabel "Using directive")
                      ]
                Right _ ->
                  expectationFailure "should have recovered from an error"

    describe "entriesFromDirectives" $
      it "a Using directive can change the default currency" $
        PED.entriesFromDirectives
          [ PT.DateCmd  $ PT.DateDir (Just $ DT.fromGregorian 2018 01 01) DT.Monday
          , PT.ExpCmd   $ PT.Expense PT.Spent (ET.Amount 5 Nothing False) "remark1" Nothing
          , PT.UsingCmd $ PT.Configuration "VND"
          , PT.ExpCmd   $ PT.Expense PT.Spent (ET.Amount 10000 Nothing False) "remark2" Nothing
          ]
          `shouldBe`
          [ ET.Entry (2018, 01, 01) (5, "SGD") "remark1" Nothing
          , ET.Entry (2018, 01, 01) (10000, "VND") "remark2" Nothing
          ]

    where
      docParser = PED.parseExpensesFile


text:
package stupidchess.network.controller;
import stupidchess.network.datagram.MessageObject;

/**
 *
 * @author Nguyen
 */
public interface IMessageProcessor {

    /**
     * Process the message object from source, depending on the message's command and parameters.
     * Usually a feedback object will be assigned to the original message, and then
     * the message will be resent back to source.
     * @param message The message to be processed.
     * @param source The source of the message.
     */
    public void process(MessageObject message, MessageTransferrer source);
}


text:
import { Component } from "@angular/core";
import {DemoSetBase} from "../../template/demo-template/demo-template";

@Component({
    templateUrl: 'demo.component.html',
})
export class DataEncapsulationDemoComponent extends DemoSetBase {
    public demoPath = "demo/data-encapsulation";

}


text:
<?php

namespace splattner\myvbc\pages;

use splattner\myvbc\models\MPerson;
use splattner\myvbc\models\MKey;

class PageKey extends MyVBCPage
{
    public function __construct()
    {
        parent::__construct();
        $this->pagename = "key";
        $this->template = "key/index.tpl";

        $this->acl->allow("vorstand", ["main", "new","delete"], ["view"]);
    }

    public function init()
    {
        parent::init();
        $this->smarty->assign("content", $this->template);
    }

    public function mainAction()
    {
        $this->smarty->assign("subContent1", "key/keyTable.tpl");

        $keys = new MKey();

        $this->smarty->assign("keys", $keys->getAllKeys());

        $persons = new MPerson();
        $this->smarty->assign("users", $persons->getRS(array(), array("name" => "ASC", "prename" => "ASC"))->fetchAll());
    }

    public function newAction()
    {
        if (isset($_POST["doNew"])) {
            $key = new MKey();
            $key->person = $_POST["person"];
            $key->label = $_POST["label"];
            $key->nr = $_POST["nr"];

            $key->insert();

            $this->smarty->assign("messages", "Schlüssel wurde hinzugefügt");

            return "main";
        }

        return "main";
    }

    public function deleteAction()
    {
        $keyID = $_GET["keyID"];

        $key = new MKey();
        $key->delete(array("id" => $keyID));

        $this->smarty->assign("messages", "Schlüssel wurde gelöscht");

        return "main";
    }
}


text:
"""High-level implementation supporting MinDiff integration for most arbitrary Keras models."""

from tensorflow_model_remediation.min_diff.keras.models.min_diff_model import MinDiffModel


text:
<?php

namespace MN\UsefulBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MNUsefulBundle extends Bundle
{
}


text:
package h;
import java.util.Arrays;
import java.util.List;

import smetana.core.__ptr__;

//2 7eimedro6z0j21rhmmxbqdssy

public interface textfont_t extends __ptr__ {
	public static List<String> DEFINITION = Arrays.asList(
"typedef struct",
"{",
"char*  name",
"char*  color",
"PostscriptAlias *postscript_alias",
"double size",
"unsigned int flags:7",
"unsigned int cnt:(sizeof(unsigned int) * 8 - 7)",
"}",
"textfont_t");
}

// typedef struct {
// 	char*  name;
// 	char*  color;
// 	PostscriptAlias *postscript_alias;
// 	double size;
// 	unsigned int flags:7;  /* HTML_UL, HTML_IF, HTML_BF, etc. */
// 	unsigned int cnt:(sizeof(unsigned int) * 8 - 7);   /* reference count */
//     } textfont_t;


text:
This is my personal website, code and content. For more information read my blog
post in [English] or [Russian].

Code is licensed under a BSD 3-clause Licencse, and content is available under
[CC BY-NC-SA 3.0].

[English]: http://vlevit.org/en/blog/tech/vlevit-org
[Russian]: http://vlevit.org/ru/blog/tech/vlevit-org
[CC BY-NC-SA 3.0]: http://creativecommons.org/licenses/by-nc-sa/3.0/


text:
import "./css/toast.less"

import * as React from "react";
import Icon from "./Icon";
import Mask from "./Mask";

export interface IToastProps {
    icon?:string;
    iconSize?:string;
    show:boolean;
}

export default class Toast extends React.Component<IToastProps,void> {
    constructor(props, context) {
        super(props, context);
    }

    static defaultProps = {
        icon: 'toast',
        show: false,
    };

    render() {
        const {icon, show, children, iconSize} = this.props;

        return (

                <Mask transparent={true}/>

                    <Icon value={icon} size={iconSize}/>

{children}

        );
    }
}


text:
FROM node:0.10
MAINTAINER Oscar Bezi

# replace sh with bash so I can use if statements below
ENTRYPOINT ["/bin/bash", "-c"]

RUN npm install -g coffee-script
# after deploy replace this with production solution
RUN npm install -g nodemon

# where the production files will go
RUN mkdir -p /opt/app
WORKDIR /opt/app

COPY . /opt/app
RUN npm install


text:
const router = require('express').Router()
const noAuth = require('./no-auth')
const user = require('./user')
const userQueries = require('../../db/user.js')

router.use( (req, res, next) => {
  let loggedIn = false
  if (req.session.user) loggedIn = true
  res.locals = {loggedIn: loggedIn}
  next()
})

router.use('/', noAuth)
router.use('/', user)

module.exports = router


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Vocabulary gradient</title>
	<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

Enter the text you want to analyze

	<textarea id="text" name="text" id="" rows="10" style="width: 100%;"></textarea>
	<button onclick="process();">Submit</button>

Statistics

The following statistics are based on the index of the word in the word frequency list. Lower index indicates that the word is more often used than higher index words. In other words, frequency(low index) > frequency(high index).

Minimum index: ∅

Average index: ∅

Median index: ∅

Maximum index: ∅

Std Dev: ∅

Word count: ∅

Unique word count: ∅

Fingerprint:
∅

Processed in ∅ s.

Vocabulary code

Text

The following section displays the text you have input, colored according to the expected frequency of the word, white/light being very frequent words while black/dark represents infrequent words. In yellow are displayed the words that are not part of the known frequency dictionary.


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Atom = require("atom");
const _ = require("underscore-plus");
const ChangeableWord_1 = require("./ChangeableWord");
class AutoCorrectView {
    constructor(state, editor) {
        /**
         * A diagnostic number to indicate how many buffer changes have been seen
         * by the view. This is used for knowing when operations have completed
         * in unit testing.
         */
        this.changesSeen = 0;
        this.checkRegexp = /([\n\s.\"])/;
        this.enabled = true;
        /**
         * Contains the persistent subscriptions on the editor buffer.
         */
        this.editorSubscriptions = new Atom.CompositeDisposable();
        /**
         * Contains the subscriptions for buffer events. These will only be
         * populated if we are listening to the buffer.
         */
        this.bufferSubscriptions = new Atom.CompositeDisposable();
        // Save the member variables for later.
        this.state = state;
        this.editor = editor;
        // Attach to the various events on the editor.
        this.editorSubscriptions.add(editor.onDidChangeGrammar(() => { this.subscribe(); }));
        this.editorSubscriptions.add(atom.config.onDidChange("autocorrect.grammars", () => { this.subscribe(); }));
        // See if we need to register listeners for this editor based on the
        // grammar.
        this.subscribe();
    }
    /**
     * Gets the unique identifier for this view.
     */
    get id() { return this.editor.id; }
    destroy() {
        this.bufferSubscriptions.dispose();
        this.editorSubscriptions.dispose();
    }
    /**
     * Starts listening to various events if the editor represents a grammar
     * that the plugin operators on.
     */
    subscribe() {
        // We default to unsubscribing the events. This handles when a grammar
        // changes from one we handle to one we don't.
        this.unsubscribe();
        // Figure out the current grammar of the editor. We also determine if
        // it is the list of grammars we are listening to.
        const grammar = this.editor.getGrammar().scopeName;
        const pluginGrammars = atom.config.get("autocorrect.grammars");
        const isAttachable = _.contains(pluginGrammars, grammar);
        // If we aren't attaching, then we don't care about the events.
        if (!isAttachable) {
            return;
        }
        // We are going to attach to the editor and listen to additional events.
        this.bufferSubscriptions.add(this.editor.onDidStopChanging((args) => {
            this.onBufferChange(args);
        }));
    }
    /**
     * Stops listening to any events or callbacks on the editor.
     */
    unsubscribe() {
        this.bufferSubscriptions.dispose();
        this.bufferSubscriptions = new Atom.CompositeDisposable();
    }
    /**
     * Triggered when the buffer changes. This is what looks for the text
     * changed and determines if we need to look for autocorrections.
     */
    onBufferChange(args) {
        // We can have multiple ranges if the user has multiple insert points,
        // such as using alt-shift to insert across multiple lines. We need to
        // deal with each one.
        this.changesSeen++;
        for (const change of args.changes) {
            this.processChange(change);
        }
    }
    processChange(change) {
        // If we are not enabled, then don't do anything.
        if (!this.enabled) {
            return;
        }
        // We only care if we see a character that indicates autocomplete
        // should be checked. In most cases, this is a whitespace or
        // terminating punctuation (e.g., not ones used in contractions).
        // We only have to check newText because we don't care if someone
        // deletes to a check point, only added.
        if (!change.newText.match(this.checkRegexp)) {
            return;
        }
        // We want to find the full word before each of the triggers.
        // These words may be outside of the new range, such as someone
        // hitting a space 300 ms after typing "teh", so we have to track
        // back through the buffer to find each one. Also, the user may have
        // written the entire word as part of the delayed change, such as
        // "and teh there was" which means we want to break it into three
        // words ("and", "teh", "there"). "was" wouldn't be processed since
        // it didn't end with a trigger. If there was something ahead of
        // "and", then that should also include with the first word.
        let wordChanges = this.getWordChanges(change.newRange);
        // HACK: Occasionally, we get undefined words from the changes. Strip
        // these out until we can figure out the reason.
        wordChanges = wordChanges.filter((wc) => { return !!wc.word; });
        // Go through each of the word changes and see if there are corrections
        // for them registered with the plugin. Since these are ordered, the
        // later ones may operate on changes from a previous once, such as one
        // handling double capital letters ("TEh") and then one fixing phrases
        // such as "teh" to "the".
        //
        // We also want to know if something changed because we have to do a lot
        // more work to actually handle the replacement.
        let hasChanged = false;
        for (const wordChange of wordChanges) {
            for (const correction of this.state.wordCorrections) {
                correction.correctWord(this.editor, wordChange);
                hasChanged = hasChanged || wordChange.changed;
            }
        }
        // If we don't have changes, there is nothing to do.
        if (!hasChanged) {
            return;
        }
        // If we have changes, we need to save the cursor and selection, replace
        // the changed words (while adjusting for the altered ranges), and then
        // restore the selection.
        this.replaceWords(wordChanges.filter((wc) => wc.changed));
    }
    getWordChanges(range) {
        // Start by splitting the word into its obvious word segments. We have
        // a capture group in checkRegexp, so this will also return the
        // triggers as their own entry in the resulting array. There will
        // always be at least one before a trigger and one after.
        const text = this.editor.getTextInRange(range);
        const tokens = text.split(this.checkRegexp);
        // Since there is always one after, we can just get rid of that since
        // it will either be text which we don't process because it didn't end
        // in a trigger or it is blank and we don't care.
        tokens.splice(tokens.length - 1, 1);
        // The first one needs to be extended back until we get to a line
        // trigger. If we are at the start of the range, we don't need to
        // do this.
        const buffer = this.editor.buffer;
        let characterIndex = buffer.characterIndexForPosition(range.start);
        if (range.start.column > 0) {
            // Get the text before the starting point.
            const leadingRange = {
                end: { column: range.start.column, row: range.start.row },
                start: { column: 0, row: range.start.row },
            };
            let leadingText = this.editor.getTextInRange(leadingRange);
            // Look for a trigger. If we don't find one, add the entire line.
            // Otherwise, just add the leading text.
            const leadingIndex = lastIndexOf(leadingText, this.checkRegexp);
            if (leadingIndex >= 0) {
                leadingText = leadingText.substring(leadingIndex + 1);
            }
            // Shift the start column back by the length of the text.
            characterIndex -= leadingText.length;
            tokens[0] = leadingText + tokens[0];
        }
        // At this point, we have an array with at least two items. The leading
        // is the text before the trigger, then a trigger, then either more
        // text or triggers.
        //
        // While we go through this, we also need to build up ranegs for each
        // of the words as we go. We do this by converting the starting
        // position to a character index, then add each element as we go.
        let lastWasTrigger = false;
        let lastWordRange = tokens;
        const changes = [];
        for (let rangeIndex = 0; rangeIndex < tokens.length; rangeIndex++) {
            // We have to advance the character index.
            const startCharacterIndex = characterIndex;
            const rangeText = tokens[rangeIndex];
            characterIndex += rangeText.length;
            // See if we are a trigger. If we aren't, then we don't need to
            // worry about processing (yet). We do this so if we have two
            // triggers in a row, then we can easily skip it.
            if (!rangeText.match(this.checkRegexp)) {
                // Keep track of our last state for the trigger element.
                lastWasTrigger = false;
                lastWordRange = {
                    end: buffer
                        .positionForCharacterIndex(characterIndex),
                    start: buffer
                        .positionForCharacterIndex(startCharacterIndex),
                };
                // Update our pointers and move on.
                continue;
            }
            // If we are preceeding a trigger, then we don't have to do
            // anything.
            if (lastWasTrigger) {
                continue;
            }
            lastWasTrigger = true;
            // Get the previous word, that's what we care about, and wrap it
            // in the appropriate object.
            const word = tokens[rangeIndex - 1];
            const wordChange = new ChangeableWord_1.ChangeableWord(word, lastWordRange);
            changes.push(wordChange);
        }
        // Return the gathered changes.
        return changes;
    }
    /**
     * Goes through the changeable words and replaces each one in the buffer
     * in rapid succession. This ensures everything will be in a single
     * update when we see onDidStopChanging again.
     */
    replaceWords(changes) {
        const editor = this.editor;
        const buffer = editor.buffer;
        for (const change of changes) {
            buffer.setTextInRange(change.range, change.word);
        }
    }
    /**
     * Alternates the enabled state for the current view.
     */
    toggle() {
        this.enabled = !this.enabled;
    }
}
exports.AutoCorrectView = AutoCorrectView;
function lastIndexOf(input, search) {
    for (let i = input.length; i > 0; i--) {
        if (input.substring(i).match(search)) {
            return i;
        }
    }
    return -1;
}
//# sourceMappingURL=AutoCorrectView.js.map


text:
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Flags: --allow-natives-syntax --opt

/* Test deopt behaviors when the prototype has elements */

// some

(function () {
  var array = [,];

  function some() {
    return array.some(v => v > 0);
  }

  %PrepareFunctionForOptimization(some);
  some(); some();

  %OptimizeFunctionOnNextCall(some);
  assertEquals(some(), false);

  array.__proto__.push(6);
  //deopt
  assertEquals(some(), true);
})();