text:
Import-Module .\TestLibs\RDFELibs.psm1 -Force
$result = ""
$testResult = ""
$resultArr = @()
$allDiskNames = @()
try
{
    $isDeployed = DeployVMS -setupType $currentTestData.setupType -Distro $Distro -xmlConfig $xmlConfig
    if ($isDeployed)
    {
        foreach ($VM in $allVMData)
        {
            $ResourceGroupUnderTest = $VM.ResourceGroupName
            $VirtualMachine = Get-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.RoleName
            $diskCount = (Get-AzureRmVMSize -Location $allVMData.Location | Where-Object {$_.Name -eq $allVMData.InstanceSize}).MaxDataDiskCount
            LogMsg "------------------------------------------"
            LogMsg "Parallel Addition of Data Disks to the VM "
            While($count -lt $diskCount)
            {
                $count += 1

                $diskName = "disk"+ $count.ToString()
                $allDiskNames += $diskName
                $diskSizeinGB = "1023"
                $VHDuri = $VirtualMachine.StorageProfile.OsDisk.Vhd.Uri
                $VHDUri = $VHDUri.Replace("osdisk",$diskName)
                LogMsg "Adding an empty data disk of size $diskSizeinGB GB"
                $out = Add-AzureRMVMDataDisk -VM $VirtualMachine -Name $diskName -DiskSizeInGB $diskSizeinGB -LUN $count -VhdUri $VHDuri.ToString() -CreateOption Empty
                LogMsg "Successfully created an empty data disk of size $diskSizeinGB GB"
            }
            LogMsg "Number of data disks added to the VM $count"
            $out = Update-AzureRMVM -VM $VirtualMachine -ResourceGroupName $ResourceGroupUnderTest
            LogMsg "Successfully added $diskCount empty data disks to the VM"
            LogMsg "Verifying if data disk is added to the VM: Running fdisk on remote VM"
            $fdiskOutput = RunLinuxCmd -username $user -password $password -ip $VM.PublicIP -port $VM.SSHPort -command "/sbin/fdisk -l | grep /dev/sd" -runAsSudo

            foreach($line in ($fdiskOutput.Split([Environment]::NewLine)))
            {

                if($line -imatch "Disk /dev/sd[^ab]" -and ([int]($line.Split()[2]) -ge [int]$diskSizeinGB))
                {
                    LogMsg "Data disk is successfully mounted to the VM: $line"
                    $verifiedDiskCount += 1
                }
            }

            LogMsg "Number of data disks verified inside VM $verifiedDiskCount"
            if($verifiedDiskCount -ge $diskCount)
            {
                LogMsg "Data disks added to the VM are successfully verified inside VM"
                $testResult = "PASS"
            }
            else
            {
                LogMsg "Data disks added to the VM failed to verify inside VM"
                $testResult = "FAIL"
                Break
            }
            LogMsg "------------------------------------------"
            LogMsg "Parallel Removal of Data Disks from the VM"
            $out = Remove-AzureRmVMDataDisk -VM $VirtualMachine -DataDiskNames $allDiskNames
            $out = Update-AzureRMVM -VM $VirtualMachine -ResourceGroupName $ResourceGroupUnderTest
            LogMsg "Successfully removed the data disk from the VM"
            LogMsg "Verifying if data disks are removed from the VM: Running fdisk on remote VM"

            $fdiskFinalOutput = RunLinuxCmd -username $user -password $password -ip $VM.PublicIP -port $VM.SSHPort -command "/sbin/fdisk -l | grep /dev/sd" -runAsSudo
            foreach($line in ($fdiskFinalOutput.Split([Environment]::NewLine)))
            {
                if($line -imatch "Disk /dev/sd[^ab]" -and ([int]($line.Split()[2]) -ge [int]$diskSizeinGB))
                {
                    LogMsg "Data disk is NOT removed from the VM at $line"
                    $testResult = "FAIL"
                    Break
                }
            }
            LogMsg "Successfully verified that all data disks are removed from the VM"
            $testResult = "PASS"
        }
    }
}
catch
{
    $ErrorMessage =  $_.Exception.Message
    LogMsg "EXCEPTION : $ErrorMessage"
}
Finally
    {
        if (!$testResult)
        {
            $testResult = "Aborted"
        }
        $resultArr += $testResult
    }
$result = GetFinalResultHeader -resultarr $resultArr

#Clean up the setup
DoTestCleanUp -result $result -testName $currentTestData.testName -ResourceGroups $isDeployed

#Return the result and summery to the test suite script..
return $result


text:
{-# LANGUAGE CPP, PackageImports #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# OPTIONS -fno-warn-name-shadowing #-}

module Graphics.UI.Threepenny.Internal.Driver
  (
  -- * Synopsis
  -- | The main internal functionality.

  -- * Server running
   serve
  ,loadFile
  ,loadDirectory

  -- * Elements
  ,newElement
  ,appendElementTo
  ,emptyEl
  ,delete

  -- * Event handling
  -- $eventhandling
  ,bind
  ,disconnect
  ,module Reactive.Threepenny

  -- * Querying
  -- $querying
  ,getHead
  ,getBody
  ,getElementsByTagName
  ,getElementsById
  ,getElementsByClassName
  ,getWindow
  ,getValuesList
  ,getRequestCookies
  ,getRequestLocation

  -- * Utilities
  ,debug
  ,callDeferredFunction
  ,atomic

  -- * JavaScript FFI
  ,ToJS, FFI, ffi, JSFunction
  ,runFunction, callFunction

  -- * Types
  ,Window
  ,Element
  ,Config(..)
  ,EventData(..)
  ) where

import           Control.Applicative
import           Control.Concurrent
import           Control.Concurrent.Chan.Extra
import           Control.Concurrent.Delay
import           Control.DeepSeq
import qualified Control.Exception
import           Control.Monad
import           Control.Monad.IO.Class
import qualified "MonadCatchIO-transformers" Control.Monad.CatchIO as E
import           Data.ByteString               (ByteString)
import           Data.ByteString.UTF8          (toString,fromString)
import           Data.Map                      (Map)
import qualified Data.Map                      as M
import           Data.Maybe
import           Data.Text                     (Text,pack,unpack)
import qualified Data.Text                     as Text
import           Data.Text.Encoding            as Text
import           Data.Time
import           Network.URI
import qualified Network.WebSockets            as WS
import qualified Network.WebSockets.Snap       as WS
import qualified Data.Attoparsec.Enumerator    as Atto
import           Prelude                       hiding (init)
import           Safe
import           Snap.Core
import qualified Snap.Http.Server              as Snap
import           Snap.Util.FileServe
import           System.Environment            (getEnvironment)
import           System.FilePath

import qualified Data.Aeson                    as JSON
import           Data.Aeson                    (Result(..))
import qualified Data.ByteString.Lazy.Char8    as LBS
import           Data.Data

import           Graphics.UI.Threepenny.Internal.Types     as Threepenny
import           Graphics.UI.Threepenny.Internal.Resources
import           Graphics.UI.Threepenny.Internal.FFI
import           Reactive.Threepenny

import qualified Foreign.Coupon as Foreign
import qualified System.Mem

{-----------------------------------------------------------------------------
    Server and and session management
------------------------------------------------------------------------------}
newServerState :: IO ServerState
newServerState = ServerState
    <$> newMVar M.empty
    <*> newMVar (0,M.empty)
    <*> newMVar (0,M.empty)

-- | Run a TP server with Snap on the specified port and the given
--   worker action.
serve :: Config -> (Session -> IO ()) -> IO ()
serve Config{..} worker = do
    env    <- getEnvironment
    let portEnv = Safe.readMay =<< Prelude.lookup "PORT" env

    server <- newServerState
    _      <- forkIO $ custodian 30 (sSessions server)
    let config = Snap.setPort      (maybe defaultPort id (tpPort `mplus` portEnv))
               $ Snap.setErrorLog  (Snap.ConfigIoLog tpLog)
               $ Snap.setAccessLog (Snap.ConfigIoLog tpLog)
               $ Snap.defaultConfig
    Snap.httpServe config . route $
        routeResources tpCustomHTML tpStatic server
        -- ++ routeCommunication worker server
        ++ routeWebsockets worker server

-- | Kill sessions after at least n seconds of disconnectedness.
custodian :: Integer -> MVar Sessions -> IO ()
custodian seconds sessions = forever $ do
  delaySeconds seconds
  modifyMVar_ sessions $ \sessions -> do
    killed <- fmap catMaybes $ forM (M.assocs sessions) $ \(key,Session{..}) -> do
      state <- readMVar sConnectedState
      case state of
        Connected -> return Nothing
        Disconnected time -> do
          now <- getCurrentTime
          let dcSeconds = diffUTCTime now time
          -- session is disconnected for more than  seconds
          if (dcSeconds > fromIntegral seconds)
             then do killThread sThreadId
                     return (Just key)
             else return Nothing

    -- remove killed sessions from the map
    return (M.filterWithKey (\k _ -> not (k `elem` killed)) sessions)

-- Run a snap action with the given session.
withSession :: ServerState -> (Session -> Snap a) -> Snap a
withSession server cont = do
    token <- readInput "token"
    case token of
        Nothing    -> error $ "Invalid session token format."
        Just token -> withGivenSession token server cont

-- Do something with the session given by its token id.
withGivenSession :: Integer -> ServerState -> (Session -> Snap a) -> Snap a
withGivenSession token ServerState{..} cont = do
    sessions <- liftIO $ withMVar sSessions return
    case M.lookup token sessions of
        Nothing      -> error $ "Nonexistant token: " ++ show token
        Just session -> cont session

{-----------------------------------------------------------------------------
    Implementation of two-way communication
    - POST and GET requests
------------------------------------------------------------------------------}
-- | Route the communication between JavaScript and the server
routeCommunication :: (Session -> IO a) -> ServerState -> Routes
routeCommunication worker server =
    [("/init"   , init worker server)
    ,("/poll"   , withSession server poll  )
    ,("/signal" , withSession server signal)
    ]

-- | Make a new session.
newSession :: ServerState -> (URI,[(String, String)]) -> Integer -> IO Session
newSession sServerState sStartInfo sToken = do
    sSignals          <- newChan
    sInstructions     <- newChan
    sMutex            <- newMVar ()
    sEventQuit        <- newEvent
    sPrizeBooth      <- Foreign.newPrizeBooth
    let sHeadElement  =  undefined -- filled in later
    let sBodyElement  =  undefined
    now               <- getCurrentTime
    sConnectedState   <- newMVar (Disconnected now)
    sThreadId         <- myThreadId
    sClosures         <- newMVar [0..]
    let session = Session {..}
    initializeElements session

-- | Make a new session and add it to the server
createSession :: (Session -> IO void) -> ServerState -> Snap Session
createSession worker server = do
    -- uri    <- snapRequestURI
    let uri = undefined -- FIXME: No URI for WebSocket requests.
    params <- snapRequestCookies
    liftIO $ modifyMVar (sSessions server) $ \sessions -> do
        let newKey = maybe 0 (+1) (lastMay (M.keys sessions))
        session <- newSession server (uri,params) newKey
        _       <- forkIO $ void $ worker session >> handleEvents session
        return (M.insert newKey session sessions, session)

-- | Respond to initialization request.
init :: (Session -> IO void) -> ServerState -> Snap ()
init worker server = do
    session <- createSession worker server
    modifyResponse . setHeader "Set-Token" . fromString . show . sToken $ session
    poll session

snapRequestURI :: Snap URI
snapRequestURI = do
    uri     <- getInput "info"
    maybe (error ("Unable to parse request URI: " ++ show uri)) return (uri >>= parseURI)

snapRequestCookies :: Snap [(String, String)]
snapRequestCookies = do
    cookies <- getsRequest rqCookies
    return $ flip map cookies $ \Cookie{..} -> (toString cookieName,toString cookieValue)

-- | Respond to poll requests.
poll :: Session -> Snap ()
poll Session{..} = do
    let setDisconnected = do
        now <- getCurrentTime
        modifyMVar_ sConnectedState (const (return (Disconnected now)))

    instructions <- liftIO $ do
        modifyMVar_ sConnectedState (const (return Connected))
        threadId <- myThreadId
        forkIO $ do
            delaySeconds $ 60 * 5 -- Force kill after 5 minutes.
            killThread threadId
        E.catch (readAvailableChan sInstructions) $ \e -> do
            -- no instructions available after some time
            when (e == Control.Exception.ThreadKilled) $ setDisconnected
            E.throw e

    writeJson instructions

-- | Handle signals sent from the client.
signal :: Session -> Snap ()
signal Session{..} = do
    input <- getParam "signal"
    let err = error $ "Unable to parse " ++ show input
    case JSON.decode . LBS.fromChunks . return =<< input of
        Just    signal -> liftIO $ writeChan sSignals signal
        Nothing        -> err

{-----------------------------------------------------------------------------
    Implementation of two-way communication
    - WebSockets
------------------------------------------------------------------------------}
-- | Route the communication between JavaScript and the server
routeWebsockets :: (Session -> IO a) -> ServerState -> Routes
routeWebsockets worker server =
    [("websocket", response)]
    where
    response = do
        session <- createSession worker server
        WS.runWebSocketsSnap (webSocket session)
        error "Threepenny.Internal.Core: runWebSocketsSnap should never return."

webSocket :: Session -> WS.PendingConnection -> IO ()
webSocket Session{..} request = void $ do
    connection <- WS.acceptRequest request
    -- websockets are always connected, don't let the custodian kill you.
    modifyMVar_ sConnectedState (const (return Connected))

    -- write data (in another thread)
    sendData <- forkIO . forever $ do
        x <- readChan sInstructions
        -- see note [Instruction strictness]
        WS.sendTextData connection . JSON.encode $ x

    -- read data
    let readData = do
            input <- WS.receiveData connection
            case input of
                "ping" -> WS.sendTextData connection . LBS.pack $ "pong"
                "quit" -> E.throw WS.ConnectionClosed
                input  -> case JSON.decode input of
                    Just signal -> writeChan sSignals signal
                    Nothing     -> E.throw $ Atto.ParseError [] $
                        "Threepenny.Internal.Core: Couldn't parse 'Signal' "
                        ++ show input

    forever readData `E.finally`
        (do
            killThread sendData             -- kill sending thread when done
            writeChan sSignals $ Quit ()    -- signal  Quit  event
        )

{- note [Instruction strictness]

The  Instruction  may contain components that evaluate to _|_.
An exception will be thrown when we try to send one of those to the browser.
However, the  WS.sendSink  function is called in a different thread
than where the faulty instruction was constructed.
We want to throw an exception in the latter thread.
Hence, we make sure that the  Instruction  is fully evaluated (deepseq)
before passing it to the thread that sends it to the web browser.

(Another, probably preferred, solution would be to make the  Instruction
data type fully strict by default.)

-}

{-----------------------------------------------------------------------------
    FFI implementation on top of the communication channel
------------------------------------------------------------------------------}
-- | Atomically execute the given computation in the context of a browser window
atomic :: Window -> IO a -> IO a
atomic window@(Session{..}) m = do
  takeMVar sMutex
  ret <- m
  putMVar sMutex ()
  return ret

-- | Send an instruction and read the signal response.
call :: Session -> Instruction -> (Signal -> IO (Maybe a)) -> IO a
call session@(Session{..}) instruction withSignal = do
  -- see note [Instruction strictness]
  Control.Exception.evaluate $ force instruction
  takeMVar sMutex
  writeChan sInstructions instruction
  newChan <- dupChan sSignals
  go sMutex newChan

  where
    go mutex newChan = do
      signal <- readChan newChan
      result <- withSignal signal
      case result of
        Just signal -> do putMVar mutex ()
                          return signal
        Nothing     -> go mutex newChan
            -- keep reading signals from the duplicated channel
            -- until the function above succeeds

-- Run the given instruction wihtout waiting for a response.
run :: Session -> Instruction -> IO ()
run (Session{..}) instruction =
    writeChan sInstructions $!! instruction  -- see note [Instruction strictness]

-- | Call the given function with the given continuation. Doesn't block.
callDeferredFunction
  :: Window                    -- ^ Browser window
  -> String                    -- ^ The function name.
  -> [String]                  -- ^ Parameters.
  -> ([Maybe String] -> IO ()) -- ^ The continuation to call if/when the function completes.
  -> IO ()
callDeferredFunction window fun params thunk = do
    closure <- newClosure window fun $ \(EventData xs) -> thunk xs
    run window $ CallDeferredFunction (closure,fun,params)

-- | Run the given JavaScript function and carry on. Doesn't block.
--
-- The client window uses JavaScript's @eval()@ function to run the code.
runFunction :: Window -> JSFunction () -> IO ()
runFunction session = run session . RunJSFunction . toCode

-- | Run the given JavaScript function and wait for results. Blocks.
--
-- The client window uses JavaScript's @eval()@ function to run the code.
callFunction :: Window -> JSFunction a -> IO a
callFunction window jsfunction =
    call window (CallJSFunction . toCode $ jsfunction) $ \signal ->
        case signal of
            FunctionResult v -> case marshalResult jsfunction window v of
                Success a -> return $ Just a
                Error   _ -> return Nothing
            _ -> return Nothing

-- | Package a Haskell function such that it can be called from JavaScript.
--
-- At the moment, we implement this as an event handler that is
-- attached to the @head@ element.
newClosure
    :: Window               -- ^ Browser window context
    -> String               -- ^ Function name (for debugging).
    -> (EventData -> IO ()) -- ^ Function to call
    -> IO Closure
newClosure window@(Session{..}) fun thunk = do
    cid <- modifyMVar sClosures $ \(x:xs) -> return (xs,x)
    let eventId = fun ++ "-" ++ show cid
    attachClosure sHeadElement eventId thunk
    return $ Closure (unprotectedGetElementId sHeadElement, eventId)

{-----------------------------------------------------------------------------
    Snap utilities
------------------------------------------------------------------------------}
-- Write JSON to output.
writeJson :: (MonadSnap m, JSON.ToJSON a) => a -> m ()
writeJson json = do
    modifyResponse $ setContentType "application/json"
    writeLBS . JSON.encode $ json

-- Get a text input from snap.
getInput :: (MonadSnap f) => ByteString -> f (Maybe String)
getInput = fmap (fmap (unpack . Text.decodeUtf8)) . getParam

-- Read an input from snap.
readInput :: (MonadSnap f,Read a) => ByteString -> f (Maybe a)
readInput = fmap (>>= readMay) . getInput

{-----------------------------------------------------------------------------
    Resourcse
------------------------------------------------------------------------------}
type Routes = [(ByteString, Snap ())]

routeResources :: Maybe FilePath -> Maybe FilePath -> ServerState -> Routes
routeResources customHTML staticDir server =
    fixHandlers noCache $
        static ++
        [("/"                          , root)
        ,("/driver/threepenny-gui.js"  , writeText jsDriverCode )
        ,("/driver/threepenny-gui.css" , writeText cssDriverCode)
        ,("/file/:name"                ,
            withFilepath (sFiles server) (flip serveFileAs))
        ,("/dir/:name"                 ,
            withFilepath (sDirs  server) (\path _ -> serveDirectory path))
        ]
    where
    fixHandlers f routes = [(a,f b) | (a,b) <- routes]
    noCache h = modifyResponse (setHeader "Cache-Control" "no-cache") >> h

    static = maybe [] (\dir -> [("/static", serveDirectory dir)]) staticDir

    root = case customHTML of
        Just file -> case staticDir of
            Just dir -> serveFile (dir </> file)
            Nothing  -> logError "Graphics.UI.Threepenny: Cannot use tpCustomHTML file without tpStatic"
        Nothing   -> writeText defaultHtmlFile

-- Get a filename from a URI
withFilepath :: MVar Filepaths -> (FilePath -> MimeType -> Snap a) -> Snap a
withFilepath rDict cont = do
    mName    <- getParam "name"
    (_,dict) <- liftIO $ withMVar rDict return
    case (\key -> M.lookup key dict) =<< mName of
        Just (path,mimetype) -> cont path mimetype
        Nothing              -> error $ "File not loaded: " ++ show mName

-- FIXME: Serving large files fails with the exception
-- System.SendFile.Darwin: invalid argument (Socket is not connected)

newAssociation :: MVar Filepaths -> (FilePath, MimeType) -> IO String
newAssociation rDict (path,mimetype) = do
    (old, dict) <- takeMVar rDict
    let new = old + 1; key = show new ++ takeFileName path
    putMVar rDict $ (new, M.insert (fromString key) (path,mimetype) dict)
    return key

-- | Begin to serve a local file under an URI.
loadFile :: Session -> MimeType -> FilePath -> IO String
loadFile Session{..} mimetype path = do
    key <- newAssociation (sFiles sServerState) (path,mimetype)
    return $ "/file/" ++ key

-- | Begin to serve a local directory under an URI.
loadDirectory :: Session -> FilePath -> IO String
loadDirectory Session{..} path = do
    key <- newAssociation (sDirs sServerState) (path,"")
    return $ "/dir/" ++ key

{-----------------------------------------------------------------------------
    Elements
        Creation, Management, Finalization
------------------------------------------------------------------------------}
-- | Create a new element of the given tag name.
newElement :: Window        -- ^ Browser window in which context to create the element
           -> String        -- ^ The tag name.
           -> Events        -- ^ Events associated to that element.
           -> IO Element    -- ^ A tag reference. Non-blocking.
newElement elSession@(Session{..}) elTagName elEvents = do
    elHandlers <- newMVar M.empty
    el         <- Foreign.newItem sPrizeBooth ElementData{..}
    Foreign.addFinalizer el $ delete el
        -- FIXME: Do not try to delete elements from the session when
        -- the session is broken/disconnected already.
        -- A fix should be part of the  run  function, though.
    return el

-- | Get 'Window' associated to an 'Element'.
getWindow :: Element -> IO Window
getWindow e = withElement e $ \_ window -> return window

-- | Look up several elements in the browser window.
lookupElements :: Session -> [ElementId] -> IO [Element]
lookupElements window = mapM (flip lookupElement window)

-- | Append a child element to a parent element. Non-blocking.
appendElementTo
    :: Element     -- ^ Parent.
    -> Element     -- ^ Child.
    -> IO ()
appendElementTo eParent eChild =
    -- TODO: Right now, parent and child need to be from the same session/browser window
    --       Implement transfer of elements across browser windows
    withElement eParent $ \parent session ->
    withElement eChild  $ \child  _       -> do
        Foreign.addReachable eParent eChild
        runFunction session $ ffi "$(%1).append($(%2))" parent child

-- | Get the head of the page.
getHead :: Window -> IO Element
getHead session = return $ sHeadElement session

-- | Get the body of the page.
getBody :: Window -> IO Element
getBody session = return $ sBodyElement session

-- | Empty the given element.
emptyEl :: Element -> IO ()
emptyEl el = withElement el $ \elid window -> do
    Foreign.clearReachable el
    runFunction window $ ffi "$(%1).contents().detach()" elid

-- | Delete the given element.
delete :: Element -> IO ()
delete el = withElement el $ \elid window ->
    run window $ Delete elid
    -- Note: We want a primitive 'Delete' here, because
    -- we do not want the implicit conversion from ElementId to element.

{-----------------------------------------------------------------------------
    Event handling
------------------------------------------------------------------------------}
{- $eventhandling

    To bind events to elements, use the 'bind' function.

    To handle DOM events, use the 'handleEvent' function, or the
    'handleEvents' function which will block forever.

    See the rest of this section for some helpful functions that do
    common binding, such as clicks, hovers, etc.
-}

-- | Handle events signalled from the client.
handleEvents :: Window -> IO ()
handleEvents window@(Session{..}) = do
    signal <- getSignal window
    case signal of
        Threepenny.Event elid eventId params -> do
            handleEvent1 window (elid,eventId,EventData params)
#ifdef REBUG
            -- debug garbage collection of elements:
            System.Mem.performGC
#endif
            handleEvents window
        Quit () -> do
            snd sEventQuit ()
            -- do not continue handling events
        _       -> do
            handleEvents window

-- | Handle a single event.
handleEvent1 :: Window -> (ElementId, EventId, EventData) -> IO ()
handleEvent1 window (elid,eventId,params) = do
    el <- lookupElement elid window
    withElementData el $ \_ eldata -> do
        handlers <- readMVar $ elHandlers eldata
        case M.lookup eventId handlers of
            Just handler -> handler params
            Nothing      -> return ()

-- Get the latest signal sent from the client.
getSignal :: Window -> IO Signal
getSignal (Session{..}) = readChan sSignals

-- | Associate a new closure with an element.
attachClosure :: Element -> EventId -> Handler EventData -> IO ()
attachClosure el eventId handler = withElementData el $ \_ eldata ->
    modifyMVar_ (elHandlers eldata) $ return .
        M.insertWith (\h1 h a -> h1 a >> h a) eventId handler

-- | Bind an event handler for a dom event to an 'Element'.
bind
    :: EventId              -- ^ The eventType, see any DOM documentation for a list of these.
    -> Element              -- ^ The element to bind to.
    -> Handler EventData    -- ^ The event handler to bind.
    -> IO ()
bind eventId e handler = withElementData e $ \elid el -> do
    handlers <- readMVar $ elHandlers el
    -- register with client if it has never been registered on the server
    when (not $ eventId `M.member` handlers) $
        run (elSession el) $ Bind eventId elid
    -- register with server
    attachClosure e eventId handler

-- | Register event handler that occurs when the client has disconnected.
disconnect :: Window -> Event ()
disconnect = fst . sEventQuit

-- | Initialize the 'head' and 'body' elements when the session starts.
initializeElements :: Session -> IO Session
initializeElements session@(Session{..}) = do
        sHeadElement <- createElement "head"
        sBodyElement <- createElement "body"
        return $ Session{..}
    where
    newEvents     e   = newEventsNamed $ \(name,_,handler) -> bind name e handler
    createElement tag = mdo
        x <- newElement session tag =<< newEvents x
        return x

{-----------------------------------------------------------------------------
    Querying the DOM
------------------------------------------------------------------------------}
-- $querying
--
-- The DOM can be searched for elements of a given name, and nodes can
-- be inspected for their values.

-- | Get all elements of the given tag name. Blocks.
getElementsByTagName :: Window -> String -> IO [Element]
getElementsByTagName window tag = do
    elids <- callFunction window $ ffi "document.getElementsByTagName(%1)" tag
    lookupElements window elids

-- | Get a list of elements by particular IDs.  Blocks.
getElementsById :: Window -> [String] -> IO [Element]
getElementsById window ids = do
    elids <- forM ids $ \x ->
        callFunction window $ ffi "[document.getElementById(%1)]" x
    lookupElements window $ concat elids

-- | Get a list of elements by particular class.  Blocks.
getElementsByClassName :: Window -> String -> IO [Element]
getElementsByClassName window cls = do
    elids <- callFunction window $ ffi "document.getElementsByClassName(%1)" cls
    lookupElements window elids

-- | Get values from inputs. Blocks. This is faster than many @getValue@ invocations.
getValuesList
    :: [Element]   -- ^ A list of elements to get the values of.
    -> IO [String] -- ^ The list of plain text values.
getValuesList []        = return []
getValuesList es@(e0:_) = withElement e0 $ \_ window -> do
    let elids  = map unprotectedGetElementId es
    call window (GetValues elids) $ \signal ->
        case signal of
            Values strs -> return $ Just strs
            _           -> return Nothing

-- | Get the request location.
getRequestLocation :: Window -> IO URI
getRequestLocation = return . fst . sStartInfo

-- | Get the request cookies.
getRequestCookies :: Window -> IO [(String,String)]
getRequestCookies = return . snd . sStartInfo

{-----------------------------------------------------------------------------
    Utilities
------------------------------------------------------------------------------}
-- | Send a debug message to the client. The behaviour of the client
--   is unspecified.
debug
    :: Window -- ^ Client window
    -> String -- ^ Some plain text to send to the client.
    -> IO ()
debug window = run window . Debug

redpajama_set_name: RedPajamaGithub


text:
package org.optaplanner.examples.dinnerparty.solver.move;

import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import org.optaplanner.core.impl.heuristic.selector.move.generic.SwapMove;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.examples.dinnerparty.domain.DinnerParty;
import org.optaplanner.examples.dinnerparty.domain.SeatDesignation;

public class DifferentGenderSwapMoveFilter implements SelectionFilter<DinnerParty, SwapMove> {

    @Override
    public boolean accept(ScoreDirector<DinnerParty> scoreDirector, SwapMove move) {
        SeatDesignation leftSeatDesignation = (SeatDesignation) move.getLeftEntity();
        SeatDesignation rightSeatDesignation = (SeatDesignation) move.getRightEntity();
        return leftSeatDesignation.getGuest().getGender() == rightSeatDesignation.getGuest().getGender();
    }

}


text:
USAGE="${0} [-R] \$PWD"
WD=`pwd`
TOOLDIR=${WD}/configs/z16f2800100zcog/tools
ME=${TOOLDIR}/dopatch.sh
PATCH=${TOOLDIR}/zneo-zdsii-5_0_1-variadic-func-fix.patch
ARGS=${1}

if [ ! -x ${ME} ]; then
  echo "ERROR:  This script must be executed from the top-level NuttX directory"
  echo ${USAGE}
  exit 1
fi

if [ ! -r ${PATCH} ]; then
  echo "ERROR: Readable patch not found at ${PATCH}"
  echo ${USAGE}
  exit 1
fi

cd .. || \
  { echo "ERROR: failed to CD to the parent directory"; exit 1; }

cat ${PATCH} | patch ${ARGS} -p1 || \
  { echo "ERROR: patch failed" ; exit 1; }


text:
require "delegate"

module Google
  module Cloud
    module Storage
      class Bucket
        ##
        # # Bucket Cors
        #
        # A special-case Array for managing the website CORS rules for a bucket.
        # Accessed via {Bucket#cors}.
        #
        # @see https://cloud.google.com/storage/docs/cross-origin Cross-Origin
        #   Resource Sharing (CORS)
        #
        # @example
        #   require "google/cloud/storage"
        #
        #   storage = Google::Cloud::Storage.new
        #
        #   bucket = storage.bucket "my-bucket"
        #
        #   bucket.cors do |c|
        #     # Remove the last CORS rule from the array
        #     c.pop
        #     # Remove all existing rules with the https protocol
        #     c.delete_if { |r| r.origin.include? "http://example.com" }
        #     c.add_rule ["http://example.org", "https://example.org"],
        #                ["GET", "POST", "DELETE"],
        #                headers: ["X-My-Custom-Header"],
        #                max_age: 3600
        #   end
        #
        class Cors < DelegateClass(::Array)
          ##
          # @private Initialize a new CORS rules builder with existing CORS
          # rules, if any.
          def initialize rules = []
            super rules
            @original = to_gapi.map(&:to_json)
          end

          # @private
          def changed?
            @original != to_gapi.map(&:to_json)
          end

          ##
          # Add a CORS rule to the CORS rules for a bucket. Accepts options for
          # setting preflight response headers. Preflight requests and responses
          # are required if the request method and headers are not both [simple
          # methods](http://www.w3.org/TR/cors/#simple-method) and [simple
          # headers](http://www.w3.org/TR/cors/#simple-header).
          #
          # @param [String, Array<String>] origin The
          #   [origin](http://tools.ietf.org/html/rfc6454) or origins permitted
          #   for cross origin resource sharing with the bucket. Note: "*" is
          #   permitted in the list of origins, and means "any Origin".
          # @param [String, Array<String>] methods The list of HTTP methods
          #   permitted in cross origin resource sharing with the bucket. (GET,
          #   OPTIONS, POST, etc) Note: "*" is permitted in the list of methods,
          #   and means "any method".
          # @param [String, Array<String>] headers The list of header field
          #   names to send in the Access-Control-Allow-Headers header in the
          #   preflight response. Indicates the custom request headers that may
          #   be used in the actual request.
          # @param [Integer] max_age The value to send in the
          #   Access-Control-Max-Age header in the preflight response. Indicates
          #   how many seconds the results of a preflight request can be cached
          #   in a preflight result cache. The default value is `1800` (30
          #   minutes.)
          #
          # @example
          #   require "google/cloud/storage"
          #
          #   storage = Google::Cloud::Storage.new
          #
          #   bucket = storage.create_bucket "my-bucket" do |b|
          #     b.cors.add_rule ["http://example.org", "https://example.org"],
          #                     "*",
          #                     headers: ["X-My-Custom-Header"],
          #                     max_age: 300
          #   end
          #
          def add_rule origin, methods, headers: nil, max_age: nil
            push Rule.new(origin, methods, headers: headers, max_age: max_age)
          end

          # @private
          def to_gapi
            map(&:to_gapi)
          end

          # @private
          def self.from_gapi gapi_list
            rules = Array(gapi_list).map { |gapi| Rule.from_gapi gapi }
            new rules
          end

          # @private
          def freeze
            each(&:freeze)
            super
          end

          class Rule
            attr_accessor :origin, :methods, :headers, :max_age

            def initialize origin, methods, headers: nil, max_age: nil
              @origin = Array(origin)
              @methods = Array(methods)
              @headers = Array(headers)
              @max_age = (max_age||1800)
            end

            def to_gapi
              Google::Apis::StorageV1::Bucket::CorsConfiguration.new(
                origin: Array(origin).dup, http_method: Array(methods).dup,
                response_header: Array(headers).dup, max_age_seconds: max_age
              )
            end

            def self.from_gapi gapi
              new gapi.origin.dup, gapi.http_method.dup, \
                  headers: gapi.response_header.dup,
                  max_age: gapi.max_age_seconds
            end

            def freeze
              @origin.freeze
              @methods.freeze
              @headers.freeze
              super
            end
          end
        end
      end
    end
  end
end


text:
namespace MyJob.Service.Test.UI
{
    partial class FormWindowsCmd
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tlpMain = new System.Windows.Forms.TableLayoutPanel();
            this.txtParam = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtCmd = new System.Windows.Forms.TextBox();
            this.btnExec = new System.Windows.Forms.Button();
            this.txtResult = new System.Windows.Forms.TextBox();
            this.tlpMain.SuspendLayout();
            this.SuspendLayout();
            //
            // tlpMain
            //
            this.tlpMain.ColumnCount = 2;
            this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F));
            this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 70F));
            this.tlpMain.Controls.Add(this.txtParam, 1, 1);
            this.tlpMain.Controls.Add(this.label1, 0, 0);
            this.tlpMain.Controls.Add(this.label2, 0, 1);
            this.tlpMain.Controls.Add(this.txtCmd, 1, 0);
            this.tlpMain.Controls.Add(this.btnExec, 0, 2);
            this.tlpMain.Controls.Add(this.txtResult, 0, 3);
            this.tlpMain.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tlpMain.Location = new System.Drawing.Point(0, 0);
            this.tlpMain.Name = "tlpMain";
            this.tlpMain.RowCount = 4;
            this.tlpMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F));
            this.tlpMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F));
            this.tlpMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 50F));
            this.tlpMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tlpMain.Size = new System.Drawing.Size(548, 331);
            this.tlpMain.TabIndex = 0;
            //
            // txtParam
            //
            this.txtParam.Location = new System.Drawing.Point(167, 53);
            this.txtParam.Name = "txtParam";
            this.txtParam.Size = new System.Drawing.Size(294, 21);
            this.txtParam.TabIndex = 3;
            this.txtParam.Text = "C:\\Windows\\ODBC.INI";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(29, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "命令";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(3, 50);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(29, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "参数";
            //
            // txtCmd
            //
            this.txtCmd.Location = new System.Drawing.Point(167, 3);
            this.txtCmd.Name = "txtCmd";
            this.txtCmd.Size = new System.Drawing.Size(294, 21);
            this.txtCmd.TabIndex = 2;
            this.txtCmd.Text = "C:\\Windows\\notepad.exe";
            //
            // btnExec
            //
            this.btnExec.Location = new System.Drawing.Point(3, 103);
            this.btnExec.Name = "btnExec";
            this.btnExec.Size = new System.Drawing.Size(75, 23);
            this.btnExec.TabIndex = 4;
            this.btnExec.Text = "执行";
            this.btnExec.UseVisualStyleBackColor = true;
            this.btnExec.Click += new System.EventHandler(this.btnExec_Click);
            //
            // txtResult
            //
            this.tlpMain.SetColumnSpan(this.txtResult, 2);
            this.txtResult.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtResult.Location = new System.Drawing.Point(3, 153);
            this.txtResult.Multiline = true;
            this.txtResult.Name = "txtResult";
            this.txtResult.ReadOnly = true;
            this.txtResult.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtResult.Size = new System.Drawing.Size(542, 175);
            this.txtResult.TabIndex = 5;
            //
            // FormWindowsCmd
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(548, 331);
            this.Controls.Add(this.tlpMain);
            this.Name = "FormWindowsCmd";
            this.Text = "Windows Cmd 作业";
            this.tlpMain.ResumeLayout(false);
            this.tlpMain.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.TableLayoutPanel tlpMain;
        private System.Windows.Forms.TextBox txtParam;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtCmd;
        private System.Windows.Forms.Button btnExec;
        private System.Windows.Forms.TextBox txtResult;
    }
}


text:
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data

'-------------------------------------------------------------------------------------------'
' Inicio de clase "rAuditorias_Fechas1"
'-------------------------------------------------------------------------------------------'
Partial Class rAuditorias_Fechas1
    Inherits vis2formularios.frmReporte

    Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try

            Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
            Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
            Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1))
            Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1))
            Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
            Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
            Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
            Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3))
            Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
            Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))
            Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5))
            Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5))
            Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6))
            Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6))

            Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
            Dim loConsulta As New StringBuilder()

            loConsulta.AppendLine("")
            loConsulta.AppendLine("CREATE TABLE #tmpAuditorias(Fecha2 NCHAR(10) COLLATE Database_Default, ")
            loConsulta.AppendLine("							Fecha NCHAR(10) COLLATE Database_Default, ")
            loConsulta.AppendLine("							Cod_Usu NCHAR(10) COLLATE Database_Default,")
            loConsulta.AppendLine("							Accion NCHAR(10) COLLATE Database_Default,  ")
            loConsulta.AppendLine("							Cantidad INTEGER,")
            loConsulta.AppendLine("	                        Dias INTEGER) ")
            loConsulta.AppendLine("")
            loConsulta.AppendLine("INSERT	INTO #tmpAuditorias(Fecha2, Fecha, Cod_Usu, Accion, Cantidad,Dias)")
            loConsulta.AppendLine("SELECT	CONVERT(NCHAR(10), Registro, 112)	AS Fecha2,	")
            loConsulta.AppendLine("			CONVERT(NCHAR(10), Registro, 103)	AS Fecha, ")
            loConsulta.AppendLine("			Cod_Usu								AS Cod_Usu,")
            loConsulta.AppendLine("			Accion								AS Accion,")
            loConsulta.AppendLine("			COUNT(*)							AS Cantidad,")
            loConsulta.AppendLine("			dbo.udf_GetISOWeekDay(Registro)         AS  Dias ")
            loConsulta.AppendLine("FROM 	Auditorias ")
            loConsulta.AppendLine("WHERE	Registro	BETWEEN " & lcParametro0Desde)
            loConsulta.AppendLine("			AND " & lcParametro0Hasta)
            loConsulta.AppendLine("		AND Cod_Usu	BETWEEN " & lcParametro1Desde)
            loConsulta.AppendLine("			AND " & lcParametro1Hasta)
            loConsulta.AppendLine("		AND Tabla	BETWEEN " & lcParametro2Desde)
            loConsulta.AppendLine("			AND " & lcParametro2Hasta)
            loConsulta.AppendLine("		AND Opcion	BETWEEN " & lcParametro3Desde)
            loConsulta.AppendLine("			AND " & lcParametro3Hasta)
            loConsulta.AppendLine("		AND Documento	BETWEEN " & lcParametro4Desde)
            loConsulta.AppendLine("			AND " & lcParametro4Hasta)
            loConsulta.AppendLine("		AND Codigo	BETWEEN " & lcParametro5Desde)
            loConsulta.AppendLine("			AND " & lcParametro5Hasta)
            loConsulta.AppendLine("		AND Cod_Emp	BETWEEN " & lcParametro6Desde)
            loConsulta.AppendLine("			AND " & lcParametro6Hasta)
            loConsulta.AppendLine("GROUP BY	CONVERT(NCHAR(10), Registro, 112),")
            loConsulta.AppendLine("			CONVERT(NCHAR(10), Registro, 103),")
            loConsulta.AppendLine("			Cod_Usu, Accion,dbo.udf_GetISOWeekDay(Registro)")
            loConsulta.AppendLine("")
            loConsulta.AppendLine("SELECT	Fecha, ")
            loConsulta.AppendLine("			Fecha2, ")
            loConsulta.AppendLine("         (CASE Dias ")
            loConsulta.AppendLine("                 WHEN 1 THEN 'LUNES'")
            loConsulta.AppendLine("                 WHEN 2 THEN 'MARTES'")
            loConsulta.AppendLine("                 WHEN 3 THEN 'MIERCOLES'")
            loConsulta.AppendLine("                 WHEN 4 THEN 'JUEVES'")
            loConsulta.AppendLine("                 WHEN 5 THEN 'VIERNES'")
            loConsulta.AppendLine("                 WHEN 6 THEN 'SABADO'")
            loConsulta.AppendLine("                 WHEN 7 THEN 'DOMINGO'")
            loConsulta.AppendLine("         END) AS Dia,")
            loConsulta.AppendLine("			COUNT(DISTINCT Cod_Usu) AS CantidadUsuarios,")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Apertura'	THEN Cantidad ELSE 0 END)) As Apertura, ")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Agregar'	THEN Cantidad ELSE 0 END)) As Agregar, ")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Anular'	THEN Cantidad ELSE 0 END)) As Anular, ")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Eliminar'	THEN Cantidad ELSE 0 END)) As Eliminar, ")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Modificar'	THEN Cantidad ELSE 0 END)) As Modificar,")
            loConsulta.AppendLine("			SUM((CASE WHEN Accion = 'Reporte'	THEN Cantidad ELSE 0 END)) As Reporte, ")
            loConsulta.AppendLine("			SUM(Cantidad) As TotalDia ")
            loConsulta.AppendLine("FROM		#tmpAuditorias")
            loConsulta.AppendLine("GROUP BY	Fecha2, Fecha,Dias ")
            loConsulta.AppendLine("ORDER BY	" & lcOrdenamiento)
            loConsulta.AppendLine("")
            loConsulta.AppendLine("")
            loConsulta.AppendLine("")

            Dim loServicios As New cusDatos.goDatos
            'Me.mEscribirConsulta(loConsulta.ToString())

            Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString, "curReportes")
            '-------------------------------------------------------------------------------------------------------
            ' Verificando si el select (tabla nº0) trae registros
            '-------------------------------------------------------------------------------------------------------

            If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
                Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
                                          "No se Encontraron Registros para los Parámetros Especificados. ", _
                                           vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
                                           "350px", _
                                           "200px")
            End If

            loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rAuditorias_Fechas1", laDatosReporte)

            Me.mTraducirReporte(loObjetoReporte)

            Me.mFormatearCamposReporte(loObjetoReporte)

            Me.crvrAuditorias_Fechas1.ReportSource = loObjetoReporte

        Catch loExcepcion As Exception

            Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
                          "No se pudo Completar el Proceso: " & loExcepcion.Message, _
                           vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
                           "auto", _
                           "auto")

        End Try

    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

        Try

            loObjetoReporte.Close()

        Catch loExcepcion As Exception

        End Try

    End Sub

End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo																			'
'-------------------------------------------------------------------------------------------'
' JFP: 15/12/08: Codigo inicial.															'
'-------------------------------------------------------------------------------------------'
' GCR: 26/03/09: Ajustes al diseño.															'
'-------------------------------------------------------------------------------------------'
' JJD: 15/08/09: Se incluyo el orden de los registros.										'
'-------------------------------------------------------------------------------------------'
' JJD: 19/12/12: Se incluyo el filtro de la empresa.										'
'-------------------------------------------------------------------------------------------'
' RJG: 21/01/13: Se agregó el número de usuarios del día. Se ajustó el SELECT para hacerlo	'
'				 más rápido.																'
'-------------------------------------------------------------------------------------------'
' RJG: 11/03/13: Se corrigió bug en totales de las auditorias.  							'
'-------------------------------------------------------------------------------------------'
' EAG: 28/08/15: Se agrego el campo dia.                          							'
'-------------------------------------------------------------------------------------------'


text:
The source code for Chip Hogg's website, [chogg.name](https://chogg.name).

For reproducibility, every page on the live site links directly back to its source (see [layouts/default.haml](https://github.com/chiphogg/chogg_name/blob/master/layouts/default.haml), near the bottom, to see how to do this).

Any source code on this blog is licensed under the Apache license, unless explicitly specified otherwise.


text:
package org.commonjava.indy.infinispan.data;

import org.commonjava.indy.action.IndyLifecycleException;
import org.commonjava.indy.action.StartupAction;
import org.commonjava.indy.data.StoreDataManager;

import javax.inject.Inject;

public class InfinispanStoreDataByPkgMapStartupAction
        implements StartupAction
{

    @Inject
    private StoreDataManager storeDataManager;

    @Override
    public void start()
            throws IndyLifecycleException
    {
        if ( storeDataManager instanceof InfinispanStoreDataManager )
        {
            ((InfinispanStoreDataManager)storeDataManager).initByPkgMap();
        }
    }

    @Override
    public int getStartupPriority()
    {
        return 11;
    }

    @Override
    public String getId()
    {
        return "Infinispan by-pkg map initializer";
    }
}


text:
#pragma once

/*
 * This header define the variables and structures used by both CDllInjectCliens, CDllInjectServer, and CDllInjectMgr
 */

namespace CWUtils
{
#ifdef __cplusplus
extern "C" {
#endif

#pragma pack( push, 8 )

typedef enum _PER_SERVER_EVT_INDEX
{
    PER_SERVER_EVT_INDEX_STOP = 0,
    PER_SERVER_EVT_INDEX_LOCAL_REQ_OK,
    PER_SERVER_EVT_INDEX_LOCAL_RSP,
    PER_SERVER_EVT_INDEX_REMOTE_REQ,
    PER_SERVER_EVT_INDEX_REMOTE_RSP_OK,
    PER_SERVER_EVT_COUNT
} PER_SERVER_EVT_INDEX;

typedef enum _PER_CLIENT_EVT_INDEX
{
    PER_CLIENT_EVT_INDEX_STOP = 0,
    PER_CLIENT_EVT_INDEX_LOCAL_REQ,
    PER_CLIENT_EVT_INDEX_LOCAL_RSP_OK,
    PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK,
    PER_CLIENT_EVT_INDEX_REMOTE_RSP,
    PER_CLIENT_EVT_COUNT
} PER_CLIENT_EVT_INDEX;

typedef enum _PER_SERVER_MUTEX_INDEX
{
    PER_SERVER_MUTEX_INDEX_REMOTE_INSTANCE = 0,
    PER_SERVER_MUTEX_INDEX_SHAREM_MEM_R2L,
    PER_SERVER_MUTEX_COUNT
} PER_SERVER_MUTEX_INDEX;

typedef enum _PER_SERVER_SM_INDEX
{
    PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL = 0,
    PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE,
    PER_SERVER_SM_COUNT
} PER_SERVER_SM_INDEX;

#define GenerateShareMemoryName( aBuf, aPid )                                                    \
    do                                                                                \
    {                                                                                \
        WCHAR wzGuid[38] = {};                                                                   \
        if ( FALSE == GetVolumeNameForVolumeMountPointW( L"C:\\", wzGuid, _countof( wzGuid ) ) ) \
        {                                                                                \
            wcsncpy_s( wzGuid, L"8ABEEEF5-29E8-4EE6-8F56-186D116618F7", _TRUNCATE );             \
        }                                                                                \
        _snwprintf_s( aBuf, _TRUNCATE, L"Global\\%ws-0x%04X", wzGuid, aPid );                    \
    } while ( 0 )

//This is a named share memory used to exchange all information needed to communicate between
//local(Osprey) and remote(Skype, Line...). All handles are created in Osprey side and duplicated to remote processes
//Be ware to use UINT64 instead of any pointer type since we need to communicate between 32 and 64 bit processes
typedef struct _DLL_INJECT_SERVER_SM_INIT
{
    struct _InitReq
    {
        struct _Local
        {
            UINT64 pLocalCtx;    //Per-process context with structure InjectClientInfo
            UINT64
                hRemoteProc;    //Remote process's handle. Job thread will use this to check whether the process exists instead of looking up ClientStateTable to speed up performance
            UINT64
                pfnFreeLibrary;    //Kernel32.dll's FreeLibrary address. This prevent FreeLibrary is hooked by others in the remote process
        } Local;

        struct _Remote
        {
            UINT64
                hEvtInitRsp;    //Per-client event. DuplicateHandle to DLL. Server wait this event and get status from InitRsp
            UINT64
                hDllInjectMgrAliveThread;    //Created in DllInjectMgr. DuplicateHandle to DLL. Used for monitoring DllInjectMgr's crash

            UINT64 hPerServerSm
                [PER_SERVER_SM_COUNT];    //Per-server share memory. DuplicateHandle to DLL. Used for data exchange (DLL_INJECT_SERVER_SM_DATA_HEADER)
            UINT64 hPerServerMutex
                [PER_SERVER_MUTEX_COUNT];    //Per-server mutex. DuplicateHandle to DLL. Used to ensure R2L's share memory integrity

            UINT64 hPerServerEvt[PER_SERVER_EVT_COUNT];
            UINT64 hPerClientEvt[PER_CLIENT_EVT_COUNT];
        } Remote;

        WCHAR wzServerDirPath[MAX_PATH];
        WCHAR wzClientCfgPath[MAX_PATH];
    } InitReq;

    struct _InitRsp
    {
        DWORD dwHookStatus;    //Win32 error code, use ERROR_SUCCESS to represent succeed
        UINT64 hModule;        //Remote DLL module's handle
    } InitRsp;
} DLL_INJECT_SERVER_SM_INIT, *PDLL_INJECT_SERVER_SM_INIT;

#define DLL_INJECT_SERVER_SM_DATA_HEADER_VER      0
#define DLL_INJECT_SERVER_SM_DATA_HEADER_MAX_SIZE ( 64 * 1024 )

typedef enum _DLL_INJECT_SERVER_SM_DATA_TYPE
{
    DLL_INJECT_SERVER_SM_DATA_TYPE_GENERAL_REQ = 0,
    DLL_INJECT_SERVER_SM_DATA_TYPE_GENERAL_RSP
} DLL_INJECT_SERVER_SM_DATA_TYPE;

//This is the general structure for per-server's private share memories between local(DllInjectServer) and remote(Skype, Line...)
//Be ware to use UINT64 instead of any pointer type since we need to communicate between 32 and 64 bit processes
typedef struct _DLL_INJECT_SERVER_SM_DATA_HEADER
{
    _DLL_INJECT_SERVER_SM_DATA_HEADER() :
        dwVersion( DLL_INJECT_SERVER_SM_DATA_HEADER_VER ),
        dwMaxSize( DLL_INJECT_SERVER_SM_DATA_HEADER_MAX_SIZE ),
        dwRemotePid( 0 ),
        hRemoteProc( NULL ),
        pLocalCtx( NULL )
    {
        ZeroMemory( &pReserved, sizeof( pReserved ) );
    }
    DWORD dwVersion;
    DWORD dwMaxSize;
    DWORD dwRemotePid;     //Remote process's PID
    UINT64 hRemoteProc;    //Remote process's handle
    UINT64 pLocalCtx;      //Per-process context with structure InjectClientInfo
    UINT64 pReserved[8];
    DLL_INJECT_SERVER_SM_DATA_TYPE uDataType;
    DWORD dwStatus;      //Useful if there is any error in the other side
    DWORD dwDataSize;    //Data size in bytes of the pData field
    CHAR pData[1];
} DLL_INJECT_SERVER_SM_DATA_HEADER, *PDLL_INJECT_SERVER_SM_DATA_HEADER;

typedef struct _DLL_INJECT_SERVER_SM_DATA_GENERAL_REQ
{
    DWORD dwReqSize;    //Data size in bytes of the pReq field
    CHAR pReq[1];
} DLL_INJECT_SERVER_SM_DATA_GENERAL_REQ;

typedef struct _DLL_INJECT_SERVER_SM_DATA_GENERAL_RSP
{
    DWORD dwRspSize;    //Data size in bytes of the pRsp field
    CHAR pRsp[1];
} DLL_INJECT_SERVER_SM_DATA_GENERAL_RSP;

#pragma pack( pop )

#ifdef __cplusplus
}
#endif

}    //End of namespace CWUtils


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Collema palmatilobum Hepp

### Remarks
null


text:
@implementation LCCollectionViewCell
@synthesize cellTitle;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        cellTitle               = [[UILabel alloc] initWithFrame:self.contentView.bounds];
        cellTitle.textAlignment = NSTextAlignmentCenter;
        cellTitle.lineBreakMode = NSLineBreakByWordWrapping;
        cellTitle.numberOfLines = 0;
        cellTitle.font          = DEFAULT_FONT(13);
        cellTitle.textColor     = [UIColor whiteColor];
        [self.contentView addSubview:cellTitle];

        self.backgroundColor = [UIColor orangeColor];
    }
    return self;
}
@end


text:
ENDPOINTS = {
        'api': 'http://www.behance.net/v2',
        'project': '/projects',
        'user': '/users',
        'wip': '/wips',
        'collection': '/collections',
        }

def url_join(*args):
    return "/".join(str(s).strip('/') for s in args)

from behance_python.api import *
from behance_python.project import *
from behance_python.exceptions import *
from behance_python.behance import *


text:
Fantastisch, **we hebben je aanmelding succesvol ontvangen**!

We zullen spoedig contact met je opnemen. In de tussentijd kun je de voortgang van je aanmelding
via deze portal in de gaten houden. Je gegevens zijn als volgt:

  * **E-mailadres**: {emailAddress}
  * **Toegangscode**: {accessCode}

Mocht je zelf nog vragen hebben, stuur dan een e-mailtje naar de
[stewardleiding](mailto:security@animecon.nl).


text:
#ifndef __HDLC_IOCTL_H__
#define __HDLC_IOCTL_H__

#define GENERIC_HDLC_VERSION 4	/* For synchronization with sethdlc utility */

#define CLOCK_DEFAULT   0	/* Default setting */
#define CLOCK_EXT	1	/* External TX and RX clock - DTE */
#define CLOCK_INT	2	/* Internal TX and RX clock - DCE */
#define CLOCK_TXINT	3	/* Internal TX and external RX clock */
#define CLOCK_TXFROMRX	4	/* TX clock derived from external RX clock */

#define ENCODING_DEFAULT	0 /* Default setting */
#define ENCODING_NRZ		1
#define ENCODING_NRZI		2
#define ENCODING_FM_MARK	3
#define ENCODING_FM_SPACE	4
#define ENCODING_MANCHESTER	5

#define PARITY_DEFAULT		0 /* Default setting */
#define PARITY_NONE		1 /* No parity */
#define PARITY_CRC16_PR0	2 /* CRC16, initial value 0x0000 */
#define PARITY_CRC16_PR1	3 /* CRC16, initial value 0xFFFF */
#define PARITY_CRC16_PR0_CCITT	4 /* CRC16, initial 0x0000, ITU-T version */
#define PARITY_CRC16_PR1_CCITT	5 /* CRC16, initial 0xFFFF, ITU-T version */
#define PARITY_CRC32_PR0_CCITT	6 /* CRC32, initial value 0x00000000 */
#define PARITY_CRC32_PR1_CCITT	7 /* CRC32, initial value 0xFFFFFFFF */

#define LMI_DEFAULT		0 /* Default setting */
#define LMI_NONE		1 /* No LMI, all PVCs are static */
#define LMI_ANSI		2 /* ANSI Annex D */
#define LMI_CCITT		3 /* ITU-T Annex A */
#define LMI_CISCO		4 /* The "original" LMI, aka Gang of Four */

typedef struct {
	unsigned int clock_rate; /* bits per second */
	unsigned int clock_type; /* internal, external, TX-internal etc. */
	unsigned short loopback;
} sync_serial_settings;          /* V.35, V.24, X.21 */

typedef struct {
	unsigned int clock_rate; /* bits per second */
	unsigned int clock_type; /* internal, external, TX-internal etc. */
	unsigned short loopback;
	unsigned int slot_map;
} te1_settings;                  /* T1, E1 */

typedef struct {
	unsigned short encoding;
	unsigned short parity;
} raw_hdlc_proto;

typedef struct {
	unsigned int t391;
	unsigned int t392;
	unsigned int n391;
	unsigned int n392;
	unsigned int n393;
	unsigned short lmi;
	unsigned short dce; /* 1 for DCE (network side) operation */
} fr_proto;

typedef struct {
	unsigned int dlci;
} fr_proto_pvc;          /* for creating/deleting FR PVCs */

typedef struct {
	unsigned int dlci;
	char master[IFNAMSIZ];	/* Name of master FRAD device */
}fr_proto_pvc_info;		/* for returning PVC information only */

typedef struct {
    unsigned int interval;
    unsigned int timeout;
} cisco_proto;

/* PPP doesn't need any info now - supply length = 0 to ioctl */

#endif /* __HDLC_IOCTL_H__ */


text:
JsonDB = function(host, user, passwd) {
	this._host = host;
	this._user = user;
	this._passwd = passwd;
	this.connect();
}

JsonDB.prototype._post = function(query, successCallback, failCallback) {
	var self = this;
	var data = {
		json: JSON.stringify(query)
	}
	if (this._user) data["user"] = this._user;
	if (this._passwd) data["password"] = this._passwd;

	jQuery.ajax(this._host, {
		method: 'post',
		dataType: 'json',
		data: data,
		success: function(data) {
			if ("error" in data) {
				console.error("[JsonDB] " + data["error"]);
				if (failCallback) failCallback.call(self, data["error"]);
			} else {
				if (successCallback) successCallback.apply(self, arguments);
			}

		},
		error: function() {
			console.log("Can't connect to server!");
			console.error(arguments);
			if (failCallback) failCallback.call(self, "Can't connect to server!");
		}
	});
};

JsonDB.prototype.connect = function(successCallback, failCallback) {
	this._post({
		type: "PING"
	}, function() {
		console.info("[JsonDB] Successfully connected!");
		if (successCallback) successCallback.apply(self, arguments);
	}, failCallback);
};

JsonDB.prototype.setUser = function(user) {
	this._user = user;
};

JsonDB.prototype.setPassword = function(passwd) {
	this._passwd = passwd;
};

JsonDB.prototype.createTable = function(tableName, successCallback, failCallback) {
	this._post({
		type: "CREATE TABLE",
		name: tableName
	}, successCallback, failCallback);
};

JsonDB.prototype.select = function(tableName, successCallback, failCallback) {
	this._post({
		type: "SELECT",
		name: tableName
	}, function(response) {
		var data = response.data;
		if (successCallback) successCallback.apply(self, [data, true]);
	}, failCallback);
};

JsonDB.prototype.write = function(tableName, data, successCallback, failCallback) {
	this._post({
		type: "WRITE",
		name: tableName,
		data: data
	}, successCallback, failCallback);
};

JsonDB.prototype.insert = function(tableName, row, successCallback, failCallback) {
	this._post({
		type: "INSERT INTO",
		name: tableName,
		row: row
	}, successCallback, failCallback);
};

JsonDB.prototype.remove = function(tableName, rowNr, successCallback, failCallback) {
	this._post({
		type: "DELETE",
		name: tableName,
		rowNr: rowNr
	}, successCallback, failCallback);
};

JsonDB.prototype.listTables = function(successCallback, failCallback) {
	this._post({
		type: "LIST TABLES"
	}, function(response) {
		var data = response.data;
		if (successCallback) successCallback.apply(self, [data]);
	}, failCallback);
};


text:
@interface Nav : UINavigationController

@end


text:
Installation
------------

If you have Anaconda Python, you can install yt using conda:

conda install yt

For any other Python distribution, you can install with pip:

pip install yt

Either of these methods should work on Linux, macOS, and Windows for 64-bit platforms. If you have a 32-bit Linux platform, pip is guaranteed to work. 32-bit Windows is not supported.

Please make sure that Jupyter is also installed (via the same methods). If you have issues with installation please show up at 9 am to get help.

Sample Datasets
---------------

The following datasets will need to be downloaded from http://yt-project.org/data:

http://yt-project.org/data/MHDSloshing.tar.gz
http://yt-project.org/data/IsolatedGalaxy.tar.gz
http://yt-project.org/data/snapshot_033.tar.gz

These are necessary to run the examples.

Jupyter Notebooks
-----------------

Please download the notebooks at http://github.com/jzuhone/cfa_yt_workshop so you
can follow along. Untar the sample data directories into the same directory as
these notebooks.

Houdini
-------

For those of you who would like to stay in the afternoon and learn how to use yt
to read your data into the industry standard Visual Effects package Houdini,
please download Houdini (the free version is fine) following these instructions
here: http://www.ytini.com/getstarted.html

Also please download the two *.hip* files here: http://www.ytini.com/listofHoudiniFiles.html


text:
package com.chrisomeara.pillar

import java.util.Date
import java.io.InputStream
import scala.collection.mutable
import scala.io.Source

object Parser {
  def apply(): Parser = new Parser

  private val MatchAttribute = """^-- (authoredAt|description|up|down):(.*)$""".r
}

class PartialMigration {
  var description: String = ""
  var authoredAt: String = ""
  var up = new mutable.MutableList[String]()
  var down: Option[mutable.MutableList[String]] = None

  def validate: Option[Map[String, String]] = {
    val errors = mutable.Map[String, String]()

    if (description.isEmpty) errors("description") = "must be present"
    if (authoredAt.isEmpty) errors("authoredAt") = "must be present"
    if (!authoredAt.isEmpty && authoredAtAsLong < 1) errors("authoredAt") = "must be a number greater than zero"
    if (up.isEmpty) errors("up") = "must be present"

    if (errors.nonEmpty) Some(errors.toMap) else None
  }

  def authoredAtAsLong: Long = {
    try {
      authoredAt.toLong
    } catch {
      case _:NumberFormatException => -1
    }
  }

}

class Parser {

  import Parser.MatchAttribute

  trait ParserState

  case object ParsingAttributes extends ParserState

  case object ParsingUp extends ParserState

  case object ParsingDown extends ParserState

  def parse(resource: InputStream): Migration = {
    val inProgress = new PartialMigration
    var state: ParserState = ParsingAttributes
    Source.fromInputStream(resource).getLines().foreach {
      case MatchAttribute("authoredAt", authoredAt) =>
        inProgress.authoredAt = authoredAt.trim
      case MatchAttribute("description", description) =>
        inProgress.description = description.trim
      case MatchAttribute("up", _) =>
        state = ParsingUp
      case MatchAttribute("down", _) =>
        inProgress.down = Some(new mutable.MutableList[String]())
        state = ParsingDown
      case cql =>
        if (!cql.isEmpty) {
          state match {
            case ParsingUp => inProgress.up += cql
            case ParsingDown => inProgress.down.get += cql
            case other => // ignored
          }
        }
    }
    inProgress.validate match {
      case Some(errors) => throw new InvalidMigrationException(errors)
      case None =>
        inProgress.down match {
          case Some(downLines) =>
            if (downLines.isEmpty) {
              Migration(inProgress.description, new Date(inProgress.authoredAtAsLong), inProgress.up.mkString("\n"), None)
            } else {
              Migration(inProgress.description, new Date(inProgress.authoredAtAsLong), inProgress.up.mkString("\n"), Some(downLines.mkString("\n")))
            }
          case None => Migration(inProgress.description, new Date(inProgress.authoredAtAsLong), inProgress.up.mkString("\n"))
        }
    }
  }
}


text:
<?php

namespace Sisgec\GestionEquipoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Caracteristica
 *
 * @ORM\Table(name="caracteristica")
 * @ORM\Entity
 */
class Caracteristica
{
    /**
     * @var integer
     *
     * @ORM\Column(name="Caracteristica_ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $caracteristicaId;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=255, nullable=false)
     */
    private $nombre;

    /**
     * @var string
     *
     * @ORM\Column(name="descripcion", type="string", length=255, nullable=false)
     */
    private $descripcion;

    /**
     * Get caracteristicaId
     *
     * @return integer
     */
    public function getCaracteristicaId()
    {
        return $this->caracteristicaId;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return Caracteristica
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return Caracteristica
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }
}


text:
package com.xiongyingqi.common.utils.ip;

import com.xiongyingqi.common.utils.string.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

/**
 * @author xiongyingqi
 * @since 17-5-11 下午9:23
 */
public abstract class RemoteIpUtils {
  private static final Logger logger = LoggerFactory.getLogger(RemoteIpUtils.class);

  public static final String LOW_CASE_X_FORWARD = "x-forwarded-for";
  private static String lastHeaderNameOfXForwardFor = null;
  public static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  public static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");

  public static String longToIpV4(long longIp) {
    int octet3 = (int) ((longIp >> 24) % 256);
    int octet2 = (int) ((longIp >> 16) % 256);
    int octet1 = (int) ((longIp >> 8) % 256);
    int octet0 = (int) ((longIp) % 256);
    return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
  }

  public static long ipV4ToLong(String ip) {
    String[] octets = ip.split("\\.");
    return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
        (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
  }

  public static boolean isIPv4Private(String ip) {
    long longIp = ipV4ToLong(ip);
    return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255")) ||
        (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255")) ||
        longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255");
  }

  public static boolean isIPv4Valid(String ip) {
    return pattern.matcher(ip).matches();
  }

  public static String getIpFromRequest(HttpServletRequest request) {
    if (request == null) {
      return null;
    }
    String ip;
    boolean found = false;
    if (logger.isDebugEnabled()) {
      logHeader(request);
    }
    String headerNameOfXForwardFor = getHeaderNameOfXForwardFor(request);
    if ((ip = request.getHeader(headerNameOfXForwardFor)) != null) {
      logger.debug("Found x-forwarded-for ip: {}", ip);
      StringTokenizer tokenizer = new StringTokenizer(ip, ",");
      while (tokenizer.hasMoreElements()) {
        ip = tokenizer.nextToken().trim();
        if (isIPv4Valid(ip) && !isIPv4Private(ip)) {
          found = true;
          break;
        }
      }
    }
    if (!found) {
      ip = request.getRemoteAddr();
    }
    logger.info("Found remote ip: {}; Is from x-forwarded-for? {}", ip, found);
    return ip;
  }

  protected static String getHeaderNameOfXForwardFor(HttpServletRequest request) {
    if (lastHeaderNameOfXForwardFor != null && StringUtils.hasText(request.getHeader(lastHeaderNameOfXForwardFor))) {
      return lastHeaderNameOfXForwardFor;
    }
    for (Enumeration headerNames = request.getHeaderNames(); headerNames
        .hasMoreElements(); ) {
      String headerName = (String) headerNames.nextElement();
      if (LOW_CASE_X_FORWARD.equalsIgnoreCase(headerName)) {
        lastHeaderNameOfXForwardFor = headerName;
        return headerName;
      }
    }
    return LOW_CASE_X_FORWARD;
  }

  private static void logHeader(HttpServletRequest httpServletRequest) {
    for (Enumeration headerNames = httpServletRequest.getHeaderNames(); headerNames
        .hasMoreElements(); ) {
      String headerName = (String) headerNames.nextElement();
      Enumeration<String> headers = httpServletRequest.getHeaders(headerName);
      logger.debug("Header: {}={}", headerName, Collections.list(headers));
    }
  }
}


text:
var trumpet = require('trumpet');
var through = require('through2');
var concat = require('concat-stream');
var u8 = require('utf8-stream');
var combine = require('stream-combiner2');
var ent = require('ent');

module.exports = function (streams) {
    if (!streams) streams = {};
    var tr = trumpet();
    tr.setMaxListeners(Infinity);
    Object.keys(streams).forEach(function (key) {
        var value = streams[key];
        var vstream;

        if (value === null) return;
        if (typeof value === 'object' && value.pipe) {
            vstream = through();
            value.pipe(vstream);
        }

        if (/:first$/.test(key)) {
            tr.select(key.replace(/:first$/,''), onmatch);
        }
        else tr.selectAll(key, onmatch);

        function onmatch (elem) {
            if (typeof value === 'string') {
                elem.createWriteStream().end(value);
            }
            else if (isStream(value)) {
                vstream.pipe(elem.createWriteStream());
            }
            else if (typeof value === 'object') {
                Object.keys(value).forEach(function (prop) {
                    var lprop = prop.toLowerCase();
                    var v = value[prop];
                    if (prop === '_html' && isStream(v)) {
                        v.pipe(elem.createWriteStream())
                    }
                    else if (prop === '_html' && (Buffer.isBuffer(v)
                    || typeof v === 'string')) {
                        elem.createWriteStream().end(v);
                    }
                    else if (prop === '_html') {
                        elem.createWriteStream().end(String(value[prop]));
                    }
                    else if (prop === '_text' && isStream(v)) {
                        v.pipe(encoder()).pipe(elem.createWriteStream());
                    }
                    else if (prop === '_text') {
                        elem.createWriteStream().end(ent.encode(String(v)));
                    }
                    else if (lprop === '_appendhtml' && (Buffer.isBuffer(v)
                    || typeof v === 'string')) {
                        var body = elem.createStream();
                        body.pipe(body, { end: false });
                        body.on('end', function () { body.end(v) });
                    }
                    else if (lprop === '_appendhtml' && isStream(v)) {
                        var body = elem.createStream();
                        body.pipe(body, { end: false });
                        body.on('end', function (){ v.pipe(body) });
                    }
                    else if (lprop === '_prependhtml' && (Buffer.isBuffer(v)
                    || typeof v === 'string')) {
                        var body = elem.createStream();
                        body.write(v);
                        body.pipe(body);
                    }
                    else if (lprop === '_prependhtml' && isStream(v)) {
                        var body = elem.createStream();
                        v.pipe(body, { end: false })
                        v.on('end', function () { body.pipe(body) });
                    }
                    else if ((prop === '_append' || lprop === '_appendtext')
                    && (Buffer.isBuffer(v) || typeof v === 'string')) {
                        var body = elem.createStream();
                        body.pipe(body, { end: false });
                        body.on('end', function () {
                            body.end(ent.encode(toStr(v)));
                        });
                    }
                    else if ((prop === '_append' || lprop === '_appendtext')
                    && isStream(v)) {
                        var body = elem.createStream();
                        body.pipe(body, { end: false });
                        body.on('end', function () {
                            v.pipe(encoder()).pipe(body);
                        });
                    }
                    else if ((prop === '_prepend' || lprop === '_prependtext')
                    && (Buffer.isBuffer(v) || typeof v === 'string')) {
                        var body = elem.createStream();
                        body.write(ent.encode(toStr(v)));
                        body.pipe(body);
                    }
                    else if ((prop === '_prepend' || lprop === '_prependtext')
                    && isStream(v)) {
                        var body = elem.createStream();
                        v.pipe(encoder()).pipe(body, { end: false })
                        v.on('end', function () { body.pipe(body) });
                    }
                    else {
                        var vp = value[prop];
                        if (vp && isObj(vp)) {
                            var cur = elem.getAttribute(prop) || '';
                            if (vp.append) cur += vp.append;
                            if (vp.prepend) cur = vp.prepend + cur;
                            elem.setAttribute(prop, cur);
                        }
                        else elem.setAttribute(prop, vp);
                    }
                });
            }
            else if (typeof value === 'function') {
                var stream = elem.createStream();
                stream.pipe(concat(function (body) {
                    stream.end(toStr(value(body.toString('utf8'))));
                }));
            }
            else {
                elem.createWriteStream().end(String(value));
            }
        }
    });
    return tr;
};

function isStream (s) {
    return s && typeof s.pipe === 'function';
}

function toStr (s) {
    if (Buffer.isBuffer(s) || typeof s === 'string') return s;
    return String(s);
}

function isObj (o) {
    return typeof o === 'object' && o !== null;
}

function encoder () {
    return combine(u8(), through(function (buf, enc, next) {
        this.push(ent.encode(buf.toString('utf8')));
        next();
    }));
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django_contact.secure

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ContactConfig',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('sent_url_redirect', models.CharField(default=b'/', help_text='Redirect page after sending the email. Only to non-ajax requests.', max_length=255)),
                ('auth_email_user', models.EmailField(help_text='User to authenticate to the SMTP server.', max_length=75)),
                ('auth_email_password', django_contact.secure.MD5Field(help_text='Password to authenticate to the SMTP server.', max_length=50)),
                ('auth_email_host', models.CharField(help_text='Host SMTP authentication server.', max_length=50)),
                ('auth_email_port', models.PositiveIntegerField(default=3306, help_text='Port SMTP authentication server. Default 3306.')),
                ('auth_email_use_tls', models.BooleanField(default=False, help_text='The SMTP server uses TLS (Transport Layer Security).')),
                ('recipient_list', models.CharField(help_text="E-mail list that will receive the contact. Separated by ','.", max_length=2048)),
                ('email_subject', models.CharField(help_text=b'Title the email that will be sent.', max_length=255)),
                ('email_html_content', models.TextField(help_text='HTML content of the email being sent.')),
                ('email_text_content', models.TextField(help_text='Plain Text content of the email being sent.')),
            ],
            options={
                'verbose_name': 'Contact Config',
                'verbose_name_plural': 'Contacts Config',
            },
            bases=(models.Model,),
        ),
    ]


text:
//-----------------------------------------------------------------
// Include Files
//-----------------------------------------------------------------
#include "Resource.h"	// include file to use resources
#include "GameEngine.h" // include file to use the game engine
#include "AbstractGame.h"

//-----------------------------------------------------------------
// Defines
//-----------------------------------------------------------------

#define GAME_ENGINE (GameEngine::GetSingleton())

//-----------------------------------------------------------------
// AbstractGame methods
//-----------------------------------------------------------------

void AbstractGame::GameInitialize(HINSTANCE hInstance)
{
	// Set the required values
	GAME_ENGINE->SetTitle("Game Engine version 2_10");
	GAME_ENGINE->SetIcon(IDI_BIG);
	//GAME_ENGINE->SetSmallIcon(IDI_SMALL);
	GAME_ENGINE->RunGameLoop(true);

	// Set the optional values
	GAME_ENGINE->SetWidth(640);
	GAME_ENGINE->SetHeight(480);
	GAME_ENGINE->SetFrameRate(60);
	//GAME_ENGINE->SetKeyList(String("QSDZ") + (TCHAR) VK_SPACE);
}


text:
// Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.

#ifndef SDC_CORE_H
#define SDC_CORE_H

#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <inttypes.h>

#include "util.h"
#include "serialize.h"
#include "script.h"
#include "ringsig.h"

enum GetMinFee_mode
{
    GMF_BLOCK,
    GMF_RELAY,
    GMF_SEND,
    GMF_ANON,
};

class CTransaction;

/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
    uint256 hash;
    unsigned int n;

    COutPoint() { SetNull(); }
    COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
    void SetNull() { hash = 0; n = (unsigned int) -1; }
    bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }

    friend bool operator<(const COutPoint& a, const COutPoint& b)
    {
        return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
    }

    friend bool operator==(const COutPoint& a, const COutPoint& b)
    {
        return (a.hash == b.hash && a.n == b.n);
    }

    friend bool operator!=(const COutPoint& a, const COutPoint& b)
    {
        return !(a == b);
    }

    std::string ToString() const
    {
        return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
    }

    void print() const
    {
        LogPrintf("%s\n", ToString().c_str());
    }
};

/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
    CTransaction* ptx;
    unsigned int n;

    CInPoint() { SetNull(); }
    CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
    void SetNull() { ptx = NULL; n = (unsigned int) -1; }
    bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};

/** An input of a transaction.  It contains the location of the previous
 * transaction's output that it claims and a signature that matches the
 * output's public key.
 */
class CTxIn
{
public:
    COutPoint prevout;
    CScript scriptSig;
    unsigned int nSequence;

    CTxIn()
    {
        nSequence = std::numeric_limits<unsigned int>::max();
    }

    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
    {
        prevout = prevoutIn;
        scriptSig = scriptSigIn;
        nSequence = nSequenceIn;
    }

    CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
    {
        prevout = COutPoint(hashPrevTx, nOut);
        scriptSig = scriptSigIn;
        nSequence = nSequenceIn;
    }

    IMPLEMENT_SERIALIZE
    (
        READWRITE(prevout);
        READWRITE(scriptSig);
        READWRITE(nSequence);
    )

    bool IsFinal() const
    {
        return (nSequence == std::numeric_limits<unsigned int>::max());
    }

    bool IsAnonInput() const
    {
        return (scriptSig.size() >= MIN_ANON_IN_SIZE
            && scriptSig[0] == OP_RETURN
            && scriptSig[1] == OP_ANON_MARKER);
    }

    friend bool operator==(const CTxIn& a, const CTxIn& b)
    {
        return (a.prevout   == b.prevout &&
                a.scriptSig == b.scriptSig &&
                a.nSequence == b.nSequence);
    }

    friend bool operator!=(const CTxIn& a, const CTxIn& b)
    {
        return !(a == b);
    }

    std::string ToString() const
    {
        std::string str;
        str += "CTxIn(";
        str += prevout.ToString();
        if (prevout.IsNull())
            str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
        else
            str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
        if (nSequence != std::numeric_limits<unsigned int>::max())
            str += strprintf(", nSequence=%u", nSequence);
        str += ")";
        return str;
    }

    void print() const
    {
        LogPrintf("%s\n", ToString().c_str());
    }

    void ExtractKeyImage(ec_point& kiOut) const
    {
        kiOut.resize(EC_COMPRESSED_SIZE);
        memcpy(&kiOut[0], prevout.hash.begin(), 32);
        kiOut[32] = prevout.n & 0xFF;
    };

    int ExtractRingSize() const
    {
        return (prevout.n >> 16) & 0xFFFF;
    };

};

/** An output of a transaction.  It contains the public key that the next input
 * must be able to sign with to claim it.
 */
class CTxOut
{
public:
    int64_t nValue;
    CScript scriptPubKey;

    CTxOut()
    {
        SetNull();
    }

    CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
    {
        nValue = nValueIn;
        scriptPubKey = scriptPubKeyIn;
    }

    IMPLEMENT_SERIALIZE
    (
        READWRITE(nValue);
        READWRITE(scriptPubKey);
    )

    void SetNull()
    {
        nValue = -1;
        scriptPubKey.clear();
    }

    bool IsNull()
    {
        return (nValue == -1);
    }

    void SetEmpty()
    {
        nValue = 0;
        scriptPubKey.clear();
    }

    bool IsEmpty() const
    {
        return (nValue == 0 && scriptPubKey.empty());
    }

    bool IsAnonOutput() const
    {
        return (scriptPubKey.size() >= MIN_ANON_OUT_SIZE
            && scriptPubKey[0] == OP_RETURN
            && scriptPubKey[1] == OP_ANON_MARKER);
    }

    uint256 GetHash() const
    {
        return SerializeHash(*this);
    }

    friend bool operator==(const CTxOut& a, const CTxOut& b)
    {
        return (a.nValue       == b.nValue &&
                a.scriptPubKey == b.scriptPubKey);
    }

    friend bool operator!=(const CTxOut& a, const CTxOut& b)
    {
        return !(a == b);
    }

    friend bool operator<(const CTxOut& a, const CTxOut& b)
    {
        return (a.nValue < b.nValue);
    }

    std::string ToString() const
    {
        if (IsEmpty()) return "CTxOut(empty)";
        return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
    }

    void print() const
    {
        LogPrintf("%s\n", ToString().c_str());
    }

    CPubKey ExtractAnonPk() const
    {
        // always use IsAnonOutput to check length
        return CPubKey(&scriptPubKey[2+1], EC_COMPRESSED_SIZE);
    };
};

class CKeyImageSpent
{
// stored in txdb, key is keyimage
public:
    CKeyImageSpent() {};

    CKeyImageSpent(uint256& txnHash_, uint32_t inputNo_, int64_t nValue_)
    {
        txnHash = txnHash_;
        inputNo = inputNo_;
        nValue  = nValue_;
    };

    uint256 txnHash;    // hash of spending transaction
    uint32_t inputNo;   // keyimage is for inputNo of txnHash
    int64_t nValue;     // reporting only

    IMPLEMENT_SERIALIZE
    (
        READWRITE(txnHash);
        READWRITE(inputNo);
        READWRITE(nValue);
    )
};

class CAnonOutput
{
// stored in txdb, key is pubkey
public:

    CAnonOutput() {};

    CAnonOutput(COutPoint& outpoint_, int64_t nValue_, int nBlockHeight_, uint8_t nCompromised_)
    {
        outpoint = outpoint_;
        nValue = nValue_;
        nBlockHeight = nBlockHeight_;
        nCompromised = nCompromised_;
    };

    COutPoint outpoint;
    int64_t nValue;         // rather store 2 bytes, digit + power 10 ?
    int nBlockHeight;
    uint8_t nCompromised;   // TODO: mark if output can be identified (spent with ringsig 1)
    IMPLEMENT_SERIALIZE
    (
        READWRITE(outpoint);
        READWRITE(nValue);
        READWRITE(nBlockHeight);
        READWRITE(nCompromised);
    )
};

class CAnonOutputCount
{ // CountAllAnonOutputs
public:

    CAnonOutputCount()
    {
        nValue = 0;
        nExists = 0;
        nSpends = 0;
        nOwned = 0;
        nLeastDepth = 0;
        nCompromised = 0;
    }

    CAnonOutputCount(int64_t nValue_, int nExists_, int nSpends_, int nOwned_, int nLeastDepth_, int nCompromised_)
    {
        nValue = nValue_;
        nExists = nExists_;
        nSpends = nSpends_;
        nOwned = nOwned_;
        nLeastDepth = nLeastDepth_;
        nCompromised = nCompromised_;
    }

    void set(int64_t nValue_, int nExists_, int nSpends_, int nOwned_, int nLeastDepth_, int nCompromised_)
    {
        nValue = nValue_;
        nExists = nExists_;
        nSpends = nSpends_;
        nOwned = nOwned_;
        nLeastDepth = nLeastDepth_;
        nCompromised = nCompromised_;
    }

    void addCoin(int nCoinDepth, int64_t nCoinValue)
    {
        nExists++;
        nValue = nCoinValue;
        if (nCoinDepth < nLeastDepth)
            nLeastDepth = nCoinDepth;
    }

    void updateDepth(int nCoinDepth, int64_t nCoinValue)
    {
        nValue = nCoinValue;
        if (nLeastDepth == 0
            || nCoinDepth < nLeastDepth)
            nLeastDepth = nCoinDepth;
    }

    void incSpends(int64_t nCoinValue)
    {
        nSpends++;
        nValue = nCoinValue;
    }

    void decSpends(int64_t nCoinValue)
    {
        nSpends--;
        nValue = nCoinValue;
    }

    void incExists(int64_t nCoinValue)
    {
        nExists++;
        nValue = nCoinValue;
    }

    void decExists(int64_t nCoinValue)
    {
        nExists--;
        nValue = nCoinValue;
    }

    int64_t nValue;
    int nExists;
    int nSpends;
    int nOwned; // todo
    int nLeastDepth;
    int nCompromised;

};

class CStakeModifier
{
// for CheckKernel
public:
    CStakeModifier() {};
    CStakeModifier(uint64_t modifier, uint256 modifierv2, int height, int64_t time)
        : nModifier(modifier), bnModifierV2(modifierv2), nHeight(height), nTime(time)
    {};

    uint64_t nModifier;
    uint256 bnModifierV2;
    int nHeight;
    int64_t nTime;
};

#endif  // SDC_CORE_H


text:
module.exports = {
  verbose: true,
  preset: 'jest-expo',
  testPathIgnorePatterns: ['node_modules', '.history'],
  testMatch: ['<rootDir>/modules/**/client-react/**/*.test.native.[jt]s?(x)'],
  rootDir: '../..',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  modulePathIgnorePatterns: [
    '<rootDir>/node_modules/react-native/Libraries/react-native/',
    '<rootDir>/node_modules/react-native/Libraries/vendor/core/whatwg-fetch.js',
    '<rootDir>/node_modules/react-native/jest/',
    '<rootDir>/node_modules/haul/',
    '<rootDir>/packages/mobile/.expo/',
    '<rootDir>/packages/mobile/node_modules/'
  ],
  globals: {
    __CLIENT__: true,
    __SERVER__: false,
    __TEST__: true
  }
};


text:
//Date: 2017-3-2
//Author:lidengke
//Desc: query usage of CpuUsage

#ifndef __CPU_USAGE_H__
#define __CPU_USAGE_H__

#include "TypeDef.h"
#include "SystemTime.h"

#ifdef __WINDOWS__
#	include <Pdh.h>
#endif //__WINDOWS__

#include <time.h>
#include <vector>

class CpuUsage
{
public:
	CpuUsage();
	~CpuUsage();

	//get the usage rate of total processor (%)
	float GetTotal();

	//get the usage rate of every logical processores; total was put at the first
	bool GetEvery(std::vector<float> &vecUsage);

	static float Calc(const SystemTime &begin, const SystemTime &end);

private:
	bool Init();
	void Destory();

private:
	SystemTime m_lastSystemTime;

#ifdef __WINDOWS__
	std::vector<HCOUNTER> m_vecHcounter;
	HQUERY m_hQuery;
#else
	//record system time of all processores last call
	std::vector<SystemTime> m_vecLastTime;
#endif //__WINDOWS__
};

#endif //__CPU_USAGE_H__


text:
package de.larmic.joinfaces.test;

import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Simple chaining builder to create JSF scoped bean that should be unit tested.
 */
public class JsfSpringBeanBuilder {

    private final Map<String, String> parameterMap = new HashMap<>();
    private final ApplicationContext context;

    public JsfSpringBeanBuilder(ApplicationContext context) {
        this.context = context;
    }

    public JsfSpringBeanBuilder withExternalParameter(String key, String value) {
        this.parameterMap.put(key, value);
        return this;
    }

    public <T> T build(Class<T> beanClass) {
        new FacesContextMock()
                .withExternalParameters(parameterMap)
                .replaceIn(context);

        return context.getBean(beanClass);
    }
}


text:
require 'migration_helpers'
class CreateGroups < ActiveRecord::Migration
  extend MigrationHelpers

  def self.up
    create_table :groups do |t|
      t.string    :name
      t.string    :description
      t.string    :created_by
      t.string    :updated_by
      t.timestamps
    end

    group_names = ['admin','developer','customer']
    group_names.each do |name|
      Group.create :name => name, :created_by => 'system', :updated_by => 'system'
    end

    create_fixture(:groups)
    add_index :groups, :name
  end

  def self.down
    drop_table :groups
  end
end