text:
local sceneName = ...

local composer = require("composer")
local display = require("display")
local physics = require("physics")
local facebookShare = require("libs.facebookShare")
local widget = require( "widget" )
local json = require ("json") -- Require the JSON library for decoding purposes
-- local math = require("math")

-- Load scene with same root filename as this file
local scene = composer.newScene( sceneName )
-- Helper libraries
local perspective = require("libs.perspective") -- Code Exchange library to manage camera view
local scoreManager = require("libs.scoreManager")
local soundManager = require("libs.soundManager")
local emittersManager = require("libs.emittersManager")
local pauseDrawer = require("libs.pauseDrawer")
local coinAnimationInfo = require("classes.coinAnimation")
local menuSpritesInfo = require("classes.menuSprites")

-- Delate time: real time 1/frame rate
local dt = 1/60

-- Game Layers
local hero, background, coinParticleGroup, collisionBlastGroup, gameLayer, pauseButton

local effectsBtnOpt, musicBtnOpt

-- Game Objects
local coin
local radius
local circle1 = {}
local circle2 = {}
local vlinear1 = {}
local hlinear1 = {}
local hlinear2 = {}

-- local bottomBar, topBar, leftBar ,rightBar
-- local floor, left_wall, right_wall, ceiling

local camera

-- Time Remaining
local timeRemainingText = 40

-- Audio
local bgMusic, whooshEffect, collisionEffect, btnClickEffect
local musicVol= 0.7
local effectsVol = 0.8

local whooshDirection={x= 0 ,y= 0}
-------------------------------------------------------------------------------

-- -- Create walls
-- local function makeWalls ()
--     --make ceiling
--     ceiling = display.newRect(display.screenOriginX , display.screenOriginY-5, background.contentWidth, 30 )
--     ceiling.myname='ceiling'

--     -- make floor
--     floor = display.newRect(display.screenOriginX , display.screenOriginY + display.contentHeight+5, background.contentWidth, 30 )
--     floor.myname='floor'

--     -- make left wall
--     left_wall = display.newRect( display.screenOriginX-5, display.screenOriginY, 30, 2*background.contentHeight )
--     left_wall.myname='leftWall'

--     -- make right wall
--     right_wall = display.newRect(0.5*background.contentWidth - 0.2*display.contentWidth, display.screenOriginY, 30, 2*background.contentHeight )
--     right_wall.myname='leftWall'
-- end

-- -- Add physics to walls for bounce
-- local function addPhysicsToWalls ()
--     physics.addBody( ceiling, "static", {friction=0.5, bounce=0.8} )
--     physics.addBody( floor, "static", {friction=0.5, bounce=0.8} )
--     physics.addBody( left_wall, "static", {friction=0.5, bounce=0.8} )
--     physics.addBody( right_wall, "static", {friction=0.5, bounce=0.8} )

-- end

-------------------------------------------------------------------------------

-- Adding physics to player
local function addPhysicsToPlayer ()
-- physics.addBody( hero, "dynamic", {density=1, friction=0.3, bounce=0.95, isSensor = true, radius=hero.contentWidth/2} )
-- physics.addBody( hero, "dynamic", { density=1, friction=0.3, bounce=0.7, radius= 0.4*hero.contentWidth } )
    physics.addBody( hero, "dynamic", { density=1, friction=0.3, bounce=0.7} )
    hero.linearDamping = 3
end

-------------------------------------------------------------------------------

-- NOT USED NOW
-- Alternate for ball bounce on collision with walls
-- local function generateWalls ()
--     bottomBar = display.newLine(0, display.contentHeight, background.contentWidth, display.contentHeight)
--     physics.addBody(bottomBar, "static", {isSensor = true})
--     bottomBar.myname='bottomBar'

--     topBar = display.newLine(0, 0, background.contentWidth, 0)
--     topBar.myname='topar'
--     physics.addBody(topBar, "static", {isSensor = true})

--     leftBar = display.newLine(0, 0, 0, display.contentHeight)
--     leftBar.myname='leftBar'
--     physics.addBody(leftBar, "static", {isSensor = true})

--     rightBar = display.newLine(background.contentWidth, 0, background.contentWidth, display.contentHeight)
--     rightBar.myname='rightBar'
--     physics.addBody(rightBar, "static", {isSensor = true})
-- end

-------------------------------------------------------------------------------

-- Attaching layers to the camera
local function setUpCamera()
    camera = perspective.createView()
    camera:setBounds( display.screenOriginX+display.contentWidth*0.4, background.contentWidth-display.contentWidth*0.8, display.contentHeight/2, display.contentHeight/2 ) -- used to keep our view from going outside the background

    camera:add(hero, 1) -- Player layer
    camera.damping = 10 -- A bit more fluid tracking

    -- self:setCameraOffset(display.contentWidth*0.3, 0)
    -- camera:setParallax(1,1)

    camera:add( coin, 1 )  -- Particles layer
    camera:add( coinParticleGroup, 2 )  -- Particles layer
    camera:add( collisionBlastGroup, 2 )
    -- camera:add( pauseButton, 2 )

    camera:add( gameLayer, 3 )  -- Game layer
    camera:add( background, 4 ) -- Background layer
end

-------------------------------------------------------------------------------

function scene:initializeAudio ()

    bgMusic = soundManager.loadAudio("bgmusic2.mp3")
    -- bgmusic2 = soundManager.loadAudio("bgmusic2.mp3")
    -- bgmusic3 = soundManager.loadAudio("bgmusic3.mp3")
    whooshEffect = soundManager.loadAudio("whoosh_effect.wav")
    collisionEffect = soundManager.loadAudio("collision_effect.wav")
    btnClickEffect = soundManager.loadAudio("btn_click.wav")

    -- local currentSoundChannel = audio.play( bgMusic, { channel=0, loops=-1, fadein=1500}  )

end

scene.playLoadedSound = function (sound, loops, fadein, vol)
    local availableChannelForMusic = soundManager.getAvailableChannel()
    local soundOptions = {
        channel = availableChannelForMusic,
        loops = loops,
        fadein = fadein
    }
    soundManager.setVolume(vol, availableChannelForMusic)
    return soundManager.playAudio(sound, soundOptions )

    -- soundManager.setVolume(availableChannelForMusic, 0.3)
end

-------------------------------------------------------------------------------

-- Not being used now
local function panelOpened( target )
    -- if ( target.completeState ) then
    --     print("panel is opened")
    -- end
end

-------------------------------------------------------------------------------

local handleCloseBtnEvent = function(event)
    if "began" == event.phase then
        scene.btnClickChannel = scene.playLoadedSound(btnClickEffect, 0, 0, effectsVol)
    elseif "ended" == event.phase then
        physics.start()
        scene.pausePanel:hide()
        -- audio.resume() -- resume all audio
        -- scene.closeDrawerButton.isVisible = false
    end
end

function removeScreenCap()
    scene.screenCap:removeSelf()
    scene.screenCap = nil
end

-- Image Capture
local function captureWithDelay()

-- To Be used when user clicks photo click
    -- local capture = display.capture( camera, {saveToPhotoLibrary= true})
    -- facebookShare.printName(capture.name)
    -- capture:removeSelf()
    -- capture = nil
    -- local alert = native.showAlert( "Success", "Screen Capture Saved to Library", { "OK" } )

--  To be used AUTOMATICALLY when the game is over

    -- scene.screenCap.x = display.contentCenterX
    -- scene.screenCap.y = display.contentCenterY

    -- -- display.save( screenCap, { filename="WOW.jpg", baseDir=system.TemporaryDirectory}} )
    -- facebookShare.score = 50
    -- facebookShare.doFBLogin()
end

-------------------------------------------------------------------------------
function handleFacebookShareEvent()
    -- captureWithDelay()
    scene.screenCap.x = display.contentCenterX
    scene.screenCap.y = display.contentCenterY

    -- display.save( screenCap, { filename="WOW.jpg", baseDir=system.TemporaryDirectory}} )
    facebookShare.score = 50
    facebookShare.doFBLogin()
end

-------------------------------------------------------------------------------

local handleReloadBtnEvent = function(event)
    if "began" == event.phase then
        scene.btnClickChannel = scene.playLoadedSound(btnClickEffect, 0, 0, effectsVol)
    elseif "ended" == event.phase then
        hero.x = display.screenOriginX + display.contentWidth*0.3
        physics.start()
        scene.pausePanel:hide()
        composer.gotoScene( "scenes.gameScene1", { effect = "fade", time = 300 } )
        -- audio.resume() -- resume all audio
        -- scene.closeDrawerButton.isVisible = false
    end
end

-------------------------------------------------------------------------------

function handleGameOverEvent(type)
    scene.pausePanel:show()
    -- audio.pause() -- pause all audio

    --Taking screen shot for game over
    scene.screenCap = display.captureScreen()
    -- Scale the screen capture, now on the screen, to half its size
    scene.screenCap:scale( 0.4, 0.4 )
    display.save( scene.screenCap, { filename="WOW.jpg", baseDir=system.TemporaryDirectory } )

    physics.pause()
    if type ==1 then
        scene.pausePanel.title = display.newText( "GAME OVER!!!", 0, -display.contentHeight*0.3, "assets/fonts/trs-million-rg.ttf" or native.systemFontBold, 22 )
    elseif type ==2 then
        scene.pausePanel.title = display.newText( "oops.. TIME OVER!!", 0, -display.contentHeight*0.3, "assets/fonts/trs-million-rg.ttf" or native.systemFontBold, 22 )
    else
       scene.pausePanel.title = display.newText( "GAME PAUSED!!", 0, -display.contentHeight*0.3, "assets/fonts/trs-million-rg.ttf" or native.systemFontBold, 22 )
    end
    scene.pausePanel.title:setFillColor( 1, 1, 1 )
    scene.pausePanel:insert(2, scene.pausePanel.title )

    scene.pausePanel:toFront()
end

local handlePauseBtnEvent = function(event)
    if "began" == event.phase then
        scene.btnClickChannel = scene.playLoadedSound(btnClickEffect, 0, 0, effectsVol)
    elseif "ended" == event.phase then
        removeScreenCap()
        handleGameOverEvent(3)
    end

    -- pauseMyMusic()
end

-------------------------------------------------------------------------------

-- Function to handle button events
local function handleEffectsBtnEvent( event )
    if "began" == event.phase then
        scene.btnClickChannel = scene.playLoadedSound(btnClickEffect, 0, 0, effectsVol)
    elseif "ended" == event.phase then
        _G.effectsSound = not _G.effectsSound   -- CHANGE EFFECTS VARIABLE
        if(_G.effectsSound) then
            scene.effectsButtonActive.isVisible = true
            scene.effectsButtonInactive.isVisible = false
        else
            scene.effectsButtonActive.isVisible = false
            scene.effectsButtonInactive.isVisible = true
        end

        scene.updateAudioOptions()
    end
end

-------------------------------------------------------------------------------

-- Function to handle button events
local function handleMusicBtnEvent( event )
    if "began" == event.phase then
        scene.btnClickChannel = scene.playLoadedSound(btnClickEffect, 0, 0, effectsVol)
    elseif "ended" == event.phase then
        _G.musicSound = not _G.musicSound   -- CHANGE MUSIC VARIABLE
        if(_G.musicSound) then
            scene.musicButtonActive.isVisible = true
            scene.musicButtonInactive.isVisible = false
        else
            scene.musicButtonActive.isVisible = false
            scene.musicButtonInactive.isVisible = true
        end
        scene.updateAudioOptions()
    end
end

-------------------------------------------------------------------------------

function scene:initializeParticles()

    coinParticleGroup = emittersManager.init("coin2.json", 2, true)
    local emitterOpt = {
        emitterGroup = coinParticleGroup,
        x = coin.x,
        y = coin.y
    }
    emittersManager.setPosition(emitterOpt)

    collisionBlastGroup = emittersManager.init("collision_blast.json", 2, false)
end

-------------------------------------------------------------------------------

scene.initializeAnimations = function (x, y)
    local myImageSheet = graphics.newImageSheet( "assets/graphics/coinAnimation.png", coinAnimationInfo:getSheet() )
    -- coin = display.newSprite( myImageSheet , {frames={coinAnimationInfo:getFrameIndex("coin_1")}} )

    local sequenceData = {
        {
        name="coinHovering",                          -- name of the animation
        width = 132,
        height = 132,
        sheet=myImageSheet,                           -- the image sheet
        start=coinAnimationInfo:getFrameIndex("coin_1"), -- first frame
        count=6,                                      -- number of frames
        time=8000,                                    -- speed
        loopCount=0,                                   -- repeat
        loopDirection = "forward"
        }
    }
    -- create sprite, set animation, play
    coin = display.newSprite( myImageSheet, sequenceData )
    coin:setSequence("coinHovering")

    local scale = display.contentScaleX
    coin:scale(1.5*scale, 1.5*scale)
    coin.x = x
    coin.y = y
    -- coin.timeScale = 20.0
    coin.timeScale = 10
    coin:play()
end

----------------------------------------
function scene.updateAudioOptions()
    if not _G.musicSound then
        musicVol = 0
    else
        musicVol = 0.7
    end

    if not _G.effectsSound then
        effectsVol = 0
    else
        effectsVol = 0.7
    end

    soundManager.setVolume(musicVol, scene.menuMusicChannel)
    soundManager.setVolume(effectsVol, scene.btnClickChannel)
end
-----------------------------------------
function scene.initializeAudioOptions ()
    if not _G.musicSound then
        musicVol = 0
    else
        musicVol = 0.7
    end

    if not _G.effectsSound then
        effectsVol = 0
    else
        effectsVol = 0.7
    end

    -- SET HERE VOLUME FOR ALL CHANNELS
    -- soundManager.setVolume(musicVol, scene.menuMusicChannel)
    -- soundManager.setVolume(effectsVol, scene.btnClickChannel)
end

-------------------------------------------------------------------------------

-- INITIALIZING POSITION OF LEVEL OBSTACLES
function scene:initializeObstaclePos ()

    -- CIRCLE: 1
    radius = circle1.path.contentWidth/2
    circle1.object.x = circle1.path.x + radius
    circle1.object.y = circle1.path.y
    circle1.theta =0

    -- CIRCLE: 2
    circle2.object.x = circle2.path.x
    circle2.object.y = circle2.path.y + radius
    circle2.theta =0

    -- VERTICAL LINEAR: 1
    local vheight = vlinear1.path.contentHeight
    vlinear1.length = vheight
    vlinear1.object.x = vlinear1.path.x
    vlinear1.object.y = vlinear1.path.y + vheight/6
    vlinear1.motionDir = 1

    -- HORIZONTAL LINEAR: 1
    local hlength = hlinear1.path.contentWidth
    hlinear1.length = hlength
    hlinear1.object.x = hlinear1.path.x
    hlinear1.object.y = hlinear1.path.y
    hlinear1.motionDir = 1

    -- HORIZONTAL LINEAR: 1
    hlinear2length = hlength
    hlinear2.object.x = hlinear2.path.x
    hlinear2.object.y = hlinear2.path.y
    hlinear2.motionDir = -1

end

function scene:setUpPauseDrawer()
    scene.pausePanel = pauseDrawer.newPanel{
        location = "top",
        onComplete = panelOpened,
        width = display.contentWidth * 0.8,
        height = display.contentHeight * 0.8,
        speed = 250,
        inEasing = easing.outBack,
        outEasing = easing.outCubic
    }
    scene.pausePanel.background = display.newRect( 0, 0, scene.pausePanel.width, scene.pausePanel.height )
    scene.pausePanel.background:setFillColor( 0, 0.25, 0.5 )
    scene.pausePanel:insert( scene.pausePanel.background )

    scene.pausePanel:hide()

    scene.closeDrawerButton = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/play_btn.png",
            overFile = "assets/graphics/unoptimized_btns/play_btn_pressed.png",
            label = "",
            onEvent = handleCloseBtnEvent
        })

    scene.closeDrawerButton.isVisible = true
    scene.pausePanel:insert( scene.closeDrawerButton)
    scene.closeDrawerButton.x = scene.closeDrawerButton.x - scene.closeDrawerButton.contentWidth/2

    scene.reloadDrawerButton = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/reload_btn.png",
            overFile = "assets/graphics/unoptimized_btns/reload_btn.png",
            label = "",
            onEvent = handleReloadBtnEvent
        })

    scene.reloadDrawerButton.isVisible = true
    scene.pausePanel:insert( scene.reloadDrawerButton)
    scene.reloadDrawerButton.x = scene.closeDrawerButton.x - 1.2*scene.reloadDrawerButton.contentWidth
    scene.reloadDrawerButton.y = scene.closeDrawerButton.y + 1.2*scene.reloadDrawerButton.contentHeight

    scene.facebookShareDrawerButton = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/facebook_share_btn.png",
            overFile = "assets/graphics/unoptimized_btns/facebook_share_btn.png",
            label = "",
            onEvent = handleFacebookShareEvent
    })

    scene.facebookShareDrawerButton.isVisible = true
    scene.pausePanel:insert( scene.facebookShareDrawerButton)
    scene.facebookShareDrawerButton.x = scene.closeDrawerButton.x + 1.2*scene.facebookShareDrawerButton.contentWidth
    scene.facebookShareDrawerButton.y = scene.closeDrawerButton.y + 1.2*scene.reloadDrawerButton.contentHeight

    scene.effectsButtonActive = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/effects_btn_active.png",
            overFile = "assets/graphics/unoptimized_btns/effects_btn_active_pressed.png",
            label = "",
            onEvent = handleEffectsBtnEvent
        })

    scene.pausePanel:insert( scene.effectsButtonActive)
    scene.effectsButtonActive.x = scene.closeDrawerButton.x - 2*scene.effectsButtonActive.contentWidth

    scene.effectsButtonInactive = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/effects_btn_inactive.png",
            overFile = "assets/graphics/unoptimized_btns/effects_btn_inactive_pressed.png",
            label = "",
            onEvent = handleEffectsBtnEvent
        })

    scene.pausePanel:insert( scene.effectsButtonInactive)
    scene.effectsButtonInactive.x = scene.closeDrawerButton.x - 2*scene.effectsButtonInactive.contentWidth

    if _G.effectsSound then
     scene.effectsButtonActive.isVisible = true
     scene.effectsButtonInactive.isVisible = false
    else
     scene.effectsButtonActive.isVisible = false
     scene.effectsButtonInactive.isVisible = true
    end

    scene.musicButtonActive = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/music_btn_active.png",
            overFile = "assets/graphics/unoptimized_btns/music_btn_active_pressed.png",
            label = "",
            onEvent = handleMusicBtnEvent
        })

    scene.pausePanel:insert( scene.musicButtonActive)
    scene.musicButtonActive.x = scene.closeDrawerButton.x + 2*scene.musicButtonActive.contentWidth

    scene.musicButtonInactive = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/unoptimized_btns/music_btn_inactive.png",
            overFile = "assets/graphics/unoptimized_btns/music_btn_inactive_pressed.png",
            label = "",
            onEvent = handleMusicBtnEvent
        })

    scene.pausePanel:insert( scene.musicButtonInactive)
    scene.musicButtonInactive.x = scene.closeDrawerButton.x + 2*scene.musicButtonInactive.contentWidth

    if _G.musicSound then
        scene.musicButtonActive.isVisible = true
        scene.musicButtonInactive.isVisible = false
    else
        scene.musicButtonActive.isVisible = false
        scene.musicButtonInactive.isVisible = true
    end

end

function scene:create( event )
    local sceneGroup = self.view
    physics.start( )

    --SPAWNING PLAYER
    hero = self:getObjectByName( "player" )
    hero.myname='hero'
    sceneGroup:insert(hero)
    addPhysicsToPlayer()
    -- facebookShare.printName("Testing facebookShare file")

    -- hero = display.newCircle(100, 40, 10)
    -- hero.x = display.screenOriginX + 20
    -- hero.y = display.screenOriginY/2

    -- SETTING UP BACKGROUND
    background = self:getObjectByName( "background" )
    background.y = display.contentHeight/2

    -- SETTING UP GAME LAYER GROUP
    gameLayer = self:getObjectByName( "gameLayer" )
    -- coin = self:getObjectByName("coin")

    -- SPAWNING CIRCLE 1
    circle1.object = self:getObjectByName("circular_obs_a")
    circle1.path = self:getObjectByName("circular_path_a")

    -- SPAWNING CIRCLE 2
    circle2.object = self:getObjectByName("circular_obs_b")
    circle2.path = self:getObjectByName("circular_path_b")

    -- SPAWNING VERTICLE LINEAR 1
    vlinear1.object = self:getObjectByName("vertical_line_obs")
    vlinear1.path = self:getObjectByName("vertical_line")

    -- SPAWNING HORIZONTAL LINEAR TOP
    hlinear1.object = self:getObjectByName("horizontal_obs_top")
    hlinear1.path = self:getObjectByName("horizontal_line_top")

    -- SPAWNING HORIZONTAL LINEAR BOTTOM
    hlinear2.object = self:getObjectByName("horizontal_obs_bottom")
    hlinear2.path = self:getObjectByName("horizontal_line_bottom")

    scene.initializeObstaclePos()
    scene.initializeAnimations(circle2.object.x, circle2.object.y-radius)

    -- INITIALIZE ALL PARTICLES IN SCENE
    scene.initializeParticles()

    -- circle1.y = circle1_path.y+ radius

    -- NOT USED NOW
    -- makeWalls()
    -- addPhysicsToWalls()

    -- NOT USED NOW
    -- generateWalls()

    scene.menuImageSheet = graphics.newImageSheet( "assets/graphics/menuSprites.png", menuSpritesInfo:getSheet() )

    pauseButton = widget.newButton({
            width = 50,
            height = 50,
            defaultFile = "assets/graphics/pause_btn.png",
            overFile = "assets/graphics/pause_btn_pressed.png",
            label = "",
            onEvent = handlePauseBtnEvent
        })

    pauseButton.x = display.screenOriginX + pauseButton.contentWidth
    pauseButton.y = display.screenOriginY + pauseButton.contentHeight

    setUpCamera() --Setup Camera

    -- GRAVITY AND DEBUG
    -- physics.setGravity( 0, 7 )
    -- physics.setDrawMode( "hybrid" )

    -- TIME LEFT LABEL
    local options =
    {
        --parent = textGroup,
        text = "Time Left: ",
        x = display.screenOriginX+120,
        y = display.screenOriginY+24,
        font = "assets/fonts/halo.ttf" or native.systemFontBold,
        fontSize = 18,
    }
    local timeLeftLabel = display.newText( options )
    timeLeftLabel:setFillColor( 1, 0.2, 0.2, 1 )

    local optionsTimeLeft = {
       x = timeLeftLabel.x + timeLeftLabel.contentWidth/2 ,
       y = display.screenOriginY + 26,
       fontSize = 24,
       font = "assets/fonts/digital-7.ttf"
    }
    -- SET UP SCORE
    timeRemainingOptions = scoreManager.init(optionsTimeLeft)

    -- Testing ScoreManager Functions
    if scoreManager.load() then
        print("WHOLLALA" .. scoreManager.load())
    end
    scoreManager.setScore( timeRemainingText )
    -- scoreManager.addInScore(2333)
    print("LATEST Score is" .. scoreManager.getScore())
    scoreManager.save()

    scene.initializeAudio()

    -- INITIALIZING AUDIO OPTIONS
    scene.initializeAudioOptions()

    scene.bgMusicChannel = scene.playLoadedSound(bgMusic, -1, 1500, musicVol)
    -- scene.bgchannel2 = scene.playLoadedSound(bgmusic2, -1, 1500, musicVol)
    -- scene.bgchannel3 = scene.playLoadedSound(bgmusic3, -1, 1500, musicVol)

    -- START BG MUSIC
    -- startBGM()

    -- soundManager.playAudio("bgMusic.mp3", 0.8)

    -- local highscore = score.load()

    -- Called when the scene's view does not exist
    --
    -- INSERT code here to initialize the scene
    -- e.g. add display objects to 'sceneGroup', add touch listeners, etc
end

function scene:show( event )
    local sceneGroup = self.view
    local phase = event.phase

    if phase == "will" then
        -- Called when the scene is off screen and is about to move on screen
        pauseButton:toFront()
        scene.setUpPauseDrawer()

    elseif phase == "did" then
        -- Called when the scene is now on screen
        --
        -- INSERT code here to make the scene come alive
        -- e.g. start timers, begin animation, play audio, etc
    end
end

function scene:hide( event )
    local sceneGroup = self.view
    local phase = event.phase

    if event.phase == "will" then
        -- Called when the scene is on screen and is about to move off screen
        --
        -- INSERT code here to pause the scene
        -- e.g. stop timers, stop animation, unload sounds, etc.)
    elseif phase == "did" then
        -- Called when the scene is now off screen
    end
end

function scene:destroy( event )
    local sceneGroup = self.view

    -- Cleaning up listener
    scene:removeEventListener( "accelerometer", heroMovex)
    scene:removeEventListener( "collision", sensorMeCollide )
    scene:removeEventListener("touch", moveMyPlayer)

    -- Removing sounds that areen't used in other scenes
    audio.dispose( bgMusic )
    bgMusic = nil  --prevents the handle from being used again

    -- Called prior to the removal of scene's "view" (sceneGroup)
    --
    -- INSERT code here to cleanup the scene
    -- e.g. remove display objects, remove touch listeners, save state, etc
end

-------------------------------------------------------------------------------

-- Video completion listener
local function onVideoComplete ( event )
    print( "video session ended with duratoin:")
end

-- Capture completion listener
local function onComplete( event )
    if event.completed then
        media.playVideo( event.url, media.RemoteSource, true, onVideoComplete )
        print( event.duration )
        print( event.fileSize )
    end
end

local function captureGameVideo()
    if media.hasSource( media.Camera ) then
        media.captureVideo( { listener=onComplete } )
    else
        native.showAlert( "Corona", "This device does not have a camera.", { "OK" } )
    end
end

-- timer.performWithDelay( 2000, captureGameVideo )
-- timer.performWithDelay( 4000, onVideoComplete )

-- TODO on button click or collision
-- timer.performWithDelay( 4000, captureWithDelay )

-------------------------------------------------------------------------------

--Set accelerometer framerate
system.setAccelerometerInterval( 60 )

 -- PLAYER MOVEMENT: ACCELEROMETER
local function heroMovex( event )
    -- if hero.x <= background.contentWidth and hero.x >=0 and hero.y <= display.contentHeight and hero.y >=0 then
        -- hero.x = hero.x + 10;
        -- Axis are landscaped

        local lastXwhooshDirection = whooshDirection.x
        local lastYwhooshDirection = whooshDirection.y

        if event.xGravity < 0 then
            whooshDirection.x = 1
        else
            whooshDirection.x = -1
        end

        if event.yGravity < 0 then
            whooshDirection.y = 1
        else
            whooshDirection.y = -1
        end

        if lastXwhooshDirection ~= whooshDirection.x then
            scene.whooshChannel = scene.playLoadedSound(whooshEffect, 0, 0, effectsVol)
        end

        if lastYwhooshDirection ~= whooshDirection.y then
            scene.whooshChannel = scene.playLoadedSound(whooshEffect, 0, 0, effectsVol)
        end

        -- hero:setLinearVelocity( 50*dt*xOffset, 50*dt*yOffset)

        hero.x = hero.x + event.yGravity*dt*-1500
        hero.y = hero.y + event.xGravity*dt*-1500
        -- player.x = display.contentCenterX - zdisplay.contentCenterX * (event.yGravity * 3))
        -- hero:setLinearVelocity( 20 * event.xGravity, 20* event.yGravity )
    -- end
end

-------------------------------------------------------------------------------

-- Collision logic

-- Sensor detection
local function sensorMeCollide ( event )
    if( event.phase == "began" ) then
        scene.collisionEffect = scene.playLoadedSound(collisionEffect, 0, 0, effectsVol)

        local emitterOpt = {
            emitterGroup = collisionBlastGroup,
            x = event.object2.x,
            y = event.object2.y
        }
        collisionBlastGroup[1]:start()
        emittersManager.setPosition(emitterOpt)

        handleGameOverEvent(2)
        return true
    end
end

-- Bounce detection
-- TODO

-------------------------------------------------------------------------------
-- Extra Gimmicks

-- Rotating the player
local sign = -1
local function setCoinContinuousRotation()
    if coin then
        if sign > 0 then
            hero.rotation = hero.rotation + 4
        else
            hero.rotation = hero.rotation - 4
        end

        coin.rotation = coin.rotation + 2
    end
end

-- Moving players eyes in the directin of motion
-- TODO

-------------------------------------------------------------------------------

-- Touch Listener for accelerometer alternative for simulator testing
function moveMyPlayer( event )
    if event.phase == "began" then
        -- print( "Touch x:" .. event.x)
        -- print( "Touch y:" .. event.y )
        -- print("Player Location" .. hero.x-display.contentWidth*math.floor(hero.x/display.contentWidth))
        -- if hero.x <= background.contentWidth and hero.x >=0 and hero.y <= display.contentHeight and hero.y >=0 then
            -- hero.x = hero.x + 10;
            -- hero.x = hero.x + (event.x-hero.x)
            -- hero.y = hero.y + (event.y - hero.y)

            -- local xOffset = event.x - (hero.x -display.contentWidth*math.floor(hero.x/display.contentWidth))
            -- local yOffset = event.y-hero.y
            -- print(xOffset)
            -- print(yOffset)

            local whatx, whaty
            -- print("CONTENT WIDTH"..display.contentWidth/display.contentScaleX)
            -- print(display.contentHeight/display.contentScaleY)
            local offsetX =  (hero.x - display.screenOriginX) % (display.contentWidth/display.contentScaleX)
            local offsetY =  (hero.y - display.screenOriginY) % (display.contentHeight/display.contentScaleY)

            if event.x/display.contentScaleX > offsetX then
                whatx = 1
            else
                whatx = -1
            end
            if event.y/display.contentScaleY  > offsetY then
                whaty = 1
            else
                whaty = -1
            end
            local vx =  math.abs(offsetX-event.x)*dt/display.contentScaleX
            if vx > 30 then
                vx = 30
            end
            -- local vy =15*math.abs(offsetY-event.y)*dt*whaty/display.contentScaleY
            -- hero:setLinearVelocity(vx*0.5*whatx, 0 )
            hero:applyLinearImpulse( whatx*vx, 0)
            -- transition.to(hero,{x= hero.x+xOffset, y = hero.y + yOffset})

            if whatx > 0 then
                sign = 1
            else
                sign = -1
            end
            -- hero:setLinearVelocity( 200 * event.xGravity, 200* event.yGravity )
        -- else
            -- hero:setLinearVelocity( 0, 0 )
        -- end
    end
    return true
end

-- CAMERA TRACKING HERO
local function trackHero( event )
    -- if hero.x <= background.contentWidth then
    --     hero.x = hero.x + 10;
    -- end

    if hero.x > display.contentWidth*0.3 and hero.x < background.contentWidth then
        -- camera.x = hero.x
        camera:setFocus(hero) -- Set the focus to the penguin so it tracks it
        camera:track(hero)
    end
end

local function revoluteCircle(body, direction, speed, confusionFactor)

    if body.theta > 0 and body.theta < 3.14 then
        speed = speed + 0.8*confusionFactor*speed
    else
        speed = speed
    end

    body.theta = body.theta + (speed)*dt
    if(body.theta >=3.14*2) then
        body.theta = body.theta % 3.14*2
    end
    body.object.x = radius* math.cos( direction*body.theta ) + body.path.x
    body.object.y = radius* math.sin( direction*body.theta ) + body.path.y
end

local function vlinearDance(body, speed, confusionFactor)
    local factor = confusionFactor*math.abs(body.object.y-body.path.y)
    speed = speed + factor

    local nextY = body.object.y + body.motionDir*speed*dt
    local limitExceed

    if(body.motionDir == 1) then --GOING DOWN
        limitExceed = nextY + body.object.contentHeight/2 >= body.path.y + body.path.contentHeight/2
    elseif(body.motionDir == -1) then --GOING UP
        limitExceed = nextY - body.object.contentHeight/2 <= body.path.y - body.path.contentHeight/2
    end

    if limitExceed then
        body.motionDir = -1 * body.motionDir
    end
    nextY = body.object.y + body.motionDir*speed*dt
    body.object.y = nextY
end

local function hlinearDance(body, speed, confusionFactor)
    local factor = confusionFactor*math.abs(body.object.x-body.path.x)
    speed = speed + factor

    local nextX = body.object.x + body.motionDir*speed*dt
    local limitExceed

    if(body.motionDir == 1) then --GOING RIGHT
        limitExceed = nextX + body.object.contentWidth/2 >= body.path.x + body.path.contentWidth/2
    elseif(body.motionDir == -1) then --GOING LEFT
        limitExceed = nextX - body.object.contentWidth/2 <= body.path.x - body.path.contentWidth/2
    end

    if limitExceed then
        body.motionDir = -1 * body.motionDir
    end
    nextX = body.object.x + body.motionDir*speed*dt
    body.object.x = nextX
end

resetHeroPosition = function()
    hero.x = display.screenOriginX + display.contentWidth/5
    hero.y = display.screenOriginY + display.contentHeight/2
end

-- GAME LOOP: 60fps
local function gameLoop(event)
    dt = 1/display.fps
    setCoinContinuousRotation()
    trackHero(event)

    revoluteCircle(circle1, 1, 6, 0)
    revoluteCircle(circle2, -1, 5, 3)

    vlinearDance(vlinear1, 400, 5)
    hlinearDance(hlinear1, 300 , 1)
    hlinearDance(hlinear2, 500, 3)

    -- Out of bounds handling
    local xScreenLimit = hero.x > display.screenOriginX+2*background.contentWidth or hero.x < display.screenOriginX - 2*background.contentWidth
    local yScreenLimit = hero.y < display.screenOriginY - 2*display.contentHeight or hero.y > display.screenOriginY + 2*display.contentHeight
    if xScreenLimit or yScreenLimit then
        resetHeroPosition()
    end
end

timeCounter = function()
    timeRemainingText = timeRemainingText - 1
    if timeRemainingText <=0 then
        timer.cancel( timerLeft )
        handleGameOverEvent(1)
    end
    scoreManager.setScore( timeRemainingText )
end

-------------------------------------------------------------------------------

timerLeft = timer.performWithDelay( 1000, timeCounter, -1 )  -- wait 2 seconds

-------------------------------------------------------------------------------

-- LISTENER SETUP
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
Runtime:addEventListener( "accelerometer", heroMovex)
Runtime:addEventListener( "collision", sensorMeCollide )
Runtime:addEventListener("touch", moveMyPlayer)
Runtime:addEventListener( 'enterFrame', gameLoop ) -- Game Loop Listener

-------------------------------------------------------------------------------

return scene


text:
var moment = require('moment');
var formats = require('./src/supportedFormats');

// Add 5 digits year variations for compatibility
formats.forEach(function(format) {
  if (format.indexOf('YYYY') !== -1) {
    formats.push(format.replace(/YYYY/, 'YYYYY'));
  }
});

module.exports = (function() {
  function parse(expression, now, roundUp, timeZone, useTimeZoneForRounding) {

    var math, time;
    if (expression.substring(0, 3) === 'now') {
      math = expression.substring(3);
      time = moment.utc(now) || moment.utc();
    } else {
      var separator = expression.indexOf('||');

      // If the math expression doesn't have separator
      if (separator === -1) {
        // Add timezone
        math = '';
        time = parseTime(expression, timeZone);
      } else {
        math = expression.substr(separator + 2);
        time = parseTime(expression.substr(0, separator), timeZone);
      }
    }

    // If there is no further expression to process
    if (!math || math === '') {
      return time.valueOf();
    }

    return evaluate(math, time, roundUp, timeZone, useTimeZoneForRounding).valueOf();
  }

  function evaluate(expression, now, roundUp, timeZone, useTimeZoneForRounding) {
    var val = 0;

    for (var i = 0; i < expression.length;) {
      var char = expression[i];
      var next;

      i += 1;

      if (i > expression.length) {
        throw new Error('truncated date math [' + expression + ']');
      }

      if (char === '/') {
        // Round result
        next = expression[i++];

        switch (next) {
          case 'y': case 'Y': now = roundDate(now, 'year', roundUp, timeZone, useTimeZoneForRounding); break;
          case 'M': now = roundDate(now, 'month', roundUp, timeZone, useTimeZoneForRounding); break;
          case 'd': case 'D': now = roundDate(now, 'date', roundUp, timeZone, useTimeZoneForRounding); break;
          case 'w': case 'W': now = roundDate(now, 'weekday', roundUp, timeZone, useTimeZoneForRounding); break;
          case 'h': case 'H': now = roundDate(now, 'hour', roundUp, timeZone, useTimeZoneForRounding); break;
          case 'm': now = roundDate(now, 'minute', roundUp); break;
          case 's': case 'S': now = roundDate(now, 'second', roundUp, timeZone, useTimeZoneForRounding); break;

        }

      } else if (char === '+' || char === '-') {
        if (i >= expression.length) {
          throw new Error('truncated date math [' + expression + ']');
        }

        val = 0;
        next = expression[i];

        while (next >= '0' && next <= '9') {
          // Consume the digit
          i += 1;

          if (i >= expression.length) {
            throw new Error('truncated date math [' + expression + ']');
          }

          val = val * 10 + parseInt(next, 10);
          next = expression[i];
        }

        val = val || 1;
        val = (char === '+') ? val : -val;

      } else if ((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z')) {
        switch (char) {
          case 'y': case 'Y': now = calculate(now, val, 'year'); break;
          case 'M': now = calculate(now, val, 'month'); break;
          case 'd': case 'D': now = calculate(now, val, 'date'); break;
          case 'w': case 'W': now = calculate(now, val, 'week'); break;
          case 'h': case 'H': now = calculate(now, val, 'hour'); break;
          case 'm': now = calculate(now, val, 'minute'); break;
          case 's': case 'S': now = calculate(now, val, 'second'); break;
          default:
            throw new Error('unit [' + char + '] not supported for date math [' + expression + ']');
        }
      } else {
        throw new Error('operator not supported for date math [' + char + ']');
      }
    }

    return now;
  }

  function calculate(now, offsetVal, unit) {
    now[unit](now[unit]() + offsetVal);

    return now;
  }

  function roundDate(now, unit, roundUp, timeZone, useTimeZoneForRounding) {
    if (useTimeZoneForRounding) {
      now = now.utcOffset(timeZone);
    }

    switch (unit) {
      case 'year': now.month(0); /* falls through */
      case 'month': now.date(1); /* falls through */
      case 'date': now.hours(0); /* falls through */
      case 'weekday': now.hours(0); /* falls through */
      case 'hour': now.minutes(0); /* falls through */
      case 'minute': now.seconds(0); /* falls through */
      case 'second': now.milliseconds(0); /* falls through */
    }

    if (roundUp) {
      if (unit === 'weekday') {
        now.weekday(8);
      } else {
        now[unit](now[unit]() + 1);
      }

      now = moment.utc(now.valueOf() - 1);
    } else {
      if (unit === 'weekday') {
        now.weekday(1);
      }
    }

    return now;
  }

  function parseTime(s, timeZone) {
    if (s && s.length > 4 && (s >= 0 || s < 0)) {
      // Timestamp
      if (s.length > 13) {
        throw new Error('Bad timestamp in [' + s + ']');
      }

      return (s.length === 10) ? moment(+s * 1000) : moment(+s);
    }

    if (!/^[\dTZ\-\+:\.]+$/.test(s)) {
      throw new Error('Bad time with format in [' + s + ']');
    }

    var time = moment.utc(s, formats);

    // Ignore the timeZone parameter if the given time already have one
    if (!/[\+\-]\d+:\d+|Z$/.test(s) && timeZone) {
      var normalizedTimezoneOffset = moment.utc().utcOffset(timeZone).utcOffset();

      time.subtract(normalizedTimezoneOffset, 'minute');
    }

    return time;
  }

  return {
    parse: parse,
    evaluate: evaluate,
    calculate: calculate,
    roundDate: roundDate,
    parseTime: parseTime
  };
})();

redpajama_set_name: RedPajamaGithub


text:
namespace ch.app {

    import autoMapper = server.automapper.AutoMapper;

    interface IOrt {
        plz: number;
        name: string;
    }

    class Ort implements IOrt {
        plz:number;
        name:string;
    }

    class PersonDto {
        constructor() {}
        vorname:string;
        alter:number;
    }

    class Person {
        name:string;
        vorname:string;
        alter:number;
        ort:IOrt;
    }

	export class Server {

		private _env:string;
        private person:Person;
        private personDto:PersonDto;
        private baseCalculator:BasicCalculator;
        private autoMapper:AutoMapper;

		constructor(env:string) {
			this._env = env;
            this.initData();
            this.baseCalculator = new BasicCalculator(100);
            console.log('Der Wert ist :', this.baseCalculator.add(25).multiply(2).currentValue());

            //this.autoMapper = new AutoMapper(10);
            //
                AutoMapper.map<Person>();
		}

        public MapPerson():void {
            // let dto = autoMapper.map.from<Person>().to<PersonDto>();
        }

        private mapTo(map:any, from:any[]):void {
            // console.log( map instanceof PersonDto);
            from.forEach(t => {
                Object.getOwnPropertyNames(t).forEach(name => {
                    //console.log(t[name].constructor);
                    let myType = t[name].constructor;
                    console.log(myType.name);
                    //console.log(typeof myType);
                    if(typeof myType === 'function') {
                        //console.log('dannn');
                        //console.log(Object.prototype.toString.call(myType));
                        //console.log(myType.name);
                        //console.log(typeof myType);
                        if(myType.name === 'Ort') {
                            //console.log('drinn..');
                        }
                    }
                    //console.log(Object.keys(t));
                    map[name] = t[name];
                });
            });
        }

        private initData():void {

            this.person = new Person();
            this.person.name = "Daniel";
            this.person.vorname = "Glenn";
            this.person.alter = 41;
            this.person.ort = new Ort();
            this.person.ort.plz = 5621;
            this.person.ort.name = 'Zufikon';

            this.personDto = new PersonDto();

            this.mapTo(this.personDto, [this.person]);
            //console.log(this.personDto);
        }
	}

    class AutoMapper {

        public constructor(protected value:number = 0) {}

        public static map<T>():void {
            let des:T;
            console.log('Demo:  ');
        }
    }

    // Fluend with extend the class return this will add new calculation metheds
    class BasicCalculator {

        public constructor(protected value: number = 0) { }

        public currentValue(): number {
            return this.value;
        }

        public add(operand: number): this {
            this.value += operand;
            return this;
        }

        public multiply(operand: number): this {
            this.value *= operand;
            return this;
        }
    }
}

// alias
import Server = ch.app.Server;

var app = new Server("debug");


text:
package infinitystorage.gui.grid.sorting;

import infinitystorage.gui.grid.stack.IClientStack;
import infinitystorage.tile.grid.TileGrid;

public class GridSortingQuantity extends GridSorting {
    @Override
    public int compare(IClientStack left, IClientStack right) {
        int leftSize = left.getQuantity();
        int rightSize = right.getQuantity();

        if (leftSize != rightSize) {
            if (sortingDirection == TileGrid.SORTING_DIRECTION_ASCENDING) {
                return (leftSize > rightSize) ? 1 : -1;
            } else if (sortingDirection == TileGrid.SORTING_DIRECTION_DESCENDING) {
                return (rightSize > leftSize) ? 1 : -1;
            }
        }

        return 0;
    }
}


text:
/*
 * Based on ImWindow code from:
 * https://github.com/thennequin/ImWindow
 *
 * MIT license:
 * https://github.com/thennequin/ImWindow/blob/master/LICENSE
 */

#ifndef IMGUI_WM_H_HEADER_GUARD
#define IMGUI_WM_H_HEADER_GUARD

#include "imgui.h"

typedef unsigned int ImU32;

#ifndef ImwList
# include <list>
# define ImwList std::list
#endif // ImList

#ifndef ImwMap
# include <unordered_map>
# define ImwMap std::unordered_map
#endif // ImMap

namespace ImGuiWM
{
    enum EDockOrientation
    {
        E_DOCK_ORIENTATION_CENTER,
        E_DOCK_ORIENTATION_TOP,
        E_DOCK_ORIENTATION_LEFT,
        E_DOCK_ORIENTATION_RIGHT,
        E_DOCK_ORIENTATION_BOTTOM,
    };

    class Id
    {
    public:
        Id();
        ImU32 GetId() const;
        const char* GetStr() const;

    private:
        ImU32 m_iId;
        char  m_pId[11];
        static int s_iNextId;
    };

    class Window
    {
        friend class WindowManager;
        friend class Container;

    public:
        virtual void OnGui() = 0;
        virtual void OnMenu() {};

        const char* GetId() const { return m_oId.GetStr(); }

        void Destroy();

        void SetTitle(const char* pTitle);
        const char* GetTitle() const;

        const ImVec2& GetLastPosition() const;
        const ImVec2& GetLastSize() const;

    protected:
        Window();
        virtual ~Window();

        char* m_pTitle;
        Id m_oId;

        ImVec2 m_oLastPosition;
        ImVec2 m_oLastSize;
    };

    typedef ImwList<Window*> WindowList;

    class PlatformWindow;

    class Container
    {
        friend class PlatformWindow;

    public:
        void Dock(Window* pWindow,EDockOrientation eOrientation = E_DOCK_ORIENTATION_CENTER);
        bool UnDock(Window* pWindow);

        bool IsEmpty();
        bool IsSplit();
        bool HasWindowTabbed();
        Container* HasWindow(const Window* pWindow);
        PlatformWindow* GetPlatformWindowParent() const;
        Container* GetBestDocking(const ImVec2 oCursorPosInContainer,EDockOrientation& oOutOrientation,ImVec2& oOutAreaPos,ImVec2& oOutAreaSize);

    protected:
        Container(Container* pParent);
        Container(PlatformWindow* pParent);
        ~Container();

        void CreateSplits();
        void Paint();

        Container* m_pParent;
        PlatformWindow* m_pParentWindow;
        WindowList m_lWindows;
        Container* m_pSplits[2];

        float m_fSplitRatio;
        bool m_bVerticalSplit;
        int m_iActiveWindow;

        bool m_bIsDrag;

        ImVec2 m_oLastPosition;
        ImVec2 m_oLastSize;
    };

    class PlatformWindow
    {
        friend class WindowManager;

    public:
        PlatformWindow(bool bMainWindow,bool bIsDragWindow);
        virtual ~PlatformWindow();

        virtual bool Init(PlatformWindow* pParent) = 0;

        virtual const ImVec2& GetPosition() const = 0;
        virtual const ImVec2& GetSize() const = 0;

        virtual void Show() = 0;
        virtual void Hide() = 0;
        virtual void SetSize(const ImVec2& size) = 0;
        virtual void SetPosition(const ImVec2& pos) = 0;
        virtual void SetTitle(const char* pTitle) = 0;

        bool IsMain();

        void Dock(Window* pWindow);
        bool UnDock(Window* pWindow);

        Container* GetContainer();
        Container* HasWindow(Window* pWindow);
        bool IsStateSet();

    protected:
        void SetState();
        void RestoreState();
        void OnLoseFocus();
        virtual void PreUpdate() = 0;
        virtual void PaintBegin() = 0;
        virtual void Paint();
        virtual void PaintEnd() = 0;
        virtual void Destroy() = 0;
        virtual void StartDrag() = 0;
        virtual void StopDrag() = 0;
        virtual bool IsDraging() = 0;

        void PaintContainer();
        void OnClose();

        Id m_oId;
        bool m_bMain;
        bool m_bIsDragWindow;
        Container* m_pContainer;
        void* m_pState;
        void* m_pPreviousState;
    };

    typedef ImwList<PlatformWindow*> PlatformWindowList;

    class WindowManager
    {
        friend class Window;
        friend class PlatformWindow;
        friend class Container;

        struct PlatformWindowAction
        {
            PlatformWindow* m_pPlatformWindow;
            unsigned int m_iFlags;
            ImVec2 m_oPosition;
            ImVec2 m_oSize;
        };

        struct DockAction
        {
            Window* m_pWindow;

            // Is Dock or Float
            bool m_bFloat;

            //For Docking
            Window* m_pWith;
            EDockOrientation m_eOrientation;
            PlatformWindow* m_pToPlatformWindow;
            Container* m_pToContainer;

            //For Floating
            ImVec2 m_oPosition;
            ImVec2 m_oSize;
        };

        struct DrawWindowAreaAction
        {
            DrawWindowAreaAction(PlatformWindow* pWindow,const ImVec2& oRectPos,const ImVec2& oRectSize,const ImColor& oColor);
            PlatformWindow* m_pWindow;
            ImVec2 m_oRectPos;
            ImVec2 m_oRectSize;
            ImColor m_oColor;
        };

    public:
        struct Config
        {
            Config();
            float m_fDragMarginRatio;
            float m_fDragMarginSizeRatio;
            ImColor m_oHightlightAreaColor;
        };

        WindowManager();
        virtual ~WindowManager();

        bool Init();
        bool Run();
        void Exit();

        PlatformWindow* GetMainPlatformWindow();
        Config& GetConfig();

        void SetMainTitle(const char* pTitle);

        void Dock(Window* pWindow, EDockOrientation eOrientation = E_DOCK_ORIENTATION_CENTER, PlatformWindow* pToPlatformWindow = NULL);
        void DockTo(Window* pWindow, EDockOrientation eOrientation = E_DOCK_ORIENTATION_CENTER, Container* pContainer = NULL);
        void DockWith(Window* pWindow, Window* pWithWindow,EDockOrientation eOrientation = E_DOCK_ORIENTATION_CENTER);
        void Float(Window* pWindow, const ImVec2& oPosition = ImVec2(-1,-1), const ImVec2& oSize = ImVec2(-1,-1));

        const WindowList& GetWindowList() const;
        PlatformWindow* GetCurrentPlatformWindow();
        PlatformWindow* GetWindowParent(Window* pWindow);

        void Log(const char* pFormat, ...);
        virtual void LogFormatted(const char* pStr) = 0;;

        static WindowManager* GetInstance();

    protected:
        virtual PlatformWindow* CreatePlatformWindow(bool bMain,PlatformWindow* pParent,bool bDragWindow) = 0;
        virtual void InternalRun() = 0;

        void AddWindow(Window* pWindow);
        void RemoveWindow(Window* pWindow);
        void DestroyWindow(Window* pWindow);

        void InternalDock(Window* pWindow,EDockOrientation eOrientation,PlatformWindow* pToPlatformWindow);
        void InternalDockTo(Window* pWindow,EDockOrientation eOrientation,Container* pToContainer);
        void InternalDockWith(Window* pWindow,Window* pWithWindow,EDockOrientation eOrientation);
        bool InternalFloat(Window* pWindow,ImVec2 oPosition,ImVec2 oSize);
        void InternalUnDock(Window* pWindow);
        void InternalDrag(Window* pWindow);

        void OnClosePlatformWindow(PlatformWindow* pWindow);

        void DrawWindowArea(PlatformWindow* pWindow,const ImVec2& oPos,const ImVec2& oSize,const ImColor& oColor);

        void PreUpdate();
        void Update();
        void UpdatePlatformwWindowActions();
        void UpdateDockActions();
        void UpdateOrphans();

        void Paint(PlatformWindow* pWindow);

        void StartDragWindow(Window* pWindow);
        void StopDragWindow();
        void UpdateDragWindow();
        Container* GetBestDocking(PlatformWindow* pPlatformWindow,const ImVec2 oCursorPos,EDockOrientation& oOutOrientation,ImVec2& oOutAreaPos,ImVec2& oOutAreaSize);

        Config m_oConfig;
        PlatformWindow* m_pMainPlatformWindow;
        PlatformWindowList m_lPlatformWindows;
        PlatformWindow* m_pDragPlatformWindow;
        WindowList m_lWindows;
        WindowList m_lOrphanWindows;
        WindowList m_lToDestroyWindows;
        PlatformWindowList m_lToDestroyPlatformWindows;
        ImwList<PlatformWindowAction*> m_lPlatformWindowActions;
        ImwList<DockAction*> m_lDockActions;
        ImwList<DrawWindowAreaAction> m_lDrawWindowAreas;

        PlatformWindow* m_pCurrentPlatformWindow;
        Window* m_pDraggedWindow;

        ImVec2 m_oDragPreviewOffset;

        static WindowManager* s_pInstance;
    };
}

#endif // IMGUI_WM_H_HEADER_GUARD


text:
import { CurvePath } from './CurvePath.js';
import { EllipseCurve } from '../curves/EllipseCurve.js';
import { SplineCurve } from '../curves/SplineCurve.js';
import { Vector2 } from '../../math/Vector2.js';
import { CubicBezierCurve } from '../curves/CubicBezierCurve.js';
import { QuadraticBezierCurve } from '../curves/QuadraticBezierCurve.js';
import { LineCurve } from '../curves/LineCurve.js';

var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {

	fromPoints: function ( vectors ) {

		this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );

		for ( var i = 1, l = vectors.length; i < l; i ++ ) {

			this.lineTo( vectors[ i ].x, vectors[ i ].y );

		}

	},

	moveTo: function ( x, y ) {

		this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?

	},

	lineTo: function ( x, y ) {

		var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
		this.curves.push( curve );

		this.currentPoint.set( x, y );

	},

	quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {

		var curve = new QuadraticBezierCurve(
			this.currentPoint.clone(),
			new Vector2( aCPx, aCPy ),
			new Vector2( aX, aY )
		);

		this.curves.push( curve );

		this.currentPoint.set( aX, aY );

	},

	bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {

		var curve = new CubicBezierCurve(
			this.currentPoint.clone(),
			new Vector2( aCP1x, aCP1y ),
			new Vector2( aCP2x, aCP2y ),
			new Vector2( aX, aY )
		);

		this.curves.push( curve );

		this.currentPoint.set( aX, aY );

	},

	splineThru: function ( pts /*Array of Vector*/ ) {

		var npts = [ this.currentPoint.clone() ].concat( pts );

		var curve = new SplineCurve( npts );
		this.curves.push( curve );

		this.currentPoint.copy( pts[ pts.length - 1 ] );

	},

	arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

		var x0 = this.currentPoint.x;
		var y0 = this.currentPoint.y;

		this.absarc( aX + x0, aY + y0, aRadius,
			aStartAngle, aEndAngle, aClockwise );

	},

	absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

		this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );

	},

	ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

		var x0 = this.currentPoint.x;
		var y0 = this.currentPoint.y;

		this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

	},

	absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

		var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

		if ( this.curves.length > 0 ) {

			// if a previous curve is present, attempt to join
			var firstPoint = curve.getPoint( 0 );

			if ( ! firstPoint.equals( this.currentPoint ) ) {

				this.lineTo( firstPoint.x, firstPoint.y );

			}

		}

		this.curves.push( curve );

		var lastPoint = curve.getPoint( 1 );
		this.currentPoint.copy( lastPoint );

	}

} );

export { PathPrototype };


text:
/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package com.sun.xml.stream.xerces.xni.parser;

/**
 * The component manager manages a parser configuration and the components
 * that make up that configuration. The manager notifies each component
 * before parsing to allow the components to initialize their state; and
 * also any time that a parser feature or property changes.
 * <p>
 * The methods of the component manager allow components to query features
 * and properties that affect the operation of the component.
 *
 * @see XMLComponent
 *
 * @author Andy Clark, IBM
 *
 * @version $Id: XMLComponentManager.java,v 1.3 2007-07-19 22:33:17 ofung Exp $
 */
public interface XMLComponentManager {

    //
    // XMLComponentManager methods
    //

    /**
     * Returns the state of a feature.
     *
     * @param featureId The feature identifier.
     *
     * @throws XMLConfigurationException Thrown on configuration error.
     */
    public boolean getFeature(String featureId)
        throws XMLConfigurationException;

    /**
     * Returns the value of a property.
     *
     * @param propertyId The property identifier.
     *
    * @throws XMLConfigurationException Thrown on configuration error.
     */
    public Object getProperty(String propertyId)
        throws XMLConfigurationException;

} // interface XMLComponentManager


text:
var App = require('ampersand-app');
var View = require('ampersand-view');

module.exports = View.extend({

  viewClass: 'log',

  template: `

Log

  `,

  bindings: {
    'output': '.output'
  },

  derived: {
    output: {
      deps: ['parent.model.consoleOutput'],
      fn: function () {
        return this.parent.model.consoleOutput.join("\n");
      }
    }
  }

});


text: chgrp root /etc/grub.conf


text:
package org.amv.highmobility.cryptotool;

import lombok.Builder;
import lombok.Getter;
import lombok.Value;

import java.io.File;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

@Getter
@Builder(builderClassName = "Builder")
public class BinaryImpl implements Binary {
    private final File file;

    public BinaryImpl(File file) {
        requireNonNull(file, "`file` must not be null");
        checkArgument(file.exists(), "`file` does not exist");
        this.file = file;
    }
}


text:
//3.0;IMAGING;**66**;1-Aug-2005
// Per VHA Directive 2004-038, this routine should not be modified.
//+---------------------------------------------------------------+
//| Property of the US Government.                                |
//| No permission to copy or redistribute this software is given. |
//| Use of unreleased versions of this software requires the user |
//| to execute a written test agreement with the VistA Imaging    |
//| Development Office of the Department of Veterans Affairs,     |
//| telephone (301) 734-0100.                                     |
//|                                                               |
//| The Food and Drug Administration classifies this software as  |
//| a medical device.  As such, it may not be changed in any way. |
//| Modifications to this software may result in an adulterated   |
//| medical device under 21CFR820, the use of which is considered |
//| to be a violation of US Federal Statutes.                     |
//+---------------------------------------------------------------+

package gov.va.med.imaging.protocol.vista.exceptions;

import gov.va.med.imaging.core.interfaces.exceptions.MethodException;

/**
 * Implementation of an SCU for DICOM Query/Retrieve.
 * <p>The ResultSetException is the exception that may
 * be thrown by the method readStudyRoot when no valid
 * result can be obtained from the HIS/RIS.
 * @author VistA Imaging - DICOM Team
 * @version 3.0.66.1
 */

public class AETitleAuthenticationException extends MethodException
{
  public AETitleAuthenticationException(){
      //constructor
  }
  public AETitleAuthenticationException(String msg)
  {
    super(msg);
  }
  public AETitleAuthenticationException(Exception e)
  {
    super(e);
  }
}


text:
package net.boreeas.riotapi.com.riotgames.platform.reroll.pojo;

import lombok.Data;
import lombok.ToString;
import net.boreeas.riotapi.rtmp.serialization.Serialization;

/**
 * Created on 7/19/2014.
 */
@Data
@ToString
@Serialization(name = "com.riotgames.platform.reroll.pojo.PointSummary")
public class PointSummary {
    private long pointsToNextRoll;
    private long maxRolls;
    private int numberOfRolls;
    private long pointsCostToRoll;
    private long currentPoints;
}


text:
var chai = require('chai');
var expect = require('chai').expect;
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
chai.use(sinonChai);

var provider = require('../lib/provider');

var before = function(){

};

var testOnInitialize = function(){
    //TODO: add unit tests
};

describe('Post Initialization', function(){
    before(before);
    it ('test initialization', testOnInitialize);
});


text:
namespace flatbuffers {
namespace tests {

void FuzzTest1();
void FuzzTest2();

}  // namespace tests
}  // namespace flatbuffers

#endif


text:
<?php

namespace LAT\TableSculptor\TypeDetector;

/**
 * @author ncastro
 */
class Date extends Base {

  public function getAlias() {
    return 'date';
  }

  public function check($scalar) {
    $dt = \DateTime::createFromFormat($this->config->getDateFormat(), $scalar);
    return $dt !== false && !array_sum($dt->getLastErrors());
  }

}


text:
namespace principia {
namespace physics {
namespace internal_dynamic_frame {

using geometry::AngularVelocity;
using geometry::Bivector;
using geometry::Displacement;
using geometry::InnerProduct;
using geometry::Normalize;
using geometry::R3x3Matrix;
using geometry::Velocity;
using geometry::Wedge;
using quantities::Pow;
using quantities::Sqrt;
using quantities::Variation;
using quantities::si::Radian;

template<typename InertialFrame, typename ThisFrame>
RigidMotion<InertialFrame, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::ToThisFrameAtTime(
    Instant const& t) const {
  return FromThisFrameAtTime(t).Inverse();
}

template<typename InertialFrame, typename ThisFrame>
RigidMotion<ThisFrame, InertialFrame>
DynamicFrame<InertialFrame, ThisFrame>::FromThisFrameAtTime(
    Instant const& t) const {
  return ToThisFrameAtTime(t).Inverse();
}

template<typename InertialFrame, typename ThisFrame>
Vector<Acceleration, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::GeometricAcceleration(
    Instant const& t,
    DegreesOfFreedom<ThisFrame> const& degrees_of_freedom) const {
  Vector<Acceleration, ThisFrame> gravitational_acceleration;
  Vector<Acceleration, ThisFrame> linear_acceleration;
  Vector<Acceleration, ThisFrame> coriolis_acceleration;
  Vector<Acceleration, ThisFrame> centrifugal_acceleration;
  Vector<Acceleration, ThisFrame> euler_acceleration;
  ComputeGeometricAccelerations(t,
                                degrees_of_freedom,
                                gravitational_acceleration,
                                linear_acceleration,
                                coriolis_acceleration,
                                centrifugal_acceleration,
                                euler_acceleration);

  return gravitational_acceleration +
         (linear_acceleration + coriolis_acceleration +
          centrifugal_acceleration + euler_acceleration);
}

template<typename InertialFrame, typename ThisFrame>
Vector<Acceleration, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::RotationFreeGeometricAccelerationAtRest(
    Instant const& t,
    Position<ThisFrame> const& position) const {
  Vector<Acceleration, ThisFrame> gravitational_acceleration;
  Vector<Acceleration, ThisFrame> linear_acceleration;
  Vector<Acceleration, ThisFrame> coriolis_acceleration;
  Vector<Acceleration, ThisFrame> centrifugal_acceleration;
  Vector<Acceleration, ThisFrame> euler_acceleration;
  ComputeGeometricAccelerations(t,
                                {position, ThisFrame::unmoving},
                                gravitational_acceleration,
                                linear_acceleration,
                                coriolis_acceleration,
                                centrifugal_acceleration,
                                euler_acceleration);

  DCHECK_EQ(coriolis_acceleration, (Vector<Acceleration, ThisFrame>{}));
  return gravitational_acceleration +
         (linear_acceleration + centrifugal_acceleration);
}

template<typename InertialFrame, typename ThisFrame>
SpecificEnergy DynamicFrame<InertialFrame, ThisFrame>::GeometricPotential(
    Instant const& t,
    Position<ThisFrame> const& position) const {
  AcceleratedRigidMotion<InertialFrame, ThisFrame> const motion =
      MotionOfThisFrame(t);
  RigidMotion<InertialFrame, ThisFrame> const& to_this_frame =
      motion.rigid_motion();
  RigidMotion<ThisFrame, InertialFrame> const from_this_frame =
      to_this_frame.Inverse();

  AngularVelocity<ThisFrame> const Ω = to_this_frame.orthogonal_map()(
      to_this_frame.template angular_velocity_of<ThisFrame>());
  Displacement<ThisFrame> const r = position - ThisFrame::origin;

  SpecificEnergy const gravitational_potential =
      GravitationalPotential(t,
                             from_this_frame.rigid_transformation()(position));
  SpecificEnergy const linear_potential = InnerProduct(
      r,
      to_this_frame.orthogonal_map()(
          motion.template acceleration_of_origin_of<ThisFrame>()));
  SpecificEnergy const centrifugal_potential = -0.5 * (Ω * r / Radian).Norm²();

  return gravitational_potential + (linear_potential + centrifugal_potential);
}

template<typename InertialFrame, typename ThisFrame>
Rotation<Frenet<ThisFrame>, ThisFrame>
DynamicFrame<InertialFrame, ThisFrame>::FrenetFrame(
    Instant const& t,
    DegreesOfFreedom<ThisFrame> const& degrees_of_freedom) const {
  Velocity<ThisFrame> const& velocity = degrees_of_freedom.velocity();
  Vector<Acceleration, ThisFrame> const acceleration =
      GeometricAcceleration(t, degrees_of_freedom);
  Vector<Acceleration, ThisFrame> const normal_acceleration =
      acceleration.OrthogonalizationAgainst(velocity);
  Vector<double, ThisFrame> tangent = Normalize(velocity);
  Vector<double, ThisFrame> normal = Normalize(normal_acceleration);
  Bivector<double, ThisFrame> binormal = Wedge(tangent, normal);
  // Maps |tangent| to {1, 0, 0}, |normal| to {0, 1, 0}, and |binormal| to
  // {0, 0, 1}.
  return Rotation<Frenet<ThisFrame>, ThisFrame>(tangent, normal, binormal);
}

template<typename InertialFrame, typename ThisFrame>
not_null<std::unique_ptr<DynamicFrame<InertialFrame, ThisFrame>>>
DynamicFrame<InertialFrame, ThisFrame>::ReadFromMessage(
    serialization::DynamicFrame const& message,
    not_null<Ephemeris<InertialFrame> const*> const ephemeris) {
  std::unique_ptr<DynamicFrame> result;
  int extensions_found = 0;
  // NOTE(egg): the |static_cast|ing below is needed on MSVC, because the silly
  // compiler doesn't see the |operator std::unique_ptr<DynamicFrame>() &&|.
  if (message.HasExtension(
          serialization::BarycentricRotatingDynamicFrame::extension)) {
    ++extensions_found;
    result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
        BarycentricRotatingDynamicFrame<InertialFrame, ThisFrame>::
            ReadFromMessage(ephemeris,
                            message.GetExtension(
                                serialization::BarycentricRotatingDynamicFrame::
                                    extension)));
  }
  if (message.HasExtension(
          serialization::BodyCentredBodyDirectionDynamicFrame::extension)) {
    ++extensions_found;
    result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
        BodyCentredBodyDirectionDynamicFrame<InertialFrame, ThisFrame>::
            ReadFromMessage(
                ephemeris,
                message.GetExtension(
                    serialization::BodyCentredBodyDirectionDynamicFrame::
                        extension)));
  }
  if (message.HasExtension(
          serialization::BodyCentredNonRotatingDynamicFrame::extension)) {
    ++extensions_found;
    result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
        BodyCentredNonRotatingDynamicFrame<InertialFrame, ThisFrame>::
            ReadFromMessage(
                ephemeris,
                message.GetExtension(
                    serialization::BodyCentredNonRotatingDynamicFrame::
                        extension)));
  }
  if (message.HasExtension(
          serialization::BodySurfaceDynamicFrame::extension)) {
    ++extensions_found;
    result = static_cast<not_null<std::unique_ptr<DynamicFrame>>>(
        BodySurfaceDynamicFrame<InertialFrame, ThisFrame>::
            ReadFromMessage(
                ephemeris,
                message.GetExtension(
                    serialization::BodySurfaceDynamicFrame::extension)));
  }
  CHECK_EQ(extensions_found, 1) << message.DebugString();
  return std::move(result);
}

template<typename InertialFrame, typename ThisFrame>
void DynamicFrame<InertialFrame, ThisFrame>::ComputeGeometricAccelerations(
    Instant const& t,
    DegreesOfFreedom<ThisFrame> const& degrees_of_freedom,
    Vector<Acceleration, ThisFrame>& gravitational_acceleration,
    Vector<Acceleration, ThisFrame>& linear_acceleration,
    Vector<Acceleration, ThisFrame>& coriolis_acceleration,
    Vector<Acceleration, ThisFrame>& centrifugal_acceleration,
    Vector<Acceleration, ThisFrame>& euler_acceleration) const {
  AcceleratedRigidMotion<InertialFrame, ThisFrame> const motion =
      MotionOfThisFrame(t);
  RigidMotion<InertialFrame, ThisFrame> const& to_this_frame =
      motion.rigid_motion();
  RigidMotion<ThisFrame, InertialFrame> const from_this_frame =
      to_this_frame.Inverse();

  // Beware, we want the angular velocity of ThisFrame as seen in the
  // InertialFrame, but pushed to ThisFrame.  Otherwise the sign is wrong.
  AngularVelocity<ThisFrame> const Ω = to_this_frame.orthogonal_map()(
      to_this_frame.template angular_velocity_of<ThisFrame>());
  Variation<AngularVelocity<ThisFrame>> const dΩ_over_dt =
      to_this_frame.orthogonal_map()(
          motion.template angular_acceleration_of<ThisFrame>());
  Displacement<ThisFrame> const r =
      degrees_of_freedom.position() - ThisFrame::origin;

  gravitational_acceleration = to_this_frame.orthogonal_map()(
      GravitationalAcceleration(t,
                                from_this_frame.rigid_transformation()(
                                    degrees_of_freedom.position())));
  linear_acceleration = -to_this_frame.orthogonal_map()(
      motion.template acceleration_of_origin_of<ThisFrame>());
  coriolis_acceleration = -2 * Ω * degrees_of_freedom.velocity() / Radian;
  centrifugal_acceleration = -Ω * (Ω * r) / Pow<2>(Radian);
  euler_acceleration = -dΩ_over_dt * r / Radian;
}

}  // namespace internal_dynamic_frame
}  // namespace physics
}  // namespace principia


text:
<html>
  <head>
  </head>
  <body ng-app='MyApp' ng-controller='MainController'>

    <p> {{ subtitle }} {{ clicks }}</p>

      <heading title='Title From Attribute ({{ title }})' subtitle='subtitle' count='clicks = clicks + 1'></heading>

      <script src='./angular.min.js'></script>
      <script src='./app.js'></script>
  </body>
</html>


text:
<?php

namespace LanguageFirst\UsuarioBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class UsuarioBundle extends Bundle
{
}


text:
package fr.adrienbrault.idea.symfony2plugin.tests.routing;

import com.jetbrains.php.lang.PhpFileType;
import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 * @see fr.adrienbrault.idea.symfony2plugin.util.DocHashTagReferenceContributor
 */
public class DocTagCompletionContributorTest extends SymfonyLightCodeInsightFixtureTestCase {

    public void setUp() throws Exception {
        super.setUp();
        myFixture.copyFileToProject("classes_routing.php");
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("routing.yml"));
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("routing.xml"));
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("PhpRouteReferenceContributor.php"));
    }

    public String getTestDataPath() {
        return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/routing/fixtures";
    }

    public void testRouteDocTagCompletion() {
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php new TestClass('<caret>');", "route_foo");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php new TestClass('<caret>');", "route_bar");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php new TestClass('<caret>');", "xml_route");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php new TestClass('<caret>');", "foo_bar");

        assertCompletionContains(PhpFileType.INSTANCE,  "<?php (new TestClass())->foo('<caret>');", "route_foo");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php (new TestClass())->foo('<caret>');", "route_bar");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php (new TestClass())->foo('<caret>');", "xml_route");
        assertCompletionContains(PhpFileType.INSTANCE,  "<?php (new TestClass())->foo('<caret>');", "foo_bar");
    }

}


text:
<?php

namespace spec\OAuth2\Security\ClientAuthenticationMethod;

use OAuth2\Exception\InvalidClientException;
use OAuth2\Http\IRequest;
use OAuth2\Storage\IClient;
use OAuth2\Storage\IClientStorage;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class RequestBodySpec extends ObjectBehavior
{

    function let(IClientStorage $clientStorage)
    {
        $this->beConstructedWith($clientStorage);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('OAuth2\Security\ClientAuthenticationMethod\RequestBody');
        $this->shouldImplement('OAuth2\Security\ClientAuthenticationMethod\IClientAuthenticationMethod');
    }

    function it_matches_to_requests_without_authorization_header(
        IRequest $request1,
        IRequest $request2
    ) {
        $request1->headers('authorization')->willReturn(null)->shouldBeCalled();
        $this->match($request1)->shouldReturn(true);

        $request2->headers('authorization')->willReturn('b')->shouldBeCalled();
        $this->match($request2)->shouldReturn(false);
    }

    function it_returns_authenticated_public_client(
        IRequest $request,
        IClientStorage $clientStorage,
        IClient $client
    ) {
        $request->request('client_id')->willReturn('public')->shouldBeCalled();
        $request->request('client_secret')->willReturn(null)->shouldBeCalled();
        $clientStorage->get('public')->willReturn($client)->shouldBeCalled();
        $client->getSecret()->willReturn(null)->shouldBeCalled();

        $this->authenticate($request)->shouldReturn($client);
    }

    function it_returns_authenticated_confidential_client(
        IRequest $request,
        IClientStorage $clientStorage,
        IClient $client
    ) {
        $request->request('client_id')->willReturn('public')->shouldBeCalled();
        $request->request('client_secret')->willReturn('secret')->shouldBeCalled();
        $clientStorage->get('public')->willReturn($client)->shouldBeCalled();
        $client->getSecret()->willReturn('secret')->shouldBeCalled();

        $this->authenticate($request)->shouldReturn($client);
    }

    function it_throws_exception_if_client_id_is_missing(
        IRequest $request
    ) {
        $request->request('client_id')->willReturn(null)->shouldBeCalled();
        $request->request('client_secret')->willReturn(null)->shouldBeCalled();

        $this
            ->shouldThrow(new InvalidClientException('Client id is missing.'))
            ->during('authenticate', [$request]);
    }

    function it_throws_exception_if_client_does_not_exist(
        IRequest $request,
        IClientStorage $clientStorage
    ) {
        $request->request('client_id')->willReturn('public')->shouldBeCalled();
        $request->request('client_secret')->willReturn(null)->shouldBeCalled();
        $clientStorage->get('public')->willReturn(null)->shouldBeCalled();

        $this
            ->shouldThrow(new InvalidClientException('Invalid client credentials.'))
            ->during('authenticate', [$request]);
    }

    function it_throw_exception_if_client_secret_is_missing_for_confidential_client(
        IRequest $request,
        IClientStorage $clientStorage,
        IClient $client
    ) {
        $request->request('client_id')->willReturn('confidential')->shouldBeCalled();
        $request->request('client_secret')->willReturn(null)->shouldBeCalled();
        $clientStorage->get('confidential')->willReturn($client)->shouldBeCalled();
        $client->getSecret()->willReturn('secret')->shouldBeCalled();

        $this
            ->shouldThrow(new InvalidClientException('Invalid client credentials.'))
            ->during('authenticate', [$request]);
    }

    function it_throws_exception_if_client_secret_is_provided_for_public_client(
        IRequest $request,
        IClientStorage $clientStorage,
        IClient $client
    ) {
        $request->request('client_id')->willReturn('public')->shouldBeCalled();
        $request->request('client_secret')->willReturn('secret')->shouldBeCalled();
        $clientStorage->get('public')->willReturn($client)->shouldBeCalled();
        $client->getSecret()->willReturn(null)->shouldBeCalled();

        $this
            ->shouldThrow(new InvalidClientException('Invalid client credentials.'))
            ->during('authenticate', [$request]);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:gesture-image="http://schemas.polites.com/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white">

    <ProgressBar
        android:id="@+id/pb_loading_vpp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:indeterminateDrawable="@anim/pb_default" />

    <client.bluerhino.cn.lib_image.imagebrowse.polites.GestureImageView
        android:id="@+id/iv_content_vpp"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        gesture-image:max-scale="10.0"
        gesture-image:min-scale="0.75" />

</FrameLayout>


text:
use std::ptr;

use bindings::{
    themis_secure_message_decrypt, themis_secure_message_encrypt, themis_secure_message_sign,
    themis_secure_message_verify,
};

use crate::error::{Error, ErrorKind, Result};
use crate::keys::{KeyPair, PrivateKey, PublicKey};
use crate::utils::into_raw_parts;

/// Secure Message encryption and decryption.
///
/// **Encrypted message** is useful when you need the full stack of protection for your data —
/// in most cases you will be using this flavor. Encrypted messages currently use Secure Cell
/// in sealing mode for data protection.
///
/// # Examples
///
/// In order to use Secure Message in encrypting mode you will need to have both public and
/// private keys available on both peers. Typical usage of Secure Message looks like this:
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureMessage;
/// use themis::keygen::gen_ec_key_pair;
///
/// // Generate and share this key pair between peers.
/// let key_pair = gen_ec_key_pair();
///
/// // Alice uses her own Secure Message instance to encrypt messages.
/// let secure_a = SecureMessage::new(key_pair.clone());
/// let encrypted = secure_a.encrypt(b"message")?;
///
/// // Bob uses his Secure Message instance to decrypt received messages.
/// let secure_b = SecureMessage::new(key_pair.clone());
/// let decrypted = secure_b.decrypt(&encrypted)?;
///
/// assert_eq!(decrypted, b"message");
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct SecureMessage {
    key_pair: KeyPair,
}

impl SecureMessage {
    /// Makes a new Secure Message using given key pair.
    ///
    /// Both ECDSA and RSA key pairs are supported.
    pub fn new(key_pair: impl Into<KeyPair>) -> Self {
        Self {
            key_pair: key_pair.into(),
        }
    }

    /// Encrypts the provided message into a secure container.
    ///
    /// # Examples
    ///
    /// You can use anything convertible into a byte slice as a message: a byte slice or an array,
    /// a `Vec<u8>`, or a `String`.
    ///
    /// ```
    /// # fn main() -> Result<(), themis::Error> {
    /// use themis::secure_message::SecureMessage;
    /// use themis::keygen::gen_ec_key_pair;
    ///
    /// let secure = SecureMessage::new(gen_ec_key_pair());
    ///
    /// secure.encrypt(b"byte string")?;
    /// secure.encrypt(&[1, 2, 3, 4, 5])?;
    /// secure.encrypt(vec![6, 7, 8, 9])?;
    /// secure.encrypt(format!("owned string"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.key_pair.private_key_bytes());
        let (public_key_ptr, public_key_len) = into_raw_parts(self.key_pair.public_key_bytes());
        let (message_ptr, message_len) = into_raw_parts(message.as_ref());

        let mut encrypted = Vec::new();
        let mut encrypted_len = 0;

        unsafe {
            let status = themis_secure_message_encrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                message_ptr,
                message_len,
                ptr::null_mut(),
                &mut encrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        encrypted.reserve(encrypted_len);

        unsafe {
            let status = themis_secure_message_encrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                message_ptr,
                message_len,
                encrypted.as_mut_ptr(),
                &mut encrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(encrypted_len <= encrypted.capacity());
            encrypted.set_len(encrypted_len as usize);
        }

        Ok(encrypted)
    }

    /// Decrypts an encrypted message back into its original form.
    pub fn decrypt(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.key_pair.private_key_bytes());
        let (public_key_ptr, public_key_len) = into_raw_parts(self.key_pair.public_key_bytes());
        let (wrapped_ptr, wrapped_len) = into_raw_parts(message.as_ref());

        let mut decrypted = Vec::new();
        let mut decrypted_len = 0;

        unsafe {
            let status = themis_secure_message_decrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                wrapped_ptr,
                wrapped_len,
                ptr::null_mut(),
                &mut decrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        decrypted.reserve(decrypted_len);

        unsafe {
            let status = themis_secure_message_decrypt(
                private_key_ptr,
                private_key_len,
                public_key_ptr,
                public_key_len,
                wrapped_ptr,
                wrapped_len,
                decrypted.as_mut_ptr(),
                &mut decrypted_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(decrypted_len <= decrypted.capacity());
            decrypted.set_len(decrypted_len as usize);
        }

        Ok(decrypted)
    }
}

/// Secure Message signing.
///
/// **Signed message** is useful for cases where you don't need data confidentiality. It allows
/// the receiver to verify the origin and integrity of the data while still allowing intermediate
/// nodes to process it accordingly (for example, route data based on its type).
///
/// Signatures can be checked with [`SecureVerify`].
///
/// [`SecureVerify`]: struct.SecureVerify.html
///
/// # Examples
///
/// In order to sign messages you need only the private half of a key pair. It does not need to be
/// shared with your peer for verification.
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureSign;
/// use themis::secure_message::SecureVerify;
/// use themis::keygen::gen_rsa_key_pair;
///
/// // Alice generates a key pair and shares `public` half with Bob
/// let (private, public) = gen_rsa_key_pair().split();
///
/// // Alice is able to sign her messages with her private key.
/// let secure_a = SecureSign::new(private);
/// let signed_message = secure_a.sign(b"important message")?;
///
/// // Bob is able to verify that signature on the message matches.
/// let secure_b = SecureVerify::new(public);
/// let received_message = secure_b.verify(&signed_message)?;
/// assert_eq!(received_message, b"important message");
/// # Ok(())
/// # }
/// ```
///
/// Note that the signed message is _not encrypted_ and contains the original data as plain text:
///
/// ```
/// # use themis::secure_message::SecureSign;
/// # use themis::secure_message::SecureVerify;
/// # use themis::keygen::gen_rsa_key_pair;
/// #
/// # let (private, _) = gen_rsa_key_pair().split();
/// # let secure = SecureSign::new(private);
/// # let signed_message = secure.sign(b"important message").unwrap();
/// #
/// let message = b"important message";
///
/// assert!(signed_message.windows(message.len()).any(|subslice| subslice == message));
/// ```
#[derive(Debug)]
pub struct SecureSign {
    private_key: PrivateKey,
}

impl SecureSign {
    /// Makes a new Secure Message using given private key.
    ///
    /// Both ECDSA and RSA keys are supported.
    pub fn new(private_key: impl Into<PrivateKey>) -> Self {
        Self {
            private_key: private_key.into(),
        }
    }

    /// Securely signs a message and returns it with signature attached.
    ///
    /// # Examples
    ///
    /// You can use anything convertible into a byte slice as a message: a byte slice or an array,
    /// a `Vec<u8>`, or a `String`.
    ///
    /// ```
    /// # fn main() -> Result<(), themis::Error> {
    /// use themis::secure_message::SecureSign;
    /// use themis::keygen::gen_ec_key_pair;
    ///
    /// let secure = SecureSign::new(gen_ec_key_pair().split().0);
    ///
    /// secure.sign(b"byte string")?;
    /// secure.sign(&[1, 2, 3, 4, 5])?;
    /// secure.sign(vec![6, 7, 8, 9])?;
    /// secure.sign(format!("owned string"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn sign(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (private_key_ptr, private_key_len) = into_raw_parts(self.private_key.as_ref());
        let (message_ptr, message_len) = into_raw_parts(message.as_ref());

        let mut signed = Vec::new();
        let mut signed_len = 0;

        unsafe {
            let status = themis_secure_message_sign(
                private_key_ptr,
                private_key_len,
                message_ptr,
                message_len,
                ptr::null_mut(),
                &mut signed_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        signed.reserve(signed_len);

        unsafe {
            let status = themis_secure_message_sign(
                private_key_ptr,
                private_key_len,
                message_ptr,
                message_len,
                signed.as_mut_ptr(),
                &mut signed_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(signed_len <= signed.capacity());
            signed.set_len(signed_len as usize);
        }

        Ok(signed)
    }
}

// TODO: provide a way to inspect signed messages
//
// It would be nice to be able to get access to plaintext data in messages returned by SecureSign.
// Consider returning something like SignedMessage which is a newtype over Vec<u8> with additional
// utility methods and impls like AsRef<[u8]> and Into<Vec<u8>>.

/// Secure Message verification.
///
/// **Signed message** is useful for cases where you don't need data confidentiality. It allows
/// the receiver to verify the origin and integrity of the data while still allowing intermediate
/// nodes to process it accordingly (for example, route data based on its type).
///
/// Verifies signatures produced by [`SecureSign`].
///
/// [`SecureSign`]: struct.SecureSign.html
///
/// # Examples
///
/// In order to verify signed messages you need the public half of a key pair corresponding to the
/// private key used by your peer to sign messages.
///
/// ```
/// # fn main() -> Result<(), themis::Error> {
/// use themis::secure_message::SecureSign;
/// use themis::secure_message::SecureVerify;
/// use themis::keygen::gen_ec_key_pair;
///
/// // Alice generates a key pair and shares `public` half with Bob
/// let (private, public) = gen_ec_key_pair().split();
///
/// // Alice is able to sign her messages with her private key.
/// let secure_a = SecureSign::new(private);
/// let signed_message = secure_a.sign(b"important message")?;
///
/// // Bob is able to verify that signature on the message matches.
/// let secure_b = SecureVerify::new(public);
/// let received_message = secure_b.verify(&signed_message)?;
/// assert_eq!(received_message, b"important message");
/// # Ok(())
/// # }
/// ```
///
/// Secure Message guarantees integrity of the message and identity of its author.
///
/// ```
/// # use themis::secure_message::SecureSign;
/// # use themis::secure_message::SecureVerify;
/// # use themis::keygen::gen_ec_key_pair;
/// #
/// # let (private, public) = gen_ec_key_pair().split();
/// # let secure_a = SecureSign::new(private);
/// # let secure_b = SecureVerify::new(public);
/// # let signed_message = secure_a.sign(b"important message").unwrap();
/// #
/// // Let's flip some bits somewhere.
/// let mut corrupted_message = signed_message.clone();
/// corrupted_message[20] = !corrupted_message[20];
///
/// // Bob is able to see that the message has been tampered.
/// assert!(secure_b.verify(&corrupted_message).is_err());
///
/// // Only Alice's public key verifies the message, any other key won't do.
/// let (_, carol_public_key) = gen_ec_key_pair().split();
/// let secure_c = SecureVerify::new(carol_public_key);
///
/// assert!(secure_c.verify(&signed_message).is_err());
/// ```
#[derive(Debug)]
pub struct SecureVerify {
    public_key: PublicKey,
}

impl SecureVerify {
    /// Makes a new Secure Message using given public key.
    ///
    /// Both ECDSA and RSA keys are supported.
    pub fn new(public_key: impl Into<PublicKey>) -> Self {
        Self {
            public_key: public_key.into(),
        }
    }

    /// Verifies the signature and returns the original message.
    pub fn verify(&self, message: impl AsRef<[u8]>) -> Result<Vec<u8>> {
        let (public_key_ptr, public_key_len) = into_raw_parts(self.public_key.as_ref());
        let (signed_ptr, signed_len) = into_raw_parts(message.as_ref());

        let mut original = Vec::new();
        let mut original_len = 0;

        unsafe {
            let status = themis_secure_message_verify(
                public_key_ptr,
                public_key_len,
                signed_ptr,
                signed_len,
                ptr::null_mut(),
                &mut original_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::BufferTooSmall {
                return Err(error);
            }
        }

        original.reserve(original_len);

        unsafe {
            let status = themis_secure_message_verify(
                public_key_ptr,
                public_key_len,
                signed_ptr,
                signed_len,
                original.as_mut_ptr(),
                &mut original_len,
            );
            let error = Error::from_themis_status(status);
            if error.kind() != ErrorKind::Success {
                return Err(error);
            }
            debug_assert!(original_len <= original.capacity());
            original.set_len(original_len as usize);
        }

        Ok(original)
    }
}


text:
namespace boost {
namespace mpl {

template<
      typename BOOST_MPL_AUX_VOID_SPEC_PARAM(T1)
    , typename BOOST_MPL_AUX_VOID_SPEC_PARAM(T2)
    >
struct pair
{
    typedef pair type;
    typedef T1 first;
    typedef T2 second;

    BOOST_MPL_AUX_LAMBDA_SUPPORT(2,pair,(T1,T2))
};

BOOST_MPL_AUX_VOID_SPEC(2, pair)

} // namespace mpl
} // namespace boost

#endif // BOOST_MPL_PAIR_HPP_INCLUDED