text:
from direct.showbase.DirectObject import DirectObject
from DirectUtil import *
from DirectGeometry import *
from DirectGlobals import *
from DirectSelection import SelectionRay
from direct.interval.IntervalGlobal import Sequence, Func
from direct.directnotify import DirectNotifyGlobal
from direct.task import Task

CAM_MOVE_DURATION = 1.2
COA_MARKER_SF = 0.0075
Y_AXIS = Vec3(0, 1, 0)

class DirectCameraControl(DirectObject):

    notify = DirectNotifyGlobal.directNotify.newCategory('DirectCameraControl')

    def __init__(self):
        # Create the grid
        self.startT = 0.0
        self.startF = 0
        self.orthoViewRoll = 0.0
        self.lastView = 0
        self.coa = Point3(0, 100, 0)
        self.coaMarker = loader.loadModel('models/misc/sphere')
        self.coaMarker.setName('DirectCameraCOAMarker')
        self.coaMarker.setTransparency(1)
        self.coaMarker.setColor(1, 0, 0, 0)
        self.coaMarker.setPos(0, 100, 0)
        useDirectRenderStyle(self.coaMarker)
        self.coaMarkerPos = Point3(0)
        self.coaMarkerColorIval = None
        self.fLockCOA = 0
        self.nullHitPointCount = 0
        self.cqEntries = []
        self.coaMarkerRef = base.direct.group.attachNewNode('coaMarkerRef')
        self.camManipRef = base.direct.group.attachNewNode('camManipRef')
        self.switchDirBelowZero = True
        self.manipulateCameraTask = None
        self.manipulateCameraInterval = None

        t = CAM_MOVE_DURATION
        self.actionEvents = [
            ['DIRECT-mouse1', self.mouseRotateStart],
            ['DIRECT-mouse1Up', self.mouseDollyStop],
            ['DIRECT-mouse2', self.mouseFlyStart],
            ['DIRECT-mouse2Up', self.mouseFlyStop],
            ['DIRECT-mouse3', self.mouseDollyStart],
            ['DIRECT-mouse3Up', self.mouseDollyStop],
            ]

        # [gjeon] moved all of the hotkeys to single place for easy remapping
##         self.keyEvents = [
##             ['c', self.centerCamIn, 0.5],
##             ['f', self.fitOnWidget],                  # Note: This function doesn't work as intended
##             ['h', self.homeCam],
##             ['shift-v', self.toggleMarkerVis],
##             ['m', self.moveToFit],                      # Note: This function doesn't work as intended; the object dissappears and screen flashes
##             ['n', self.pickNextCOA],
##             ['u', self.orbitUprightCam],
##             ['shift-u', self.uprightCam],
##             [repr(1), self.spawnMoveToView, 1],
##             [repr(2), self.spawnMoveToView, 2],
##             [repr(3), self.spawnMoveToView, 3],
##             [repr(4), self.spawnMoveToView, 4],
##             [repr(5), self.spawnMoveToView, 5],
##             [repr(6), self.spawnMoveToView, 6],
##             [repr(7), self.spawnMoveToView, 7],
##             [repr(8), self.spawnMoveToView, 8],
##             ['9', self.swingCamAboutWidget, -90.0, t],
##             ['0', self.swingCamAboutWidget,  90.0, t],
##             ['`', self.removeManipulateCameraTask],
##             ['=', self.zoomCam, 0.5, t],
##             ['+', self.zoomCam, 0.5, t],
##             ['-', self.zoomCam, -2.0, t],
##             ['_', self.zoomCam, -2.0, t],
##             ]

        self.keyEvents = [
            ['DIRECT-centerCamIn', self.centerCamIn, 0.5],
            ['DIRECT-fitOnWidget', self.fitOnWidget],                  # Note: This function doesn't work as intended
            ['DIRECT-homeCam', self.homeCam],
            ['DIRECT-toggleMarkerVis', self.toggleMarkerVis],
            ['DIRECT-moveToFit', self.moveToFit],                      # Note: This function doesn't work as intended; the object dissappears and screen flashes
            ['DIRECT-pickNextCOA', self.pickNextCOA],
            ['DIRECT-orbitUprightCam', self.orbitUprightCam],
            ['DIRECT-uprightCam', self.uprightCam],
            ['DIRECT-spwanMoveToView-1', self.spawnMoveToView, 1],
            ['DIRECT-spwanMoveToView-2', self.spawnMoveToView, 2],
            ['DIRECT-spwanMoveToView-3', self.spawnMoveToView, 3],
            ['DIRECT-spwanMoveToView-4', self.spawnMoveToView, 4],
            ['DIRECT-spwanMoveToView-5', self.spawnMoveToView, 5],
            ['DIRECT-spwanMoveToView-6', self.spawnMoveToView, 6],
            ['DIRECT-spwanMoveToView-7', self.spawnMoveToView, 7],
            ['DIRECT-spwanMoveToView-8', self.spawnMoveToView, 8],
            ['DIRECT-swingCamAboutWidget-0', self.swingCamAboutWidget, -90.0, t],
            ['DIRECT-swingCamAboutWidget-1', self.swingCamAboutWidget,  90.0, t],
            ['DIRECT-removeManipulateCameraTask', self.removeManipulateCameraTask],
            ['DIRECT-zoomInCam', self.zoomCam, 0.5, t],
            ['DIRECT-zoomOutCam', self.zoomCam, -2.0, t],
            ]
        # set this to true to prevent the camera from rolling
        self.lockRoll = False
        # NIK - flag to determine whether to use maya camera controls
        self.useMayaCamControls = 0
        self.altDown = 0
        self.perspCollPlane = None # [gjeon] used for new LE
        self.perspCollPlane2 = None # [gjeon] used for new LE

    def toggleMarkerVis(self):
##        if base.direct.cameraControl.coaMarker.isHidden():
##            base.direct.cameraControl.coaMarker.show()
##        else:
##            base.direct.cameraControl.coaMarker.hide()

        if self.coaMarker.isHidden():
            self.coaMarker.show()
        else:
            self.coaMarker.hide()

    def mouseRotateStart(self, modifiers):
        if self.useMayaCamControls and modifiers == 4:          # alt is pressed - use maya controls
            # base.direct.pushUndo([base.direct.camera])        # Wasteful use of undo
            self.spawnMouseRotateTask()

    def mouseDollyStart(self, modifiers):
        if self.useMayaCamControls and modifiers == 4: # alt is pressed - use maya controls
            # Hide the marker for this kind of motion
            self.coaMarker.hide()
            # Record time of start of mouse interaction
            self.startT= globalClock.getFrameTime()
            self.startF = globalClock.getFrameCount()
            # If the cam is orthogonal, spawn differentTask
            if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
               base.direct.camera.getName() != 'persp':
                self.spawnOrthoZoom()
            else:
                # Start manipulation
                self.spawnHPanYZoom()

    def __stopManipulateCamera(self):
        if self.manipulateCameraTask:
            taskMgr.remove(self.manipulateCameraTask)
            self.manipulateCameraTask = None

        if self.manipulateCameraInterval:
            self.manipulateCameraInterval.finish()
            self.manipulateCameraInterval = None

    def __startManipulateCamera(self, func = None, task = None, ival = None):
        self.__stopManipulateCamera()
        if func:
            assert(task is None)
            task = Task.Task(func)
        if task:
            self.manipulateCameraTask = taskMgr.add(task, 'manipulateCamera')
        if ival:
            ival.start()
            self.manipulateCameraInterval = ival

    def mouseDollyStop(self):
        self.__stopManipulateCamera()

    def mouseFlyStart(self, modifiers):
        # Record undo point
        # base.direct.pushUndo([base.direct.camera])            # Wasteful use of undo
        if self.useMayaCamControls and modifiers == 4:          # alt is down, use maya controls
            # Hide the marker for this kind of motion
            self.coaMarker.hide()
            # Record time of start of mouse interaction
            self.startT= globalClock.getFrameTime()
            self.startF = globalClock.getFrameCount()
            # Start manipulation
            # If the cam is orthogonal, spawn differentTask
            if hasattr(base.direct, "manipulationControl") and base.direct.manipulationControl.fMultiView and\
               base.direct.camera.getName() != 'persp':
                self.spawnOrthoTranslate()
            else:
                self.spawnXZTranslate()
            self.altDown = 1
        elif not self.useMayaCamControls:
            # Where are we in the display region?
            if ((abs(base.direct.dr.mouseX) < 0.9) and (abs(base.direct.dr.mouseY) < 0.9)):
                # MOUSE IS IN CENTRAL REGION
                # Hide the marker for this kind of motion
                self.coaMarker.hide()
                # Record time of start of mouse interaction
                self.startT= globalClock.getFrameTime()
                self.startF = globalClock.getFrameCount()
                # Start manipulation
                self.spawnXZTranslateOrHPanYZoom()
                # END MOUSE IN CENTRAL REGION
            else:
                if ((abs(base.direct.dr.mouseX) > 0.9) and
                    (abs(base.direct.dr.mouseY) > 0.9)):
                    # Mouse is in corners, spawn roll task
                    self.spawnMouseRollTask()
                else:
                    # Mouse is in outer frame, spawn mouseRotateTask
                    self.spawnMouseRotateTask()
        if not modifiers == 4:
            self.altDown = 0

    def mouseFlyStop(self):
        self.__stopManipulateCamera()
        stopT = globalClock.getFrameTime()
        deltaT = stopT - self.startT
        stopF = globalClock.getFrameCount()
        deltaF = stopF - self.startF
        ## No reason this shouldn't work with Maya cam on
        # if not self.useMayaCamControls and (deltaT <= 0.25) or (deltaF <= 1):

        # Do this when not trying to manipulate camera
        if not self.altDown and len(base.direct.selected.getSelectedAsList()) == 0:
            # Check for a hit point based on
            # current mouse position
            # Allow intersection with unpickable objects
            # And then spawn task to determine mouse mode
            # Don't intersect with hidden or backfacing objects
            skipFlags = SKIP_HIDDEN | SKIP_BACKFACE
            # Skip camera (and its children), unless control key is pressed
            skipFlags |= SKIP_CAMERA * (1 - base.getControl())
            self.computeCOA(base.direct.iRay.pickGeom(skipFlags = skipFlags))
            # Record reference point
            self.coaMarkerRef.iPosHprScale(base.cam)
            # Record entries
            self.cqEntries = []
            for i in range(base.direct.iRay.getNumEntries()):
                self.cqEntries.append(base.direct.iRay.getEntry(i))
        # Show the marker
        self.coaMarker.show()
        # Resize it
        self.updateCoaMarkerSize()

    def mouseFlyStartTopWin(self):
        print "Moving mouse 2 in new window"
        #altIsDown = base.getAlt()
        #if altIsDown:
        #    print "Alt is down"

    def mouseFlyStopTopWin(self):
        print "Stopping mouse 2 in new window"

    def spawnXZTranslateOrHPanYZoom(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn the new task
        t = Task.Task(self.XZTranslateOrHPanYZoomTask)
        # For HPanYZoom
        t.zoomSF = Vec3(self.coaMarker.getPos(base.direct.camera)).length()
        self.__startManipulateCamera(task = t)

    def spawnXZTranslateOrHPPan(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        self.__startManipulateCamera(func = self.XZTranslateOrHPPanTask)

    def spawnXZTranslate(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        self.__startManipulateCamera(func = self.XZTranslateTask)

    def spawnOrthoTranslate(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        self.__startManipulateCamera(func = self.OrthoTranslateTask)

    def spawnHPanYZoom(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        t = Task.Task(self.HPanYZoomTask)
        t.zoomSF = Vec3(self.coaMarker.getPos(base.direct.camera)).length()
        self.__startManipulateCamera(task = t)

    def spawnOrthoZoom(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        t = Task.Task(self.OrthoZoomTask)
        self.__startManipulateCamera(task = t)

    def spawnHPPan(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Spawn new task
        self.__startManipulateCamera(func = self.HPPanTask)

    def XZTranslateOrHPanYZoomTask(self, state):
        if base.direct.fShift:
            return self.XZTranslateTask(state)
        else:
            return self.HPanYZoomTask(state)

    def XZTranslateOrHPPanTask(self, state):
        if base.direct.fShift:
            # Panning action
            return self.HPPanTask(state)
        else:
            # Translation action
            return self.XZTranslateTask(state)

    def XZTranslateTask(self, state):
        coaDist = Vec3(self.coaMarker.getPos(base.direct.camera)).length()
        xlateSF = (coaDist / base.direct.dr.near)
        base.direct.camera.setPos(base.direct.camera,
                             (-0.5 * base.direct.dr.mouseDeltaX *
                              base.direct.dr.nearWidth *
                              xlateSF),
                             0.0,
                             (-0.5 * base.direct.dr.mouseDeltaY *
                              base.direct.dr.nearHeight *
                              xlateSF))
        return Task.cont

    def OrthoTranslateTask(self, state):
        # create ray from the camera to detect 3d position
        iRay = SelectionRay(base.direct.camera)
        iRay.collider.setFromLens(base.direct.camNode, base.direct.dr.mouseX, base.direct.dr.mouseY)
        #iRay.collideWithBitMask(1)
        iRay.collideWithBitMask(BitMask32.bit(21))
        iRay.ct.traverse(base.direct.grid)

        entry = iRay.getEntry(0)
        hitPt = entry.getSurfacePoint(entry.getFromNodePath())
        iRay.collisionNodePath.removeNode()
        del iRay
        if hasattr(state, 'prevPt'):
            base.direct.camera.setPos(base.direct.camera, (state.prevPt - hitPt))
        state.prevPt = hitPt
        return Task.cont

    def HPanYZoomTask(self, state):
        # If the cam is orthogonal, don't rotate or zoom.
        if (hasattr(base.direct.cam.node(), "getLens") and
            base.direct.cam.node().getLens().__class__.__name__ == "OrthographicLens"):
            return

        if base.direct.fControl:
            moveDir = Vec3(self.coaMarker.getPos(base.direct.camera))
            # If marker is behind camera invert vector
            if moveDir[1] < 0.0:
                moveDir.assign(moveDir * -1)
            moveDir.normalize()
        else:
            moveDir = Vec3(Y_AXIS)

        if self.useMayaCamControls : # use maya controls
            moveDir.assign(moveDir * ((base.direct.dr.mouseDeltaX -1.0 * base.direct.dr.mouseDeltaY)
                                    * state.zoomSF))
            hVal = 0.0
        else:
            moveDir.assign(moveDir * (-1.0 * base.direct.dr.mouseDeltaY *
                                        state.zoomSF))
            if base.direct.dr.mouseDeltaY > 0.0:
                moveDir.setY(moveDir[1] * 1.0)

            hVal = 0.5 * base.direct.dr.mouseDeltaX * base.direct.dr.fovH

        base.direct.camera.setPosHpr(base.direct.camera,
                                moveDir[0],
                                moveDir[1],
                                moveDir[2],
                                hVal,
                                0.0, 0.0)
        if (self.lockRoll == True):
            # flatten roll
            base.direct.camera.setR(0)

        return Task.cont

    def OrthoZoomTask(self, state):
        filmSize = base.direct.camNode.getLens().getFilmSize()
        factor = (base.direct.dr.mouseDeltaX -1.0 * base.direct.dr.mouseDeltaY) * 0.1
        x = base.direct.dr.getWidth()
        y = base.direct.dr.getHeight()
        base.direct.dr.orthoFactor -= factor
        if base.direct.dr.orthoFactor < 0:
            base.direct.dr.orthoFactor = 0.0001
        base.direct.dr.updateFilmSize(x, y)
        return Task.cont

    def HPPanTask(self, state):
        base.direct.camera.setHpr(base.direct.camera,
                             (0.5 * base.direct.dr.mouseDeltaX *
                              base.direct.dr.fovH),
                             (-0.5 * base.direct.dr.mouseDeltaY *
                              base.direct.dr.fovV),
                             0.0)
        return Task.cont

    def spawnMouseRotateTask(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        if self.perspCollPlane:
            iRay = SelectionRay(base.direct.camera)
            iRay.collider.setFromLens(base.direct.camNode, 0.0, 0.0)
            iRay.collideWithBitMask(1)

            if base.direct.camera.getPos().getZ() >=0:
                iRay.ct.traverse(self.perspCollPlane)
            else:
                iRay.ct.traverse(self.perspCollPlane2)

            if iRay.getNumEntries() > 0:
                entry = iRay.getEntry(0)
                hitPt = entry.getSurfacePoint(entry.getFromNodePath())

                # create a temp nodePath to get the position
                np = NodePath('temp')
                np.setPos(base.direct.camera, hitPt)
                self.coaMarkerPos = np.getPos()
                np.remove()
                self.coaMarker.setPos(self.coaMarkerPos)

            iRay.collisionNodePath.removeNode()
            del iRay

        # Set at markers position in render coordinates
        self.camManipRef.setPos(self.coaMarkerPos)
        self.camManipRef.setHpr(base.direct.camera, ZERO_POINT)
        t = Task.Task(self.mouseRotateTask)
        if abs(base.direct.dr.mouseX) > 0.9:
            t.constrainedDir = 'y'
        else:
            t.constrainedDir = 'x'
        self.__startManipulateCamera(task = t)

    def mouseRotateTask(self, state):
        # If the cam is orthogonal, don't rotate.
        if (hasattr(base.direct.cam.node(), "getLens") and
            base.direct.cam.node().getLens().__class__.__name__ == "OrthographicLens"):
            return
        # If moving outside of center, ignore motion perpendicular to edge
        if ((state.constrainedDir == 'y') and (abs(base.direct.dr.mouseX) > 0.9)):
            deltaX = 0
            deltaY = base.direct.dr.mouseDeltaY
        elif ((state.constrainedDir == 'x') and (abs(base.direct.dr.mouseY) > 0.9)):
            deltaX = base.direct.dr.mouseDeltaX
            deltaY = 0
        else:
            deltaX = base.direct.dr.mouseDeltaX
            deltaY = base.direct.dr.mouseDeltaY
        if base.direct.fShift:
            base.direct.camera.setHpr(base.direct.camera,
                                 (deltaX * base.direct.dr.fovH),
                                 (-deltaY * base.direct.dr.fovV),
                                 0.0)
            if (self.lockRoll == True):
                # flatten roll
                base.direct.camera.setR(0)
            self.camManipRef.setPos(self.coaMarkerPos)
            self.camManipRef.setHpr(base.direct.camera, ZERO_POINT)
        else:
            if base.direct.camera.getPos().getZ() >=0 or not self.switchDirBelowZero:
                dirX = -1
            else:
                dirX = 1

            wrt = base.direct.camera.getTransform(self.camManipRef)
            self.camManipRef.setHpr(self.camManipRef,
                                    (dirX * deltaX * 180.0),
                                    (deltaY * 180.0),
                                    0.0)

            if (self.lockRoll == True):
                # flatten roll
                self.camManipRef.setR(0)
            base.direct.camera.setTransform(self.camManipRef, wrt)
        return Task.cont

    def spawnMouseRollTask(self):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Set at markers position in render coordinates
        self.camManipRef.setPos(self.coaMarkerPos)
        self.camManipRef.setHpr(base.direct.camera, ZERO_POINT)
        t = Task.Task(self.mouseRollTask)
        t.coaCenter = getScreenXY(self.coaMarker)
        t.lastAngle = getCrankAngle(t.coaCenter)
        # Store the camera/manipRef offset transform
        t.wrt = base.direct.camera.getTransform(self.camManipRef)
        self.__startManipulateCamera(task = t)

    def mouseRollTask(self, state):
        wrt = state.wrt
        angle = getCrankAngle(state.coaCenter)
        deltaAngle = angle - state.lastAngle
        state.lastAngle = angle
        self.camManipRef.setHpr(self.camManipRef, 0, 0, deltaAngle)
        if (self.lockRoll == True):
            # flatten roll
            self.camManipRef.setR(0)
        base.direct.camera.setTransform(self.camManipRef, wrt)
        return Task.cont

    def lockCOA(self):
        self.fLockCOA = 1
        base.direct.message('COA Lock On')

    def unlockCOA(self):
        self.fLockCOA = 0
        base.direct.message('COA Lock Off')

    def toggleCOALock(self):
        self.fLockCOA = 1 - self.fLockCOA
        if self.fLockCOA:
            base.direct.message('COA Lock On')
        else:
            base.direct.message('COA Lock Off')

    def pickNextCOA(self):
        """ Cycle through collision handler entries """
        if self.cqEntries:
            # Get next entry and rotate entries
            entry = self.cqEntries[0]
            self.cqEntries = self.cqEntries[1:] + self.cqEntries[:1]
            # Filter out object's under camera
            nodePath = entry.getIntoNodePath()
            if base.direct.camera not in nodePath.getAncestors():
                # Compute new hit point
                hitPt = entry.getSurfacePoint(entry.getFromNodePath())
                # Move coa marker to new point
                self.updateCoa(hitPt, ref = self.coaMarkerRef)
            else:
                # Remove offending entry
                self.cqEntries = self.cqEntries[:-1]
                self.pickNextCOA()

    def computeCOA(self, entry):
        coa = Point3(0)
        dr = base.direct.drList.getCurrentDr()
        if self.fLockCOA:
            # COA is locked, use existing point
            # Use existing point
            coa.assign(self.coaMarker.getPos(base.direct.camera))
            # Reset hit point count
            self.nullHitPointCount = 0
        elif entry:
            # Got a hit point (hit point is in camera coordinates)
            # Set center of action
            hitPt = entry.getSurfacePoint(entry.getFromNodePath())
            hitPtDist = Vec3(hitPt).length()
            coa.assign(hitPt)
            # Handle case of bad coa point (too close or too far)
            if ((hitPtDist < (1.1 * dr.near)) or
                (hitPtDist > dr.far)):
                # Just use existing point
                coa.assign(self.coaMarker.getPos(base.direct.camera))
            # Reset hit point count
            self.nullHitPointCount = 0
        else:
            # Increment null hit point count
            self.nullHitPointCount = (self.nullHitPointCount + 1) % 7
            # No COA lock and no intersection point
            # Use a point out in front of camera
            # Distance to point increases on multiple null hit points
            # MRM: Would be nice to be able to control this
            # At least display it
            dist = pow(10.0, self.nullHitPointCount)
            base.direct.message('COA Distance: ' + repr(dist))
            coa.set(0, dist, 0)
        # Compute COA Dist
        coaDist = Vec3(coa - ZERO_POINT).length()
        if coaDist < (1.1 * dr.near):
            coa.set(0, 100, 0)
            coaDist = 100
        # Update coa and marker
        self.updateCoa(coa, coaDist = coaDist)

    def updateCoa(self, ref2point, coaDist = None, ref = None):
        self.coa.set(ref2point[0], ref2point[1], ref2point[2])
        if not coaDist:
            coaDist = Vec3(self.coa - ZERO_POINT).length()
        # Place the marker in render space
        if ref == None:
            # KEH: use the current display region
            # ref = base.cam
            ref = base.direct.drList.getCurrentDr().cam
        self.coaMarker.setPos(ref, self.coa)
        pos = self.coaMarker.getPos()
        self.coaMarker.setPosHprScale(pos, Vec3(0), Vec3(1))
        # Resize it
        self.updateCoaMarkerSize(coaDist)
        # Record marker pos in render space
        self.coaMarkerPos.assign(self.coaMarker.getPos())

    def updateCoaMarkerSizeOnDeath(self):
        # Needed because tasks pass in state as first arg
        self.updateCoaMarkerSize()

    def updateCoaMarkerSize(self, coaDist = None):
        if not coaDist:
            coaDist = Vec3(self.coaMarker.getPos(base.direct.camera)).length()
        # Nominal size based on default 30 degree vertical FOV
        # Need to adjust size based on distance and current FOV
        sf = COA_MARKER_SF * coaDist * (base.direct.drList.getCurrentDr().fovV/30.0)
        if sf == 0.0:
            sf = 0.1
        self.coaMarker.setScale(sf)
        # Lerp color to fade out
        if self.coaMarkerColorIval:
            self.coaMarkerColorIval.finish()
        self.coaMarkerColorIval = Sequence(
            Func(self.coaMarker.unstash),
            self.coaMarker.colorInterval(1.5, Vec4(1, 0, 0, 0),
                                         startColor = Vec4(1, 0, 0, 1),
                                         blendType = 'easeInOut'),
            Func(self.coaMarker.stash)
            )
        self.coaMarkerColorIval.start()

    def homeCam(self):
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        base.direct.camera.reparentTo(render)
        base.direct.camera.clearMat()
        # Resize coa marker
        self.updateCoaMarkerSize()

    def uprightCam(self):
        self.__stopManipulateCamera()
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        # Pitch camera till upright
        currH = base.direct.camera.getH()
        ival = base.direct.camera.hprInterval(CAM_MOVE_DURATION,
                                              (currH, 0, 0),
                                              other = render,
                                              blendType = 'easeInOut',
                                              name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def orbitUprightCam(self):
        self.__stopManipulateCamera()
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        # Transform camera z axis to render space
        mCam2Render = Mat4(Mat4.identMat()) # [gjeon] fixed to give required argument
        mCam2Render.assign(base.direct.camera.getMat(render))
        zAxis = Vec3(mCam2Render.xformVec(Z_AXIS))
        zAxis.normalize()
        # Compute rotation angle needed to upright cam
        orbitAngle = rad2Deg(math.acos(CLAMP(zAxis.dot(Z_AXIS), -1, 1)))
        # Check angle
        if orbitAngle < 0.1:
            # Already upright
            return
        # Compute orthogonal axis of rotation
        rotAxis = Vec3(zAxis.cross(Z_AXIS))
        rotAxis.normalize()
        # Find angle between rot Axis and render X_AXIS
        rotAngle = rad2Deg(math.acos(CLAMP(rotAxis.dot(X_AXIS), -1, 1)))
        # Determine sign or rotation angle
        if rotAxis[1] < 0:
            rotAngle *= -1
        # Position ref CS at coa marker with xaxis aligned with rot axis
        self.camManipRef.setPos(self.coaMarker, Vec3(0))
        self.camManipRef.setHpr(render, rotAngle, 0, 0)
        # Reparent Cam to ref Coordinate system
        parent = base.direct.camera.getParent()
        base.direct.camera.wrtReparentTo(self.camManipRef)
        # Rotate ref CS to final orientation
        ival = self.camManipRef.hprInterval(CAM_MOVE_DURATION,
                                            (rotAngle, orbitAngle, 0),
                                            other = render,
                                            blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.reparentCam, parent),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def centerCam(self):
        self.centerCamIn(1.0)

    def centerCamNow(self):
        self.centerCamIn(0.)

    def centerCamIn(self, t):
        self.__stopManipulateCamera()
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        # Determine marker location
        markerToCam = self.coaMarker.getPos(base.direct.camera)
        dist = Vec3(markerToCam - ZERO_POINT).length()
        scaledCenterVec = Y_AXIS * dist
        delta = markerToCam - scaledCenterVec
        self.camManipRef.setPosHpr(base.direct.camera, Point3(0), Point3(0))
        ival = base.direct.camera.posInterval(CAM_MOVE_DURATION,
                                              Point3(delta),
                                              other = self.camManipRef,
                                              blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.updateCoaMarkerSizeOnDeath),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def zoomCam(self, zoomFactor, t):
        self.__stopManipulateCamera()
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        # Find a point zoom factor times the current separation
        # of the widget and cam
        zoomPtToCam = self.coaMarker.getPos(base.direct.camera) * zoomFactor
        # Put a target nodePath there
        self.camManipRef.setPos(base.direct.camera, zoomPtToCam)
        # Move to that point
        ival = base.direct.camera.posInterval(CAM_MOVE_DURATION,
                                              ZERO_POINT,
                                              other = self.camManipRef,
                                              blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.updateCoaMarkerSizeOnDeath),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def spawnMoveToView(self, view):
        # Kill any existing tasks
        self.__stopManipulateCamera()
        # Record undo point
        base.direct.pushUndo([base.direct.camera])
        # Calc hprOffset
        hprOffset = VBase3()
        if view == 8:
            # Try the next roll angle
            self.orthoViewRoll = (self.orthoViewRoll + 90.0) % 360.0
            # but use the last view
            view = self.lastView
        else:
            self.orthoViewRoll = 0.0
        # Adjust offset based on specified view
        if view == 1:
            hprOffset.set(180., 0., 0.)
        elif view == 2:
            hprOffset.set(0., 0., 0.)
        elif view == 3:
            hprOffset.set(90., 0., 0.)
        elif view == 4:
            hprOffset.set(-90., 0., 0.)
        elif view == 5:
            hprOffset.set(0., -90., 0.)
        elif view == 6:
            hprOffset.set(0., 90., 0.)
        elif view == 7:
            hprOffset.set(135., -35.264, 0.)
        # Position target
        self.camManipRef.setPosHpr(self.coaMarker, ZERO_VEC,
                                   hprOffset)
        # Scale center vec by current distance to target
        offsetDistance = Vec3(base.direct.camera.getPos(self.camManipRef) -
                              ZERO_POINT).length()
        scaledCenterVec = Y_AXIS * (-1.0 * offsetDistance)
        # Now put the camManipRef at that point
        self.camManipRef.setPosHpr(self.camManipRef,
                                   scaledCenterVec,
                                   ZERO_VEC)
        # Record view for next time around
        self.lastView = view
        ival = base.direct.camera.posHprInterval(CAM_MOVE_DURATION,
                                                 pos = ZERO_POINT,
                                                 hpr = VBase3(0, 0, self.orthoViewRoll),
                                                 other = self.camManipRef,
                                                 blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.updateCoaMarkerSizeOnDeath),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def swingCamAboutWidget(self, degrees, t):
        # Remove existing camera manipulation task
        self.__stopManipulateCamera()

        # Record undo point
        base.direct.pushUndo([base.direct.camera])

        # Coincident with widget
        self.camManipRef.setPos(self.coaMarker, ZERO_POINT)
        # But aligned with render space
        self.camManipRef.setHpr(ZERO_POINT)

        parent = base.direct.camera.getParent()
        base.direct.camera.wrtReparentTo(self.camManipRef)

        ival = self.camManipRef.hprInterval(CAM_MOVE_DURATION,
                                            VBase3(degrees, 0, 0),
                                            blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.reparentCam, parent),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def reparentCam(self, parent):
        base.direct.camera.wrtReparentTo(parent)
        self.updateCoaMarkerSize()

    def fitOnWidget(self, nodePath = 'None Given'):
        # Fit the node on the screen
        # stop any ongoing tasks
        self.__stopManipulateCamera()
        # How big is the node?
        nodeScale = base.direct.widget.scalingNode.getScale(render)
        maxScale = max(nodeScale[0], nodeScale[1], nodeScale[2])
        maxDim = min(base.direct.dr.nearWidth, base.direct.dr.nearHeight)

        # At what distance does the object fill 30% of the screen?
        # Assuming radius of 1 on widget
        camY = base.direct.dr.near * (2.0 * maxScale)/(0.3 * maxDim)

        # What is the vector through the center of the screen?
        centerVec = Y_AXIS * camY

        # Where is the node relative to the viewpoint
        vWidget2Camera = base.direct.widget.getPos(base.direct.camera)

        # How far do you move the camera to be this distance from the node?
        deltaMove = vWidget2Camera - centerVec

        # Move a target there
        try:
            self.camManipRef.setPos(base.direct.camera, deltaMove)
        except Exception:
            self.notify.debug

        parent = base.direct.camera.getParent()
        base.direct.camera.wrtReparentTo(self.camManipRef)
        ival = base.direct.camera.posInterval(CAM_MOVE_DURATION,
                                              Point3(0, 0, 0),
                                              blendType = 'easeInOut')
        ival = Sequence(ival, Func(self.reparentCam, parent),
                        name = 'manipulateCamera')
        self.__startManipulateCamera(ival = ival)

    def moveToFit(self):
        # How big is the active widget?
        widgetScale = base.direct.widget.scalingNode.getScale(render)
        maxScale = max(widgetScale[0], widgetScale[1], widgetScale[2])
        # At what distance does the widget fill 50% of the screen?
        camY = ((2 * base.direct.dr.near * (1.5 * maxScale)) /
                min(base.direct.dr.nearWidth, base.direct.dr.nearHeight))
        # Find a point this distance along the Y axis
        # MRM: This needs to be generalized to support non uniform frusta
        centerVec = Y_AXIS * camY
        # Before moving, record the relationship between the selected nodes
        # and the widget, so that this can be maintained
        base.direct.selected.getWrtAll()
        # Push state onto undo stack
        base.direct.pushUndo(base.direct.selected)
        # Remove the task to keep the widget attached to the object
        taskMgr.remove('followSelectedNodePath')
        # Spawn a task to keep the selected objects with the widget
        taskMgr.add(self.stickToWidgetTask, 'stickToWidget')
        # Spawn a task to move the widget
        ival = base.direct.widget.posInterval(CAM_MOVE_DURATION,
                                              Point3(centerVec),
                                              other = base.direct.camera,
                                              blendType = 'easeInOut')
        ival = Sequence(ival, Func(lambda: taskMgr.remove('stickToWidget')),
                        name = 'moveToFit')
        ival.start()

    def stickToWidgetTask(self, state):
        # Move the objects with the widget
        base.direct.selected.moveWrtWidgetAll()
        # Continue
        return Task.cont

    def enableMouseFly(self, fKeyEvents = 1):
        # disable C++ fly interface
        base.disableMouse()
        # Enable events
        for event in self.actionEvents:
            self.accept(event[0], event[1], extraArgs = event[2:])
        if fKeyEvents:
            for event in self.keyEvents:
                self.accept(event[0], event[1], extraArgs = event[2:])
        # Show marker
        self.coaMarker.reparentTo(base.direct.group)

    def disableMouseFly(self):
        # Hide the marker
        self.coaMarker.reparentTo(hidden)
        # Ignore events
        for event in self.actionEvents:
            self.ignore(event[0])
        for event in self.keyEvents:
            self.ignore(event[0])
        # Kill tasks
        self.removeManipulateCameraTask()
        taskMgr.remove('stickToWidget')
        base.enableMouse()

    def removeManipulateCameraTask(self):
        self.__stopManipulateCamera()


text:
//
//  RKOrbBasicPrintMessage.h
//  RobotKit
//
//  Created by Jon Carroll on 3/16/12.
//  Copyright (c) 2012 Orbotix Inc. All rights reserved.
//

#import <RobotKit/RKDeviceAsyncData.h>

/*!
 * Class to encapsulate asyncronous messages sent from a Sphero. To receive this object
 * register as an asynchronous data observer with RKDeviceMessenger.
 */
@interface RKOrbBasicPrintMessage : RKDeviceAsyncData {
@private
   NSString *message;
}

/*! The message that was returned from orbBasic for printing on the screen. */
@property ( nonatomic, readonly ) NSString *message;

@end

redpajama_set_name: RedPajamaGithub


text:
.UiMessage-container {
  position: fixed;
  top: 1.5vh;
  left: 0;
  right: 0;

  display: flex;
  align-items: center;
  justify-content: center;

  z-index: 4;
}

.UiMessage-message {
  font-size: 2.5vh;
  border: 0.25vh solid white;
  border-radius: 1.5vh;
  padding: 1vh;
  color: white;
  opacity: 0.7;

  display: flex;
  flex-direction: row;
  align-items: center;
}

.UiMessage-hidden {
  display: none;
}

.UiMessage-severityInfo {
  background-color: navy;
}

.UiMessage-severityError {
  background-color: firebrick;
}

.UiMessage-text,
.UiMessage-dismiss {
  padding: 0 0.75vh;
}

.UiMessage-dismiss:hover {
  cursor: pointer;
}


text:
from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement

from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext as _

from .utils import get_model

class ArticlePlugin(CMSPluginBase):
    model = get_model('ArticlePlugin')
    name = _('Article')
    text_enabled = True

    def render(self, context, instance, placeholder):
        context.update({
            'plugin': instance,
            'article': instance.article,
            'placeholder': placeholder,
        })
        return context

class LastArticlesPlugin(CMSPluginBase):
    model = get_model('LastArticlesPlugin')
    name = _('Last articles')
    text_enabled = True

    def render(self, context, instance, placeholder):
        context.update({
            'plugin': instance,
            'articles': instance.articles,
            'placeholder': placeholder,
        })
        return context


text:
var marked = require('../index');
console.log(marked('# I am using h1 header.'));


text:
var fs = require('fs');
var tmp = require('tmp');
var getport = require('getport');
var parallel = require('run-parallel');
var FixedServer = require('fixed-server').FixedServer;

module.exports = Fixtures;

function Fixtures(test) {
  test('setup', this.setup.bind(this));
}

Fixtures.prototype.teardown = function(test) {
  var self = this;

  test('teardown', function(t) {
    self.fixedServer.destroy(t.end);
  });
};

Fixtures.prototype.addFixture = function addFixture(route, response) {
  var self = this;

  self.fixtureNames.push(route);

  self.fixedServer.installFixture({
    method: 'post',
    route: route,
    response: function(req, res) {
      res.json(response);
    }
  });
};

Fixtures.prototype.setup = function setup(t) {
  var self = this;

  parallel({
    tmpName: tmp.tmpName,
    tokenTmpName: tmp.tmpName,
    port: getport
  }, function(err, results) {
    if (err) throw err;

    self.configFile = results.tmpName;
    self.tokenConfigFile = results.tokenTmpName;
    self.port = results.port;

    self.fixedServer = new FixedServer({
      port: self.port
    });

    self.host = 'http:\/\/localhost:' + self.port + '\/api\/';
    self.arcConfig = {
      hosts: {}
    };
    self.arcConfig.hosts[self.host] = {
      'user': 'test',
      'cert': 'test-certificate'
    };

    self.tokenArcConfig = {
      hosts: {}
    };
    self.tokenArcConfig.hosts[self.host] = {
      token: 'test-token'
    };

    fs.writeFileSync(self.configFile, JSON.stringify(self.arcConfig));
    fs.writeFileSync(self.tokenConfigFile, JSON.stringify(self.tokenArcConfig));

    self.fixtureNames = [];

    self.addFixture('/api/conduit.connect', {
      'result': {
        'connectionID': 12345,
        'sessionKey': 'secret-key',
        'userPHID': 'PHID-USER-12345'
      },
      'error_code': null,
      'error_info': null
    });

    self.fixedServer.listen();
    t.end();
  });
};


text:
FactoryGirl.define do
  factory :activity do
    actor
    object { create(:user) }
    event 'test'
    notifier_type 'test_notifier'
  end
end


text:
package org.reldb.rel.client.connection.stream;

import java.net.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;

public class ClientNetworkConnection extends ClientConnection {

	private Socket socket;
	private PrintStream outputToServer;

	/** Establish a connection with a server. */
	public ClientNetworkConnection(String serverName, int port) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		socket = new Socket(serverName, port);
		outputToServer = new PrintStream(socket.getOutputStream());
		obtainInitialServerResponse();
	}

	public InputStream getServerResponseInputStream() throws IOException {
		return socket.getInputStream();
	}

	private void send(String src) throws IOException {
		if (src == null)
			throw new IllegalArgumentException("Attempt to execute null source code.");
		outputToServer.println(src);
		outputToServer.flush();
		if (outputToServer.checkError())
			throw new IOException("Lost connection to server.");
	}

	public void reset() throws IOException {
		send('R' + "<EOT>");
	}

	public void sendEvaluate(String source) throws IOException {
		send('E' + source + "<EOT>");
	}

	public void sendExecute(String source) throws IOException {
		send('X' + source + "<EOT>");
	}

	public void close() throws IOException {
		outputToServer.close();
		socket.close();
	}
}


text:
Utility that takes a JSON topology description file and generates a `sys.config` configuration file for the [LINC Switch](http://github.com/FlowForwarding/LINC-Switch).

## Usage

Compile with:

```
$ ./rebar get-deps compile
```

Start the Erlang shell:

```
$ erl -pa deps/jsx/ebin ebin

Eshell V5.10.4  (abort with ^G)
1> config_generator:parse("json_example.json", "sys.config.template", "localhost", 4343).
ok
```

This will generate a `sys.config` file.


text:
package de.choesel.blechwiki;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

import de.choesel.blechwiki.model.Buch;
import de.choesel.blechwiki.model.Titel;
import de.choesel.blechwiki.orm.BlechWikiRepository;
import de.choesel.blechwiki.orm.DatabaseHelper;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;

/**
 * A fragment representing a list of Items.
 *

 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class TitelFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;
    private RecyclerView recyclerView;

    private class myAsyncTask extends AsyncTask<Void, Void, List<Titel>> {

        DatabaseHelper databaseHelper;
        String buchId = "";

        private myAsyncTask(String buchId, Context context) {
            this.buchId = buchId;
            databaseHelper = new DatabaseHelper(context);
        }

        private myAsyncTask(Context context) {
            this("",context);
        }

        @Override
        protected void onPostExecute(List<Titel> result) {
            super.onPostExecute(result);
            databaseHelper.close();
            recyclerView.setAdapter(new TitelRecyclerViewAdapter(result, mListener));
            //mSwipeView.setRefreshing(false);
        }

        @Override
        protected List<Titel> doInBackground(Void... arg0) {
            BlechWikiRepository blechWikiRepository = new BlechWikiRepository(databaseHelper);
            if (buchId != null && !buchId.isEmpty()) {

                try {
                    Buch sample = new Buch();
                    sample.setId(UUID.fromString(buchId));
                    Buch buch = databaseHelper.getBuchDao().queryForSameId(sample);

                    List<Titel> result = new ArrayList<>(buch.getStuecke());
                    Collections.sort(result, new Comparator<Titel>() {
                        @Override
                        public int compare(Titel lhs, Titel rhs) {
                            return Double.valueOf(lhs.getNummer()).compareTo(Double.valueOf(rhs.getNummer()));
                        }
                    });
                    return result;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return new ArrayList<>();
            }

            return new ArrayList<>();
        }
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TitelFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static TitelFragment newInstance(int columnCount) {
        TitelFragment fragment = new TitelFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_titel_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new TitelRecyclerViewAdapter(new ArrayList<Titel>(), mListener));
            Intent intent = getActivity().getIntent();
            String buchID = intent.getStringExtra(MainActivity.BUCH_ID);
            if(buchID != null){
                myAsyncTask myRequest = new myAsyncTask(buchID,getContext());
                myRequest.execute();
            }
            //recyclerView.setAdapter(new TitelRecyclerViewAdapter(DummyContent.ITEMS, mListener));
        }
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(Titel item);
    }
}


text:
Intel processors since around 2010 support the [AES-NI][] instruction set,
which provides hardware acceleration for the [AES][] block cipher.

There is plenty of AES-NI code out there, including the [Linux kernel][] and
Intel's own [sample code][].  However I struggled to find a really clear,
self-contained example of how these instructions work.  Eventually I put
together these programs as a test of my understanding, and a demonstration
which may be useful to others.  The programs are very simple, there is little
going on besides AES-NI, and they are thoroughly commented.

This code is available under a BSD-style license; see `LICENSE`.

## Warning

**Do not use this code in any context where actual security is required!** This
is just a demonstration, for learning purposes, of an AES-128 block encryption
/ decryption primitive.  I've expended zero effort at the level of protocol or
application security.  Each block is encrypted the same way regardless of where
it appears in the input stream — this is known as ECB mode and it's [very
insecure][].  Furthermore there may be implementation bugs, side channel
exposures, etc.  Even with a perfect implementation of AES, there are [many
ways to screw up][] using it.

It really should go without saying, but **you should not use assembly programs
from some random person on GitHub in your security-critical systems**.  I take
absolutely no responsibility for what happens if you do (see `LICENSE`).

## Usage

`encrypt` will read a 16-byte AES-128 key from standard input, followed by zero
or more 16-byte plaintext blocks, and will write the corresponding ciphertext
to standard output.  `decrypt` works the same way, with the roles of plaintext
and ciphertext reversed.  Run `build-and-test.sh` to build both programs and
then test them against a few hundred AES-128 test vectors.

Both programs are written in assembly for amd64 Linux, and will run without
needing `libc` or any other libraries.  If you want to port these programs to
another amd64 platform (with a GNU-compatible assembler), all of the
OS-specific code is at the top of `common.s`.

To see if your CPU supports AES-NI, check for `aes` in `/proc/cpuinfo`.

Other caveats: This code doesn't have any error handling.  It assumes it can
always read/write 16 bytes at a time, and doesn't handle `EINTR`.  It doesn't
handle input that is not a multiple of the AES block size, nor does it check
the decrypted plaintext against any kind of padding spec.  It doesn't prevent
key material from being swapped to disk.

## Details

In AES, a single block of data goes through a number of encryption or
decryption rounds, each against a separate round key.  The 16-byte round keys
are derived from the user-specified key (also 16 bytes in AES-128) through a
process called key expansion.

The macro `key_expand` in `common.s` computes a single round key, by invoking
the `AESKEYGENASSIST` instruction and then calling the function `key_combine`
for additional processing.  The actual encryption / decryption rounds are
performed by `AESENC` / `AESDEC` instructions, with a variant used on the last
round.  See the Intel [white paper][] for more details on the individual
instructions.  That document also explains how to use AES-NI with 192- or
256-bit keys, which my code does not support.

In these programs, almost all of the action happens in registers; we only use
memory for calling `read` and `write`.  Conveniently, an AES round key or data
block is the same size as an SSE register.  The user-specified key goes in
`%xmm5` and the other round keys are computed and stored in `%xmm6` through
`%xmm15`.  `%xmm0` through `%xmm2` are used for various scratch purposes;
`%xmm3` and `%xmm4` are unused.

The key expansion code in `encrypt.s` and `decrypt.s` is similar and could be
combined using an additional macro, but I chose to leave them separate for
clarity.

AES-NI itself is very fast.  However, don't expect great performance from these
programs, because they make two system calls per 16 bytes processed.  A
high-throughput version would buffer I/O to reduce system call overhead.

Using AES-NI eliminates the need for AES lookup tables, which have been a
source of [cache-related timing side channel vulnerabilities][] [PDF].  Indeed
my programs have no data-dependent control flow or memory access.  (You can see
this clearly in the disassembly, which is free of the usual `libc` noise and is
actually quite readable.)  However I won't go so far as to claim there are no
timing side channels, especially because I haven't performed any measurements.

[AES]:           http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
[AES-NI]:        http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-instructions-aes-ni
[Linux kernel]:  http://lxr.linux.no/linux+v3.8.5/arch/x86/crypto/aesni-intel_asm.S
[sample code]:   http://software.intel.com/en-us/articles/download-the-intel-aesni-sample-library
[white paper]:   http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set
[very insecure]: http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
[many ways to screw up]: http://chargen.matasano.com/chargen/2009/7/22/if-youre-typing-the-letters-a-e-s-into-your-code-youre-doing.html
[cache-related timing side channel vulnerabilities]: http://tau.ac.il/~tromer/papers/cache-joc-20090619.pdf


text:
hljs.registerLanguage("tap",(()=>{"use strict";return e=>({
name:"Test Anything Protocol",case_insensitive:!0,
contains:[e.HASH_COMMENT_MODE,{className:"meta",variants:[{
begin:"^TAP version (\\d+)$"},{begin:"^1\\.\\.(\\d+)$"}]},{begin:/---$/,
end:"\\.\\.\\.$",subLanguage:"yaml",relevance:0},{className:"number",
begin:" (\\d+) "},{className:"symbol",variants:[{begin:"^ok"},{begin:"^not ok"}]
}]})})());


text:
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Grid.Domain;
using MaxSearchAlg;

namespace GridTest
{
    [TestClass]
    public class SeparateBiconnectedComponentsHeuristicTest
    {
        private static World _basicWorld2;
        private static World _basicWorld3;
        private static World _basicWorld4a;
        private static World _basicWorld4b;
        private static World _basicWorld5a;
        private static World _basicWorld5b;
        private static World _basicWorld5c;
        private static World _basicWorld5d;
        private static World _basicWorld5e;
        private static World _basicWorld5f;
        private static World _basicWorld5g;
        private static World _basicWorldSeparateBccV1;
        private static World _basicWorldSeparateBccV2;

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {
            _basicWorld2 = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_2x2.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld3 = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_3x3.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld4a = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_4x4A.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld4b = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_4x4B.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5a = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B2_E0_O2.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5b = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B2_E2_O0_V1.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5c = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B2_E2_O0_V2.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5d = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B3_E1_O2.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5e = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B3_E3_O0.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5f = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B4_E0_O4.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorld5g = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_5x5_B4_E4_O0.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorldSeparateBccV1 = new World(File.ReadAllText(@"..\..\Grid_size_SeparateBCC_V1.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
            _basicWorldSeparateBccV2 = new World(File.ReadAllText(@"..\..\AlternateStepsHeuristic_Test_7x6v1.grd"), new SeparateAlternateStepsBiconnectedComponentsHeuristic());
        }

        [TestMethod]
        public void IsEvenLocation_ReturnsCorrectResult_OnLocationsSet()
        {
            var h = new AlternateStepsBiconnectedComponentsHeuristic();
            //when grid is oddXodd we get alternate linear location all the way
            bool shouldBeEven = true;
            for (int i = 0; i < _basicWorld5a.Height; i++)
            {
                for (int j = 0; j < _basicWorld5a.Width; j++)
                {
                    int linearLoc = i * _basicWorld5a.Width + j;
                    Assert.AreEqual(shouldBeEven, h.IsEvenLocation(_basicWorld5a, linearLoc));
                    shouldBeEven = !shouldBeEven;
                }
            }
        }

        [TestMethod]
        public void hValue_heuristicFor2x2_Equals2()
        {
            GridSearchNode initialState = _basicWorld2.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(2, initialState.h);
        }
        [TestMethod]
        public void hValue_heuristicFor3x3_Equals8()
        {
            GridSearchNode initialState = _basicWorld3.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(8, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor4x4A_Equals14()
        {
            GridSearchNode initialState = _basicWorld4a.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(14, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor4x4B_Equals15()
        {
            GridSearchNode initialState = _basicWorld4b.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(15, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5A_Equals20()
        {
            GridSearchNode initialState = _basicWorld5a.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(20, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5B_Equals20()
        {
            GridSearchNode initialState = _basicWorld5b.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(20, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5C_Equals21()
        {
            GridSearchNode initialState = _basicWorld5c.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(21, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5D_Equals20()
        {
            GridSearchNode initialState = _basicWorld5d.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(20, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5E_Equals18()
        {
            GridSearchNode initialState = _basicWorld5e.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(18, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5F_Equals20()
        {
            GridSearchNode initialState = _basicWorld5f.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(16, initialState.h);
        }

        [TestMethod]
        public void hValue_heuristicFor5x5G_Equals20()
        {
            GridSearchNode initialState = _basicWorld5g.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(14, initialState.h);
        }

        [TestMethod]
        public void hValue_basicWorldSeparateBccV1_Equals20()
        {
            GridSearchNode initialState = _basicWorldSeparateBccV1.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(14, initialState.h);
        }

        [TestMethod]
        public void hValue_basicWorldSeparateBccV2_Equals31()
        {
            GridSearchNode initialState = _basicWorldSeparateBccV2.GetInitialSearchNode<GridSearchNode>();
            Assert.AreEqual(31, initialState.h);
        }

    }
}


text:
namespace CovarianceAndContravariance.ClassHierarchy
{
    public class LastClass : MiddleClass
    {
    }
}


text:
from .XML_config import core_config
#app map interface
from .app_map import AppMap


text:
module Arel
  module Ltree
    module Predications
      def ancestor_of(other)
        Arel::Ltree::Nodes::AncestorOf.new(self, other)
      end

      def descendant_of(other)
        Arel::Ltree::Nodes::DescendantOf.new(self, other)
      end

      def matches(other = nil)
        case other
        when Attributes::Ltxtquery
          Arel::Ltree::Nodes::Matches.new(self).ltxtquery(other)
        when Attributes::Lquery
          Arel::Ltree::Nodes::Matches.new(self).lquery(other)
        when Attributes::Ltree
          Arel::Ltree::Nodes::Matches.new(self).ltree(other)
        when nil
          Arel::Ltree::Nodes::Matches.new(self)
        else
          super
        end
      end
    end

    module MatchesPredications
      def lquery(other)
        ltree_matches_node(other, Attributes::Lquery)
      end

      def ltree(other)
        ltree_matches_node(other, Attributes::Ltree)
      end

      def ltxtquery(other)
        ltree_matches_node(other, Attributes::Ltxtquery)
      end

      private

      def ltree_matches_node(other, rop_node_klass)
        case other
        when String
          Nodes::Matches.new(self.left, rop_node_klass.new(other))
        when Array
          Nodes::Matches.new(self.left, other.map { |o| rop_node_klass.new(o) })
        else
          Nodes::Matches.new(self.left, other)
        end
      end
    end

    Nodes::Matches.send :include, MatchesPredications
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.jugular</groupId>
    <artifactId>build-tools</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <name>⚒ build-tools</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

    </dependencies>
</project>


text:
<?php namespace Toyotadjakarta\ContactsModule\Contact\Form;

use Anomaly\Streams\Platform\Ui\Form\FormBuilder;

class ContactFormBuilder extends FormBuilder
{

    /**
     * The form fields.
     *
     * @var array|string
     */
    protected $fields = [];

    /**
     * Fields to skip.
     *
     * @var array|string
     */
    protected $skips = [];

    /**
     * The form actions.
     *
     * @var array|string
     */
    protected $actions = [];

    /**
     * The form buttons.
     *
     * @var array|string
     */
    protected $buttons = [];

    /**
     * The form options.
     *
     * @var array
     */
    protected $options = [];

    /**
     * The form sections.
     *
     * @var array
     */
    protected $sections = [];

    /**
     * The form assets.
     *
     * @var array
     */
    protected $assets = [];

}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.13">
  <compounddef id="class_pathfinder_1_1_util_1_1_exe_info_manager" kind="class" language="C#" prot="public">
    <compoundname>Pathfinder::Util::ExeInfoManager</compoundname>
    <innerclass refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" prot="public">Pathfinder::Util::ExeInfoManager::ExecutableInfo</innerclass>
      <sectiondef kind="private-static-attrib">
      <memberdef kind="variable" id="class_pathfinder_1_1_util_1_1_exe_info_manager_1a01cbfb321231f2e63cc460366751c8a1" prot="private" static="yes" mutable="no">
        <type>Dictionary< string, <ref refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" kindref="compound">ExecutableInfo</ref> ></type>
        <definition>Dictionary<string, ExecutableInfo> Pathfinder.Util.ExeInfoManager.nameToExeStruct</definition>
        <argsstring></argsstring>
        <name>nameToExeStruct</name>
        <initializer>= new Dictionary<string, <ref refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" kindref="compound">ExecutableInfo</ref>>()</initializer>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="Pathfinder/Util/ExeInfoManager.cs" line="97" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="97" bodyend="-1"/>
      </memberdef>
      </sectiondef>
      <sectiondef kind="package-static-func">
      <memberdef kind="function" id="class_pathfinder_1_1_util_1_1_exe_info_manager_1aa6c24ceea354e8ed7b94970648701169" prot="package" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>void</type>
        <definition>static void Pathfinder.Util.ExeInfoManager.LoadExecutableStruct</definition>
        <argsstring>(Event.GameLoadContentEvent e)</argsstring>
        <name>LoadExecutableStruct</name>
        <param>
          <type><ref refid="class_pathfinder_1_1_event_1_1_game_load_content_event" kindref="compound">Event.GameLoadContentEvent</ref></type>
          <declname>e</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="Pathfinder/Util/ExeInfoManager.cs" line="99" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="99" bodyend="114"/>
      </memberdef>
      </sectiondef>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="class_pathfinder_1_1_util_1_1_exe_info_manager_1ae37ee0af06892afa5a837a326abfea03" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type><ref refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" kindref="compound">ExecutableInfo</ref></type>
        <definition>static ExecutableInfo Pathfinder.Util.ExeInfoManager.GetExecutableInfo</definition>
        <argsstring>(string name)</argsstring>
        <name>GetExecutableInfo</name>
        <param>
          <type>string</type>
          <declname>name</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="Pathfinder/Util/ExeInfoManager.cs" line="116" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="116" bodyend="122"/>
      </memberdef>
      <memberdef kind="function" id="class_pathfinder_1_1_util_1_1_exe_info_manager_1ad7e5e3c7d00e175baddaf29412a31f44" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type><ref refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" kindref="compound">ExecutableInfo</ref></type>
        <definition>static ExecutableInfo Pathfinder.Util.ExeInfoManager.GetExecutableInfo</definition>
        <argsstring>(int index)</argsstring>
        <name>GetExecutableInfo</name>
        <param>
          <type>int</type>
          <declname>index</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="Pathfinder/Util/ExeInfoManager.cs" line="124" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="124" bodyend="131"/>
      </memberdef>
      <memberdef kind="function" id="class_pathfinder_1_1_util_1_1_exe_info_manager_1a933366d771546e3c6ffdf178bd6b123a" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <type>List< <ref refid="struct_pathfinder_1_1_util_1_1_exe_info_manager_1_1_executable_info" kindref="compound">ExecutableInfo</ref> ></type>
        <definition>static List<ExecutableInfo> Pathfinder.Util.ExeInfoManager.GetInfoList</definition>
        <argsstring>()</argsstring>
        <name>GetInfoList</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="Pathfinder/Util/ExeInfoManager.cs" line="133" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="133" bodyend="139"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="Pathfinder/Util/ExeInfoManager.cs" line="7" column="1" bodyfile="Pathfinder/Util/ExeInfoManager.cs" bodystart="6" bodyend="140"/>
    <listofallmembers>
      <member refid="class_pathfinder_1_1_util_1_1_exe_info_manager_1ae37ee0af06892afa5a837a326abfea03" prot="public" virt="non-virtual"><scope>Pathfinder::Util::ExeInfoManager</scope><name>GetExecutableInfo</name></member>
      <member refid="class_pathfinder_1_1_util_1_1_exe_info_manager_1ad7e5e3c7d00e175baddaf29412a31f44" prot="public" virt="non-virtual"><scope>Pathfinder::Util::ExeInfoManager</scope><name>GetExecutableInfo</name></member>
      <member refid="class_pathfinder_1_1_util_1_1_exe_info_manager_1a933366d771546e3c6ffdf178bd6b123a" prot="public" virt="non-virtual"><scope>Pathfinder::Util::ExeInfoManager</scope><name>GetInfoList</name></member>
      <member refid="class_pathfinder_1_1_util_1_1_exe_info_manager_1aa6c24ceea354e8ed7b94970648701169" prot="package" virt="non-virtual"><scope>Pathfinder::Util::ExeInfoManager</scope><name>LoadExecutableStruct</name></member>
      <member refid="class_pathfinder_1_1_util_1_1_exe_info_manager_1a01cbfb321231f2e63cc460366751c8a1" prot="private" virt="non-virtual"><scope>Pathfinder::Util::ExeInfoManager</scope><name>nameToExeStruct</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
{{exampleData?.title}}

    <button mat-icon-button type="button" (click)="toggleSourceView()"
            [matTooltip]="'View source'">
      <mat-icon>
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fit="" preserveAspectRatio="xMidYMid meet" focusable="false">
          <path fill="none" d="M0 0h24v24H0V0z"></path>
          <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"></path>
        </svg>
      </mat-icon>
    </button>

  <stackblitz-button [example]="example"></stackblitz-button>

    <mat-tab-group>
      <mat-tab *ngFor="let tabName of _getExampleTabNames()" [label]="tabName">

          <button mat-icon-button type="button" class="docs-example-source-copy"
                  title="Copy example source" aria-label="Copy example source to clipboard"
                  (click)="copySource(viewer.textContent)">
            <mat-icon>content_copy</mat-icon>
          </button>

<doc-viewer
              #viewer [documentUrl]="exampleTabs[tabName]"></doc-viewer>

      </mat-tab>
    </mat-tab-group>

    <ng-template [cdkPortalOutlet]="selectedPortal"></ng-template>


text:
package org.greenrobot.greendao.query;

import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.DaoLog;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.annotation.apihint.Experimental;
import org.greenrobot.greendao.internal.SqlUtils;
import org.greenrobot.greendao.rx.RxQuery;

import java.util.ArrayList;
import java.util.List;

/**
 * Builds custom entity queries using constraints and parameters and without SQL (QueryBuilder creates SQL for you). To
 * acquire an QueryBuilder, use {@link AbstractDao#queryBuilder()} or {@link AbstractDaoSession#queryBuilder(Class)}.
 * Entity properties are referenced by Fields in the "Properties" inner class of the generated DAOs. This approach
 * allows compile time checks and prevents typo errors occuring at build time.

 *

 * Example: Query for all users with the first name "Joe" ordered by their last name. (The class Properties is an inner
 * class of UserDao and should be imported before.)

 *
 * List<User> joes = dao.queryBuilder().where(Properties.FirstName.eq("Joe")).orderAsc(Properties.LastName).list();
 *
 *
 * @param <T> Entity class to create an query for.
 * @author Markus
 */
public class QueryBuilder<T> {

    /** Set to true to debug the SQL. */
    public static boolean LOG_SQL;

    /** Set to see the given values. */
    public static boolean LOG_VALUES;
    private final WhereCollector<T> whereCollector;

    private StringBuilder orderBuilder;

    private final List<Object> values;
    private final List<Join<T, ?>> joins;
    private final AbstractDao<T, ?> dao;
    private final String tablePrefix;

    private Integer limit;
    private Integer offset;
    private boolean distinct;

    /** stored with a leading space */
    private String stringOrderCollation;

    /** For internal use by greenDAO only. */
    public static <T2> QueryBuilder<T2> internalCreate(AbstractDao<T2, ?> dao) {
        return new QueryBuilder<T2>(dao);
    }

    protected QueryBuilder(AbstractDao<T, ?> dao) {
        this(dao, "T");
    }

    protected QueryBuilder(AbstractDao<T, ?> dao, String tablePrefix) {
        this.dao = dao;
        this.tablePrefix = tablePrefix;
        values = new ArrayList<Object>();
        joins = new ArrayList<Join<T, ?>>();
        whereCollector = new WhereCollector<T>(dao, tablePrefix);
        stringOrderCollation = " COLLATE NOCASE";
    }

    private void checkOrderBuilder() {
        if (orderBuilder == null) {
            orderBuilder = new StringBuilder();
        } else if (orderBuilder.length() > 0) {
            orderBuilder.append(",");
        }
    }

    /** Use a SELECT DISTINCT to avoid duplicate entities returned, e.g. when doing joins. */
    public QueryBuilder<T> distinct() {
        distinct = true;
        return this;
    }

    /**
     * If using Android's embedded SQLite, this enables localized ordering of strings
     * (see {@link #orderAsc(Property...)} and {@link #orderDesc(Property...)}). This uses "COLLATE LOCALIZED", which
     * is unavailable in SQLCipher (in that case, the ordering is unchanged).
     *
     * @see #stringOrderCollation
     */
    public QueryBuilder<T> preferLocalizedStringOrder() {
        // SQLCipher 3.5.0+ does not understand "COLLATE LOCALIZED"
        if (dao.getDatabase().getRawDatabase() instanceof SQLiteDatabase) {
            stringOrderCollation = " COLLATE LOCALIZED";
        }
        return this;
    }

    /**
     * Customizes the ordering of strings used by {@link #orderAsc(Property...)} and {@link #orderDesc(Property...)}.
     * Default is "COLLATE NOCASE".
     *
     * @see #preferLocalizedStringOrder
     */
    public QueryBuilder<T> stringOrderCollation(String stringOrderCollation) {
        // SQLCipher 3.5.0+ does not understand "COLLATE LOCALIZED"
        if (dao.getDatabase().getRawDatabase() instanceof SQLiteDatabase) {
            this.stringOrderCollation = stringOrderCollation == null || stringOrderCollation.startsWith(" ") ?
                    stringOrderCollation : " " + stringOrderCollation;
        }
        return this;
    }

    /**
     * Adds the given conditions to the where clause using an logical AND. To create new conditions, use the properties
     * given in the generated dao classes.
     */
    public QueryBuilder<T> where(WhereCondition cond, WhereCondition... condMore) {
        whereCollector.add(cond, condMore);
        return this;
    }

    /**
     * Adds the given conditions to the where clause using an logical OR. To create new conditions, use the properties
     * given in the generated dao classes.
     */
    public QueryBuilder<T> whereOr(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore) {
        whereCollector.add(or(cond1, cond2, condMore));
        return this;
    }

    /**
     * Creates a WhereCondition by combining the given conditions using OR. The returned WhereCondition must be used
     * inside {@link #where(WhereCondition, WhereCondition...)} or
     * {@link #whereOr(WhereCondition, WhereCondition, WhereCondition...)}.
     */
    public WhereCondition or(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore) {
        return whereCollector.combineWhereConditions(" OR ", cond1, cond2, condMore);
    }

    /**
     * Creates a WhereCondition by combining the given conditions using AND. The returned WhereCondition must be used
     * inside {@link #where(WhereCondition, WhereCondition...)} or
     * {@link #whereOr(WhereCondition, WhereCondition, WhereCondition...)}.
     */
    public WhereCondition and(WhereCondition cond1, WhereCondition cond2, WhereCondition... condMore) {
        return whereCollector.combineWhereConditions(" AND ", cond1, cond2, condMore);
    }

    /**
     * Expands the query to another entity type by using a JOIN. The primary key property of the primary entity for
     * this QueryBuilder is used to match the given destinationProperty.
     */
    public <J> Join<T, J> join(Class<J> destinationEntityClass, Property destinationProperty) {
        return join(dao.getPkProperty(), destinationEntityClass, destinationProperty);
    }

    /**
     * Expands the query to another entity type by using a JOIN. The given sourceProperty is used to match the primary
     * key property of the given destinationEntity.
     */
    public <J> Join<T, J> join(Property sourceProperty, Class<J> destinationEntityClass) {
        AbstractDao<J, ?> destinationDao = (AbstractDao<J, ?>) dao.getSession().getDao(destinationEntityClass);
        Property destinationProperty = destinationDao.getPkProperty();
        return addJoin(tablePrefix, sourceProperty, destinationDao, destinationProperty);
    }

    /**
     * Expands the query to another entity type by using a JOIN. The given sourceProperty is used to match the given
     * destinationProperty of the given destinationEntity.
     */
    public <J> Join<T, J> join(Property sourceProperty, Class<J> destinationEntityClass, Property destinationProperty) {
        AbstractDao<J, ?> destinationDao = (AbstractDao<J, ?>) dao.getSession().getDao(destinationEntityClass);
        return addJoin(tablePrefix, sourceProperty, destinationDao, destinationProperty);
    }

    /**
     * Expands the query to another entity type by using a JOIN. The given sourceJoin's property is used to match the
     * given destinationProperty of the given destinationEntity. Note that destination entity of the given join is used
     * as the source for the new join to add. In this way, it is possible to compose complex "join of joins" across
     * several entities if required.
     */
    public <J> Join<T, J> join(Join<?, T> sourceJoin, Property sourceProperty, Class<J> destinationEntityClass,
                               Property destinationProperty) {
        AbstractDao<J, ?> destinationDao = (AbstractDao<J, ?>) dao.getSession().getDao(destinationEntityClass);
        return addJoin(sourceJoin.tablePrefix, sourceProperty, destinationDao, destinationProperty);
    }

    private <J> Join<T, J> addJoin(String sourceTablePrefix, Property sourceProperty, AbstractDao<J, ?> destinationDao,
                                   Property destinationProperty) {
        String joinTablePrefix = "J" + (joins.size() + 1);
        Join<T, J> join = new Join<T, J>(sourceTablePrefix, sourceProperty, destinationDao, destinationProperty,
                joinTablePrefix);
        joins.add(join);
        return join;
    }

    /** Adds the given properties to the ORDER BY section using ascending order. */
    public QueryBuilder<T> orderAsc(Property... properties) {
        orderAscOrDesc(" ASC", properties);
        return this;
    }

    /** Adds the given properties to the ORDER BY section using descending order. */
    public QueryBuilder<T> orderDesc(Property... properties) {
        orderAscOrDesc(" DESC", properties);
        return this;
    }

    private void orderAscOrDesc(String ascOrDescWithLeadingSpace, Property... properties) {
        for (Property property : properties) {
            checkOrderBuilder();
            append(orderBuilder, property);
            if (String.class.equals(property.type) && stringOrderCollation != null) {
                orderBuilder.append(stringOrderCollation);
            }
            orderBuilder.append(ascOrDescWithLeadingSpace);
        }
    }

    /** Adds the given properties to the ORDER BY section using the given custom order. */
    public QueryBuilder<T> orderCustom(Property property, String customOrderForProperty) {
        checkOrderBuilder();
        append(orderBuilder, property).append(' ');
        orderBuilder.append(customOrderForProperty);
        return this;
    }

    /**
     * Adds the given raw SQL string to the ORDER BY section. Do not use this for standard properties: orderAsc and
     * orderDesc are preferred.
     */
    public QueryBuilder<T> orderRaw(String rawOrder) {
        checkOrderBuilder();
        orderBuilder.append(rawOrder);
        return this;
    }

    protected StringBuilder append(StringBuilder builder, Property property) {
        whereCollector.checkProperty(property);
        builder.append(tablePrefix).append('.').append('\'').append(property.columnName).append('\'');
        return builder;
    }

    /** Limits the number of results returned by queries. */
    public QueryBuilder<T> limit(int limit) {
        this.limit = limit;
        return this;
    }

    /**
     * Sets the offset for query results in combination with {@link #limit(int)}. The first {@code offset} results are
     * skipped and the total number of results will be limited by {@code limit}. You cannot use offset without limit.
     */
    public QueryBuilder<T> offset(int offset) {
        this.offset = offset;
        return this;
    }

    /**
     * Builds a reusable query object (Query objects can be executed more efficiently than creating a QueryBuilder for
     * each execution.
     */
    public Query<T> build() {
        StringBuilder builder = createSelectBuilder();
        int limitPosition = checkAddLimit(builder);
        int offsetPosition = checkAddOffset(builder);

        String sql = builder.toString();
        checkLog(sql);

        return Query.create(dao, sql, values.toArray(), limitPosition, offsetPosition);
    }

    /**
     * Builds a reusable query object for low level android.database.Cursor access.
     * (Query objects can be executed more efficiently than creating a QueryBuilder for each execution.
     */
    public CursorQuery buildCursor() {
        StringBuilder builder = createSelectBuilder();
        int limitPosition = checkAddLimit(builder);
        int offsetPosition = checkAddOffset(builder);

        String sql = builder.toString();
        checkLog(sql);

        return CursorQuery.create(dao, sql, values.toArray(), limitPosition, offsetPosition);
    }

    private StringBuilder createSelectBuilder() {
        String select = SqlUtils.createSqlSelect(dao.getTablename(), tablePrefix, dao.getAllColumns(), distinct);
        StringBuilder builder = new StringBuilder(select);

        appendJoinsAndWheres(builder, tablePrefix);

        if (orderBuilder != null && orderBuilder.length() > 0) {
            builder.append(" ORDER BY ").append(orderBuilder);
        }
        return builder;
    }

    private int checkAddLimit(StringBuilder builder) {
        int limitPosition = -1;
        if (limit != null) {
            builder.append(" LIMIT ?");
            values.add(limit);
            limitPosition = values.size() - 1;
        }
        return limitPosition;
    }

    private int checkAddOffset(StringBuilder builder) {
        int offsetPosition = -1;
        if (offset != null) {
            if (limit == null) {
                throw new IllegalStateException("Offset cannot be set without limit");
            }
            builder.append(" OFFSET ?");
            values.add(offset);
            offsetPosition = values.size() - 1;
        }
        return offsetPosition;
    }

    /**
     * Builds a reusable query object for deletion (Query objects can be executed more efficiently than creating a
     * QueryBuilder for each execution.
     */
    public DeleteQuery<T> buildDelete() {
        if (!joins.isEmpty()) {
            throw new DaoException("JOINs are not supported for DELETE queries");
        }
        String tablename = dao.getTablename();
        String baseSql = SqlUtils.createSqlDelete(tablename, null);
        StringBuilder builder = new StringBuilder(baseSql);

        // tablePrefix gets replaced by table name below. Don't use tableName here because it causes trouble when
        // table name ends with tablePrefix.
        appendJoinsAndWheres(builder, tablePrefix);

        String sql = builder.toString();
        // Remove table aliases, not supported for DELETE queries.
        // TODO(?): don't create table aliases in the first place.
        sql = sql.replace(tablePrefix + ".\"", '"' + tablename + "\".\"");
        checkLog(sql);

        return DeleteQuery.create(dao, sql, values.toArray());
    }

    /**
     * Builds a reusable query object for counting rows (Query objects can be executed more efficiently than creating a
     * QueryBuilder for each execution.
     */
    public CountQuery<T> buildCount() {
        String tablename = dao.getTablename();
        String baseSql = SqlUtils.createSqlSelectCountStar(tablename, tablePrefix);
        StringBuilder builder = new StringBuilder(baseSql);
        appendJoinsAndWheres(builder, tablePrefix);

        String sql = builder.toString();
        checkLog(sql);

        return CountQuery.create(dao, sql, values.toArray());
    }

    private void checkLog(String sql) {
        if (LOG_SQL) {
            DaoLog.d("Built SQL for query: " + sql);
        }
        if (LOG_VALUES) {
            DaoLog.d("Values for query: " + values);
        }
    }

    private void appendJoinsAndWheres(StringBuilder builder, String tablePrefixOrNull) {
        values.clear();
        for (Join<T, ?> join : joins) {
            builder.append(" JOIN ").append(join.daoDestination.getTablename()).append(' ');
            builder.append(join.tablePrefix).append(" ON ");
            SqlUtils.appendProperty(builder, join.sourceTablePrefix, join.joinPropertySource).append('=');
            SqlUtils.appendProperty(builder, join.tablePrefix, join.joinPropertyDestination);
        }
        boolean whereAppended = !whereCollector.isEmpty();
        if (whereAppended) {
            builder.append(" WHERE ");
            whereCollector.appendWhereClause(builder, tablePrefixOrNull, values);
        }
        for (Join<T, ?> join : joins) {
            if (!join.whereCollector.isEmpty()) {
                if (!whereAppended) {
                    builder.append(" WHERE ");
                    whereAppended = true;
                } else {
                    builder.append(" AND ");
                }
                join.whereCollector.appendWhereClause(builder, join.tablePrefix, values);
            }
        }
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#list() list()}; see {@link Query#list()} for
     * details. To execute a query more than once, you should build the query and keep the {@link Query} object for
     * efficiency reasons.
     */
    public List<T> list() {
        return build().list();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#__InternalRx()}.
     */
    @Experimental
    public RxQuery<T> rx() {
        return build().__InternalRx();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#__internalRxPlain()}.
     */
    @Experimental
    public RxQuery<T> rxPlain() {
        return build().__internalRxPlain();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#listLazy() listLazy()}; see
     * {@link Query#listLazy()} for details. To execute a query more than once, you should build the query and keep the
     * {@link Query} object for efficiency reasons.
     */
    public LazyList<T> listLazy() {
        return build().listLazy();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#listLazyUncached() listLazyUncached()}; see
     * {@link Query#listLazyUncached()} for details. To execute a query more than once, you should build the query and
     * keep the {@link Query} object for efficiency reasons.
     */
    public LazyList<T> listLazyUncached() {
        return build().listLazyUncached();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#listIterator() listIterator()}; see
     * {@link Query#listIterator()} for details. To execute a query more than once, you should build the query and keep
     * the {@link Query} object for efficiency reasons.
     */
    public CloseableListIterator<T> listIterator() {
        return build().listIterator();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#unique() unique()}; see {@link Query#unique()}
     * for details. To execute a query more than once, you should build the query and keep the {@link Query} object for
     * efficiency reasons.
     */
    public T unique() {
        return build().unique();
    }

    /**
     * Shorthand for {@link QueryBuilder#build() build()}.{@link Query#uniqueOrThrow() uniqueOrThrow()}; see
     * {@link Query#uniqueOrThrow()} for details. To execute a query more than once, you should build the query and
     * keep
     * the {@link Query} object for efficiency reasons.
     */
    public T uniqueOrThrow() {
        return build().uniqueOrThrow();
    }

    /**
     * Shorthand for {@link QueryBuilder#buildCount() buildCount()}.{@link CountQuery#count() count()}; see
     * {@link CountQuery#count()} for details. To execute a query more than once, you should build the query and keep
     * the {@link CountQuery} object for efficiency reasons.
     */
    public long count() {
        return buildCount().count();
    }

}


text:
import { RequestUtil } from "mesosphere-shared-reactjs";

import ActionTypes from "../constants/ActionTypes";
import AppDispatcher from "./AppDispatcher";
import Config from "../config/Config";
import MesosStateUtil from "../utils/MesosStateUtil";

var MesosStateActions = {
  fetchState: RequestUtil.debounceOnError(
    Config.getRefreshRate(),
    function(resolve, reject) {
      return function() {
        RequestUtil.json({
          url: `${Config.historyServer}/mesos/master/state`,
          timeout: 2000,
          success(response) {
            AppDispatcher.handleServerAction({
              type: ActionTypes.REQUEST_MESOS_STATE_SUCCESS,
              data: MesosStateUtil.flagMarathonTasks(response)
            });
            resolve();
          },
          error(xhr) {
            AppDispatcher.handleServerAction({
              type: ActionTypes.REQUEST_MESOS_STATE_ERROR,
              data: xhr.message,
              xhr
            });
            reject();
          },
          hangingRequestCallback() {
            AppDispatcher.handleServerAction({
              type: ActionTypes.REQUEST_MESOS_STATE_ONGOING
            });
          }
        });
      };
    },
    { delayAfterCount: Config.delayAfterErrorCount }
  )
};

module.exports = MesosStateActions;


text:
module Leech
  # Handlers are extending functionality of server by defining custom
  # command handling callbacks or server instance methods.
  #
  # @example Writing own handler
  #     class CustomHandler < Leech::Handler
  #       def self.used(server)
  #         server.instance_eval { extend ServerMethods }
  #       end
  #
  #       module ServerMethods
  #         def say_hello
  #           answer("Hello!")
  #         end
  #       end
  #
  #       handle /^Hello server!$/, :say_hello
  #       handle /^Bye!$/ do |env,params|
  #         env.answer("Take care!")
  #       end
  #     end
  #
  # @example Enabling handlers by server
  #   Leech::Server.new { use CustomHandler }
  #
  # @abstract
  class Handler
    # Default handler error
    class Error < StandardError; end

    # List of declared matchers
    def self.matchers
      @matchers ||= {}
    end

    # It defines matching pattern and callback related with. When specified
    # command will match this pattern then callback will be called.
    #
    # @param [Regexp] patern
    #   Block will be executed for passed command will be maching it.
    # @param [Symbol, nil] method
    #   Name of server method, which should be called when pattern will
    #   match with command
    #
    # @example
    #     handle(/^PRINT) (.*)$/ {|env,params| print params[0]}
    #     handle(/^DELETE FILE (.*)$/) {|env,params| File.delete(params[0])}
    #     handle(/^HELLO$/, :say_hello)
    #
    # @raise [Leech::Error]
    #   When specified callback is not valid method name or Proc.
    def self.handle(pattern, method=nil, &block)
      if block_given?
        method = block
      end
      if method.is_a?(Proc) || method.is_a?(Symbol)
        self.matchers[pattern] = method
      else
        raise Error, "Invalid handler callback"
      end
    end

    # You should implement this method in your handler eg. if you would like
    # to modify server class.
    def self.used(server)
      # nothing...
    end

    # @return [Leecher::Server]
    #   Passed server instance
    attr_reader :env

    # @return [Array<String>]
    #   Parameters matched in passed command
    attr_reader :params

    # Constructor.
    #
    # @param [Leech::Server]
    #   Server instance
    def initialize(env)
      @env = env
    end

    # Compare specified command with declared patterns.
    #
    # @param [String] command
    #   Command to handle.
    #
    # @return [Leech::Handler,nil]
    #   When command match one of declared patterns then it returns itself,
    #   otherwise it returns nil.
    def match(command)
      self.class.matchers.each_pair do |p,m|
        if @params = p.match(command)
          @matcher = m
          return self
        end
      end
      nil
    end

    # This method can be called only after #match. It executes callback
    # related with matched pattern.
    #
    # @raise [Leech::Error]
    #   When @matcher is not defined, which means that #match method wasn't
    #   called before.
    def call
      case @matcher
      when Proc
        @matcher.call(env, params)
      when String, Symbol
        env.send(@matcher.to_sym, params)
      else
        raise Error, "Can not call unmatched command"
      end
    end
  end # Handler
end # Leech