text:
"""
This class implements Editra's main notebook control.
@summary: Editra's main notebook class

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_pages.py 72278 2012-08-02 14:24:23Z CJP $"
__revision__ = "$Revision: 72278 $"

#--------------------------------------------------------------------------#
# Dependencies
import os
import sys
import glob
import wx

# Editra Libraries
import ed_glob
from profiler import Profile_Get, Profile_Set
import ed_editv
import syntax.synglob as synglob
import syntax.syntax as syntax
import ed_search
import util
import ed_msg
import ed_txt
import ed_mdlg
import ed_session
import ebmlib
import eclib
from extern import aui
import ed_book

#--------------------------------------------------------------------------#
# Globals
ID_IDLE_TIMER = wx.NewId()
SIMULATED_EVT_ID = -1
_ = wx.GetTranslation

#--------------------------------------------------------------------------#

class EdPages(ed_book.EdBaseBook):
    """Editra's editor buffer notebook
    @todo: allow for tab styles to be configurable (maybe)

    """
    def __init__(self, parent):
        """Initialize a notebook with a blank text control in it
        @param parent: parent window of the notebook

        """
        style = aui.AUI_NB_DEFAULT_STYLE | \
                aui.AUI_NB_WINDOWLIST_BUTTON | \
                aui.AUI_NB_SMART_TABS | \
                aui.AUI_NB_USE_IMAGES_DROPDOWN | \
                aui.AUI_NB_TAB_EXTERNAL_MOVE | \
                aui.AUI_NB_TAB_FIXED_WIDTH | \
                aui.AUI_NB_ORDER_BY_ACCESS
        super(EdPages, self).__init__(parent, style=style)

        # Notebook attributes
        self.LOG = wx.GetApp().GetLog()
        self._idletimer = wx.Timer(self, ID_IDLE_TIMER)
        self.DocMgr = ed_editv.EdEditorView.DOCMGR
        self._searchctrl = ed_search.SearchController(self, self.GetCurrentCtrl)
        self._searchctrl.SetLookinChoices(Profile_Get('SEARCH_LOC',
                                                      default=list()))
        self._searchctrl.SetFileFilters(Profile_Get('SEARCH_FILTER', default=u''))

        self.pg_num = -1              # Track new pages (aka untitled docs)
        self.mdown = -1
        self.control = None
        self.frame = self.GetTopLevelParent() # MainWindow
        self._ses_load = False
        self._menu = ebmlib.ContextMenuManager()

        # Setup Tab Navigator
        ed_icon = ed_glob.CONFIG['SYSPIX_DIR'] + u"editra.png"
        bmp = wx.Bitmap(ed_icon, wx.BITMAP_TYPE_PNG)
        if bmp.IsOk():
            self.SetNavigatorIcon(bmp)
        else:
            util.Log("[ed_pages][warn] Bad bitmap: %s" % ed_icon)

        # Set custom options
        self.SetMinMaxTabWidth(125, 135)

        # Notebook Events
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnPageClosing)
        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.OnPageClosed)
        self.Bind(aui.EVT_AUINOTEBOOK_TAB_DCLICK, self.OnTabLeftDClick)
        self.Bind(aui.EVT_AUINOTEBOOK_BG_DCLICK, self.OnBGLeftDClick)
        self.Bind(aui.EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN, self.OnMClickDown)
        self.Bind(aui.EVT_AUINOTEBOOK_TAB_MIDDLE_UP, self.OnMClickUp)
        self.Bind(aui.EVT_AUINOTEBOOK_TAB_RIGHT_UP, self.OnTabMenu)
        self.Bind(aui.EVT_AUINOTEBOOK_ALLOW_DND, self.OnAllowDnD)
        self.Bind(aui.EVT_AUINOTEBOOK_END_DRAG, self.OnDragFinished)
        self.Bind(aui.EVT_AUINOTEBOOK_DRAG_DONE, self.OnDragFinished)

        self.Bind(wx.stc.EVT_STC_CHANGE, self.OnUpdatePageText)
        self.Bind(wx.EVT_MENU, self.OnMenu)
        self.Bind(wx.EVT_TIMER, self.OnIdle, id=ID_IDLE_TIMER)

        # Message handlers
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_NOTEBOOK)
        ed_msg.Subscribe(self.OnUpdatePosCache, ed_msg.EDMSG_UI_STC_POS_JUMPED)
        ed_msg.Subscribe(self.OnGetOpenFiles, ed_msg.EDMSG_FILE_GET_OPENED)
        ed_msg.RegisterCallback(self.OnDocPointerRequest,
                                ed_msg.EDREQ_DOCPOINTER)

        # Add a blank page
        self.NewPage()
        self._idletimer.Start(400)

    #---- End Init ----#

    #---- Implementation ----#

    def OnDestroy(self, evt):
        if self and evt.Id == self.Id:
            ed_msg.Unsubscribe(self.OnThemeChanged)
            ed_msg.Unsubscribe(self.OnUpdatePosCache)
            ed_msg.Unsubscribe(self.OnGetOpenFiles)
            ed_msg.UnRegisterCallback(self.OnDocPointerRequest)

    def _HandleEncodingError(self, control):
        """Handle trying to reload the file the file with a different encoding
        Until it succeeds or gives up.
        @param control: stc
        @return: bool

        """
        # Loop while the load fails prompting to try a new encoding
        tried = None
        fname = control.GetFileName().strip(os.sep)
        fname = fname.split(os.sep)[-1]
        while True:
            doc = control.GetDocument()
            doc.ClearLastError()
            if tried is None:
                enc = doc.GetEncoding()
                if enc is None:
                    enc = ed_txt.DEFAULT_ENCODING
            else:
                enc = tried

            msg = _("The correct encoding of '%s' could not be determined.\n\n"
                    "Choose an encoding and select Ok to open the file with the chosen encoding.\n"
                    "Click Cancel to abort opening the file") % fname

            # On some systems it seems that default encoding ends up being
            # None so default to utf-8 for choices.
            if enc is None:
                enc = 'utf_8'

            dlg = eclib.EncodingDialog(self, msg=msg,
                                        title=_("Choose an Encoding"),
                                        default=enc)
            bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOCPROP),
                                           wx.ART_OTHER)
            if bmp.IsOk():
                dlg.SetBitmap(bmp)
            dlg.CenterOnParent()
            result = dlg.ShowModal()
            if dlg:
                enc = dlg.GetEncoding()
                dlg.Destroy()
            else:
                result = wx.ID_CANCEL

            # Don't want to open it in another encoding
            if result == wx.ID_CANCEL:
                return False
            else:
                control.SetEncoding(enc)
                tried = enc
                ok = control.LoadFile(control.GetFileName())
                if ok:
                    return True
                else:
                    # Artificially add a short pause, because if its not there
                    # the dialog will be shown again so fast it wont seem
                    # like reloading the file was even tried.
                    wx.Sleep(1)

    def _NeedOpen(self, path):
        """Check if a file needs to be opened. If the file is already open in
        the notebook a dialog will be opened to ask if the user wants to reopen
        the file again. If the file is not open and exists or the user chooses
        to reopen the file again the function will return True else it will
        return False.
        @param path: file to check for
        @return: bool

        """
        result = wx.ID_YES
        if self.HasFileOpen(path):
            mdlg = wx.MessageDialog(self,
                                    _("File is already open in an existing "
                                      "page.\nDo you wish to open it again?"),
                                    _("Open File") + u"?",
                                    wx.YES_NO | wx.NO_DEFAULT | \
                                    wx.ICON_INFORMATION)
            result = mdlg.ShowModal()
            mdlg.Destroy()
            if result == wx.ID_NO:
                self.GotoPage(path)
        elif os.path.exists(path) and not os.path.isfile(path):
            result = wx.ID_NO
        else:
            pass

        return result == wx.ID_YES

    def AddPage(self, page, text=u'', select=True, imgId=-1):
        """Add a page to the notebook"""
        bNewPage = False
        if not len(text):
            self.pg_num += 1
            if self.pg_num != 0:
                text = _("untitled %d") % self.pg_num
            else:
                text = _("untitled")
            bNewPage = True
        page.SetTabLabel(text)
        bmp = wx.NullBitmap
        if Profile_Get('TABICONS'):
            bmp = page.GetTabImage()
        super(EdPages, self).AddPage(page, text, select, bitmap=bmp)
        self.UpdateIndexes()
        if not self._ses_load and not bNewPage:
            # Only auto save session when using default session
            mgr = ed_session.EdSessionMgr()
            if Profile_Get('LAST_SESSION') == mgr.DefaultSession:
                self.SaveCurrentSession()

    def DocDuplicated(self, path):
        """Check for if the given path is open elsewhere and duplicate the
        docpointer.
        @param path: string

        """
        doc = ed_msg.RequestResult(ed_msg.EDREQ_DOCPOINTER, [self, path])
        if hasattr(doc, 'GetDocPointer'):
            self.OpenDocPointer(doc.GetDocPointer(), doc.GetDocument())
            return True
        else:
            return False

    def GetCurrentCtrl(self):
        """Returns the control of the currently selected
        page in the notebook.
        @return: window object contained in current page or None

        """
        return self.control

    def GetFileNames(self):
        """Gets the name of all open files in the notebook
        @return: list of file names

        """
        rlist = list()
        for buff in self.GetTextControls():
            fname = buff.GetFileName()
            if fname != wx.EmptyString:
                rlist.append(fname)
        return rlist

    def GetFindDialog(self):
        """Get the active find dialog or None if one is not active
        @return: FindDialog or None

        """
        return self._searchctrl.GetDialog()

    def GetMenuHandlers(self):
        """Get the (id, evt_handler) tuples that this window should
        handle.
        @return: list of tuples

        """
        rlist = [(ed_glob.ID_FIND, self._searchctrl.OnShowFindDlg),
                 (ed_glob.ID_FIND_REPLACE, self._searchctrl.OnShowFindDlg),
                 (ed_glob.ID_FIND_NEXT, self._searchctrl.OnFind),
                 (ed_glob.ID_FIND_PREVIOUS, self._searchctrl.OnFind),
                 (ed_glob.ID_FIND_SELECTED, self._searchctrl.OnFindSelected),
                 (ed_glob.ID_NEXT_POS, self.OnNavigateToPos),
                 (ed_glob.ID_PRE_POS, self.OnNavigateToPos)]

        return rlist

    def GetUiHandlers(self):
        """Get the update ui handlers that this window supplies
        @return: list of tuples

        """
        return [(ed_glob.ID_FIND_NEXT, self._searchctrl.OnUpdateFindUI),
                (ed_glob.ID_FIND_PREVIOUS, self._searchctrl.OnUpdateFindUI),
                (ed_glob.ID_NEXT_POS, self.OnUpdateNaviUI),
                (ed_glob.ID_PRE_POS, self.OnUpdateNaviUI)]

    def InsertPage(self, index, page, text, select=False,
                   bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap,
                   control=None):
        """Insert a page into the notebook"""
        super(EdPages, self).InsertPage(index, page, text, select,
                                        bitmap, disabled_bitmap, control)
        self.UpdateIndexes()

    def SaveCurrentSession(self):
        """Save the current session"""
        if self._ses_load:
            return

        session = Profile_Get('LAST_SESSION')
        # Compatibility with older session data
        if not isinstance(session, basestring) or not len(session):
            mgr = ed_session.EdSessionMgr()
            session = mgr.DefaultSession
            Profile_Set('LAST_SESSION', session)
        self.SaveSessionFile(session)

    def SaveSessionFile(self, session):
        """Save the current open files to the given session file
        @param session: path to session file
        @return: tuple (error desc, error msg) or None

        """
        if self._ses_load:
            return

        try:
            mgr = ed_session.EdSessionMgr()
            flist = self.GetFileNames()
            bSaved = mgr.SaveSession(session, flist)
        except Exception, msg:
            self.LOG("[ed_pages][err] SaveSession error %s" % msg)
        return None

    def LoadSessionFile(self, session):
        """Load files from saved session data in profile
        @param session: session filename
        @return: tuple (error desc, error msg), or None if no error

        """
        self._ses_load = True

        mgr = ed_session.EdSessionMgr()
        flist = list()
        try:
            flist = mgr.LoadSession(session)
        except Exception, msg:
            self._ses_load = False
            errdict = dict(sessionname=session, error=msg)
            return (_("Session Load Error"),
                    _("Failed to load the session: %(sessionname)s\n\nError: %(error)s") % errdict)

        if not len(flist):
            self._ses_load = False
            return (_("Empty File"), _("Session file is empty."))

        # Close current files
        self.CloseAllPages()

        missingfns = []
        for loadfn in flist:
            if os.path.exists(loadfn) and os.access(loadfn, os.R_OK):
                if not ebmlib.IsUnicode(loadfn):
                    try:
                        loadfn = loadfn.decode(sys.getfilesystemencoding())
                    except UnicodeDecodeError:
                        self.LOG("[ed_pages][err] LoadSessionFile: Failed to decode file name")
                self.OpenPage(os.path.dirname(loadfn),
                              os.path.basename(loadfn))
            else:
                missingfns.append(loadfn)

        if missingfns:
            rmsg = (_("Missing session files"),
                    _("Some files in saved session could not be found on disk:\n")+
                    u'\n'.join(missingfns))
            self._ses_load = False
            return rmsg

        self._ses_load = False

        if self.GetPageCount() == 0:
            self.NewPage()

        self.Refresh()
        return None

    def NewPage(self):
        """Create a new notebook page with a blank text control
        @postcondition: a new page with an untitled document is opened

        """
        frame = self.TopLevelParent
        with eclib.Freezer(frame) as _tmp:
            self.control = ed_editv.EdEditorView(self)
            self.LOG("[ed_pages][evt] New Page Created")
            self.AddPage(self.control)

        # Set the control up the the preferred default lexer
        dlexer = Profile_Get('DEFAULT_LEX', 'str', synglob.LANG_TXT)
        ext_reg = syntax.ExtensionRegister()
        ext_lst = ext_reg.get(dlexer, ['txt', ])
        self.control.FindLexer(ext_lst[0])
        self.SetPageBitmap(self.GetSelection(), self.control.GetTabImage())

        # Set the modified callback notifier
        doc = self.control.GetDocument()
        doc.AddModifiedCallback(self.control.FireModified)

    def OnAllowDnD(self, evt):
        """Handle allowing tab drag and drop events"""
        dsource = evt.GetDragSource()
        if isinstance(dsource, EdPages):
            evt.Allow()
            wx.CallAfter(self.UpdateIndexes)

    def OnDragFinished(self, evt):
        self.UpdateIndexes()
        evt.Skip()

    def OnMenu(self, evt):
        """Handle context menu events
        @param evt: wx.MenuEvent

        """
        ctab = self.GetCurrentPage()
        handler = self._menu.GetHandler(evt.Id)
        if handler is not None:
            handler(ctab, evt)
        elif ctab is not None:
            ctab.OnTabMenu(evt)
        else:
            evt.Skip()

    def OnDocPointerRequest(self, args):
        """Get a buffer that has the same file open as the requested path.
        @param args: [sender, path]
        @return: EdEditorView reference or ed_msg.NullValue

        """
        sender, path = args
        for buf in self.GetTextControls():
            if buf.GetFileName() == path:
                return buf
        else:
            return ed_msg.NullValue()

    def OnTabLeftDClick(self, evt):
        """Handle left double clicks and open new tab when in empty area.
        @param evt: aui.EVT_AUINOTEBOOK_TAB_DCLICK

        """
        tlw = self.GetTopLevelParent()
        if hasattr(tlw, 'OnMaximizeEditor'):
            tlw.OnMaximizeEditor(None)

    def OnBGLeftDClick(self, evt):
        """Handle clicks on tab background area
        @param evt: aui.EVT_AUINOTEBOOK_BG_DCLICK

        """
        self.NewPage()

    def OnMClickDown(self, evt):
        """Handle tab middle mouse button down click event
        @param evt: aui.EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN

        """
        self.mdown = evt.Page
        idx = self.GetPageIndex(self.mdown)
        self.SetSelection(idx)
        self.LOG("[ed_pages][evt] OnMClickDown: %d" % idx)

    def OnMClickUp(self, evt):
        """Handle tab middle click event
        @param evt: aui.EVT_AUINOTEBOOK_TAB_MIDDLE_UP

        """
        sel = self.GetPageIndex(evt.Page)
        self.LOG("[ed_pages][evt] OnMClickUp: %d" % sel)
        if evt.Page is self.mdown:
            self.ClosePage()
        self.mdown = None

    def OnNavigateToPos(self, evt):
        """Handle buffer position history navigation events"""
        e_id = evt.GetId()
        fname, pos = (None, None)
        cname = self.control.GetFileName()
        cpos = self.control.GetCurrentPos()
        if e_id == ed_glob.ID_NEXT_POS:
            if self.DocMgr.CanNavigateNext():
                fname, pos = self.DocMgr.GetNextNaviPos()
                if (fname, pos) == (cname, cpos):
                    fname, pos = (None, None)
                    tmp = self.DocMgr.GetNextNaviPos()
                    if tmp is not None:
                        fname, pos = tmp
        elif e_id == ed_glob.ID_PRE_POS:
            if self.DocMgr.CanNavigatePrev():
                fname, pos = self.DocMgr.GetPreviousNaviPos()
                if (fname, pos) == (cname, cpos):
                    fname, pos = (None, None)
                    tmp = self.DocMgr.GetPreviousNaviPos()
                    if tmp is not None:
                        fname, pos = tmp
        else:
            evt.Skip()
            return

        ctrl = self.FindBuffer(fname)
        if ctrl is None:
            # Open the file in the editor
            if fname is not None:
                self.OpenPage(ebmlib.GetPathName(fname),
                              ebmlib.GetFileName(fname))
                self.control.SetCaretPos(pos)
        else:
            # Raise page to top and goto position
            pages = [self.GetPage(page) for page in range(self.GetPageCount())]
            idx = pages.index(ctrl)
            self.ChangePage(idx)
            ctrl.SetCaretPos(pos)

    def OnTabMenu(self, evt):
        """Show the tab context menu"""
        self._menu.Clear()

        # Construct the menu
        tab = self.GetPageIndex(evt.Page)
        if tab != self.GetSelection():
            self.SetSelection(tab)

        ctab = self.GetCurrentPage()
        if ctab is not None:
            menu = ctab.GetTabMenu()
            if menu is None:
                return # Tab has no menu

            self._menu.SetMenu(menu)
            self._menu.SetUserData("page", ctab)

            # Allow clients to customize the menu prior to showing it
            ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_TABMENU, self._menu)

            # Show the menu
            self.PopupMenu(self._menu.Menu)

    def GetMainWindow(self):
        return self.TopLevelParent

    @ed_msg.mwcontext
    def OnGetOpenFiles(self, msg):
        """Report all opened files"""
        if not self:
            return

        data = msg.GetData()
        if not isinstance(data, list):
            return
        flist = self.GetFileNames()
        data.extend(flist)

    def OnThemeChanged(self, msg):
        """Update icons when the theme has changed
        @param msg: Message Object

        """
        self.UpdateAllImages()

    def OnUpdatePosCache(self, msg):
        """Update the position cache for buffer position changes
        @param msg: message data

        """
        if not self or self._ses_load:
            return

        if self.TopLevelParent.Id == msg.GetContext():
            data = msg.GetData()
            self.DocMgr.AddNaviPosition(data['fname'], data['prepos'])
            self.DocMgr.AddNaviPosition(data['fname'], data['pos'])

    def OnUpdateNaviUI(self, evt):
        """UpdateUI handler for position navigator"""
        e_id = evt.Id
        if e_id == ed_glob.ID_NEXT_POS:
            evt.Enable(self.DocMgr.CanNavigateNext())
        elif e_id == ed_glob.ID_PRE_POS:
            evt.Enable(self.DocMgr.CanNavigatePrev())
        else:
            evt.Skip()

    def OpenDocPointer(self, ptr, doc, title=u''):
        """Open a page using an stc document poiner
        @param ptr: EdEditorView document Pointer
        @param doc: EdFile instance
        @keyword title: tab title

        """
        with eclib.Freezer(self.TopLevelParent) as _tmp:
            nbuff = self.GetCurrentPage()
            need_add = False
            if nbuff.GetFileName() or nbuff.GetLength():
                need_add = True
                nbuff = ed_editv.EdEditorView(self)

            nbuff.SetDocPointer(ptr)
            nbuff.SetDocument(doc)
            doc.AddModifiedCallback(nbuff.FireModified)
            nbuff.FindLexer()

            path = nbuff.GetFileName()
            if Profile_Get('SAVE_POS'):
                pos = self.DocMgr.GetPos(path)
                nbuff.SetCaretPos(pos)
                nbuff.ScrollToColumn(0)

            if title:
                filename = title
            else:
                filename = ebmlib.GetFileName(path)

            if need_add:
                self.AddPage(nbuff, filename)
            else:
                self.SetPageText(self.GetSelection(), filename)

            self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

            # Set tab image
            self.SetPageBitmap(self.GetSelection(), nbuff.GetTabImage())

            # Refocus on selected page
            self.control = nbuff
            self.GoCurrentPage()
            ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED,
                               nbuff.GetFileName(),
                               context=self.frame.Id)

    def OpenFileObject(self, fileobj):
        """Open a new text editor page with the given file object. The file
        object must be an instance of ed_txt.EdFile.
        @param fileobj: File Object

        """
        # Create the control
        with eclib.Freezer(self.TopLevelParent) as _tmp:
            control = ed_editv.EdEditorView(self)
            control.Hide()

            # Load the files data
            path = fileobj.GetPath()
            filename = ebmlib.GetFileName(path)
            control.SetDocument(fileobj)
            result = control.ReloadFile()

            # Setup the buffer
            fileobj.AddModifiedCallback(control.FireModified)

            # Setup the notebook
            self.control = control
            self.control.FindLexer()
            self.control.EmptyUndoBuffer()
            self.control.Show()
            self.AddPage(self.control, filename)

            self.frame.AddFileToHistory(path)
            self.SetPageText(self.GetSelection(), filename)
            self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

            # Set tab image
            cpage = self.GetSelection()
            self.SetPageBitmap(cpage, self.control.GetTabImage())

        # Refocus on selected page
        self.GoCurrentPage()
        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED,
                           self.control.GetFileName(),
                           context=self.frame.Id)

        if Profile_Get('WARN_EOL', default=True) and not fileobj.IsRawBytes():
            self.control.CheckEOL()

    def OpenPage(self, path, filename, quiet=False):
        """Open a File Inside of a New Page
        @param path: files base path
        @param filename: name of file to open
        @keyword quiet: Open/Switch to the file quietly if
                        it is already open.

        """
        path2file = os.path.join(path, filename)

        # Resolve links to real file
        if ebmlib.IsLink(path2file):
            path2file = ebmlib.ResolveRealPath(path2file)
            path = ebmlib.GetPathName(path2file)
            filename = ebmlib.GetFileName(path2file)

        if self.DocDuplicated(path2file):
            return

        # Check if file needs to be opened
        # TODO: these steps could be combined together with some
        #       refactoring of the _NeedOpen method. Requires extra
        #       testing though to check for dependencies on current
        #       behavior.
        if quiet and self.HasFileOpen(path2file):
            self.GotoPage(path2file)
            return
        elif not self._NeedOpen(path2file):
            return

        # Create new control to place text on if necessary
        with eclib.Freezer(self.TopLevelParent) as _tmp:
            new_pg = True
            if self.GetPageCount():
                if self.control.GetModify() or self.control.GetLength() or \
                   self.control.GetFileName() != u'':
                    control = ed_editv.EdEditorView(self, wx.ID_ANY)
                    control.Hide()
                else:
                    new_pg = False
                    control = self.control
            else:
                control = ed_editv.EdEditorView(self, wx.ID_ANY)
                control.Hide()

            # Open file and get contents
            result = False
            if os.path.exists(path2file):
                try:
                    result = control.LoadFile(path2file)
                except Exception, msg:
                    self.LOG("[ed_pages][err] Failed to open file %s\n" % path2file)
                    self.LOG("[ed_pages][err] %s" % msg)

                    # File could not be opened/read give up
                    # Don't raise a dialog during a session load error as if the
                    # dialog is shown before the mainwindow is ready it can cause
                    # the app to freeze.
                    if not self._ses_load:
                        ed_mdlg.OpenErrorDlg(self, path2file, msg)
                    control.GetDocument().ClearLastError()
                    control.SetFileName('') # Reset the file name

                    if new_pg:
                        control.Destroy()

                    return
            else:
                control.SetFileName(path2file)
                result = True

            # Check if there was encoding errors
            if not result and not self._ses_load:
                result = self._HandleEncodingError(control)

            # Cleanup after errors
            if not result:
                if new_pg:
                    # We created a new one so destroy it
                    control.Destroy()
                else:
                    # We where using an existing buffer so reset it
                    control.SetText('')
                    control.SetDocument(ed_txt.EdFile())
                    control.SetSavePoint()

                return

            # Put control into page an place page in notebook
            if new_pg:
                control.Show()
                self.control = control

            # Setup Document
            self.control.FindLexer()
            self.control.EmptyUndoBuffer()
            doc = self.control.GetDocument()
            doc.AddModifiedCallback(self.control.FireModified)

            # Add the buffer to the notebook
            if new_pg:
                self.AddPage(self.control, filename)
            else:
                self.frame.SetTitle(self.control.GetTitleString())

            self.frame.AddFileToHistory(path2file)
            self.SetPageText(self.GetSelection(), filename)

            # Set tab image
            cpage = self.GetSelection()
            self.SetPageBitmap(cpage, self.control.GetTabImage())

            if Profile_Get('WARN_EOL', default=True) and not doc.IsRawBytes():
                self.control.CheckEOL()

            if not control.IsLoading():
                self.DoPostLoad()

            # Refocus on selected page
            self.GoCurrentPage()
            self.LOG("[ed_pages][evt] Opened Page: %s" % filename)

    def DoPostLoad(self):
        """Perform post file open actions"""
        # Ensure that document buffer is writable after an editable
        # document is opened in the buffer.
        doc = self.control.GetDocument()
        if not doc.IsReadOnly() and not doc.IsRawBytes():
            self.control.SetReadOnly(False)

        # Set last known caret position if the user setting is enabled
        # and the caret position has not been changed during a threaded
        # file loading operation.
        if Profile_Get('SAVE_POS') and self.control.GetCurrentPos() <= 0:
            pos = self.DocMgr.GetPos(self.control.GetFileName())
            self.control.SetCaretPos(pos)
            self.control.ScrollToColumn(0)

        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENED,
                           self.control.GetFileName(),
                           context=self.frame.Id)

    def GoCurrentPage(self):
        """Move Focus to Currently Selected Page.
        @postcondition: focus is set to current page

        """
        current_page = self.GetSelection()
        if current_page >= 0:
            control = self.GetPage(current_page)
            self.control = control
        return current_page

    def GotoPage(self, fname):
        """Go to the page containing the buffer with the given file.
        @param fname: file path (string)

        """
        for page in xrange(self.GetPageCount()):
            ctrl = self.GetPage(page)
            if fname == ctrl.GetFileName():
                self.ChangePage(page)
                break

    def GetPageText(self, pg_num):
        """Gets the tab text from the given page number, stripping
        the * mark if there is one.
        @param pg_num: index of page to get tab text from
        @return: the tabs text

        """
        # Used to be needed with flatnotebook under certain cases
        # TODO: may not be necessary anymore
        try:
            txt = super(EdPages, self).GetPageText(pg_num)
        except Exception:
            txt = ''

        if not txt or txt[0] != u"*":
            return txt
        return txt[1:]

    def GetRawPageText(self, pg_num):
        """Get the unformatted raw page text
        @param pg_num: int
        @return: string

        """
        try:
            txt = super(EdPages, self).GetPageText(pg_num)
        except Exception:
            txt = ''
        return txt

    def ImageIsReadOnly(self, index):
        """Does the given page currently have a ReadOnly Image
        shown on it?
        @return: bool

        """
        bReadOnly = False
        try:
            if index < self.GetPageCount():
                bReadOnly = self.GetPageImage(index) == self._index[ed_glob.ID_READONLY]
            else:
                self.LOG("[ed_pages][warn] ImageIsReadOnly: Bad index: %d" % index)
        except Exception, msg:
            # TODO: investigate possible upstream issue
            self.LOG("[ed_pages][err] ImageIsReadOnly: %s" % msg)
        return bReadOnly

    def SetPageText(self, pg_num, txt):
        """Set the pages tab text
        @param pg_num: page index
        @param txt: string

        """
        super(EdPages, self).SetPageText(pg_num, txt)
        page = self.GetPage(pg_num)
        page.SetTabLabel(txt)

    def GetTextControls(self):
        """Gets all the currently opened text controls
        @return: list containing reference to all stc controls opened in the
                 notebook.

        """
        pages = [self.GetPage(page) for page in xrange(self.GetPageCount())]
        return [page for page in pages if page.GetName() == "EditraTextCtrl"]

    def HasFileOpen(self, fpath):
        """Checks if one of the currently active buffers has
        the named file in it.
        @param fpath: full path of file to check
        @return: bool indicating whether file is currently open or not

        """
        for ctrl in self.GetTextControls():
            if fpath == ctrl.GetFileName():
                return True
        return False

    def FindBuffer(self, fpath):
        """Find the buffer containing the given file
        @param fpath: full path of file to look for
        @return: EdStc or None
        @todo: handle matching based on the buffer control itself

        """
        for ctrl in self.GetTextControls():
            if fpath == ctrl.GetFileName():
                return ctrl
        return None

    #---- Event Handlers ----#
    def OnDrop(self, files):
        """Opens dropped files
        @param files: list of file paths
        @postcondition: all files that could be properly opend are added to
                        the notebook

        """
        # Check file properties and make a "clean" list of file(s) to open
        valid_files = list()
        for fname in files:
            self.LOG("[ed_pages][evt] File(s) Dropped: %s" % fname)
            if not os.path.exists(fname):
                self.frame.PushStatusText(_("Invalid file: %s") % fname, \
                                          ed_glob.SB_INFO)
            elif os.path.isdir(fname):
                dcnt = glob.glob(os.path.join(fname, '*'))
                dcnt = util.FilterFiles(dcnt)
                dlg = None
                if not len(dcnt):
                    dlg = wx.MessageDialog(self,
                                           _("There are no files that Editra"
                                             " can open in %s") % fname,
                                           _("No Valid Files to Open"),
                                           style=wx.OK | wx.CENTER | \
                                                 wx.ICON_INFORMATION)
                elif len(dcnt) > 5:
                    # Warn when the folder contains many files
                    dlg = wx.MessageDialog(self,
                                           _("Do you wish to open all %d files"
                                             " in this directory?\n\nWarning:"
                                             " opening many files at once may"
                                             " cause the editor to temporarily "
                                             " freeze.") % len(dcnt),
                                           _("Open Directory?"),
                                           style=wx.YES | wx.NO | \
                                                 wx.ICON_INFORMATION)
                if dlg is not None:
                    result = dlg.ShowModal()
                    dlg.Destroy()
                else:
                    result = wx.ID_YES

                if result == wx.ID_YES:
                    valid_files.extend(dcnt)
                else:
                    pass
            else:
                valid_files.append(fname)

        for fname in valid_files:
            pathname = ebmlib.GetPathName(fname)
            the_file = ebmlib.GetFileName(fname)
            self.OpenPage(pathname, the_file)
            self.frame.PushStatusText(_("Opened file: %s") % fname, \
                                      ed_glob.SB_INFO)
        return

    def OnIdle(self, evt):
        """Update tabs and check if files have been modified
        @param evt: wx.TimerEvent

        """
        if wx.GetApp().IsActive():
            for idx in range(self.GetPageCount()):
                page = self.GetPage(idx)
                if page is not None and page.IsShown():
                    page.DoOnIdle()

    def OnPageChanging(self, evt):
        """Page changing event handler.
        @param evt: aui.EVT_AUINOTEBOOK_PAGE_CHANGING

        """
        evt.Skip()
        pages = (evt.GetOldSelection(), evt.GetSelection())
        self.LOG("[ed_pages][evt] Control Changing from Page: "
                  "%d to Page: %d\n" % pages)

        # Check if it has been destroyed already
        if self.control:
            self.control.DoDeactivateTab()

        ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGING,
                           (self,) + pages,
                           context=self.frame.Id)

    def ChangePage(self, pg_num, old=-2):
        """Change the page and focus to the the given page id
        @param pg_num: Page number to change
        @keyword old: previous selection

        """
        cpage = self.GetSelection()
        if cpage != pg_num:
            self.SetSelection(pg_num)

        # Get the window that is the current page
        window = self.GetPage(pg_num)
        self.control = window

        # Update Frame Title
        self.frame.SetTitle(self.control.GetTitleString())

        # Only post page changes when the change is not from the app exiting
        # NOTE: -2 is used as default value, cant use -1 as it comes from
        #       page close events.
        if old > -2:
            cpage = old

        if not self.frame.IsExiting() and cpage != pg_num:
            ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CHANGED,
                               (self, pg_num),
                               context=self.frame.Id)

    def OnPageChanged(self, evt):
        """Actions to do after a page change
        @param evt: aui.EVT_AUINOTEBOOK_PAGE_CHANGED

        """
        cpage = evt.GetSelection()
        self.ChangePage(cpage, old=evt.GetOldSelection())
        self.LOG("[ed_pages][evt] Page Changed to %d" % cpage)

        # Call the tab specific selection handler
        page = self.GetCurrentPage()
        if page:
            page.DoTabSelected()
        self.GoCurrentPage()

    def OnPageClosing(self, evt):
        """Checks page status to flag warnings before closing
        @param evt: aui.EVT_AUINOTEBOOK_PAGE_CLOSE

        """
        page = self.GetPage(evt.GetSelection())
        if page and page.CanCloseTab():
            sel = self.GetSelection()
            self.LOG("[ed_pages][evt] Closing Page: #%d" % sel)

            # Call the tab specific close handler
            page.DoTabClosing()

            evt.Skip()
            ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CLOSING,
                               (self, sel),
                               context=self.frame.Id)
        else:
            evt.Veto()

    def OnPageClosed(self, evt):
        """Handles Paged Closed Event
        @param evt: aui.EVT_AUINOTEBOOK_PAGE_CLOSED

        """
        frame = self.TopLevelParent
        with eclib.Freezer(frame) as _tmp:
            cpage = evt.GetSelection()
            evt.Skip()
            self.LOG("[ed_pages][evt] Closed Page: #%d" % cpage)
            self.UpdateIndexes()
            ed_msg.PostMessage(ed_msg.EDMSG_UI_NB_CLOSED,
                               (self, cpage),
                               context=self.frame.Id)

            if not self.GetPageCount() and \
               hasattr(frame, 'IsExiting') and not frame.IsExiting():
                self.NewPage()
            elif not self.frame.IsExiting():
                self.SaveCurrentSession()

    #---- End Event Handlers ----#

    def _ClosePageNum(self, idx, deletepg=True):
        """Close the given page
        @param idx: int
        @keyword deletepg: bool (Internal Use Only!)
        @return bool: was page deleted?

        """
        result = True
        try:
            page = self.GetPage(idx)
            result = page.CanCloseTab()

            # TODO: this makes very little sense, why did this deletepg
            #       value get added, this function is useless when it
            #       is not true...
            if result and deletepg:
                evt = aui.AuiNotebookEvent(aui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE,
                                           SIMULATED_EVT_ID)
                evt.SetSelection(idx)
                self.OnPageClosing(evt)
                with eclib.Freezer(self.TopLevelParent) as _tmp:
                    self.DeletePage(idx)
                evt = aui.AuiNotebookEvent(aui.wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSED,
                                           SIMULATED_EVT_ID)
                evt.SetSelection(idx)
                self.OnPageClosed(evt)
        except Exception:
            # TODO: workaround for crash in base on destruction
            pass

        return result

    def CloseAllPages(self):
        """Closes all open pages"""
        for page in range(self.GetPageCount()):
            if not self.ClosePage():
                break

    def CloseOtherPages(self):
        """Close all but the currently selected tab"""
        cpage = self.GetCurrentPage()
        to_del = list()
        for pnum in range(self.GetPageCount()):
            page = self.GetPage(pnum)
            if not page:
                break
            if not (page == cpage):
                if page.CanCloseTab():
                    to_del.append(pnum)

        if len(to_del):
            to_del.sort()
            to_del.reverse()
            for pnum in to_del:
                self._ClosePageNum(pnum)

    def ClosePage(self, deletepg=True):
        """Closes currently selected page
        @keyword deletepg: bool (actually delete the page) internal use only
        @return: bool

        """
        pnum = self.GetSelection()
        result = self._ClosePageNum(pnum, deletepg)
        return result

    def CanClosePage(self):
        """Can the current page be closed?
        @return: bool

        """
        self.GoCurrentPage()
        page = self.GetCurrentPage()
        if page:
            return page.CanCloseTab()
        return False

    def UpdateAllImages(self):
        """Reload and Reset all images in the notebook pages and
        the corresponding imagelist to match those of the current theme
        @postcondition: all images in control are updated

        """
        bUseIcons = Profile_Get('TABICONS')
        for page in range(self.GetPageCount()):
            if bUseIcons:
                tab = self.GetPage(page)
                self.SetPageBitmap(page, tab.GetTabImage())
            else:
                self.SetPageBitmap(page, wx.NullBitmap)
        self.Refresh()

    def UpdateIndexes(self):
        """Update all page indexes"""
        pages = [self.GetPage(page) for page in range(self.GetPageCount())]
        for idx, page in enumerate(pages):
            page.SetTabIndex(idx)

    def UpdatePageImage(self):
        """Updates the page tab image
        @postcondition: page image is updated to reflect any changes in ctrl

        """
        tab = self.GetCurrentPage()
        self.SetPageBitmap(self.GetSelection(), tab.GetTabImage())

    def OnUpdatePageText(self, evt):
        """Update the title text of the current page
        @param evt: stc.EVT_STC_MODIFY (unused)
        @note: this method must complete its work very fast it gets
               called every time a character is entered or removed from
               the document.

        """
        try:
            if self.control.Id == evt.Id:
                # Wait till file is completely loaded before updating ui based
                # on modification events.
                if self.control.IsLoading():
                    return

                pg_num = self.GetSelection()
                title = self.GetPageText(pg_num)
                if self.control.GetModify():
                    title = u"*" + title

                # Only Update if the text has changed
                if title != super(EdPages, self).GetPageText(pg_num):
                    self.SetPageText(pg_num, title)
                    ftitle = self.control.GetTitleString()
                    self.frame.SetTitle(ftitle)
            else:
                # A background page has changed
                for page in range(self.GetPageCount()):
                    control = self.GetPage(page)
                    if control.Id == evt.Id:
                        title = self.GetPageText(page)
                        if control.GetModify():
                            title = u"*" + title
                        if title != super(EdPages, self).GetPageText(page):
                            self.SetPageText(page, title)
        except wx.PyDeadObjectError:
            pass

    def UpdateTextControls(self):
        """Updates all text controls to use any new settings that have
        been changed since initialization.
        @postcondition: all stc controls in the notebook are reconfigured
                        to match profile settings

        """
        for control in self.GetTextControls():
            control.UpdateAllStyles()
            control.Configure()

#---- End Function Definitions ----#


text:
package hex.genmodel.algos.coxph;

import hex.genmodel.ModelMojoReader;

import java.io.IOException;
import java.util.*;

public class CoxPHMojoReader extends ModelMojoReader<CoxPHMojoModel> {

  @Override
  public String getModelName() {
    return "CoxPH";
  }

  @Override
  protected void readModelData() throws IOException {
    _model._x_mean_cat = readRectangularDoubleArray("x_mean_cat");
    _model._x_mean_num = readRectangularDoubleArray("x_mean_num");
    _model._coef = readkv("coef");
    _model._strata = readStrata();
    _model._strata_len = readStrataLen();
    _model._cat_offsets = readkv("cat_offsets");
    _model._cats = readkv("cats");
    _model._useAllFactorLevels = readkv("use_all_factor_levels");
    _model._lpBase = _model.computeLpBase();
  }

  private HashMap<CoxPHMojoModel.Strata, Integer> readStrata() {
    final int count = readkv("strata_count");
    final HashMap<CoxPHMojoModel.Strata, Integer> result = new HashMap<>(count);
    for (int i = 0; i < count; i++) {
      final double[] strata = readkv("strata_" + i);
      result.put(new CoxPHMojoModel.Strata(strata, strata.length), i);
    }
    return result;
  }

  private int readStrataLen() {
    final int count = readkv("strata_count");

    if (0 == count) {
      return 0;
    } else {
      final double[] strata = readkv("strata_0");
      return strata.length;
    }
  }

  @Override
  protected CoxPHMojoModel makeModel(String[] columns, String[][] domains, String responseColumn) {
    return new CoxPHMojoModel(columns, domains, responseColumn);
  }

  @Override public String mojoVersion() { return "1.00"; }

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "altruct/structure/container/binary_search_tree.h"

#include <cstdlib>
#include <functional>

namespace altruct {
namespace container {

/**
 * Bidirectional iterator.
 */
template<typename T, typename IT>
struct lazy_treap_iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
    typedef std::iterator<std::bidirectional_iterator_tag, T> it_t;
    typedef typename it_t::difference_type difference_type;
    IT it;
    lazy_treap_iterator() { }
    lazy_treap_iterator(IT it) : it(it) { }
    int count() const { return it.count(); }
    int size() const { return it.size(); }
    T& operator * () { return *it; }
    T* operator -> () { return &*it; }
    bool operator == (const lazy_treap_iterator& rhs) const { return it == rhs.it; }
    bool operator != (const lazy_treap_iterator& rhs) const { return it != rhs.it; }
    lazy_treap_iterator& operator--() { --it; return *this; }
    lazy_treap_iterator operator--(int) { return it--; }
    lazy_treap_iterator& operator++() { ++it; return *this; }
    lazy_treap_iterator operator++(int) { return it++; }

    // `pos` and `add` are not suitable when duplicate mode is set to COUNT
    int pos() const { return it.pos(); }
    lazy_treap_iterator add(difference_type off) { return it.add(off); }

    lazy_treap_iterator parent() const { return it.parent(); }
    lazy_treap_iterator right() const { return it.right(); }
    lazy_treap_iterator left() const { return it.left(); }
};

/**
 * Bidirectional const iterator.
 */
template<typename T, typename CIT, typename IT>
struct lazy_treap_const_iterator : public std::iterator<std::bidirectional_iterator_tag, const T> {
    typedef std::iterator<std::bidirectional_iterator_tag, const T> it_t;
    typedef typename it_t::difference_type difference_type;
    CIT it;
    lazy_treap_const_iterator() { }
    lazy_treap_const_iterator(CIT it) : it(it) { }
    lazy_treap_const_iterator(IT it) : it(it) { }
    lazy_treap_const_iterator(lazy_treap_iterator<T, IT> it) : it(it.it) { }
    int count() const { return it.count(); }
    int size() const { return it.size(); }
    const T& operator * () const { return *it; }
    const T* operator -> () const { return &*it; }
    bool operator == (const lazy_treap_const_iterator& rhs) const { return it == rhs.it; }
    bool operator != (const lazy_treap_const_iterator& rhs) const { return it != rhs.it; }
    lazy_treap_const_iterator& operator--() { --it; return *this; }
    lazy_treap_const_iterator operator--(int) { return it--; }
    lazy_treap_const_iterator& operator++() { ++it; return *this; }
    lazy_treap_const_iterator operator++(int) { return it++; }

    // `pos` and `add` are not suitable when duplicate mode is set to COUNT
    int pos() const { return it.pos(); }
    lazy_treap_const_iterator add(difference_type off) { return it.add(off); }

    lazy_treap_const_iterator parent() const { return it.parent(); }
    lazy_treap_const_iterator right() const { return it.right(); }
    lazy_treap_const_iterator left() const { return it.left(); }
};

/**
 * Treap with lazy propagation.
 *
 * Note, balancing is performed based on random numbers.
 *
 * Space complexity: `O(n)`.
 * Time complexities:
 *   find:   `O(h)`
 *   insert: `O(h)`
 *   erase:  `O(h)`
 * Where `h` is height that is proportional to `log(n)` with
 * very high probability.
 *
 * param T - element type
 * param f_up - associative functor for upward propagation; commutativity is not required.
 * param f_down - associative functor for lazy downward propagation; commutativity is not required.
 * param CMP - comparison functor type
 * param RAND - random generator type
 * param ALLOC - allocator type
 */
template<
    typename T,
    typename CMP = std::less<T>,
    typename F_UP = std::function<void(T& parent, const T& left, const T& right)>,
    typename F_DOWN = std::function<void(T& parent, T& left, T& right)>,
    typename RAND = std::function<int()>,
    typename ALLOC = std::allocator<bst_node<T>>>
class lazy_treap {
protected:
    typedef binary_search_tree<T, T, bst_duplicate_handling::STORE, CMP, ALLOC> bst_t;
    bst_t tree;
    RAND rnd;
    F_UP f_up;     // for up-propagation on update
    F_DOWN f_down; // for down-propagation for lazy updating
    T id, dummy;

public:
    typedef T key_type;
    typedef T value_type;
    typedef lazy_treap_iterator<T, typename bst_t::iterator> iterator;
    typedef lazy_treap_const_iterator<T, typename bst_t::const_iterator, typename bst_t::iterator> const_iterator;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

    lazy_treap(const F_UP& f_up, const F_DOWN& f_down, const CMP& cmp = CMP(), const RAND& rnd = rand, const ALLOC& alloc = ALLOC()) :
        tree(cmp, alloc), rnd(rnd), f_up(f_up), f_down(f_down) {
    }

    template<typename It>
    lazy_treap(It begin, It end, const F_UP& f_up, const F_DOWN& f_down, const CMP& cmp = CMP(), const RAND& rnd = rand, const ALLOC& alloc = ALLOC()) :
        lazy_treap(f_up, f_down, cmp, rnd, alloc) {
        for (It it = begin; it != end; ++it) {
            insert(*it);
        }
    }

    lazy_treap(lazy_treap&& rhs) :
        lazy_treap(rhs.f_up, rhs.f_down) {
        swap(rhs);
    }

    lazy_treap(const lazy_treap& rhs) :
        tree(rhs.tree),
        rnd(rhs.rnd),
        f_up(rhs.f_up),
        f_down(rhs.f_down) {
    }

    lazy_treap& operator=(lazy_treap&& rhs) {
        swap(rhs);
        return *this;
    }

    lazy_treap& operator=(const lazy_treap& rhs) {
        tree = rhs.tree;
        rnd = rhs.rnd;
        f_up = rhs.f_up;
        f_down = rhs.f_down;
        return *this;
    }

    void swap(lazy_treap& rhs) {
        tree.swap(rhs.tree);
        std::swap(rnd, rhs.rnd);
    }

    void clear() {
        tree.clear();
    }

    bool empty() const {
        return tree.empty();
    }

    int size() const {
        return tree.size();
    }

public: // iterators
    iterator root() { return tree.root(); }
    const_iterator root() const { return tree.root(); }
    const_iterator croot() const { return tree.croot(); }
    iterator begin() { return tree.begin(); }
    const_iterator begin() const { return tree.begin(); }
    const_iterator cbegin() const { return tree.cbegin(); }
    iterator end() { return tree.end(); }
    const_iterator end() const { return tree.end(); }
    const_iterator cend() const { return tree.cend(); }
    reverse_iterator rbegin() { return reverse_iterator(end()); }
    const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
    const_reverse_iterator crbegin() const { return const_reverse_iterator(cend()); }
    reverse_iterator rend() { return reverse_iterator(begin()); }
    const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
    const_reverse_iterator crend() const { return const_reverse_iterator(cbegin()); }

public: // relational operators
    bool operator == (const lazy_treap& rhs) const { return tree == rhs.tree; }
    bool operator < (const lazy_treap& rhs) const { return tree < rhs.tree; }
    bool operator != (const lazy_treap& rhs) const { return !(*this == rhs); }
    bool operator >(const lazy_treap& rhs) const { return (rhs < *this); }
    bool operator <= (const lazy_treap& rhs) const { return !(rhs < *this); }
    bool operator >= (const lazy_treap& rhs) const { return !(*this < rhs); }

public: // query & update
    //int count_less_or_equal(const key_type& key) const {
    //    return tree.count_less_or_equal(key);
    //}

    //int count_less(const key_type& key) const {
    //    return tree.count_less(key);
    //}

    //int count(const key_type& key) const {
    //    return tree.count(key);
    //}

    //const_iterator find_kth(int k) const {
    //    return tree.find_kth(k);
    //}

    //iterator find_kth(int k) {
    //    return tree.find_kth(k);
    //}

    // TODO: propagate down on iterator operations?
    //   this can perhaps be achieved by having enter_child hooks in bst?
    //   alternatively, we could do that on dereferencing iterator?
    //   what is the perf hit?

    iterator find(const key_type& key) {
        iterator res = end();
        for (iterator it = root(); it != end();) {
            propagate_down(it);
            if (tree.compare(*it, key)) {
                it = it.right();
            } else if (tree.compare(key, *it)) {
                it = it.left();
            } else {
                res = it;
                it = it.left();
            }
        }
        return res;
    }

    iterator lower_bound(const key_type& key) {
        iterator res = end();
        for (iterator it = root(); it != end();) {
            propagate_down(it);
            if (tree.compare(*it, key)) {
                it = it.right();
            } else {
                res = it;
                it = it.left();
            }
        }
        return res;
    }

    iterator upper_bound(const key_type& key) {
        iterator res = end();
        for (iterator it = root(); it != end();) {
            propagate_down(it);
            if (tree.compare(key, *it)) {
                res = it;
                it = it.left();
            } else {
                it = it.right();
            }
        }
        return res;
    }

    std::pair<iterator, iterator> equal_range(const key_type& key) {
        return{ lower_bound(key), upper_bound(key) };
    }

    iterator insert(const value_type& val, int cnt = 1) {
        upper_bound(val); // to propagate down
        return propagate_up(retrace_up(tree.insert(val, cnt)));
    }

    iterator insert_before(const_iterator it, const value_type& val, int cnt = 1) {
        return propagate_up(retrace_up(tree.insert_before(it.it, val, cnt)));
    }

    iterator erase(const key_type& key, int cnt = std::numeric_limits<int>::max()) {
        return erase(lower_bound(key), upper_bound(key));
    }

    iterator erase(const_iterator b, const_iterator e, int cnt = std::numeric_limits<int>::max()) {
        iterator res;
        while (b != e) res = erase(b++, cnt);
        return res;
    }

    iterator erase(const_iterator it, int cnt = std::numeric_limits<int>::max()) {
        return propagate_up(tree.erase(retrace_down(it).it, cnt));
    }

    T get(const_iterator _b, const_iterator _e) {
        auto b = remove_const(_b), e = remove_const(_e);
        if (b == e--) return id;
        auto a = remove_const(lowest_common_ancestor(b, e));
        T rb = id;
        for (bool was_left = true; b != a; b = b.parent()) {
            if (was_left) dummy = rb, rb = *b, f_up(rb, dummy, _val_or_id(b.right())); // aggregate b and its right child
            was_left = (b == b.parent().left());
        }
        T re = id;
        for (bool was_right = true; e != a; e = e.parent()) {
            if (was_right) dummy = re, re = *e, f_up(re, _val_or_id(e.left(), dummy)); // aggregate e and its left child
            was_right = (e == e.parent().right());
        }
        T r = *a; f_up(r, rb, re); // aggregate a
        return r;
    }

    template<typename F_UPDATE>
    void update(const_iterator _b, const_iterator _e, const F_UPDATE& f) {
        auto b = remove_const(_b), e = remove_const(_e);
        if (b == e--) return;
        auto a = remove_const(lowest_common_ancestor(b, e));
        for (bool was_left = true; b != a; b = b.parent()) {
            if (was_left) f(*b), f_down(*b, dummy, _val_or_dummy(b.right())); // update b and its right child
            was_left = (b == b.parent().left());
        }
        for (bool was_right = true; e != a; e = e.parent()) {
            if (was_right) f(*e), f_down(*e, _val_or_dummy(e.left()), dummy); // update e and its left child
            was_right = (e == e.parent().right());
        }
        f(*a), f_down(*a, dummy, dummy); // update a
    }

    void propagate_down_to(const_iterator it) {
        if (it == end()) return;
        propagate_down_to(it.parent());
        propagate_down(it);
    }

public: // const casting logic
    iterator remove_const(const_iterator it) {
        // the iterator itself is const, but this method is not so this is safe
        return tree.remove_const(it.it);
    }

    const lazy_treap* const_this() const {
        // it is always safe to cast from non-const to const
        return static_cast<const lazy_treap*>(this);
    }

protected: // lowest_common_ancestor
    const_iterator lowest_common_ancestor(const_iterator b, const_iterator e) {
        int db = depth(b), de = depth(e);
        for (; db > de; db--) b = b.parent();
        for (; de > db; de--) e = e.parent();
        while (b != e) b = b.parent(), e = e.parent();
        return b;
    }

    int depth(const_iterator it) {
        int d = 0;
        for (; it != end(); it = it.parent()) d++;
        return d;
    }

protected: // balancing
    iterator retrace_up(const_iterator _it) {
        auto it = remove_const(_it).it;
        if (it == tree.end()) return it;
        it.balance() = rnd();
        while (it.balance() < it.parent().balance()) {
            if (it.parent().left() == it) {
                tree.rotate_right(it.parent());
            } else {
                tree.rotate_left(it.parent());
            }
        }
        return it;
    }

    iterator retrace_down(const_iterator _it) {
        auto it = remove_const(_it).it;
        if (it == tree.end()) return it;
        propagate_down(it);
        while (it.left() != tree.end() && it.right() != tree.end()) {
            if (it.left().balance() < it.right().balance()) {
                propagate_down(it.left());
                tree.rotate_right(it);
            } else {
                propagate_down(it.right());
                tree.rotate_left(it);
            }
        }
        return it;
    }

public: // aggregation
    iterator propagate_up(const_iterator _it) {
        auto it = remove_const(_it);
        for (auto it2 = it; it2 != tree.end(); it2 = it2.parent()) {
            f_up(*it2, _val_or_id(it2.left()), _val_or_id(it2.right()));
        }
        return it;
    }

    iterator propagate_down(const_iterator _it) {
        auto it = remove_const(_it);
        if (it == tree.end()) return it;
        f_down(*it, _val_or_dummy(it.left()), _val_or_dummy(it.right()));
        return it;
    }

private:
    const T& _val_or_id(iterator it) {
        return (it != tree.end()) ? *it : id;
    }

    T& _val_or_dummy(iterator it) {
        return (it != tree.end()) ? *it : dummy;
    }
};

} // container
} // altruct


text:
DevHub [https://github.com/volpe28v/DevHub](https://github.com/volpe28v/DevHub) dockerfile

# Usage
At first, build or docker pull.

```sh
docker run -it --rm hitsumabushi/devhub
```


text:
+++
date = "2016-05-02T12:52:27-05:00"
title = "welcome"
type = "event"
aliases = ["/events/2012-newyork"]

+++

We're in this together

17 and 18 January 2013 (originally scheduled for 2012)
Brooklyn, NYC

You can become a sponsor.

This event was livestreamed thanks to @livestream - Watch it live


text:
using CommonClassLibrary.Settings;

namespace CygnusAuxBoardMonitor.Settings
{
	class SetupCommunicationSettings : SettingsBase
	{
		public string UARTPort { set; get; }

		public SetupCommunicationSettings()
				: base("Main", "CommunicationSettings")
		{
			SetDefaultValues();
		}

		override public void SetDefaultValues()
		{
			UARTPort = "";
		}
	}
}


text:
package jp.co.acroquest.endosnipe.web.explorer.entity;

public abstract class AbstractConnectionModel
{
    private ComponentModel source_;

    private ComponentModel target_;

    /**
     * このコネクションの根元 をsource に接続します。

     */
    public void attachSource()
    {
        // このコネクションが既に接続されている場合は何もしない
        if (!this.source_.getModelSourceConnections().contains(this))
        {
            this.source_.addSourceConnection(this);
        }
    }

    /**
     * このコネクションの先端を target に接続します。

     */
    public void attachTarget()
    {
        // このコネクションが既に接続されている場合は何もしない
        if (!this.target_.getModelTargetConnections().contains(this))
        {
            this.target_.addTargetConnection(this);
        }
    }

    /**
     * このコネクションの根元を source から取り外します。

     */
    public void detachSource()
    {
        this.source_.removeSourceConnection(this);
    }

    /**
     * このコネクションの先端を target から取り外します。

     */
    public void detachTarget()
    {
        this.target_.removeTargetConnection(this);
    }

    public ComponentModel getSource()
    {
        return this.source_;
    }

    public ComponentModel getTarget()
    {
        return this.target_;
    }

    public void setSource(final ComponentModel model)
    {
        this.source_ = model;
    }

    public void setTarget(final ComponentModel model)
    {
        this.target_ = model;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString()
    {
        return getSource().getComponentName() + "->" + getTarget().getComponentName();
    }
}


text:
package org.apache.poi.ss.formula.functions;

import org.apache.poi.ss.formula.eval.*;
import org.apache.poi.util.StringUtil;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Tests WEEKDAY(serial_number[, return_type]) excep function
 * https://support.office.com/en-us/article/WEEKDAY-function-60E44483-2ED1-439F-8BD0-E404C190949A
 */
public class TestWeekdayFunc {
    private static final double TOLERANCE = 0.001;

    private void assertEvaluateEquals(double expected, double serial_number) {
        String formula = "WEEKDAY(" + serial_number + ")";
        ValueEval[] args = new ValueEval[] { new NumberEval(serial_number) };
        NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0);
        assertEquals(formula, expected, result.getNumberValue(), TOLERANCE);
    }
    private void assertEvaluateEquals(double expected, double serial_number, double return_type) {
        String formula = "WEEKDAY(" + serial_number + ", " + return_type + ")";
        ValueEval[] args = new ValueEval[] { new NumberEval(serial_number), new NumberEval(return_type) };
        NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0);
        assertEquals(formula, expected, result.getNumberValue(), TOLERANCE);
    }

    @Test
    public void testEvaluate() throws Exception {
        assertEvaluateEquals(2.0,  1.0);
        assertEvaluateEquals(2.0,  1.0, 1.0);
        assertEvaluateEquals(1.0,  1.0, 2.0);
        assertEvaluateEquals(0.0,  1.0, 3.0);
        assertEvaluateEquals(1.0, 1.0, 11.0);
        assertEvaluateEquals(7.0, 1.0, 12.0);
        assertEvaluateEquals(6.0, 1.0, 13.0);
        assertEvaluateEquals(5.0, 1.0, 14.0);
        assertEvaluateEquals(4.0, 1.0, 15.0);
        assertEvaluateEquals(3.0, 1.0, 16.0);
        assertEvaluateEquals(2.0, 1.0, 17.0);

        assertEvaluateEquals(3.0, 39448.0);
        assertEvaluateEquals(3.0, 39448.0, 1.0);
        assertEvaluateEquals(2.0, 39448.0, 2.0);
        assertEvaluateEquals(1.0, 39448.0, 3.0);
        assertEvaluateEquals(2.0, 39448.0, 11.0);
        assertEvaluateEquals(1.0, 39448.0, 12.0);
        assertEvaluateEquals(7.0, 39448.0, 13.0);
        assertEvaluateEquals(6.0, 39448.0, 14.0);
        assertEvaluateEquals(5.0, 39448.0, 15.0);
        assertEvaluateEquals(4.0, 39448.0, 16.0);
        assertEvaluateEquals(3.0, 39448.0, 17.0);
    }

    // for testing invalid invocations
    private void assertEvaluateEquals(String message, ErrorEval expected, ValueEval... args) {
        String formula = "WEEKDAY(" + StringUtil.join(args, ", ") + ")";
        ValueEval result = WeekdayFunc.instance.evaluate(args, 0, 0);
        assertEquals(formula + ": " + message, expected, result);
    }

    @Test
    public void testEvaluateInvalid() throws Exception {
        assertEvaluateEquals("no args",       ErrorEval.VALUE_INVALID);
        assertEvaluateEquals("too many args", ErrorEval.VALUE_INVALID, new NumberEval(1.0), new NumberEval(1.0), new NumberEval(1.0));
        assertEvaluateEquals("negative date", ErrorEval.NUM_ERROR, new NumberEval(-1.0));
        assertEvaluateEquals("cannot coerce serial_number to number", ErrorEval.VALUE_INVALID, new StringEval(""));
        assertEvaluateEquals("cannot coerce return_type to number",   ErrorEval.VALUE_INVALID, new StringEval("1"), new StringEval(""));
        assertEvaluateEquals("return_type is blank",   ErrorEval.NUM_ERROR, new StringEval("2"), BlankEval.instance);
        assertEvaluateEquals("return_type is missing", ErrorEval.NUM_ERROR, new StringEval("3"), MissingArgEval.instance);
        assertEvaluateEquals("invalid return_type",    ErrorEval.NUM_ERROR, new NumberEval(1.0), new NumberEval(18.0));
    }
}


text:
package net.sf.jasperreports.export.parameters;

import java.util.Map;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.export.ExporterOutput;

/**
 * @deprecated To be removed.
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: AbstractParametersExporterOutput.java 7199 2014-08-27 13:58:10Z teodord $
 */
public abstract class AbstractParametersExporterOutput implements ExporterOutput
{
	/**
	 *
	 */
	private final JRPropertiesUtil propertiesUtil;
	protected final Map<JRExporterParameter, Object> parameters;
	private ParameterResolver parameterResolver;

	/**
	 *
	 */
	public AbstractParametersExporterOutput(
		JasperReportsContext jasperReportsContext,
		Map<JRExporterParameter, Object> parameters,
		JasperPrint jasperPrint
		)
	{
		this.propertiesUtil = JRPropertiesUtil.getInstance(jasperReportsContext);
		this.parameters = parameters;

		boolean parametersOverrideHints;
		Boolean param = (Boolean) parameters.get(JRExporterParameter.PARAMETERS_OVERRIDE_REPORT_HINTS);
		if (param == null)
		{
			parametersOverrideHints = getPropertiesUtil().getBooleanProperty(JRExporterParameter.PROPERTY_EXPORT_PARAMETERS_OVERRIDE_REPORT_HINTS);
		}
		else
		{
			parametersOverrideHints = param.booleanValue();
		}

		if (parametersOverrideHints)
		{
			parameterResolver =
				new ParameterOverrideResolver(
					jasperReportsContext,
					jasperPrint,
					parameters
					);
		}
		else
		{
			parameterResolver =
				new ParameterOverriddenResolver(
					jasperReportsContext,
					jasperPrint,
					parameters
					);
		}

	}

	/**
	 *
	 */
	protected ParameterResolver getParameterResolver()
	{
		return parameterResolver;
	}

	/**
	 *
	 */
	protected JRPropertiesUtil getPropertiesUtil()
	{
		return propertiesUtil;
	}

}


text:
//
//  ZWStaticOptionCell.m
//  ZWCommonTableDemo
//
//  Created by 王子武 on 2017/8/19.
//  Copyright © 2017年 wang_ziwu. All rights reserved.
//

#import "ZWStaticOptionCell.h"
#import "ZWCommonTableData.h"
#import "ZWStaticOptionModel.h"
@interface ZWStaticOptionCell ()
/** cellModel*/
@property (nonatomic, strong) ZWStaticOptionModel *cellModel;
@end
@implementation ZWStaticOptionCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}
-(void)refreshCellData:(ZWCommonTableRow *)rowData tableView:(UITableView *)tableView{
    self.cellModel = rowData.cellExtraInfo;
    [self refreshData];
}
#pragma mark - config
#pragma mark - lifeCycle
#pragma mark - delegate
#pragma mark - actionFunction
#pragma mark - function
- (void)refreshData{
    self.optionTitleLab.text = self.cellModel.optionTitle;
    if (self.cellModel.optionValue.length) {
        self.optionDetailLab.text = self.cellModel.optionValue;
        self.optionDetailLab.textColor = [UIColor blackColor];
    }else{
        self.optionDetailLab.text = self.cellModel.optionDefaultText;
        self.optionDetailLab.textColor = [UIColor lightGrayColor];
    }
}
#pragma mark - layzing
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
using FurnitureManufacturer.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurnitureManufacturer.Models
{
    public abstract class Furniture : IFurniture
    {
        private string model;
        private decimal price;
        private decimal height;

        public virtual string Model
        {
            get { return this.model; }
            protected set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("Model cannot be emptyor null");
                }

                if (value.Length < 3)
                {
                    throw new ArgumentException("Cannot be less than 3 symbols");
                }

                this.model = value;
            }
        }

        public virtual decimal Price
        {
            get
            {
                return this.price;
            }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentException("Price cannot be less or equal to $0.00");
                }

                this.price = value;
            }
        }

        public virtual decimal Height
        {
            get { return this.height; }
            protected set
            {
                if (value <= 0)
                {
                    throw new ArgumentException("Height cannot be less or equal to 0.00m");
                }

                this.height = value;
            }
        }

        public virtual string Material
        {
            get
            {
                return this.MaterialType.ToString();
            }
        }

        protected MaterialType MaterialType { get; set; }
    }
}


text:
The structure of the page is:

```
https://pub.com
<html>
  <iframe srcdoc="...">
    #document
      <iframe src="https://sp.com"></iframe>
  </iframe>
</html>
```

For results, see https://docs.google.com/document/d/1PV8xgs5oaU1DMuLA3O_qc1EgjaUqOoTYietA0Afu8GE/edit#

TODO: merge results into this file.


text:
package tablesaw.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 Created by bhawkins on 3/13/14.
 */
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Provides
	{
	String value();
	}


text:
KisTA enables the report of \textbf{different types of time metrics} associated both to the application and to the
the platfom resources.
Kista enables the reporting of metrics offline (at the end of the simulation) and
during the simulation.
In addition, KisTA-XML front end enables to report metrics \textbf{in a XML file, supporting
the \emph{Multicube}} interface for DSE.

In its latest version, a capability for reporting basic \textbf{energy and power} metrics has been also added.

\subsubsection{Wors-Case and Actual Case measurements}
An important consideration is that KisTA is a tool oriented to the assessment of predictable systems.
Because of that, the tool, bu default, employs worst-case annotations both for computational loads
and for communication loads by default.
%
This means that the assessemnts obtained refer to worst-case situations.
%
In addition, KisTA can provide assessments for annotations based on the actual computational and communicaiton
load, and the time-dependent state of the system.
This enable more accurate assessemnts, either related to specific scenario or to the average case
(this is exploited for instance in the joint-analytical and simulation based DSE methodology proposed
by KTH, PoliMi and UC partners in the FP7 CONTREX project).

\subsubsection{Estimating Actual Computation times}
The user can configure the KisTA tool to consider \emph{actual computational} loads
(instead the worst-case computational loads captured in the model via the WCET and/or WCEI annotations).
%
These actual times have to be provided by an annotation mechanism integrated in the functional code
employed by the KisTA model.
%
Then, for estimating actual computation times, the user needs to do two things:

\begin{itemize}
\item Compile the functional code to add the instrumentation
\item Redefine the consumption macros, e.g. $CONSUME\_T$, in order to employ
the time estimations from the instrumented code, instead from the WCEI/WCET annotations.
\end{itemize}

Currently, KisTA supports one annotation mechanisms, which serves as reference for introducing
new annotations mechanisms in the library.
%
This annotation mechanism relies on the use of the \emph{scope-g++} compilation tool,
provided by the SCoPE tool developed by the University of Cantabria (http://www.teisa.unican.es/scope).
%
SCoPE provide several annotation mechanism.
Among them, the simples one, based on the annotation of the source code
based on the source-levle operations found (opcost).
This method is open and freely available, and therefore, it has been introduced in KisTA
as a reference (without preventing that other more accurate methods, e.g. based on ASM analysis
can be included).

KisTA integrates a pre-compiled version of the SCOPE opcost compiler, which is
installed in $\$KISTA\_HOME\\bin$ (executables \emph{opcost} and \emph{scope-g++}).

This way, the compilation of the functional code can be done with \emph{scope-g++} instead with gcc.
The user can find an example of how the functional code of the VAD is compiled in
{\tt \$KISTA\_HOME/examples/VAD/fun/Makefile}, i.e. the \emph{Makefile} , used to compile
the VAD functionality of the VAD example distributed in KisTA.

The re-definiton of the $CONSUME\_T$ macros is done by including the headers of the annotation plugin.
The simplest way to do so is to add the $-D\_USE\_AUTOMATIC\_CODE\_ANNOTATION$ flag in the
compilation command.
The user finds an example in the
{\tt \$KISTA\_HOME/examples/VAD/fun/Makefile}
file of the
VAD example (by simply uncommenting the line and re-compiling, the annotation is used).
%
Another alternative is to define the variable by means of a $\#define$ clause in the
functional code, right before the include of the kista header.

The definition of the $\_USE\_AUTOMATIC\_CODE\_ANNOTATION$ includes the
$annotation\_plugin/annotation\_plugin.hpp$ generic header.
This header in turn, selects one among the available annotation headers.
In this case, right the SCoPE annotation header:
$annotation\_plugin/scope\_opcost.hpp$.
%
The SCoPE annotation header provide implementations for the time consumption
macros, e.g. $CONSUME\_T$, which invoke code which computes from the instrumented
code, the actual computational weight as a function of the instructions accounted from the instrumentation,
and as a function of the configured frequency and cycles per instructions associated to the processing element
where the task is running.

\subsubsection{Time related reports}
TBC

\subsubsection{Energy and Power related output metrics}
TBC


text:
<!--
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. See accompanying LICENSE file.
-->
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <servlet-name>jaxrs</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>org.apache.hadoop.ozone.s3.GatewayApplication</param-value>
    </init-param>
    <init-param>
      <param-name>jersey.config.servlet.filter.staticContentRegex</param-name>
      <param-value>/static/images/*.ico</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>jaxrs</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
  </listener>

</web-app>


text:
<ion-view title="{{navTitle}}" hide-back-button="true" left-buttons="leftButtons" right-buttons="rightButtons" hide-back-button="true">

	<ion-content padding="true">

		<button class="button button-positive" ng-click="sendTest()">BT Send 0101</button>

		<button class="button button-positive" ng-click="autobaud()">Auto Rate</button>

		<button class="button button-positive" ng-click="sendReset()">Reset MCU</button>

Debug Output

		<textarea ng-bind="debugString" style="height: 300px; width:100%; background-color:white; border: solid 1px grey; height: 100vh;">
		</textarea>

	</ion-content>

</ion-view>


text:
from __future__ import absolute_import, division, print_function

from os import path
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
from .compat import bytes_to_str
import os

def compile_less(less_filename, css_filename, minify=False, source_map=True):
    cmd = ['lessc', '--silent']

    if minify:
        cmd += ['--clean-css=--s1 --advanced']
    if source_map:
        cmd += ['--source-map']

    less_basename = path.basename(less_filename)
    less_pathname = path.dirname(less_filename)

    cmd += [less_basename, css_filename]

    proc = Popen(cmd, cwd=less_pathname)
    proc.communicate()

    return True

def compile_scss(scss_filename, css_filename, minify=False, source_map=True,
                 autoprefix=True):
    basename = path.basename(scss_filename)
    dirname = path.dirname(scss_filename)
    cmd = ['sassc']

    if source_map:
        cmd += ['-m']
    if minify:
        cmd += ['-t', 'compressed']
    cmd += [basename, css_filename]

    proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, cwd=dirname)
    out, err = proc.communicate()
    out = bytes_to_str(out)

    if len(out):
        raise RuntimeError(out.rstrip())

    if autoprefix:
        cmd = ['postcss', '--use', 'autoprefixer', '--replace',
               css_filename]
        proc = Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=dirname)
        out, err = proc.communicate()
        err = bytes_to_str(err)
        if len(err):
            raise RuntimeError(err.rstrip())

    mtime = path.getmtime(scss_filename)
    os.utime(css_filename, (mtime, mtime))

    return True

def compile_coffee(coffee_filename, js_filename, minify=False):
    cmd = ['coffeebar', '-c']

    if minify:
        cmd += ['-m']

    cmd += ['-o', js_filename, coffee_filename]
    proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    out = bytes_to_str(out)

    if 'error' in out:
        raise RuntimeError(out)

    mtime = path.getmtime(coffee_filename)
    os.utime(js_filename, (mtime, mtime))

    return True


text:
//-----------------------------------------------------------------------
// <copyright file="PersistentViewSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using Akka.Actor;
using Akka.TestKit;
using Xunit;

namespace Akka.Persistence.Tests
{
    public partial class PersistentViewSpec : PersistenceSpec
    {
        protected IActorRef _pref;
        protected IActorRef _view;
        protected TestProbe _prefProbe;
        protected TestProbe _viewProbe;

        public PersistentViewSpec()
            : base(Configuration("PersistentViewSpec"))
        {
            _prefProbe = CreateTestProbe();
            _viewProbe = CreateTestProbe();

            _pref = ActorOf(() => new TestPersistentActor(Name, _prefProbe.Ref));
            _pref.Tell("a");
            _pref.Tell("b");

            _prefProbe.ExpectMsg("a-1");
            _prefProbe.ExpectMsg("b-2");
        }

        protected override void AfterAll()
        {
            if (Sys != null)
            {
                Sys.Stop(_pref);
                Sys.Stop(_view);
            }
            base.AfterAll();
        }

        [Fact]
        public void PersistentView_should_receive_past_updates_from_persistent_actor()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
        }

        [Fact]
        public void PersistentView_should_receive_live_updates_from_persistent_actor()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _pref.Tell("c");
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact]
        public void PersistentView_should_run_updates_at_specified_interval()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(2), null));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _pref.Tell("c");
            _viewProbe.ExpectNoMsg(TimeSpan.FromSeconds(1));
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact]
        public void PersistentView_should_run_updates_on_user_request()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _pref.Tell("c");
            _prefProbe.ExpectMsg("c-3");
            _view.Tell(new Update(isAwait: false));
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact]
        public void PersistentView_should_run_updates_on_user_request_and_wait_for_update()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _pref.Tell("c");
            _prefProbe.ExpectMsg("c-3");
            _view.Tell(new Update(isAwait: true));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact]
        public void PersistentView_should_run_updates_again_on_failure_outside_an_update_cycle()
        {
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _view.Tell("boom");
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
        }

        [Fact]
        public void PersistentView_should_run_updates_again_on_failure_during_an_update_cycle()
        {
            _pref.Tell("c");
            _prefProbe.ExpectMsg("c-3");
            _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), "b"));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact(Skip = "FIXME: working, but random timeouts can occur when running all tests at once")]
        public void PersistentView_should_run_size_limited_updates_on_user_request()
        {
            _pref.Tell("c");
            _pref.Tell("d");
            _pref.Tell("e");
            _pref.Tell("f");
            _prefProbe.ExpectMsg("c-3");
            _prefProbe.ExpectMsg("d-4");
            _prefProbe.ExpectMsg("e-5");
            _prefProbe.ExpectMsg("f-6");

            //TODO: performance optimization
            _view = ActorOf(() => new PassiveTestPersistentView(Name, _viewProbe.Ref, null));
            _view.Tell(new Update(isAwait: true, replayMax: 2));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-b-2");

            _view.Tell(new Update(isAwait: true, replayMax: 1));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-c-3");

            _view.Tell(new Update(isAwait: true, replayMax: 4));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-f-6");
        }

        [Fact]
        public void PersistentView_should_run_size_limited_updates_automatically()
        {
            var replayProbe = CreateTestProbe();
            _pref.Tell("c");
            _pref.Tell("d");
            _prefProbe.ExpectMsg("c-3");
            _prefProbe.ExpectMsg("d-4");

            SubscribeToReplay(replayProbe);

            _view = ActorOf(() => new ActiveTestPersistentView(Name, _viewProbe.Ref));

            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _viewProbe.ExpectMsg("replicated-c-3");
            _viewProbe.ExpectMsg("replicated-d-4");

            replayProbe.ExpectMsg<ReplayMessages>(m => m.FromSequenceNr == 1L && m.Max == 2L);
            replayProbe.ExpectMsg<ReplayMessages>(m => m.FromSequenceNr == 3L && m.Max == 2L);
            replayProbe.ExpectMsg<ReplayMessages>(m => m.FromSequenceNr == 5L && m.Max == 2L);
        }

        [Fact]
        public void PersistentView_should_support_Context_Become()
        {
            _view = ActorOf(() => new BecomingPersistentView(Name, _viewProbe.Ref));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
        }

        [Fact]
        public void PersistentView_should_check_if_incoming_message_is_persistent()
        {
            _pref.Tell("c");
            _prefProbe.ExpectMsg("c-3");

            _view = ActorOf(() => new PersistentOrNotTestPersistentView(Name, _viewProbe.Ref));
            _view.Tell("d");
            _view.Tell("e");

            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _viewProbe.ExpectMsg("replicated-c-3");
            _viewProbe.ExpectMsg("normal-d-3");
            _viewProbe.ExpectMsg("normal-e-3");

            _pref.Tell("f");
            _viewProbe.ExpectMsg("replicated-f-4");
        }

        [Fact]
        public void PersistentView_should_take_snapshots()
        {
            _view = ActorOf(() => new SnapshottingPersistentView(Name, _viewProbe.Ref));
            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _view.Tell("snap");
            _viewProbe.ExpectMsg("snapped");
            _view.Tell("restart");
            _pref.Tell("c");
            _viewProbe.ExpectMsg("replicated-b-2");
            _viewProbe.ExpectMsg("replicated-c-3");
        }

        [Fact]
        public void PersistentView_should_support_stash()
        {
            _view = ActorOf(() => new StashingPersistentView(Name, _viewProbe.Ref));
            _view.Tell("other");
            _view.Tell("unstash");
            _viewProbe.ExpectMsg("a-2"); // note that the LastSequenceNr is 2, since we have replayed b-2
            _viewProbe.ExpectMsg("b-2");
            _viewProbe.ExpectMsg("other-2");
        }

        private void SubscribeToReplay(TestProbe probe)
        {
            Sys.EventStream.Subscribe(probe.Ref, typeof(ReplayMessages));
        }
    }
}


text:
package daemon

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/Clever/sphinx/config"
)

func TestConfigReload(t *testing.T) {
	conf, err := config.New("../example.yaml")
	if err != nil {
		t.Fatal("Error loading config: " + err.Error())
	}
	d := daemon{}
	d.LoadConfig(conf)
	if d.handler == nil {
		t.Fatal("Didn't assign handler")
	}
}

func TestFailedReload(t *testing.T) {
	conf, err := config.New("../example.yaml")
	if err != nil {
		t.Fatal("Error loading config: " + err.Error())
	}
	daemon, err := New(conf)
	if err != nil {
		t.Fatal("Error creating new daemon: " + err.Error())
	}
	conf2 := config.Config{}
	err = daemon.LoadConfig(conf2)
	if err == nil {
		t.Fatal("Should have errored on empty configuration")
	}

	conf.Proxy.Listen = ":1000"
	err = daemon.LoadConfig(conf)
	if err == nil {
		t.Fatalf("Should have errored on changed listen port")
	}
}

func setUpDaemonWithLocalServer(conf config.Config) error {
	// Set up a local server that 404s everywhere except route '/healthyroute'.
	mux := http.NewServeMux()
	mux.HandleFunc("/healthyroute", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("healthy"))
	})
	mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		rw.WriteHeader(http.StatusNotFound)
		rw.Write([]byte("404"))
	})

	// Start local server on the port config points to.
	colonIdx := strings.LastIndex(conf.Proxy.Host, ":")
	localServerListen := conf.Proxy.Host[colonIdx:]
	go http.ListenAndServe(localServerListen, mux)

	// Set up and start the daemon.
	daemon, err := New(conf)
	if err != nil {
		return err
	}

	go daemon.Start()
	time.Sleep(10 * time.Millisecond)
	return nil
}

// testProxyRequest calls the proxy server at the given path and verifies that
// the request returns the given HTTP status and body content.
func testProxyRequest(t *testing.T, url string, expectedStatus int, expectedBody string) {
	resp, err := http.Get(url)
	if err != nil {
		t.Fatalf("Proxy request failed on '%s': %s", url, err.Error())
	}

	if resp.StatusCode != expectedStatus {
		t.Fatalf("Response status with url %s does not match expected value.  Actual: %d.  Expected: %d.",
			url, resp.StatusCode, expectedStatus)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Couldn't read response body: %s", err.Error())
	}

	bodyStr := string(body)
	if bodyStr != expectedBody {
		t.Fatalf("Response body does not match expected value. Actual: \"%s\" Expected: \"%s\"",
			bodyStr, expectedBody)
	}
}

func TestHealthCheck(t *testing.T) {
	// Set up the daemon config to proxy to the local server.
	conf, err := config.New("../example.yaml")
	if err != nil {
		t.Fatalf("Couldn't load daemon config: %s", err.Error())
	}
	conf.Proxy.Host = "http://localhost:8000"
	conf.Proxy.Listen = ":6634"
	conf.HealthCheck.Port = "60002"
	conf.HealthCheck.Enabled = true

	err = setUpDaemonWithLocalServer(conf)
	if err != nil {
		t.Fatalf("Test daemon setup failed: %s", err.Error())
	}

	localProxyURL := "http://localhost" + conf.Proxy.Listen

	// Test a route that should be proxied to 404.
	testProxyRequest(t, localProxyURL+"/helloworld", http.StatusNotFound, "404")

	// Test a route that should be proxied to a valid response.
	testProxyRequest(t, localProxyURL+"/healthyroute", http.StatusOK, "healthy")

	healthCheckURL := fmt.Sprintf("http://localhost:%s/health/check", conf.HealthCheck.Port)

	// Test the health check.
	testProxyRequest(t, healthCheckURL, http.StatusOK, "")
}

func TestDaemonWithNoHealthCheck(t *testing.T) {
	// Set up the daemon config to proxy to the local server.
	conf, err := config.New("../example.yaml")
	if err != nil {
		t.Fatalf("Couldn't load daemon config: %s", err.Error())
	}
	conf.Proxy.Host = "http://localhost:8001"
	conf.Proxy.Listen = ":6635"
	conf.HealthCheck.Port = "60003"
	conf.HealthCheck.Enabled = false

	err = setUpDaemonWithLocalServer(conf)
	if err != nil {
		t.Fatalf("Test daemon setup failed: %s", err.Error())
	}

	// Because so many servers are starting, sleep for a second to make sure
	// they start.
	time.Sleep(time.Second)

	localProxyURL := "http://localhost" + conf.Proxy.Listen

	// Test a route that should be proxied to 404.
	testProxyRequest(t, localProxyURL+"/helloworld", http.StatusNotFound, "404")

	// Test a route that should be proxied to a valid response.
	testProxyRequest(t, localProxyURL+"/healthyroute", http.StatusOK, "healthy")
}