code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE BangPatterns #-} module RGB565 (toRGB565, toRGB565Hex, to4Hex, toHex) where import Data.Bits (shiftL, shiftR, (.|.)) import Data.Word (Word8()) toRGB565Hex :: (Word8, Word8, Word8) -> String toRGB565Hex rgb = to4Hex (toRGB565 rgb) toRGB565 :: (Word8, Word8, Word8) -> Int toRGB565 (r, g, b) = r' .|. g' .|. b' where r' = ((toInt r) `shiftR` 3) `shiftL` 11 g' = ((toInt g) `shiftR` 2) `shiftL` 5 b' = (toInt b) `shiftR` 3 toInt :: Word8 -> Int toInt = fromIntegral toHex :: Int -> String toHex = go "" where go !acc x = case quotRem x 16 of (0,r) -> hex r : acc (q,r) -> go (hex r : acc) q to4Hex :: Int -> String to4Hex x = go hx where hx = toHex x go :: String -> String go !str | length str < 4 = go ('0':str) | otherwise = str hex :: Int -> Char hex 0 = '0' hex 1 = '1' hex 2 = '2' hex 3 = '3' hex 4 = '4' hex 5 = '5' hex 6 = '6' hex 7 = '7' hex 8 = '8' hex 9 = '9' hex 10 = 'A' hex 11 = 'B' hex 12 = 'C' hex 13 = 'D' hex 14 = 'E' hex 15 = 'F' hex x = error $ "Exceeded bounds of 'hex' - " ++ show x
cirquit/Personal-Repository
Haskell/Playground/UTFTConverter/src/RGB565.hs
mit
1,139
0
13
353
534
287
247
44
2
{-# LANGUAGE TemplateHaskell , DeriveDataTypeable #-} module Types where import Control.Applicative import Control.Lens import Data.Acid import Data.Aeson import Data.Aeson.TH import Data.SafeCopy import Data.Typeable import qualified Data.IntMap as I import qualified Data.Text.Lazy as T tupleMap :: (a -> b) -> (a,a) -> (b,b) tupleMap f = bimap f f data Play = Rock | Paper | Scissors deriving (Eq,Show,Enum,Read) data RoundResult = Win | Draw | Lose deriving (Eq,Show,Read) invertRoundResult :: RoundResult -> RoundResult invertRoundResult Win = Lose invertRoundResult Lose = Win invertRoundResult Draw = Draw calculateRoundResult :: Play -> Play -> RoundResult calculateRoundResult Rock Paper = Lose calculateRoundResult Paper Scissors = Lose calculateRoundResult Scissors Rock = Lose calculateRoundResult x y | x == y = Draw | otherwise = invertRoundResult $ calculateRoundResult y x data Player = Player { _name :: T.Text , _playerIdNum :: Int } deriving (Eq,Show,Typeable) makeLenses ''Player data Game = Game { _participants :: (Int,Int) , _plays :: (Maybe Play, Maybe Play) , _lastPlay :: (Maybe Play, Maybe Play) , _results :: [RoundResult] , _winThreshold :: Int , _winner :: Maybe Int } deriving (Eq,Show,Typeable) makeLenses ''Game data App = App { _players :: I.IntMap Player , _games :: I.IntMap Game } deriving (Eq,Show,Typeable) makeLenses ''App deriveSafeCopy 0 'base ''Play deriveSafeCopy 0 'base ''RoundResult deriveSafeCopy 0 'base ''Game deriveSafeCopy 0 'base ''Player deriveSafeCopy 0 'base ''App $(deriveJSON defaultOptions ''Play) $(deriveJSON defaultOptions ''RoundResult) $(deriveJSON defaultOptions {fieldLabelModifier = drop 1} ''Game) $(deriveJSON defaultOptions {fieldLabelModifier = drop 1} ''Player) $(deriveJSON defaultOptions {fieldLabelModifier = drop 1} ''App)
edwardwas/rockPaperScissors
server/src/Types.hs
mit
1,874
0
10
322
649
344
305
55
1
-- | Like Throughput, but send every ping from a different process -- (i.e., require a lightweight connection per ping) {-# LANGUAGE BangPatterns #-} import Hypervisor.XenStore import Hypervisor.DomainInfo import Hypervisor.Debug import Data.List import Control.Monad import Control.Applicative import Control.Concurrent import Control.Distributed.Process import Control.Distributed.Process.Node import Network.Transport.IVC (createTransport, waitForDoms, waitForKey) import Data.Binary (encode, decode) counter :: Process () counter = go 0 where go :: Int -> Process () go !n = do b <- expect case b of Nothing -> go (n + 1) Just them -> send them n >> go 0 count :: Int -> ProcessId -> Process () count n them = do replicateM_ n . spawnLocal $ send them (Nothing :: Maybe ProcessId) go 0 where go :: Int -> Process () go n' | n' == n = liftIO $ writeDebugConsole "done\n" | otherwise = do us <- getSelfPid send them (Just us) m <- expect :: Process Int go (n' + m) initialProcess :: XenStore -> String -> Process () initialProcess xs "SERVER" = do us <- getSelfPid liftIO $ xsWrite xs "/process/counter-pid" (show (encode us)) counter initialProcess xs "CLIENT" = do them <- liftIO $ decode . read <$> waitForKey xs "/process/counter-pid" count 10 them -- perfom badly for large n main :: IO () main = do xs <- initXenStore Right transport <- createTransport xs doms <- sort <$> waitForDoms xs 2 me <- xsGetDomId xs let role = if me == head doms then "SERVER" else "CLIENT" node <- newLocalNode transport initRemoteTable runProcess node $ initialProcess xs role
hackern/network-transport-ivc
benchmarks/Spawns/Main.hs
mit
1,681
0
14
372
554
269
285
48
2
printHello = print "hello world" reverseList [] = [] reverseList (x:xs) = reverseList xs ++ [x]
ddccffvv/fun-with-haskell
first_steps.hs
mit
97
0
7
17
46
23
23
3
1
{-# LANGUAGE FlexibleInstances #-} module Cache.InMemory where import qualified Data.Map as M import Control.Applicative import Control.Monad.State.Class import Cache import Types data InMemoryCache instance Cache (FactorizerM InMemoryCache ui) where cacheWrite k v = FM $ modify $ M.insert (show k) (show v) cacheRead k = FM $ M.lookup k <$> get
mg50avant/factorizer
src/Cache/InMemory.hs
mit
356
0
9
59
110
61
49
-1
-1
{-| Module: Flaw.Oil.ClientRepo Description: Oil client repo. License: MIT -} {-# LANGUAGE PatternSynonyms, ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-missing-pattern-synonym-signatures #-} module Flaw.Oil.ClientRepo ( ClientRepo() , openClientRepo , clientRepoRevision , clientRepoGetRevisionValue , clientRepoChange , clientRepoGetKeysPrefixed , ClientRepoPushState(..) , pushClientRepo , isClientRepoPushEmpty , ClientRepoPullInfo(..) , pullClientRepo , cleanupClientRepo , syncClientRepo ) where import Control.Exception import Control.Monad import qualified Data.ByteString as B import Data.Int import qualified Data.Text as T import Foreign.C.Types import Flaw.Book import Flaw.Data.Sqlite import Flaw.Exception import Flaw.Oil.Repo data ClientRepo = ClientRepo { clientRepoDb :: !SqliteDb , clientRepoStmtManifestGet :: !SqliteStmt , clientRepoStmtManifestSet :: !SqliteStmt , clientRepoStmtGetKeyItems :: !SqliteStmt , clientRepoStmtGetKeyItemsByOneItemId :: !SqliteStmt , clientRepoStmtGetKeyServerItem :: !SqliteStmt , clientRepoStmtGetKeyItemKey :: !SqliteStmt , clientRepoStmtGetKeyItemRevValue :: !SqliteStmt , clientRepoStmtAddKeyItem :: !SqliteStmt , clientRepoStmtChangeKeyItemRev :: !SqliteStmt , clientRepoStmtChangeKeyItemRevValue :: !SqliteStmt , clientRepoStmtSelectKeysToPush :: !SqliteStmt , clientRepoStmtGetPushLag :: !SqliteStmt , clientRepoStmtMassChangeRev :: !SqliteStmt , clientRepoStmtEnumerateKeysBegin :: !SqliteStmt , clientRepoStmtEnumerateKeysBeginEnd :: !SqliteStmt , clientRepoStmtAddChunk :: !SqliteStmt , clientRepoStmtPreCutChunks :: !SqliteStmt , clientRepoStmtCutChunks :: !SqliteStmt , clientRepoStmtGetUpperRevision :: !SqliteStmt } openClientRepo :: T.Text -> IO (ClientRepo, IO ()) openClientRepo fileName = describeException "failed to open oil client repo" $ withSpecialBook $ \bk -> do -- open db db <- book bk $ openRepoDb fileName clientRepoVersion -- enable normal synchronous mode (db correctness is a concern, but durability is not for client repo) sqliteExec db $ T.pack "PRAGMA synchronous = NORMAL" -- ensure tables and indices exist -- manifest table sqliteExec db $ T.pack "CREATE TABLE IF NOT EXISTS manifest (\ \key INTEGER PRIMARY KEY, \ \value ANY NOT NULL)" -- items table sqliteExec db $ T.pack "CREATE TABLE IF NOT EXISTS items (\ \id INTEGER PRIMARY KEY, \ \value BLOB NOT NULL, \ \key BLOB NOT NULL, \ \rev INTEGER NOT NULL)" -- items_key_rev index sqliteExec db $ T.pack "CREATE UNIQUE INDEX IF NOT EXISTS items_key_rev ON items (key, rev)" -- items_rev_partial index sqliteExec db $ T.pack $ "CREATE INDEX IF NOT EXISTS items_rev_partial ON items (rev) WHERE\ \ rev = " ++ show (ItemRevClient :: Int) ++ " OR rev = " ++ show (ItemRevTransient :: Int) ++ " OR rev = " ++ show (ItemRevPostponed :: Int) -- chunks table sqliteExec db $ T.pack "CREATE TABLE IF NOT EXISTS chunks (\ \prerev INTEGER PRIMARY KEY, \ \postrev INTEGER NOT NULL)" -- create statements let createStmt str = book bk $ sqliteStmt db $ T.pack str stmtManifestGet <- createStmt "SELECT value FROM manifest WHERE key = ?1" stmtManifestSet <- createStmt "INSERT OR REPLACE INTO manifest (key, value) VALUES (?1, ?2)" stmtGetKeyItems <- createStmt "SELECT id, rev FROM items WHERE key = ?1 AND rev < 0" stmtGetKeyItemsByOneItemId <- createStmt "SELECT id, rev FROM items WHERE key = (SELECT key FROM items WHERE id = ?1) AND rev < 0" stmtGetKeyServerItem <- createStmt "SELECT id, rev FROM items WHERE key = ?1 AND rev > 0 ORDER BY rev DESC LIMIT 1" stmtGetKeyItemKey <- createStmt "SELECT key FROM items WHERE id = ?1" stmtGetKeyItemRevValue <- createStmt "SELECT rev, value FROM items WHERE id = ?1" stmtAddKeyItem <- createStmt "INSERT OR REPLACE INTO items (key, value, rev) VALUES (?1, ?2, ?3)" stmtChangeKeyItemRev <- createStmt "UPDATE OR REPLACE items SET rev = ?2 WHERE id = ?1" stmtChangeKeyItemRevValue <- createStmt "UPDATE items SET rev = ?2, value = ?3 WHERE id = ?1" stmtSelectKeysToPush <- createStmt $ "SELECT id, key, value FROM items WHERE rev = " ++ show (ItemRevClient :: Int) ++ " ORDER BY id LIMIT ?1" stmtGetPushLag <- createStmt $ "SELECT COUNT(*) FROM items WHERE rev = " ++ show (ItemRevClient :: Int) stmtMassChangeRev <- createStmt "UPDATE OR REPLACE items SET rev = ?2 WHERE rev = ?1" stmtEnumerateKeysBegin <- createStmt "SELECT DISTINCT key FROM items WHERE key >= ?1 ORDER BY key" stmtEnumerateKeysBeginEnd <- createStmt "SELECT DISTINCT key FROM items WHERE key >= ?1 AND key < ?2 ORDER BY key" stmtAddChunk <- createStmt "INSERT INTO chunks (prerev, postrev) VALUES (?1, ?2)" stmtPreCutChunks <- createStmt "SELECT MAX(postrev) FROM chunks WHERE prerev <= ?1" stmtCutChunks <- createStmt "DELETE FROM chunks WHERE prerev <= ?1" stmtGetUpperRevision <- createStmt "SELECT MIN(prerev) FROM chunks" return ClientRepo { clientRepoDb = db , clientRepoStmtManifestGet = stmtManifestGet , clientRepoStmtManifestSet = stmtManifestSet , clientRepoStmtGetKeyItems = stmtGetKeyItems , clientRepoStmtGetKeyItemsByOneItemId = stmtGetKeyItemsByOneItemId , clientRepoStmtGetKeyServerItem = stmtGetKeyServerItem , clientRepoStmtGetKeyItemKey = stmtGetKeyItemKey , clientRepoStmtGetKeyItemRevValue = stmtGetKeyItemRevValue , clientRepoStmtAddKeyItem = stmtAddKeyItem , clientRepoStmtChangeKeyItemRev = stmtChangeKeyItemRev , clientRepoStmtChangeKeyItemRevValue = stmtChangeKeyItemRevValue , clientRepoStmtSelectKeysToPush = stmtSelectKeysToPush , clientRepoStmtGetPushLag = stmtGetPushLag , clientRepoStmtMassChangeRev = stmtMassChangeRev , clientRepoStmtEnumerateKeysBegin = stmtEnumerateKeysBegin , clientRepoStmtEnumerateKeysBeginEnd = stmtEnumerateKeysBeginEnd , clientRepoStmtAddChunk = stmtAddChunk , clientRepoStmtPreCutChunks = stmtPreCutChunks , clientRepoStmtCutChunks = stmtCutChunks , clientRepoStmtGetUpperRevision = stmtGetUpperRevision } -- Item pseudo revs. -- Correct revisions (commited to server) are > 0. -- If it's < 0, it's a special pseudo-revision. -- Zero revision means no revision. -- client change based on 'server' in case of no conflict pattern ItemRevClient = -1 -- client change based on 'server' which is in process of committing to server pattern ItemRevTransient = -2 -- client change based on 'transient', waiting for results of commit of 'transient' pattern ItemRevPostponed = -3 -- Manifest keys. pattern ManifestKeyGlobalRevision = 0 type ItemId = Int64 getManifestValue :: ClientRepo -> CInt -> Int64 -> IO Int64 getManifestValue ClientRepo { clientRepoStmtManifestGet = stmtManifestGet } key defaultValue = sqliteQuery stmtManifestGet $ \query -> do sqliteBind query 1 key r <- sqliteStep query if r then sqliteColumn query 0 else return defaultValue setManifestValue :: ClientRepo -> CInt -> Int64 -> IO () setManifestValue ClientRepo { clientRepoStmtManifestSet = stmtManifestSet } key value = sqliteQuery stmtManifestSet $ \query -> do sqliteBind query 1 key sqliteBind query 2 value sqliteFinalStep query -- | Get global revision in client repo. -- Tries to increase global revision found in manifest, by using chunks, and then removes those chunks. clientRepoRevision :: ClientRepo -> IO Revision clientRepoRevision repo@ClientRepo { clientRepoStmtPreCutChunks = stmtPreCutChunks , clientRepoStmtCutChunks = stmtCutChunks } = do -- get global revision from manifest, and try to increase it using chunks let preCutChunks globalRevision = do preCutRevision <- sqliteQuery stmtPreCutChunks $ \query -> do sqliteBind query 1 globalRevision r <- sqliteStep query unless r $ throwIO $ DescribeFirstException "failed to get pre-cut revision" sqliteColumn query 0 -- try again if it actually increased if preCutRevision > globalRevision then preCutChunks preCutRevision else return globalRevision firstGlobalRevision <- getManifestValue repo ManifestKeyGlobalRevision 0 globalRevision <- preCutChunks firstGlobalRevision -- if global revision has actually incresed, remember it in manifest when (globalRevision > firstGlobalRevision) $ setManifestValue repo ManifestKeyGlobalRevision globalRevision -- remove chunks behind global revision sqliteQuery stmtCutChunks $ \query -> do sqliteBind query 1 globalRevision sqliteFinalStep query return globalRevision addKeyItem :: ClientRepo -> B.ByteString -> B.ByteString -> Revision -> IO () addKeyItem ClientRepo { clientRepoStmtAddKeyItem = stmtAddKeyItem } key value revision = sqliteQuery stmtAddKeyItem $ \query -> do sqliteBind query 1 key sqliteBind query 2 value sqliteBind query 3 revision sqliteFinalStep query changeKeyItemRevision :: ClientRepo -> ItemId -> Revision -> IO () changeKeyItemRevision ClientRepo { clientRepoStmtChangeKeyItemRev = stmtChangeKeyItemRev } itemId newRevision = sqliteQuery stmtChangeKeyItemRev $ \query -> do sqliteBind query 1 itemId sqliteBind query 2 newRevision sqliteFinalStep query getKeyItemRevisionValue :: ClientRepo -> ItemId -> IO (Revision, B.ByteString) getKeyItemRevisionValue ClientRepo { clientRepoStmtGetKeyItemRevValue = stmtGetKeyItemRevValue } itemId = sqliteQuery stmtGetKeyItemRevValue $ \query -> do sqliteBind query 1 itemId r <- sqliteStep query unless r $ throwIO $ DescribeFirstException "failed to get key item revision and value" revision <- sqliteColumn query 0 value <- sqliteColumn query 1 return (if revision > 0 then revision else 0, value) changeKeyItemRevisionValue :: ClientRepo -> ItemId -> Revision -> B.ByteString -> IO () changeKeyItemRevisionValue ClientRepo { clientRepoStmtChangeKeyItemRevValue = stmtChangeKeyItemRevValue } itemId newRevision newValue = sqliteQuery stmtChangeKeyItemRevValue $ \query -> do sqliteBind query 1 itemId sqliteBind query 2 newRevision sqliteBind query 3 newValue sqliteFinalStep query -- | Collection of items with the same key. data KeyItems = KeyItems { keyItemsClientItemId :: {-# UNPACK #-} !ItemId , keyItemsTransientItemId :: {-# UNPACK #-} !ItemId , keyItemsPostponedItemId :: {-# UNPACK #-} !ItemId } deriving Show fillKeyItems :: SqliteQuery -> IO KeyItems fillKeyItems query = step KeyItems { keyItemsClientItemId = 0 , keyItemsTransientItemId = 0 , keyItemsPostponedItemId = 0 } where step keyItems = do r <- sqliteStep query if r then do itemId <- sqliteColumn query 0 itemRevision <- sqliteColumn query 1 case itemRevision :: Revision of ItemRevClient -> step keyItems { keyItemsClientItemId = itemId } ItemRevTransient -> step keyItems { keyItemsTransientItemId = itemId } ItemRevPostponed -> step keyItems { keyItemsPostponedItemId = itemId } _ -> throwIO $ DescribeFirstException "wrong item status rev" else return keyItems getKeyItems :: ClientRepo -> B.ByteString -> IO KeyItems getKeyItems ClientRepo { clientRepoStmtGetKeyItems = stmtGetKeyItems } key = sqliteQuery stmtGetKeyItems $ \query -> do sqliteBind query 1 key fillKeyItems query getKeyItemsByOneItemId :: ClientRepo -> ItemId -> IO KeyItems getKeyItemsByOneItemId ClientRepo { clientRepoStmtGetKeyItemsByOneItemId = stmtGetKeyItemsByOneItemId } itemId = sqliteQuery stmtGetKeyItemsByOneItemId $ \query -> do sqliteBind query 1 itemId fillKeyItems query getKeyServerItem :: ClientRepo -> B.ByteString -> IO ItemId getKeyServerItem ClientRepo { clientRepoStmtGetKeyServerItem = stmtGetKeyServerItem } key = sqliteQuery stmtGetKeyServerItem $ \query -> do sqliteBind query 1 key r <- sqliteStep query if r then sqliteColumn query 0 else return 0 mapKeyRevisionItem :: ClientRepo -> B.ByteString -> a -> (ItemId -> IO a) -> IO a mapKeyRevisionItem repo key defaultResult f = do KeyItems { keyItemsClientItemId = clientItemId , keyItemsTransientItemId = transientItemId , keyItemsPostponedItemId = postponedItemId } <- getKeyItems repo key -- check key items in this particular order if postponedItemId > 0 then f postponedItemId else if transientItemId > 0 then f transientItemId else if clientItemId > 0 then f clientItemId else do -- check server item serverItemId <- getKeyServerItem repo key if serverItemId > 0 then f serverItemId else return defaultResult getKeyRevisionValue :: ClientRepo -> B.ByteString -> IO (Revision, B.ByteString) getKeyRevisionValue repo key = mapKeyRevisionItem repo key (0, B.empty) $ getKeyItemRevisionValue repo -- | Get revision and value by key. clientRepoGetRevisionValue :: ClientRepo -> B.ByteString -> IO (Revision, B.ByteString) clientRepoGetRevisionValue repo@ClientRepo { clientRepoDb = db } key = sqliteTransaction db $ \_commit -> getKeyRevisionValue repo key -- | Change value for given key. clientRepoChange :: ClientRepo -> B.ByteString -> B.ByteString -> IO () clientRepoChange repo@ClientRepo { clientRepoDb = db } key value = sqliteTransaction db $ \commit -> do KeyItems { keyItemsClientItemId = clientItemId , keyItemsTransientItemId = transientItemId , keyItemsPostponedItemId = postponedItemId } <- getKeyItems repo key let (newRev, revItemId) = if transientItemId > 0 then (ItemRevPostponed, postponedItemId) else (ItemRevClient, clientItemId) if revItemId > 0 then changeKeyItemRevisionValue repo revItemId newRev value else addKeyItem repo key value newRev void $ getKeyItems repo key commit -- | Get all keys having the string given as a prefix. -- Empty-valued keys are returned too for removed values, for purpose of detecting changes. clientRepoGetKeysPrefixed :: ClientRepo -> B.ByteString -> IO [B.ByteString] clientRepoGetKeysPrefixed ClientRepo { clientRepoDb = db , clientRepoStmtEnumerateKeysBegin = stmtEnumerateKeysBegin , clientRepoStmtEnumerateKeysBeginEnd = stmtEnumerateKeysBeginEnd } keyPrefix = sqliteTransaction db $ \_commit -> case maybeUpperBound of Just upperBound -> sqliteQuery stmtEnumerateKeysBeginEnd $ \query -> do sqliteBind query 1 keyPrefix sqliteBind query 2 upperBound process query Nothing -> sqliteQuery stmtEnumerateKeysBegin $ \query -> do sqliteBind query 1 keyPrefix process query where keyPrefixLength = B.length keyPrefix -- get upper bound for a query -- essentially we need "prefix + 1", i.e. increment first byte from end which is < 0xFF -- and set to zero all bytes after it -- if the whole prefix looks like "0xFFFFFFFFFF..." then no upper bound is needed maybeUpperBound = let f i | i >= 0 = let b = keyPrefix `B.index` i in if b < 0xFF then Just $ B.take i keyPrefix <> B.singleton (b + 1) <> B.replicate (keyPrefixLength - i - 1) 0 else f $ i - 1 f _ = Nothing in f $ keyPrefixLength - 1 process query = let step previousKeys = do r <- sqliteStep query if r then step =<< (: previousKeys) <$> sqliteColumn query 0 else return previousKeys in reverse <$> step [] -- | State of push, needed for pull. newtype ClientRepoPushState = ClientRepoPushState { clientRepoPushStateTransientIds :: [ItemId] } -- | Perform push. pushClientRepo :: ClientRepo -> Manifest -> IO (Push, ClientRepoPushState) pushClientRepo repo@ClientRepo { clientRepoDb = db , clientRepoStmtSelectKeysToPush = stmtSelectKeysToPush , clientRepoStmtGetUpperRevision = stmtGetUpperRevision } Manifest { manifestMaxPushItemsCount = maxPushItemsCount , manifestMaxPushValuesTotalSize = maxPushValuesTotalSize } = describeException "failed to push client repo" $ sqliteTransaction db $ \commit -> do -- get global revision clientRevision <- clientRepoRevision repo -- get upper revision clientUpperRevision <- sqliteQuery stmtGetUpperRevision $ \query -> do r <- sqliteStep query unless r $ throwIO $ DescribeFirstException "failed to get upper revision" sqliteColumn query 0 -- select keys to push (reverse -> items, reverse -> transientIds) <- sqliteQuery stmtSelectKeysToPush $ \query -> do sqliteBind query 1 (fromIntegral maxPushItemsCount :: Int64) let step pushValuesTotalSize prevItems prevItemsIds = do -- get next row r <- sqliteStep query if r then do -- get value value <- sqliteColumn query 2 -- check limits let newPushValuesTotalSize = pushValuesTotalSize + B.length value if newPushValuesTotalSize > maxPushValuesTotalSize then return ([], []) else do -- get key key <- sqliteColumn query 1 -- get id of item itemId <- sqliteColumn query 0 -- change status of item to 'transient' changeKeyItemRevision repo itemId ItemRevTransient -- get rest of the items and return step newPushValuesTotalSize ((key, value) : prevItems) (itemId : prevItemsIds) else return (prevItems, prevItemsIds) in step 0 [] [] -- commit and return commit return (Push { pushClientRevision = clientRevision , pushClientUpperRevision = clientUpperRevision , pushItems = items }, ClientRepoPushState { clientRepoPushStateTransientIds = transientIds }) isClientRepoPushEmpty :: ClientRepoPushState -> Bool isClientRepoPushEmpty ClientRepoPushState { clientRepoPushStateTransientIds = transientIds } = null transientIds data ClientRepoPullInfo = ClientRepoPullInfo { clientRepoPullRevision :: {-# UNPACK #-} !Revision , clientRepoPullLag :: {-# UNPACK #-} !Int64 , clientRepoPullChanges :: [(Revision, B.ByteString, B.ByteString)] } -- | Perform pull, i.e. process answer from server, marking pushed changes and remembering outside changes. pullClientRepo :: ClientRepo -> Pull -> ClientRepoPushState -> IO ClientRepoPullInfo pullClientRepo repo@ClientRepo { clientRepoDb = db , clientRepoStmtAddChunk = stmtAddChunk } Pull { pullLag = lag , pullPrePushRevision = prePushRevision , pullPostPushRevision = postPushRevision , pullItems = itemsToPull , pullNewClientRevision = newClientRevision } ClientRepoPushState { clientRepoPushStateTransientIds = transientIds } = describeException "failed to pull client repo" $ sqliteTransaction db $ \commit -> do -- process commited keys forM_ (zip [(prePushRevision + 1)..] transientIds) $ \(revision, transientItemId) -> do -- get key items KeyItems { keyItemsPostponedItemId = postponedItemId } <- getKeyItemsByOneItemId repo transientItemId -- 'transient' becomes 'server' changeKeyItemRevision repo transientItemId revision -- 'postponed' becomes 'client' when (postponedItemId > 0) $ changeKeyItemRevision repo postponedItemId ItemRevClient -- add chunk if something has been committed when (prePushRevision < postPushRevision) $ sqliteQuery stmtAddChunk $ \query -> do sqliteBind query 1 prePushRevision sqliteBind query 2 postPushRevision sqliteFinalStep query -- pull keys forM_ itemsToPull $ \(revision, key, value) -> do -- value always becomes 'server' -- see what we need to do serverItemId <- getKeyServerItem repo key if serverItemId > 0 then changeKeyItemRevisionValue repo serverItemId revision value else when (B.length value > 0) $ addKeyItem repo key value revision -- set new client revision setManifestValue repo ManifestKeyGlobalRevision newClientRevision -- commit and return commit return ClientRepoPullInfo { clientRepoPullRevision = newClientRevision , clientRepoPullLag = lag , clientRepoPullChanges = itemsToPull } -- | Perform cleanup after interrupted sync (i.e. after push, but without pull). -- It's harmless to do it without push. cleanupClientRepo :: ClientRepo -> IO () cleanupClientRepo ClientRepo { clientRepoDb = db , clientRepoStmtMassChangeRev = stmtMassChangeStatus } = sqliteTransaction db $ \commit -> do -- change 'transient' items to 'client' sqliteQuery stmtMassChangeStatus $ \query -> do sqliteBind query 1 (ItemRevTransient :: Revision) sqliteBind query 2 (ItemRevClient :: Revision) sqliteFinalStep query -- change 'postponed' items to 'client' (possibly replacing former 'transient' items) sqliteQuery stmtMassChangeStatus $ \query -> do sqliteBind query 1 (ItemRevPostponed :: Revision) sqliteBind query 2 (ItemRevClient :: Revision) sqliteFinalStep query -- commit commit -- | Helper function to perform sync. syncClientRepo :: ClientRepo -> Manifest -> (Push -> IO Pull) -> IO ClientRepoPullInfo syncClientRepo repo manifest sync = flip onException (cleanupClientRepo repo) $ do -- perform push on client repo (push, pushState) <- pushClientRepo repo manifest pull <- sync push pullClientRepo repo pull pushState instance Repo ClientRepo where repoDb = clientRepoDb
quyse/flaw
flaw-oil/Flaw/Oil/ClientRepo.hs
mit
21,593
9
29
4,514
4,220
2,144
2,076
434
5
module Simulator where import Types import qualified Data.Heap as H import qualified Data.List.NonEmpty as NE import Data.Monoid ((<>)) -- remainingResources :: Time -> MachineSchedule -> Machine computeStats :: Time -> [MachineSchedule] -> ResourceBundle Double computeStats time schedules = fmap fromIntegral $ mconcat $ map (remainingResources time) schedules simulate :: Scheduler -> [Job] -> H.MinHeap Time -> FarmState -> FarmState simulate scheduler [] finishTimes farmState@(FarmState currentTime machineSchedules stats) = -- all jobs already scheduled case H.view finishTimes of Nothing -> farmState -- simulation finished Just (t, newFinishTimes) -> let newStats = Stats (fromIntegral(t - currentTime)) (computeStats currentTime machineSchedules) newFarmState = FarmState t machineSchedules (stats <> newStats) in simulate scheduler [] newFinishTimes newFarmState simulate scheduler (job:jobs) finishTimes (FarmState currentTime machineSchedules stats) = case NE.nonEmpty $ findCandidateMachines currentTime job machineSchedules of Nothing -> case H.view finishTimes of -- no machine available, wait for the first job to finish Nothing -> error $ "Job too large? " ++ show job Just (t, newFinishTimes) -> let newStats = Stats (fromIntegral(t - currentTime)) (computeStats currentTime machineSchedules) newFarmState = FarmState t machineSchedules (stats <> newStats) in simulate scheduler (job:jobs) newFinishTimes newFarmState Just candidateMachines -> -- use the scheduler let machineId = scheduler currentTime job candidateMachines in simulate scheduler jobs (H.insert (currentTime + duration job) finishTimes) (FarmState currentTime (addJobToSchedule currentTime machineSchedules job machineId) stats)
mohsen3/haskell-tutorials
src/job-scheduling/src/Simulator.hs
mit
1,916
0
19
417
492
254
238
29
4
-- Count of positives / sum of negatives -- https://www.codewars.com/kata/576bb71bbbcf0951d5000044 module Kata where countPositivesSumNegatives :: Maybe [Int] -> [Int] countPositivesSumNegatives Nothing = [] countPositivesSumNegatives (Just []) = [] countPositivesSumNegatives (Just xs) = [pl, ns] where pl = length . filter (>0) $ xs ns = sum . filter(<0) $ xs
gafiatulin/codewars
src/8 kyu/CountPosSumNeg.hs
mit
374
0
10
62
114
63
51
7
1
{-# LANGUAGE Arrows, NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards, NamedFieldPuns #-} module Main where -- XXX: fromArchive . toArchive /= id import Codec.Archive.Zip (toArchive, fromEntry, Archive(zEntries), Entry(eRelativePath)) import Control.Applicative ((<$>)) import Data.Char (isAlphaNum) import Data.List ((\\), find, isSuffixOf, sort) import Data.Maybe (fromMaybe) import Data.Set (fromList, toList) import Network.Curl (URLString, curlGetString, CurlCode(CurlOK), CurlOption(CurlFollowLocation)) import Network.Curl.Download.Lazy (openLazyURIWithOpts) import System.Environment (getArgs) import System.IO (hPutStrLn, stderr) import Text.Regex.Applicative ((<|>), (*>), (<*), (=~), RE, string, anySym, psym, sym, few, some) import Text.XML.HXT.Core ((>>>), (<+>), when, runX, txt, mkelem, processTopDown, replaceChildren, neg, returnA, deep, hasName, isElem, getChildren, getText, readString) import qualified Crypto.Hash.SHA1 as SHA1 import qualified Data.ByteString.Base16 as Base16 import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as LBS jenkinsDownloadPlugins :: URLString jenkinsDownloadPlugins = "https://updates.jenkins-ci.org/download/plugins/" type PluginName = String type PluginVersion = String pluginName :: RE Char PluginName pluginName = few $ psym isAlphaNum <|> sym '-' pluginVersion :: RE Char PluginVersion pluginVersion = few $ foldr1 (<|>) $ map sym "0123456789.-" pluginNames :: RE Char [PluginName] pluginNames = some $ few anySym *> string "href=\"" *> pluginName <* string "/\">" <* few anySym pluginVersions :: RE Char [PluginVersion] pluginVersions = some $ few anySym *> string ">" *> pluginVersion <* string "</a>" <* few anySym data PluginInfo = PluginInfo { name :: PluginName, version :: PluginVersion, sha1 :: String, depends :: [PluginName] } deriving (Show, Eq, Ord) getPluginInfo :: PluginName -> PluginVersion -> IO PluginInfo getPluginInfo name version = do hPutStrLn stderr $ "fetching " ++ hpi ++ " ..." try 1 where hpi = jenkinsDownloadPlugins ++ name ++ "/" ++ version ++ "/" ++ name ++ ".hpi" try :: Int -> IO PluginInfo try 7 = error "giving up :-(" try n = do out <- openLazyURIWithOpts [CurlFollowLocation True] hpi case out of Left err -> do hPutStrLn stderr $ "failed (" ++ err ++ ") trying again ..." try $ n + 1 Right cnt -> do let sha1 = BS.unpack $ Base16.encode (SHA1.hashlazy cnt) depends <- getRuntimeDeps <$> getAllDeps (getPomXml $ toArchive cnt) return PluginInfo { .. } getPluginVersions :: PluginName -> IO [PluginVersion] getPluginVersions plugin = do (rc, html) <- curlGetString (jenkinsDownloadPlugins ++ plugin ++ "/") [] if rc /= CurlOK then error $ "not found: " ++ plugin else case html =~ pluginVersions of Nothing -> error "No versions were found. HTML parsing has failed." Just names -> return names -- XXX: unpack vs. UTF-8 getPomXml :: Archive -> String getPomXml hpi = LBS.unpack . fromEntry $ fromMaybe (error "No pom.xml found") pomXml where pomXml = find isPomXml (zEntries hpi) isPomXml = isSuffixOf "/pom.xml" . eRelativePath data Dependency = Dependency { artifactId :: PluginName, scope :: String, groupId :: String } deriving (Show, Eq) getAllDeps :: String -> IO [Dependency] getAllDeps pomXml = runX $ readString [] pomXml >>> addRuntimeScope >>> deep (isElem >>> hasName "dependency") >>> proc d -> do artifactId <- value "artifactId" -< d scope <- value "scope" -< d groupId <- value "groupId" -< d returnA -< Dependency { .. } where addRuntimeScope = processTopDown (runtimeScope `when` noScope) value tag = getChildren >>> isElem >>> hasName tag >>> getChildren >>> getText noScope = isElem >>> hasName "dependency" >>> neg ( getChildren >>> isElem >>> hasName "scope" ) runtimeScope = replaceChildren $ getChildren <+> mkelem "scope" [] [txt "runtime"] getRuntimeDeps :: [Dependency] -> [PluginName] getRuntimeDeps deps = [ artifactId d | d <- deps, scope d == "runtime", groupId d == "org.jenkins-ci.plugins" ] toNix :: [PluginInfo] -> String toNix [] = "{}\n" toNix l = "{\n" ++ show' (sort l) ++ "}\n" where show' = foldr ((++) . showPlugin) "" showPlugin (PluginInfo n v sha1 d) = " " ++ show n ++ " = {\n" ++ " version = " ++ show v ++ ";\n" ++ " sha1 = " ++ show sha1 ++ ";\n" ++ " depends = [ " ++ unwords (show <$> d) ++ " ];\n" ++ " };\n" getPluginsInfo :: [PluginName] -> IO [PluginInfo] getPluginsInfo [] = return [] getPluginsInfo names = getUnknown [] names where getUnknown _ [] = return [] getUnknown seen names' = do new <- getInfo $ names' \\ (name <$> seen) more <- getUnknown (seen ++ new) (alldeps new) return $ new ++ more alldeps new = toList . fromList $ concat (depends <$> new) getInfo nn = sequence $ getLastest <$> nn getLastest name = head <$> getPluginVersions name >>= getPluginInfo name main :: IO () main = do names <- getArgs putStrLn "# Generated by jenkins4nix, https://github.com/zalora/jenkins4nix" putStrLn $ "# Command: jenkins4nix " ++ unwords names getPluginsInfo names >>= putStr . toNix
zalora/jenkins4nix
src/Main.hs
mit
5,578
1
21
1,323
1,702
904
798
125
3
{-# LANGUAGE CPP #-} module GHCJS.DOM.SVGAnimatedInteger ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.SVGAnimatedInteger #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.SVGAnimatedInteger #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/SVGAnimatedInteger.hs
mit
367
0
5
33
33
26
7
4
0
--listy.hs module Listy where newtype Listy a = Listy [a] deriving (Eq, Show) instance Monoid (Listy a) where mempty = Listy [] mappend (Listy l) (Listy l') = Listy $ mappend l l'
deciduously/Haskell-First-Principles-Exercises
5-Common Structures/15-Monoid, Semigroup/code/orphan-instance/Listy.hs
mit
190
0
8
43
83
45
38
7
0
module Light.Shape.Cylinder -- ADT ( Cylinder, cylinder, cylinderRadius, cylinderHeight -- Default Instances , unitCylinder ) where import Light.Math import Light.Geometry import Light.Shape data Cylinder = Cylinder { cylinderTransform :: Transform , cylinderRadius :: Double , cylinderHeight :: Double } deriving (Show, Read) cylinder :: Double -> Double -> Cylinder cylinder = Cylinder identityTransform unitCylinder :: Cylinder unitCylinder = cylinder 1 1 instance Transformable Cylinder where transform t' (Cylinder t r h) = Cylinder (compose t' t) r h instance Shape Cylinder where shapeTransform = cylinderTransform bound (Cylinder _ r h) = fromPoints [ Point (-r) (-r) 0, Point r r h ] surfaceArea (Cylinder _ r h) = 2 * pi * r * h intersections theRay (Cylinder t r h) = filter f $ quadratic a b c where r' = transform (inverse t) theRay rdx = dx $ rayDirection r' rdy = dy $ rayDirection r' rox = px $ rayOrigin r' roy = py $ rayOrigin r' a = (rdx*rdx) + (rdy*rdy) b = 2 * ((rdx*rox) + (rdy*roy)) c = (rox*rox) + (roy*roy) - r*r f time = let rz = pz (r' `atTime` time) in time > 0 && rz >= 0 && rz <= h
jtdubs/Light
src/Light/Shape/Cylinder.hs
mit
1,371
0
14
460
487
260
227
31
1
module GLUI (openGLUI) where import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import Data.Vector.V2 hiding (Vector2) import qualified Data.Vector.V2 as V import Data.IORef ( IORef, newIORef, writeIORef, readIORef, modifyIORef) import Control.Applicative import Data.Time.Clock import Data.Angle import System.IO import Foreign.Marshal.Alloc import Foreign.Ptr import Control.Exception as E import Paths_LambdaWars import Core import WorldRules import GeometryUtils (xAxisVector, radiansToDegrees, angleDegrees) import qualified GeometryUtils as Geom import SimpleBots -- | The type to contain all the OpenGL drawing state data GLUI = GLUI { hullTexture :: TextureObject, turretTexture :: TextureObject, worldStepper :: World -> World, isMatchOver :: World -> MatchResult, world :: IORef World } arenaHeightP :: GLfloat arenaHeightP = realToFrac arenaHeight arenaWidthP :: GLfloat arenaWidthP = realToFrac arenaWidth -- | The rate at which the game plays in frames per second. fps = 15 -- | This is the main function in this module. Pass in the initial world -- to draw and a world step function to update the world on every turn. openGLUI :: UI openGLUI = UI $ \initial stepper resultCheck -> do getArgsAndInitialize createWindow "Lambda Wars" -- Create an OpenGL window the same size as the Arena and transform -- it so that coordinate sytem of the window matches that of the arena. -- This will make drawing much easier later on. windowSize $= Size (round arenaWidth) (round arenaHeight) scale (realToFrac $ 2/arenaWidth) (realToFrac $ 2/arenaHeight) (1 :: GLfloat) translate $ Vector3 (-arenaHeightP/2) (-arenaWidthP/2) 0 worldState <- newIORef initial (bodyTexture, turretTexture) <- loadAllTextures let glui = GLUI bodyTexture turretTexture stepper resultCheck worldState displayCallback $= (drawWorld glui worldState) keyboardCallback $= (Just $ keyPressed worldState stepper) timeRef <- getCurrentTime >>= newIORef idleCallback $= Just (onIdle glui timeRef) mainLoop onIdle :: GLUI -> IORef UTCTime -> IO () onIdle glui lastFrameRef = do lastFrame <- readIORef lastFrameRef now <- getCurrentTime let sinceLastFrame = realToFrac $ now `diffUTCTime` lastFrame if sinceLastFrame < (1/fps) then return () else do writeIORef lastFrameRef now modifyIORef (world glui) (worldStepper glui) postRedisplay Nothing tryWinning glui -- | Check if the match is over and notify the user if it is. tryWinning :: GLUI -> IO () tryWinning glui = do world <- readIORef (world glui) case isMatchOver glui world of Draw -> do putStrLn "The match is a draw" idleCallback $= Nothing Won name -> do putStrLn $ "The winnder is:" ++ name idleCallback $= Nothing _ -> return () -- | This function is here to help debug the bot display. -- It draws a collection of bots on screen showTestWorld :: IO () showTestWorld = runUI openGLUI world id (const (Ongoing [])) where world = World bots bullets arenaBBox bots = zip (repeat (start sittingDuck)) $ map mkState [0..20] bullets = map mkBullet [0..10] mkBullet n = Bullet (V.Vector2 (n * 10) 200) (V.Vector2 1 1 ) mkState n = BotState "" position velocity turret radar Fire where position = (V.Vector2 (n * 20) (n * 20)) velocity = (V.Vector2 0 0) turret = Geom.rotate (Degrees (10 * n)) (V.Vector2 1 0) radar = Geom.rotate (Degrees (-10 * n)) (V.Vector2 1 0) loadAllTextures :: IO (TextureObject, TextureObject) loadAllTextures = do bodyTexturePath <- getDataFileName "resources/body.tex" turretTexturePath <- getDataFileName "resources/turret.tex" bodyTexture <- loadTexture (TextureSize2D 36 36) bodyTexturePath turretTexture <- loadTexture (TextureSize2D 20 54) turretTexturePath return (bodyTexture, turretTexture) drawWorld :: GLUI -> IORef World -> IO () drawWorld glui worldRef = do (World bots bullets _) <- readIORef worldRef -- This sets the color of the battlefield background clearColor $= (Color4 0 0 0 1) clear [ColorBuffer,DepthBuffer] texture Texture2D $= Enabled blend $= Enabled blendFunc $= (SrcAlpha, OneMinusSrcAlpha) mapM_ (drawBot glui . snd) bots mapM_ (drawBullet glui) bullets flush -- | Draw a bot drawBot :: GLUI -> BotState -> IO () drawBot glui (BotState _ position velocity turretDirection radarDirection _) = do preservingMatrix $ do translate $ vectorToVector3 position rotateZ $ angleDegrees velocity xAxisVector drawHull glui drawTurret glui turretDirection drawRadar glui radarDirection -- | Draws the main body of the bot drawHull :: GLUI -> IO () drawHull glui = do textureBinding Texture2D $= Just (hullTexture glui) texturedQuad (realToFrac botSize) (realToFrac botSize) textureBinding Texture2D $= Nothing -- | Draw a bot's turret. The direction is relative to the bot hull. drawTurret :: GLUI -> Direction -> IO () drawTurret glui direction = preservingMatrix $ do rotateZ $ angleDegrees direction xAxisVector texture Texture2D $= Enabled textureBinding Texture2D $= Just (turretTexture glui) texturedQuad 54 20 textureBinding Texture2D $= Nothing texturedQuad :: GLfloat -> GLfloat -> IO () texturedQuad width height = do renderPrimitive Polygon $ do color $ Color4 1 1 1 (1::GLfloat) vertex $ Vertex2 (-xOffset) (-yOffset) texCoord $ TexCoord2 0 (0::GLfloat) vertex $ Vertex2 xOffset (-yOffset) texCoord $ TexCoord2 1 (0::GLfloat) vertex $ Vertex2 xOffset ( yOffset) texCoord $ TexCoord2 1 (1 :: GLfloat) vertex $ Vertex2 (-xOffset) ( yOffset) texCoord $ TexCoord2 0 (1 ::GLfloat) where xOffset = width / 2 yOffset = height / 2 -- | Draw a bots radar. The direction of the radar is relative to the bot hull. drawRadar :: GLUI -> Direction -> IO () drawRadar glui direction = preservingMatrix $ do rotateZ $ angleDegrees direction xAxisVector renderPrimitive Lines $ do color radarColor vertex $ Vertex2 0 (0::GLint) vertex $ Vertex2 0 (100::GLint) -- | Draw a single bullet drawBullet :: GLUI -> Bullet -> IO () drawBullet glui (Bullet position velocity) = preservingMatrix $ do translate $ vectorToVector3 position renderPrimitive Polygon $ do color bulletColor vertex $ Vertex2 (-2) (-2::GLint) vertex $ Vertex2 2 (-2::GLint) vertex $ Vertex2 2 ( 2::GLint) vertex $ Vertex2 (-2) ( 2::GLint) -- | Rotate the current transform matrix by the supplied number of degrees around the Z axis origin. rotateZ :: GLdouble -> IO () rotateZ angle = rotate angle $ Vector3 0 0 1 -- | Converts an 2D AC-Vector vector to a 3D OpenGL vector vectorToVector3 :: V.Vector2 -> Vector3 GLfloat vectorToVector3 vec = Vector3 x y 0 where x = (realToFrac . v2x $ vec) y = (realToFrac . v2y $ vec) -- | Handle ke presses keyPressed :: (IORef World) -> (World -> World) -> Char -> Position -> IO () keyPressed _ _ 'q' _ = leaveMainLoop keyPressed world worldStep ' ' _ = modifyIORef world worldStep >> postRedisplay Nothing keyPressed _ _ _ _ = return () -- Texture Loading code -- | Loads a texture from a file. The file must contain raw RGBA values -- with one byte per channel. There is a PNG to RGBA conversion tool on -- github (https://github.com/andreyLevushkin/TextureConverter) but -- it's very hacky and woun't work for all PNGs. loadTexture :: TextureSize2D -> String -> IO TextureObject loadTexture texSize path = do [name] <- genObjectNames 1 textureBinding Texture2D $= (Just name) tex <- loadTextureBuffer path let pixDat = PixelData RGBA UnsignedByte tex texImage2D Texture2D NoProxy 0 RGBA' texSize 0 pixDat textureFilter Texture2D $= ((Linear', Nothing), Linear') textureWrapMode Texture2D S $= (Repeated, ClampToEdge) textureWrapMode Texture2D T $= (Repeated, ClampToEdge) free tex return name -- | Allocate a byte buffer outside of Haskell runtime and load the contents of -- of the file into it. You are responsible for freeing the buffer. loadTextureBuffer :: String -> IO (Ptr a) loadTextureBuffer path = do h <- openBinaryFile path ReadMode fileSize <- hFileSize h buf <- mallocBytes (fromIntegral fileSize) hGetBuf h buf (fromIntegral fileSize) hClose h return buf -- | Colors bulletColor = Color3 1 1 (1 :: GLfloat) radarColor = Color3 1 0 (0:: GLfloat)
andreyLevushkin/LambdaWars
src/GLUI.hs
mit
9,013
0
14
2,302
2,462
1,223
1,239
179
3
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- ---------------------------------------------------------------------------- {- | Module : Holumbus.Index.Common.DocId Copyright : Copyright (C) 2011 Sebastian M. Schlatt, Timo B. Huebel, Uwe Schmidt License : MIT Maintainer : Timo B. Huebel ([email protected]) Stability : experimental Portability: none portable The document identifier type DocId -} -- ---------------------------------------------------------------------------- module Holumbus.Index.Common.DocId where import Control.DeepSeq import Data.Binary (Binary (..)) import qualified Data.Binary as B import Data.Typeable import Text.XML.HXT.Core #if sizeable == 1 import Data.Size #endif -- ------------------------------------------------------------ -- | The unique identifier of a document -- (created upon insertion into the document table). newtype DocId = DocId { theDocId :: Int } deriving (Eq, Ord, Enum, NFData, Typeable) instance Show DocId where show = show . theDocId {-# INLINE show #-} instance Binary DocId where put = B.put . theDocId get = B.get >>= return . DocId {-# INLINE put #-} {-# INLINE get #-} incrDocId :: DocId -> DocId incrDocId = DocId . (1+) . theDocId addDocId :: DocId -> DocId -> DocId addDocId id1 id2 = DocId $ theDocId id1 + theDocId id2 subDocId :: DocId -> DocId -> DocId subDocId id1 id2 = DocId $ theDocId id1 - theDocId id2 nullDocId :: DocId nullDocId = DocId 0 firstDocId :: DocId firstDocId = DocId 1 mkDocId :: Integer -> DocId mkDocId = DocId . fromIntegral xpDocId :: PU DocId xpDocId = xpWrap (DocId, theDocId) xpPrim {-# INLINE incrDocId #-} {-# INLINE addDocId #-} {-# INLINE subDocId #-} {-# INLINE nullDocId #-} {-# INLINE firstDocId #-} {-# INLINE mkDocId #-} -- ------------------------------------------------------------ #if sizeable == 1 instance Sizeable DocId where dataOf = dataOf . theDocId bytesOf = bytesOf . theDocId statsOf = statsOf . theDocId #endif -- ------------------------------------------------------------
ichistmeinname/holumbus
src/Holumbus/Index/Common/DocId.hs
mit
2,714
0
8
950
366
214
152
39
1
{-# LANGUAGE PatternSynonyms, ViewPatterns #-} {-# LANGUAGE TypeSynonymInstances #-} -- This module is a wrapper (shim) for the extracted version of -- Data.IntSet.Internal module ExtractedIntSet where import Unsafe.Coerce -- import other extracted modules import qualified Base import qualified Datatypes import qualified BinNums import qualified Num import qualified Foldable import qualified Internal0 as S2 import qualified Data.Semigroup import qualified Data.Monoid import qualified Data.Foldable import qualified Data.Bits import qualified Control.Arrow as A import Control.DeepSeq(NFData,rnf) import Test.QuickCheck(NonNegative(..)) -- Shim for number types import ExtractedNumbers type IntSet = S2.IntSet pattern Nil = S2.Nil pattern Tip x y = S2.Tip x y pattern Bin x1 x2 x3 x4 = S2.Bin x1 x2 x3 x4 type Mask = S2.Mask type BitMap = S2.BitMap type Prefix = S2.Prefix type Key = S2.Key type Nat = NonNegative Integer binZToNonNeg :: Num.Word -> Nat binZToNonNeg = NonNegative . fromBinN nonNegToBinZ :: Nat -> Num.Word nonNegToBinZ = toBinN . getNonNegative ---------------------------------------------------- instance NFData (S2.IntSet) where rnf (S2.Tip p b) = p `seq` b `seq` () rnf (S2.Bin p y l r) = p `seq` y `seq` rnf l `seq` rnf r rnf S2.Nil = () ---------------------------------------------------- instance Eq (S2.IntSet) where (==) = S2.coq_Eq___IntSet_op_zeze__ (/=) = S2.coq_Eq___IntSet_op_zsze__ instance Prelude.Ord (S2.IntSet) where compare = S2.coq_Ord__IntSet_compare (>) = S2.coq_Ord__IntSet_op_zg__ (>=) = S2.coq_Ord__IntSet_op_zgze__ (<) = S2.coq_Ord__IntSet_op_zl__ (<=) = S2.coq_Ord__IntSet_op_zlze__ max = S2.coq_Ord__IntSet_max min = S2.coq_Ord__IntSet_min instance Data.Semigroup.Semigroup (S2.IntSet) where (<>) = S2.coq_Semigroup__IntSet_op_zlzlzgzg__ sconcat = error "no defn" stimes = error "no defn" instance Data.Monoid.Monoid (S2.IntSet) where mempty = S2.coq_Monoid__IntSet_mempty mappend = S2.coq_Monoid__IntSet_mappend mconcat = S2.coq_Monoid__IntSet_mconcat instance Show (S2.IntSet) where showsPrec p xs = showParen (p > 10) $ showString "fromList " . shows (toList xs) zero :: Nat -> Mask -> Bool zero x m = S2.zero (nonNegToBinZ x) m ---------------------------------------------------------------- -- for unit tests ---------------------------------------------------------------- lookupLT :: Nat -> IntSet -> Maybe Nat lookupLT x s = binZToNonNeg <$> S2.lookupLT (nonNegToBinZ x) s lookupGT :: Nat -> IntSet -> Maybe Nat lookupGT x s = binZToNonNeg <$> S2.lookupGT (nonNegToBinZ x) s lookupLE :: Nat -> IntSet -> Maybe Nat lookupLE x s = binZToNonNeg <$> S2.lookupLE (nonNegToBinZ x) s lookupGE :: Nat -> IntSet -> Maybe Nat lookupGE x s = binZToNonNeg <$> S2.lookupGE (nonNegToBinZ x) s -------------------------------------------------- -- Indexed -------------------------------------------------- -- findIndex = error "findIndex: partial function" -- elemAt = error "elemAt: partial function" -- deleteAt = error "deleteAt: partial function" -------------------------------------------------- -- Valid Trees -------------------------------------------------- -- I dunno how to get pattern synonyms to do this bin s = S2.Bin (toBinN s) -- need to translate BinNums.Z -> Int size :: IntSet -> Int size x = fromIntegral $ fromBinN (S2.size x) -------------------------------------------------- -- Single, Member, Insert, Delete -------------------------------------------------- empty :: IntSet empty = S2.empty singleton :: Nat -> IntSet singleton x = S2.singleton (nonNegToBinZ x) member :: Nat -> IntSet -> Bool member x = S2.member (nonNegToBinZ x) notMember :: Nat -> IntSet -> Bool notMember x = S2.notMember (nonNegToBinZ x) insert :: Nat -> IntSet -> IntSet insert x = S2.insert (nonNegToBinZ x) delete :: Nat -> IntSet -> IntSet delete x = S2.delete (nonNegToBinZ x) {-------------------------------------------------------------------- Balance --------------------------------------------------------------------} split :: Nat -> IntSet -> (IntSet, IntSet) split x = S2.split (nonNegToBinZ x) link = S2.link {-------------------------------------------------------------------- Union --------------------------------------------------------------------} union :: (IntSet) -> (IntSet) -> IntSet union = S2.union difference :: (IntSet) -> (IntSet) -> IntSet difference = S2.difference intersection :: (IntSet) -> (IntSet) -> IntSet intersection = S2.intersection disjoint :: (IntSet) -> (IntSet) -> Bool disjoint = S2.disjoint null :: IntSet -> Bool null = S2.null {-------------------------------------------------------------------- Lists --------------------------------------------------------------------} --fromAscList :: [Nat] -> IntSet --fromAscList xs = error "fromAscList: untranslated" --fromDistinctAscList :: [Nat] -> IntSet --fromDistinctAscList xs = error "fromDistinctAscList: untranslated" fromList :: [Nat] -> IntSet fromList xs = S2.fromList (Prelude.map nonNegToBinZ xs) toDescList :: IntSet -> [Nat] toDescList x = Prelude.map binZToNonNeg (S2.toDescList x) toAscList :: IntSet -> [Nat] toAscList x = Prelude.map binZToNonNeg (S2.toAscList x) toList :: IntSet -> [Nat] toList x = Prelude.map binZToNonNeg (S2.toList x) {-------------------------------------------------------------------- Set operations are like IntSet operations --------------------------------------------------------------------} foldr :: (Nat -> a -> a) -> a -> IntSet -> a foldr f b s = S2.foldr (f . binZToNonNeg) b s foldr' :: (Nat -> a -> a) -> a -> IntSet -> a foldr' f b s = S2.foldr' (f . binZToNonNeg) b s foldl' :: (a -> Nat -> a) -> a -> IntSet -> a foldl' f b s = S2.foldl' (\ x y -> f x (binZToNonNeg y)) b s foldl :: (a -> Nat -> a) -> a -> IntSet -> a foldl f b s = S2.foldl (\x y -> f x (binZToNonNeg y)) b s fold = S2.fold filter = S2.filter map = S2.map elems :: IntSet -> [Nat] elems x = Prelude.map binZToNonNeg (S2.elems x) isProperSubsetOf :: IntSet -> IntSet -> Bool isProperSubsetOf = S2.isProperSubsetOf isSubsetOf :: IntSet -> IntSet -> Bool isSubsetOf = S2.isSubsetOf findMax :: IntSet -> Nat findMax = error "partial" findMin :: IntSet -> Nat findMin = error "partial" minView :: IntSet -> Maybe (Nat,IntSet) minView s = (A.first binZToNonNeg) <$> S2.minView s maxView :: IntSet -> Maybe (Nat,IntSet) maxView s = (A.first binZToNonNeg) <$> S2.maxView s splitMember :: Nat -> IntSet -> (IntSet, Bool, IntSet) splitMember m s = (x,y,z) where ((x,y),z) = S2.splitMember (nonNegToBinZ m) s -- See comment in src/ExtractedSet.hs unions :: [IntSet] -> IntSet unions = S2.unions (unsafeCoerce (\_ -> Foldable.coq_Foldable__list)) splitRoot :: IntSet -> [IntSet] splitRoot = S2.splitRoot partition :: (Nat -> Bool) -> IntSet -> (IntSet, IntSet) partition f = S2.partition (f . binZToNonNeg) match :: Nat -> S2.Prefix -> S2.Mask -> Prelude.Bool match x y z = S2.match_ (nonNegToBinZ x) y z
antalsz/hs-to-coq
examples/containers/extraction/src/ExtractedIntSet.hs
mit
7,092
0
10
1,163
2,042
1,114
928
139
1
{- Copyright (c) 2010-2012, Benedict R. Gaster All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module TupleServer ( TupleServerMsg(..), createTupleServer, createProxyServer, createLogServer ) where import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TChan import Control.Concurrent.MVar import Data.HashTable as HT import Data.Map as MP -------------------------------------------------------------------------------- import TupleType import NetworkTuple import TupleStore ------------------------------------------------------------------------------ data TupleServerMsg = TSMsgIn Int -- thread ID Bool -- remove Template -- pattern ([AtomicVal] -> NetID -> IO ()) -- reply fn | TSMsgCancel Int -- thread ID | TSMsgAccept Int NetID -- thread ID * NetID instance Show TupleServerMsg where show (TSMsgIn id b template f) = "TSMsgIn " ++ show id ++ " " ++ show b ++ " " ++ show template show (TSMsgCancel id) = "TSMsgCancel " ++ show id show (TSMsgAccept id netID) = "TSMsgAccept " ++ show id ++ " " ++ show netID data ConOps = ConOps (Int -> Bool -> Template -> IO ()) -- sendInReg (Int -> IO ()) -- sendAccept (Int -> IO ()) -- sendCancel (TChan NetReply) -- replyChannel data TransactionInfo = TransInfo Int ([AtomicVal] -> Int -> IO ()) instance Show TransactionInfo where show (TransInfo id f) = "TransInfo " ++ show id data TransactionKey = TransKey Int Int instance Show TransactionKey where show (TransKey x y) = "TransKey " ++ show x ++ " " ++ show y instance Eq TransactionKey where TransKey x x' == TransKey y y' | (x' == -1 || y' == -1) = (x == y) | (x == -1) || (y == -1) = (x' == y') | otherwise = (x == y) && (x' == y') instance Ord TransactionKey where TransKey x x' <= TransKey y y' | (x' == -1 || y' == -1) = (x <= y) | (x == -1) || (y == -1) = (x' <= y') | otherwise = (x <= y) && (x' <= y') type TransactionTable = MP.Map TransactionKey TransactionInfo -------------------------------------------------------------------------------- proxyServer :: NetID -> ConOps -> TChan TupleServerMsg -> [TupleServerMsg] -> IO () proxyServer myID (ConOps sInReg sAccept sCancel replyChan) reqChan initInReqs = do tableVar <- newMVar (MP.empty :: TransactionTable) idVar <- newMVar (0 :: Int) mapM (handleMsg tableVar idVar) initInReqs forkIO $ loop tableVar idVar return () where loop tableVar idVar = do r <- atomically $ (Left `fmap` readTChan reqChan) `orElse`(Right `fmap` readTChan replyChan) case r of Left tsMsg -> handleMsg tableVar idVar tsMsg >> loop tableVar idVar Right netReply -> handleReply tableVar netReply >> loop tableVar idVar handleMsg tableVar idVar (TSMsgIn transId remove template replyFn) = do id <- nextID idVar table <- takeMVar tableVar print ("insert: " ++ show transId) putMVar tableVar $ MP.insert (TransKey transId id) (TransInfo id replyFn) table sInReg id remove template handleMsg tableVar _ (TSMsgCancel transId) = do table <- takeMVar tableVar let mb = MP.lookup (TransKey transId (-1::Int)) table case mb of Nothing -> error "unexpected loopup failure proxyServer" Just (TransInfo id _) -> do takeMVar tableVar >>= \_ -> putMVar tableVar $ MP.delete (TransKey transId (-1::Int)) table sCancel id handleMsg tableVar _ (TSMsgAccept transId tsID) = do table <- readMVar tableVar print ("transID: " ++ show transId) let mb = MP.lookup (TransKey transId (-1::Int)) table case mb of Nothing -> return () --error "unexpected lookup failure proxyServer" Just (TransInfo id _) -> do takeMVar tableVar >>= \_ -> putMVar tableVar $ MP.delete (TransKey transId (-1::Int)) table if tsID == myID then sAccept id else sCancel id handleReply tableVar (NetReply transID vals) = do table <- readMVar tableVar let mb = MP.lookup (TransKey (-1::Int) transID) table case mb of Nothing -> return () Just (TransInfo id replyFn) -> replyFn vals myID nextID idVar = do id <- takeMVar idVar putMVar idVar (id+1) return id createProxyServer :: NetID -> ServerConn -> TChan TupleServerMsg -> [TupleServerMsg] -> IO () createProxyServer myID conn reqChan initInReqs = proxyServer myID (ConOps (sendInReqNet conn) (sendAcceptNet conn) (sendCancelNet conn) (replyNet conn)) reqChan initInReqs -------------------------------------------------------------------------------- tupleServer :: TChan ClientReq -> IO () tupleServer msgChan = do tupleStore <- createTupleStore () forkIO $ serverLoop tupleStore return () where serverLoop tupleStore = do msg <- atomically (readTChan msgChan) handleReq tupleStore msg serverLoop tupleStore replyIfMatch Nothing = return () replyIfMatch (Just (Match (_,id) reply ext)) = reply (NetReply id ext) handleReq tupleStore (NetOutTuple tuple) = addTS tupleStore tuple >>= replyIfMatch handleReq tupleStore (NetInReq netID transID remove template reply) = do mb <-inputTS tupleStore (Match (netID, transID) reply template) case mb of Nothing -> return () Just (Match id reply binds) -> reply (NetReply transID binds) handleReq tupleStore (NetAccept netID transID) = removeTS tupleStore (netID, transID) handleReq tupleStore (NetCancel netID transID) = cancelTS tupleStore (netID, transID) >>= replyIfMatch createTupleServer :: NetID -> TChan ClientReq -> TChan TupleServerMsg -> IO () createTupleServer netID msgChan reqChan = do rChan <- atomically newTChan tupleServer msgChan proxyServer netID (conn rChan) (reqChan) [] return () where conn rChan = ConOps (sendInReg rChan) sendAccept sendCancel rChan sendInReg rChan transID remove template = atomically $ writeTChan msgChan (NetInReq netID transID remove template (replyFn rChan)) sendAccept transID = atomically $ writeTChan msgChan (NetAccept netID transID) sendCancel transID = atomically $ writeTChan msgChan (NetCancel netID transID) replyFn rChan reply = atomically $ writeTChan rChan reply; -------------------------------------------------------------------------------- createLogServer :: TChan TupleServerMsg -> IO (() -> IO (TChan TupleServerMsg, [TupleServerMsg])) createLogServer masterChan = do log <- HT.new (==) hashInt (call, entry) <- makeRPC (handleGetLog log) forkIO $ serverLoop entry log return call where serverLoop entry log = do e <- entry r <- atomically $ (Left `fmap` readTChan e) `orElse`(Right `fmap` readTChan masterChan) case r of Left _ -> serverLoop entry log Right t -> handleTrans log t >> serverLoop entry log handleGetLog log _ = do newChan <- atomically $ dupTChan masterChan logs <- HT.toList log return (newChan, Prelude.map snd logs) handleTrans log (trans@(TSMsgIn tid _ _ _)) = HT.insert log tid trans handleTrans log (trans@(TSMsgCancel tid)) = HT.delete log tid handleTrans log (trans@(TSMsgAccept tid _)) = HT.delete log tid makeRPC f = do reqChan <- atomically $ newTChan return (call reqChan, entry reqChan) where call reqChan arg = do reply <- atomically $ newTChan atomically $ writeTChan reqChan (arg, reply) (a,b) <- atomically $ readTChan reply return (a,b) entry reqChan = do (arg, replyV) <- atomically $ readTChan reqChan (newChan, result) <- f arg atomically $ writeTChan replyV (newChan, result) return newChan
bgaster/hlinda
TupleServer.hs
mit
11,403
0
21
4,253
2,680
1,316
1,364
179
8
-- Least Common Multiple -- http://www.codewars.com/kata/5259acb16021e9d8a60010af/ module LeastCommonMultiple where import Prelude hiding (lcm) lcm :: Integral a => [a] -> a lcm = abs . foldl1 lcm' where lcm' a b | a == 0 || b == 0 = 0 | otherwise = (* b) . (a `div`) . gcd a $ b
gafiatulin/codewars
src/5 kyu/LeastCommonMultiple.hs
mit
305
0
12
79
110
60
50
6
1
{-| Module : PostgREST.RangeQuery Description : Logic regarding the `Range`/`Content-Range` headers and `limit`/`offset` querystring arguments. -} module PostgREST.RangeQuery ( rangeParse , rangeRequested , rangeLimit , rangeOffset , restrictRange , rangeGeq , allRange , NonnegRange , rangeStatusHeader , contentRangeH ) where import qualified Data.ByteString.Char8 as BS import Data.List (lookup) import Text.Regex.TDFA ((=~)) import Control.Applicative import Data.Ranged.Boundaries import Data.Ranged.Ranges import Network.HTTP.Types.Header import Network.HTTP.Types.Status import Protolude hiding (toS) import Protolude.Conv (toS) type NonnegRange = Range Integer rangeParse :: BS.ByteString -> NonnegRange rangeParse range = do let rangeRegex = "^([0-9]+)-([0-9]*)$" :: BS.ByteString case listToMaybe (range =~ rangeRegex :: [[BS.ByteString]]) of Just parsedRange -> let [_, mLower, mUpper] = readMaybe . toS <$> parsedRange lower = maybe emptyRange rangeGeq mLower upper = maybe allRange rangeLeq mUpper in rangeIntersection lower upper Nothing -> allRange rangeRequested :: RequestHeaders -> NonnegRange rangeRequested headers = maybe allRange rangeParse $ lookup hRange headers restrictRange :: Maybe Integer -> NonnegRange -> NonnegRange restrictRange Nothing r = r restrictRange (Just limit) r = rangeIntersection r $ Range BoundaryBelowAll (BoundaryAbove $ rangeOffset r + limit - 1) rangeLimit :: NonnegRange -> Maybe Integer rangeLimit range = case [rangeLower range, rangeUpper range] of [BoundaryBelow lower, BoundaryAbove upper] -> Just (1 + upper - lower) _ -> Nothing rangeOffset :: NonnegRange -> Integer rangeOffset range = case rangeLower range of BoundaryBelow lower -> lower _ -> panic "range without lower bound" -- should never happen rangeGeq :: Integer -> NonnegRange rangeGeq n = Range (BoundaryBelow n) BoundaryAboveAll allRange :: NonnegRange allRange = rangeGeq 0 rangeLeq :: Integer -> NonnegRange rangeLeq n = Range BoundaryBelowAll (BoundaryAbove n) rangeStatusHeader :: NonnegRange -> Int64 -> Maybe Int64 -> (Status, Header) rangeStatusHeader topLevelRange queryTotal tableTotal = let lower = rangeOffset topLevelRange upper = lower + toInteger queryTotal - 1 contentRange = contentRangeH lower upper (toInteger <$> tableTotal) status = rangeStatus lower upper (toInteger <$> tableTotal) in (status, contentRange) where rangeStatus :: Integer -> Integer -> Maybe Integer -> Status rangeStatus _ _ Nothing = status200 rangeStatus lower upper (Just total) | lower > total = status416 -- 416 Range Not Satisfiable | (1 + upper - lower) < total = status206 -- 206 Partial Content | otherwise = status200 -- 200 OK contentRangeH :: (Integral a, Show a) => a -> a -> Maybe a -> Header contentRangeH lower upper total = ("Content-Range", toUtf8 headerValue) where headerValue = rangeString <> "/" <> totalString :: Text rangeString | totalNotZero && fromInRange = show lower <> "-" <> show upper | otherwise = "*" totalString = maybe "*" show total totalNotZero = Just 0 /= total fromInRange = lower <= upper
steve-chavez/postgrest
src/PostgREST/RangeQuery.hs
mit
3,330
0
15
721
908
477
431
80
2
import System.Random randomRankN :: Int -> Int -> [Int] -> IO [Int] randomRankN n m l = do r' <- getStdRandom (randomR (0, m)) let r = fromIntegral r' if elem r l then randomRankN n m l else do let ll = r:l if length ll > n then return ll else randomRankN n m ll
mingzhi0/misc
hs_code/randomRankN.hs
gpl-2.0
338
0
13
132
142
69
73
12
3
module Infernu.Lib where import Data.Maybe (fromMaybe) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Infernu.Prelude matchZip :: [a] -> [b] -> Maybe [(a,b)] matchZip [] [] = Just [] matchZip (_:_) [] = Nothing matchZip [] (_:_) = Nothing matchZip (x:xs) (y:ys) = fmap ((x,y):) $ matchZip xs ys safeLookup :: Eq a => [(a,a)] -> a -> a safeLookup assoc n = fromMaybe n $ lookup n assoc -- | Creates an inverse map. Multiple keys mapping to the same values are collected into Sets. -- -- >>> flipMap $ Map.fromList [(1,2),(2,2)] -- fromList [(2,fromList [1,2])] flipMap :: (Ord k, Ord v) => Map k v -> Map v (Set k) flipMap m = Map.foldrWithKey (\k v m' -> Map.alter (Just . addKeyToSet' k) v m') Map.empty m where addKeyToSet' k Nothing = Set.singleton k addKeyToSet' k (Just s) = Set.insert k s splatMap :: Ord k => Map (Set k) a -> Map k a splatMap m = Map.foldrWithKey (\ks v m' -> foldr (\k m'' -> Map.insert k v m'') m' (Set.toList ks)) Map.empty m
sinelaw/infernu
src/Infernu/Lib.hs
gpl-2.0
1,168
0
12
318
475
253
222
20
2
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module Proxy ( handleRequest ) where import Control.Concurrent import Network.Socket hiding (send, recv) import Control.Monad (unless) import Network.Socket.ByteString import Data.ByteString.UTF8 (fromString) import qualified Data.ByteString as BS import qualified Control.Concurrent.Thread.Group as TG import Control.Exception import Text.Printf import Data.List import Data.CaseInsensitive (mk) import Server import HTTPWorker import HTTPParser type State = (Maybe ThreadId, [(String, Socket)]) handleRequest :: HTTPRequest -> Send -> Recv -> State -> IO (Bool, State) handleRequest req cSend cRecv (Just tid, openSockets) = do killThread tid handleRequest req cSend cRecv (Nothing, openSockets) handleRequest req cSend cRecv (Nothing, openSockets) = case lookup "Host" (httpHeaders req) of Nothing -> do cSend "HTTP/1.1 502 Bad Gateway\r\n\r\n" printf "Host not found in headers\n" return (True, (Nothing, openSockets)) Just h -> do case find (\(a, _) -> a == h) openSockets of Just (h, s) -> do isR <- isReadable s if isR then do tid <- forkIO $ handleSocket req cSend (sendAll s) (recv s (2^11)) return (True, (Just tid, (h, s):filter (\(a, _) -> a /= h) openSockets)) else do close s handleRequest req cSend cRecv $ (Nothing, filter (\(a, _) -> a /= h) openSockets) Nothing -> do let (host, port') = break (== ':') h port = if null port' then "80" else tail port' s <- socket AF_INET Stream defaultProtocol addr <- try $ getAddrInfo Nothing (Just host) (Just port) case addr of Left (_ :: IOException) -> do cSend "HTTP/1.1 502 Bad Gateway\r\n\r\n" printf "Could not resolve address: %s\n" host return (True, (Nothing, openSockets)) Right (a:_) -> do connect s $ addrAddress a case httpMethod req of "CONNECT" -> do putStrLn $ "CONNECT " ++ h handleConnect cSend cRecv (sendAll s) (recv s (2^11)) close s return (False, (Nothing, openSockets)) _ -> do putStrLn $ httpMethod req ++ " " ++ httpPath req tid <- forkIO $ handleSocket req cSend (sendAll s) (recv s (2^11)) return (True, (Just tid, (h, s):openSockets)) handleSocket :: HTTPRequest -> Send -> Send -> Recv -> IO () handleSocket req cSend sSend sRecv = do sSend $ fromString $ show (trim req) -- check output, trim req transfer where transfer = do b <- sRecv unless (BS.null b) $ do cSend b transfer handleConnect :: Send -> Recv -> Send -> Recv -> IO () handleConnect cSend cRecv sSend sRecv = do g <- TG.new cSend "HTTP/1.1 200 Ok\r\nConnection: Close\r\n\r\n" TG.forkIO g $ transfer sSend cRecv TG.forkIO g $ transfer cSend sRecv TG.waitN 2 g where transfer snd rcv = do b <- rcv unless (BS.null b) $ do snd b transfer snd rcv trim :: HTTPRequest -> HTTPRequest trim (HTTPRequest m p v h b) = HTTPRequest m path v headers b where path = trimPath p headers = trimHeaders h ++ [("Connection", "Keep-Alive")] trimPath p = if "http" == mk (take 4 p) then dropWhile (/= '/') $ drop 7 p else p trimHeaders = filter (shouldBe.fst) shouldBe = not.(`elem` ["Proxy-Connection", "Connection"])
amir-sabbaghi/proxy
src/Proxy.hs
gpl-3.0
3,792
1
31
1,258
1,270
646
624
92
7
module ScadTreeView( createEmptyTreeStore, createTreeView, updateTreeStore, emptyForest ) where import Data.Tree import Data.IORef import Data.List import Graphics.UI.Gtk import Control.Monad.IO.Class (liftIO) import DSL.Scad import Gui data MenuAction = Add3Object | AddTransformation | AddBooleanOperation | DeleteNode | Move isMenuActionAllowed :: MenuAction -> Scad -> Bool isMenuActionAllowed DeleteNode Root = False isMenuActionAllowed DeleteNode _ = True isMenuActionAllowed _ (Sphere _) = False isMenuActionAllowed _ (Cube _) = False isMenuActionAllowed _ (Cylinder _ _ _ _) = False isMenuActionAllowed _ _ = True isScadNodeMovable :: Scad -> Bool isScadNodeMovable Root = False isScadNodeMovable _ = True createEmptyTreeStore :: IO (TreeStore Scad) createEmptyTreeStore = do treeStore <- treeStoreNewDND emptyForest (Just treeStoreDragSourceIface) (Just treeStoreDragDestIface) return treeStore emptyForest :: Forest Scad emptyForest = [Node Root []] updateTreeStore :: TreeStore Scad -> Forest Scad -> IO() updateTreeStore treeStore forest = do treeStoreClear treeStore treeStoreInsertForest treeStore [] 0 forest createTreeView :: Gui -> IO(ConnectId TreeView) createTreeView gui = do let treeStore = _treeStore gui let treeView = _treeView gui treeViewSetModel treeView treeStore treeViewSetReorderable treeView True col <- treeViewColumnNew renderer <- cellRendererTextNew cellLayoutPackStart col renderer False cellLayoutSetAttributes col renderer treeStore $ \ind -> [cellText := show(ind)] treeViewAppendColumn treeView col treeSelection <- treeViewGetSelection treeView treeSelectionSetMode treeSelection SelectionSingle on treeSelection treeSelectionSelectionChanged (nodeSelected treeStore treeSelection) on treeView buttonPressEvent (tryEvent (do button <- eventButton time <- eventTime pos <- eventCoordinates case button of RightButton -> liftIO (handleMouseButtonPressed time pos gui) _ -> stopEvent )) createSubMenu :: Menu -> String -> Bool -> IO(Menu) createSubMenu parentMenu label enabled = do menuItem <- menuItemNewWithLabel label menuShellAppend parentMenu menuItem subMenu <- menuNew case enabled of True -> do menuItemSetSubmenu menuItem subMenu False -> do disableChildWidget menuItem return subMenu addMenuItem :: Menu -> String -> Bool -> IO() -> IO() addMenuItem menu label enabled callback = do menuItem <- menuItemNewWithLabel label menuShellAppend menu menuItem case enabled of True -> do on menuItem menuItemActivated callback return () False -> do disableChildWidget menuItem disableChildWidget :: BinClass bin => bin -> IO() disableChildWidget bin = do maybeWidget <- binGetChild bin case maybeWidget of Just widget -> do widgetSetSensitive widget False Nothing -> return () addNode :: Gui -> TreePath -> Scad -> IO() addNode gui path node = do let treeStore = _treeStore gui let treeView = _treeView gui treeStoreInsert treeStore path (-1) node pathToNewElement <- pathToLastChild treeStore path treeViewExpandToPath treeView pathToNewElement sel <- treeViewGetSelection treeView treeSelectionSelectPath sel pathToNewElement pathToLastChild :: TreeStore a -> TreePath -> IO(TreePath) pathToLastChild treeStore parentPath = do parentForest <- treeStoreGetTree treeStore parentPath let children = subForest parentForest let lastChild = (length children) -1 return (parentPath ++ [lastChild]) deleteNode :: Gui -> TreePath -> IO() deleteNode gui path = do let treeStore = _treeStore gui treeStoreRemove treeStore path return () handleMouseButtonPressed :: TimeStamp -> (Double, Double) -> Gui -> IO() handleMouseButtonPressed time pos gui = do let treeView = _treeView gui let treeStore = _treeStore gui let menuIORef = _menu gui let (x,y) = pos pathInfo <- treeViewGetPathAtPos treeView (floor x, floor y) sel <- treeViewGetSelection treeView case pathInfo of Just (path, _, _) -> do treeSelectionSelectPath sel path node <- treeStoreGetValue treeStore path menu <- menuNew writeIORef menuIORef (Just menu) let add3dObjectAllowed = isMenuActionAllowed Add3Object node subMenu <- createSubMenu menu "Add 3D Object" add3dObjectAllowed addMenuItem subMenu "Sphere" True (addNode gui path (Sphere (Radius 1.0))) addMenuItem subMenu "Cube" True (addNode gui path (Cube $ Size 1.0)) addMenuItem subMenu "Cylinder" True (addNode gui path (Cylinder 1.0 (Radius 1.0) Nothing True)) let addTransformationAllowed = isMenuActionAllowed AddTransformation node subMenu <- createSubMenu menu "Add Transformation" addTransformationAllowed addMenuItem subMenu "Translate" True (addNode gui path (Translate 0 0 0)) addMenuItem subMenu "Rotate" True (addNode gui path (Rotate 0 0 0)) let addBooleanAllowed = isMenuActionAllowed AddBooleanOperation node subMenu <- createSubMenu menu "Add Boolean Operation" addBooleanAllowed addMenuItem subMenu "Union" True (addNode gui path (Union)) addMenuItem subMenu "Difference" True (addNode gui path (Difference)) addMenuItem subMenu "Intersection" True (addNode gui path (Intersection)) let deleteAllowed = isMenuActionAllowed DeleteNode node addMenuItem menu "Delete Node" deleteAllowed (deleteNode gui path) widgetShowAll menu menuPopup menu (Just (RightButton, time)) Nothing -> return () nodeSelected :: TreeStore Scad -> TreeSelection -> IO() nodeSelected treeStore treeSelection = do maybeTreeIter <- treeSelectionGetSelected treeSelection case maybeTreeIter of Just treeIter -> do treePath <- treeModelGetPath treeStore treeIter value <- treeStoreGetValue treeStore treePath putStrLn $ "Selected node:" ++ show (value) Nothing -> return () treeStoreDragSourceIface :: DragSourceIface TreeStore Scad treeStoreDragSourceIface = DragSourceIface { treeDragSourceRowDraggable = \treeStore src -> do node <- treeStoreGetValue treeStore src return (isScadNodeMovable node), treeDragSourceDragDataGet = treeSetRowDragData, treeDragSourceDragDataDelete = \model dest@(_:_) -> do liftIO $ treeStoreRemove model dest return True } treeStoreDragDestIface :: DragDestIface TreeStore Scad treeStoreDragDestIface = DragDestIface { treeDragDestRowDropPossible = \model dest -> do mModelPath <- treeGetRowDragData case mModelPath of Nothing -> return False Just (model', source) -> if (toTreeModel model/=toTreeModel model') then return False else liftIO $ do case (init dest) of (_:_) -> do if (isPrefixOf source dest) then return False else do valueParrentDest <- treeStoreGetValue model (init dest) return (isMenuActionAllowed Move valueParrentDest) [] -> return False, treeDragDestDragDataReceived = \model dest@(_:_) -> do mModelPath <- treeGetRowDragData case mModelPath of Nothing -> return False Just (_, []) -> return False Just (model', source@(_:_)) -> if toTreeModel model/=toTreeModel model' then return False else liftIO $ do row <- treeStoreGetTree model source treeStoreInsertTree model (init dest) (last dest) row return True }
Norberg/gui_scad
src/ScadTreeView.hs
gpl-3.0
8,560
0
28
2,626
2,252
1,064
1,188
195
8
module System.Serverman.Actions.Env (OS(..), getOS, releaseToOS) where import System.Serverman.Utils import System.Serverman.Types import System.Serverman.Log import System.Process import Data.List import System.IO.Error import Data.Either import Data.Char import Control.Monad.State getOS = do verbose "detecting os" arch_release <- execute "cat" ["/etc/os-release"] "" False deb_release <- execute "cat" ["/etc/lsb-release"] "" False let release = map toLower . head . rights $ [arch_release, deb_release] distro = releaseToOS release state <- get put $ state { os = distro } return () releaseToOS :: String -> OS releaseToOS release | or $ map (`isInfixOf` release) ["ubuntu", "debian", "raspbian"] = Debian | "arch" `isInfixOf` release = Arch | otherwise = Unknown
mdibaiee/serverman
src/System/Serverman/Actions/Env.hs
gpl-3.0
851
0
13
183
261
142
119
24
1
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} module Main(main) where import qualified Codec.Archive.CnCMix as F import Codec.Archive.CnCMix ( File(File) , CnCMix(CnCMix) , CnCID() --, CnCGame ) import Data.Map (Map()) import qualified Data.Map as Map import System.IO import System.FilePath import System.Directory import System.Console.CmdLib import Control.Monad --import Control.Monad.Parallel import qualified Data.ByteString.Lazy as L import Data.Binary -- so we don't need extensions in cncmix proper --deriving instance Data CnCGame --deriving instance Typeable CnCGame data Basic = Info { mixPaths :: [FilePath] , lType :: Bool , lCont :: Bool } | Mod { mixIn :: FilePath , mixOut :: FilePath , addFs :: [FilePath] , rmFs :: [String] , mixType :: Int --CnCGame , safe :: Bool } | Extract { mixPath :: FilePath , outputDir :: FilePath } deriving (Typeable, Data, Eq) instance Attributes Basic where attributes _ = foldl1 (%%) [ mixPaths %> [ {-Short ['i'] , Long ["mix"] , Help "the path to the Mix to print information about" ,-} ArgHelp "Paths to Mixes" , Required True , Extra True ] , lType %> [ Short ['t'] , Long ["print-type"] , Help "Should CnCMix print the type of Mix?" , Invertible True , Default True ] , lCont %> [ Short ['c'] , Long ["list-files"] , Help "Should CnCMix print a list of the Mix's content?" , Invertible True , Default True ] -------------------------- , mixOut %> [ Short ['o'] , Long ["output-mix"] , Help "the path to write the mix to" , ArgHelp "Path" , Required True ] , mixIn %> [ Short ['i'] , Long ["input-mix"] , Help "the path to read the mix to" , ArgHelp "Path" ] , addFs %> [ Short ['a'] , Long ["add"] , Help $ "the files used to create or modify the Mix. " ++ "Folders will be recurred into" , ArgHelp "Paths" ] , rmFs %> [ Short ['d'] , Long ["remove"] , Help $ "the name or ID of each file to be removed." ++ " IDs should be prefixed with \'0x\' and written in hexadecimal" , ArgHelp "Names and IDs" ] , mixType %> [ Short ['t'] , Long ["type"] , Help "which type of Mix should be created?" , ArgHelp "Game-Name" , Required True ] -------------------------- , mixPath %> [ Short ['i'] , Long ["mix"] , Help "the path to the Mix to be extracted" , ArgHelp "Path" , Required True ] , outputDir %> [ Short ['o'] , Help "the directory to extract the files into" , ArgHelp "Path" , Required True ] ] -- noAttributes = [Help $ "CnCMixer by Sonarpulse" -- ++ "\n" ++ "A simple tool to manipulate Mix archives of the older" -- ++ "Command & Conquer Games, designed especially for automated use." -- ++ "\n" ++ "source at http://github.com/Sonarpulse/CnC-Red-Alert" -- ++ "\n" ++ "run again with \"--help\" to see avaible options"] main :: IO () main = parse =<< getArgs where parse :: [String] -> IO () parse x = dispatchR [] x >>= (flip run' x :: Basic -> IO ()) instance RecordCommand Basic where mode_summary Info {} = "Print information about a Mix" ++ "\n" mode_summary Mod {} = "Create or modify a Mix archive" ++ "\n" mode_summary Extract {} = "Extract files from a Mix" ++ "\n" mode_help Info {} = "\n" ++ "The two options below control what information is printed about each mix." ++ "\n" ++ "Other arguments will treated as paths to mixes. Information about every" ++ "\n" ++ "mix will be printed in the order the paths are given." ---------- mode_help Mod {} = "\n" ++ "The is the Swiss army knife. No matter what, the only thing the tool will" ++ "\n" ++ "create or change is a mix at the given output path." ++ "\n\n" ++ "The files in that mix will come from an optionally specified input mix or" ++ "\n" ++ "list of paths: files in the list will simply be added, directories will" ++ "\n" ++ "be substituted for their contents as a MIX is a flat filesystem." ++ "\n\n" ++ "Before any files are added, however, their names and IDs will be matched" ++ "\n" ++ "against the list of IDs and files to be excluded. Naturally, files that" ++ "\n" ++ "match will not be added." ++ "\n\n" ++ "CnCMix is smart and will adjust if an input mix is given at the same path" ++ "\n" ++ "as the output mix. Instead of reading the input mix and writing to the" ++ "\n" ++ "output mix (which really are the same), it will write to a temporary file" ++ "\n" ++ "and then rename the temporary file to overwrite the original file in" ++ "\n" ++ "order to still work with constant memory. Use this feature to modify an" ++ "\n" ++ "existing mix. It will likewise adjust for symlinks or hardlinks, so be" ++ "\n" ++ "careful." ++ "\n\n" ++ "Lastly, it is required that a mix type be given, in case a wholly new mix" ++ "\n" ++ "is being made. However, if an input mix is given, it's type will be used" ++ "\n" ++ "instead." ---------- mode_help Extract {} = "\n" ++ "All files from will be placed in the directory specified. " ++ "\n" ++ "Pretty self-explanatory I would think." ---------- -- -- Logic of the CLI -- run' Info { lType = sType -- should we Show the Type? , lCont = sCont , mixPaths = mPaths } _ = forM_ mPaths $ L.readFile >=> \mixFile -> do putStrLn "" when sType $ putStrLn $ ("Mix Type:\t" ++) $ show $ F.detectGame $ mixFile when sCont $ do CnCMix mix <- return $ decode mixFile putStrLn $ ("File Count:\t" ++) $ show $ Map.size mix putStrLn $ "Names " ++ "\t" ++ "IDs" mapM_ (putStrLn . \(a,b) -> a ++ "\t" ++ b) $ F.showHeaders mix run' Extract { outputDir = oDir , mixPath = mPath} _ = do CnCMix mix <- decodeFile mPath F.writeMany oDir mix run' Mod { mixType = mType , mixOut = mOut , mixIn = mIn , addFs = aFs , rmFs = rFs } _ = do temP <- doesFileExist mIn -- if mIn exists -- if mIn is specified and valid let validImputMixExists = mIn /= "" && (temP || error "input Mix does not exist") -- if mIn and mOut are the same (and mIn is valid) willMutateMix = validImputMixExists && mIn == mOut tmpF <- if willMutateMix then uncurry openBinaryTempFile $ splitFileName mOut else liftM ((,) []) $ openBinaryFile mOut WriteMode -- repetition nessisary for type checking L.hPut (snd tmpF) =<< if validImputMixExists then do CnCMix old <- decodeFile mIn addMap <- F.readMany =<< getAllWithin aFs let remover :: CnCID id => FilePath -> Map id File -> Map id File remover f m = Map.delete (F.stringToID f) m return $ encode $ foldr remover (Map.union addMap old) rFs else do CnCMix dummy <- return $ F.manualConstraint $ toEnum mType return . encode . Map.union dummy =<< F.readMany =<< getAllWithin aFs -- close and (maybe) rename hClose $ snd tmpF when willMutateMix $ renameFile (fst tmpF) mOut getAllWithin :: CnCID id => [FilePath] -> IO (Map id FilePath) getAllWithin = foldr helper $ return Map.empty where helper :: CnCID id => FilePath -> IO (Map id FilePath) -> IO (Map id FilePath) helper "." oldMap = oldMap -- don't want to reccur forever with this helper ".." oldMap = oldMap -- or this helper path oldMap = doesDirectoryExist path >>= \x -> if x then liftM2 Map.union (liftM (Map.map (path </>)) filesWithin) oldMap -- subdirectory else liftM (Map.insert (F.stringToID path) path) oldMap -- single file where filesWithin = getAllWithin =<< getDirectoryContents path
cnc-patch/cncmix
Main.hs
gpl-3.0
9,510
0
40
3,748
1,821
963
858
161
4
{-# LANGUAGE TemplateHaskell #-} module Lamdu.Sugar.Types.Tag ( Tag(..), tagName, tagVal, tagInstance , TagOption(..), toInfo, toPick , TagChoice(..), tcOptions, tcNewTag , TagRef(..), tagRefTag, tagRefReplace, tagRefJumpTo , OptionalTag(..), oTag, oPickAnon ) where import qualified Control.Lens as Lens import qualified Lamdu.Calc.Type as T import Lamdu.Sugar.Internal.EntityId (EntityId) import Lamdu.Prelude data Tag name = Tag { _tagName :: name , _tagInstance :: EntityId -- Unique across different uses of a tag , _tagVal :: T.Tag } deriving (Eq, Ord, Show, Generic) data TagOption name o = TagOption { _toInfo :: Tag name , _toPick :: o () } deriving Generic data TagChoice name o = TagChoice { _tcOptions :: [TagOption name o] , _tcNewTag :: TagOption name o } deriving Generic -- | A mutable tag (that can be replaced with a different tag) data TagRef name i o = TagRef { _tagRefTag :: Tag name , _tagRefReplace :: i (TagChoice name o) , _tagRefJumpTo :: Maybe (o EntityId) } deriving Generic data OptionalTag name i o = OptionalTag { _oTag :: TagRef name i o , _oPickAnon :: o EntityId } deriving Generic traverse Lens.makeLenses [''Tag, ''TagOption, ''TagRef, ''TagChoice, ''OptionalTag] <&> concat
lamdu/lamdu
src/Lamdu/Sugar/Types/Tag.hs
gpl-3.0
1,331
0
11
308
372
230
142
34
0
module PatternMatching where import Hip.Prelude -- Some different definitions of boolean or or1 True b = True or1 False b = b or2 True b = True or2 a b = b or3 False False = False or3 a b = True prop_or12eq x y = or1 x y =:= or2 x y prop_or23eq x y = or2 x y =:= or3 x y prop_or13eq x y = or1 x y =:= or3 x y data Tree = Leaf | Bin Tree Tree mirror2fix (Bin a b) = Bin left right where left = case b of Bin l r -> Bin (mirror2fix r) (mirror2fix l) Leaf -> Leaf right = case a of Bin l r -> Bin (mirror2fix r) (mirror2fix l) Leaf -> Leaf mirror2fix Leaf = Leaf mirror2wfix (Bin a b) = Bin left right where left = case b of Bin l r -> Bin (mirror2wfix r) (mirror2wfix l) _ -> Leaf right = case a of Bin l r -> Bin (mirror2wfix r) (mirror2wfix l) _ -> Leaf mirror2wfix _ = Leaf mirror2 (Bin a b) = case a of Leaf -> case b of Bin ba bb -> Bin (Bin (mirror2 bb) (mirror2 ba)) Leaf Leaf -> Bin Leaf Leaf Bin aa ab -> case b of Bin ba bb -> Bin (Bin (mirror2 bb) (mirror2 ba)) (Bin (mirror2 ab) (mirror2 aa)) Leaf -> Bin Leaf (Bin (mirror2 ab) (mirror2 aa)) mirror2 Leaf = Leaf mirror2w (Bin a b) = case a of Bin aa ab -> case b of Bin ba bb -> Bin (Bin (mirror2w bb) (mirror2w ba)) (Bin (mirror2w ab) (mirror2w aa)) nb -> Bin nb (Bin (mirror2w ab) (mirror2w aa)) na -> case b of Bin ba bb -> Bin (Bin (mirror2w bb) (mirror2w ba)) na nb -> Bin nb na mirror2w n = n mirror (Bin a b) = Bin (mirror b) (mirror a) mirror Leaf = Leaf mirrorw (Bin a b) = Bin (mirrorw b) (mirrorw a) mirrorw n = n prop_tests :: Prop Tree prop_tests = mirror2 (Bin (Bin Leaf Leaf) Leaf) =:= Bin Leaf (Bin Leaf Leaf) prop_testk :: Prop Tree prop_testk = mirror2w (Bin (Bin Leaf Leaf) Leaf) =:= Bin Leaf (Bin Leaf Leaf) prop_testp :: Prop Tree prop_testp = mirror (Bin (Bin Leaf Leaf) Leaf) =:= Bin Leaf (Bin Leaf Leaf) prop_testw :: Prop Tree prop_testw = mirrorw (Bin (Bin Leaf Leaf) Leaf) =:= Bin Leaf (Bin Leaf Leaf) prop_mirror2fix x = mirror2fix (mirror2fix x) =:= x prop_mirror2wfix x = mirror2wfix (mirror2wfix x) =:= x prop_mirror2 x = mirror2 (mirror2 x) =:= x prop_mirror2w x = mirror2w (mirror2w x) =:= x prop_mirror x = mirror (mirror x) =:= x prop_mirrorw x = mirrorw (mirrorw x) =:= x prop_eq_w_ x = mirrorw x =:= mirror x prop_eq_2_ x = mirror2 x =:= mirror x prop_eq_2w_w x = mirror2w x =:= mirrorw x prop_eq_2w_2 x = mirror2w x =:= mirror2 x prop_eq_2wfix_2fix x = mirror2wfix x =:= mirror2fix x prop_eq_2wfix_ x = mirror2wfix x =:= mirror x prop_eq_2fix_w x = mirror2wfix x =:= mirrorw x prop_eq_2wfix_w x = mirror2wfix x =:= mirrorw x prop_eq_2fix_ x = mirror2 x =:= mirror x
danr/hipspec
examples/old-examples/hip/PatternMatching.hs
gpl-3.0
3,158
0
15
1,119
1,330
640
690
73
4
-- terminos_robison.hs -- Implementación del algorítmo de Robinson -- Sevilla, 14 de Junio de 2016 -- --------------------------------------------------------------------- import Data.Maybe import Terminos -- (resuelve2 ts) es la sustitución resultante para el problema de -- unificación ts. -- λ> resuelve2 [(V ("x",2), V ("x",2))] -- Just [] -- λ> resuelve2 [(V ("x",2), V ("x",3))] -- Just [(V ("x",3),V ("x",2))] -- λ> resuelve2 [(V ("x",2), V ("x",3))] -- Just [(V ("x",3),V ("x",2))] -- λ> resuelve2 [(V ("x",2), T "f" [V ("x",2)])] -- Nothing -- λ> resuelve2 [(V ("x",2),T "f" [V ("x",3)]),(V ("x",3),T "f" [V ("x",4)])] -- Just [(T "f" [T "f" [V ("x",4)]],V ("x",2)),(T "f" [V ("x",4)],V ("x",3))] -- λ> resuelve2 [(V ("x",1), T "f" [V ("a",1)]),(T "g" [V ("x",1),V ("x",1)], T "g" [V ("x",1),V ("y",1)])] -- Just [(T "f" [V ("a",1)],V ("x",1)),(T "f" [V ("a",1)],V ("y",1))] resuelve2:: [(Termino,Termino)] -> Maybe [(Termino, Termino)] resuelve2 [(t1, t2)] = unificaTerm t1 t2 resuelve2 ((t1,t2):ts) | Nothing == subs1 = Nothing | otherwise = subs3 where subs1 = unificaTerm t1 t2 subs1' = fromJust subs1 subs_tms1 = aplicaSust2 subs1' (fst $ unzip ts) subs_tms2 = aplicaSust2 subs1' (snd $ unzip ts) subs2 = resuelve2 (zip subs_tms1 subs_tms2) subs3 = comboSust subs1 subs2 -- -- Con las funciones auxiliares-------------------------------------------- -- (unificaTerm t1 t2) es la sustitución basada en t1 y t2. -- λ> unificaTerm (V ("x",2)) (T "a" []) -- Just [(T "a" [],V ("x",2))] -- λ> unificaTerm (V ("x",2)) (T "a" [V ("y",3)]) -- Just [(T "a" [V ("y",3)],V ("x",2))] -- λ> unificaTerm (T "a" [V ("y",3)]) (T "a" []) -- Nothing unificaTerm :: Termino -> Termino -> Maybe [(Termino,Termino)] unificaTerm (T a []) (T b []) | a == b = Just [] | otherwise = Nothing unificaTerm v1@(V _) v2@(V _) | v1 == v2 = Just [] | otherwise = Just [(v2,v1)] unificaTerm c@(T _ []) v@(V _) = Just [(c,v)] unificaTerm v@(V _) c@(T _ []) = Just [(c,v)] unificaTerm (T _ []) (T _ _) = Nothing unificaTerm (T _ _) (T _ []) = Nothing unificaTerm f@(T _ _) v@(V a) | contenidoVar a f = Nothing | otherwise = Just [(f,v)] unificaTerm v@(V a) f@(T _ _) | contenidoVar a f = Nothing | otherwise = Just [(f,v)] unificaTerm (T n1 l1) (T n2 l2) | n1 /= n2 = Nothing | (length l1) /= (length l2) = Nothing | otherwise = resuelve2 $ zip l1 l2 aplicaSust2 :: [(Termino,Termino)] -> [Termino] -> [Termino] aplicaSust2 [] t = t aplicaSust2 (s:[]) t = map (aplicaUnaSust s) t aplicaSust2 (s:ss@(_:_)) t = aplicaSust2 ss (map (aplicaUnaSust s) t) aplicaUnaSust :: (Termino,Termino) -> Termino -> Termino aplicaUnaSust (t, v1@(V a)) v2@(V _) | contenidoVar a v2 = t | otherwise = v2 aplicaUnaSust (_, V _) c@(T _ []) = c aplicaUnaSust s@(t, V _) (T f ts) = T f (map (aplicaUnaSust s) ts) comboSust :: Maybe [(Termino,Termino)] -> Maybe [(Termino,Termino)] -> Maybe [(Termino,Termino)] comboSust _ Nothing = Nothing comboSust sust1 (Just []) = sust1 comboSust (Just []) sust2@(Just (_:_)) = sust2 comboSust (Just sust1@(_:_)) (Just sust2@(_:_)) = Just (s1 ++ sust2) where tsc1 = map fst sust1 vsc1 = map snd sust1 tsc1' = aplicaSust2 sust2 tsc1 s1 = zip tsc1' vsc1 -- ---------------------------------------------------------------------
migpornar/SRTenHaskell
Codigo_Haskell/Codigo de ejemplo/UnificacionRobison.hs
gpl-3.0
3,537
0
10
840
1,179
622
557
55
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.Projects.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets one project by ID. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.projects.get@. module Network.Google.Resource.DFAReporting.Projects.Get ( -- * REST Resource ProjectsGetResource -- * Creating a Request , projectsGet , ProjectsGet -- * Request Lenses , proXgafv , proUploadProtocol , proAccessToken , proUploadType , proProFileId , proId , proCallback ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.projects.get@ method which the -- 'ProjectsGet' request conforms to. type ProjectsGetResource = "dfareporting" :> "v3.5" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "projects" :> Capture "id" (Textual Int64) :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Project -- | Gets one project by ID. -- -- /See:/ 'projectsGet' smart constructor. data ProjectsGet = ProjectsGet' { _proXgafv :: !(Maybe Xgafv) , _proUploadProtocol :: !(Maybe Text) , _proAccessToken :: !(Maybe Text) , _proUploadType :: !(Maybe Text) , _proProFileId :: !(Textual Int64) , _proId :: !(Textual Int64) , _proCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'proXgafv' -- -- * 'proUploadProtocol' -- -- * 'proAccessToken' -- -- * 'proUploadType' -- -- * 'proProFileId' -- -- * 'proId' -- -- * 'proCallback' projectsGet :: Int64 -- ^ 'proProFileId' -> Int64 -- ^ 'proId' -> ProjectsGet projectsGet pProProFileId_ pProId_ = ProjectsGet' { _proXgafv = Nothing , _proUploadProtocol = Nothing , _proAccessToken = Nothing , _proUploadType = Nothing , _proProFileId = _Coerce # pProProFileId_ , _proId = _Coerce # pProId_ , _proCallback = Nothing } -- | V1 error format. proXgafv :: Lens' ProjectsGet (Maybe Xgafv) proXgafv = lens _proXgafv (\ s a -> s{_proXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). proUploadProtocol :: Lens' ProjectsGet (Maybe Text) proUploadProtocol = lens _proUploadProtocol (\ s a -> s{_proUploadProtocol = a}) -- | OAuth access token. proAccessToken :: Lens' ProjectsGet (Maybe Text) proAccessToken = lens _proAccessToken (\ s a -> s{_proAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). proUploadType :: Lens' ProjectsGet (Maybe Text) proUploadType = lens _proUploadType (\ s a -> s{_proUploadType = a}) -- | User profile ID associated with this request. proProFileId :: Lens' ProjectsGet Int64 proProFileId = lens _proProFileId (\ s a -> s{_proProFileId = a}) . _Coerce -- | Project ID. proId :: Lens' ProjectsGet Int64 proId = lens _proId (\ s a -> s{_proId = a}) . _Coerce -- | JSONP proCallback :: Lens' ProjectsGet (Maybe Text) proCallback = lens _proCallback (\ s a -> s{_proCallback = a}) instance GoogleRequest ProjectsGet where type Rs ProjectsGet = Project type Scopes ProjectsGet = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient ProjectsGet'{..} = go _proProFileId _proId _proXgafv _proUploadProtocol _proAccessToken _proUploadType _proCallback (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy ProjectsGetResource) mempty
brendanhay/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Projects/Get.hs
mpl-2.0
4,798
0
19
1,202
821
474
347
115
1
module Qemu where import Control.Applicative import Control.Monad import Data.Maybe import Data.List import System.FilePath import System.Posix.User import System.Posix.Files import Types import MAC import Resource data Qemu = Qemu { qUserIfOpts :: [(String,String)], qStdioConsole :: Bool, qVm :: Vm } qemu :: FilePath -> MAC -> Qemu -> [String] qemu rundir mac Qemu { qVm = Vm { vName, vCfg = VmCfg {..}, vSysCfg = VmSysCfg {..}, vNetCfg = VmNetCfg {..}, vQCfg = VmQCfg {..} }, .. } = concat $ [ [arch vArch], ["-sandbox", "on"], -- seccomp yey ["-cpu", "host"], ["-machine", "pc,accel=kvm"], ["-nographic"], ["-vga", "none"], ["-option-rom", "/usr/share/qemu/sgabios.bin"], case qStdioConsole of True -> [] False -> concat [ ["-monitor", "unix:"++ (rundir </> "kib-" ++ vName ++ "-monitor.unix") ++ ",server,nowait"], ["-serial", "unix:"++ (rundir </> "kib-" ++ vName ++ "-ttyS0.unix") ++ ",server,nowait"], ["-qmp", "stdio"] ], smp vCpus, mem vMem, case vDriveDevice of "scsi-hd" -> ["-device", "virtio-scsi-pci"] _ -> [], concat $ map (\(i, n) -> disk i ("/dev" </> vVg </> n) vDriveDevice Nothing) $ [0..] `zip` (vName : map ((vName ++ "-")++) vAddDisks), vUserIf ==> userNet "virtio" 2 qUserIfOpts, vPublicIf ==> net ("kpu-"++vName) "virtio" 0 mac, vPrivateIf ==> net ("kpr-"++vName) "virtio" 0 mac -- TODO: in theory MAC addresses only have to be unique per segment, since -- the private net is a seperate bridge we should be fine but who knows TODO: -- TODO: Group interfaces ] where True ==> f = f False ==> _ = [] smp :: Int -> [String] smp n = [ "-smp", show n ] mem :: Int -> [String] mem b = [ "-m", show b] arch a = "/usr/bin/qemu-system-" ++ a disk i file device mfmt = [ "-drive", opts [ ("file", file) , ("id", "hdd" ++ show i) , ("format", fromMaybe "raw" mfmt) , ("if", "none") ] , "-device", device ++ "," ++ opts [ ("drive", "hdd" ++ show i) ] ] net ifname model vlan mac = [ "-nic", "tap," ++ opts [ ("mac", showMAC mac) , ("model", model) , ("ifname", ifname) , ("script", "no") , ("downscript", "no") ] ] userNet model vlan adopts = [ "-nic", "user," ++ opts (("model", model) : adopts) ] opts = intercalate "," . map (\(k,v) -> k++"="++v)
DanielG/kvm-in-a-box
src/Qemu.hs
agpl-3.0
2,479
0
18
676
878
501
377
-1
-1
{-# language ExistentialQuantification, FunctionalDependencies, RecordWildCards, NamedFieldPuns, FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, ImpredicativeTypes #-} -- module for often used types (in one Base module, to avoid module import cycles.) module Base.Types ( module Base.Types, module Base.Types.Events, module Base.Types.LevelMetaData, Offset, Seconds, ) where import Data.Set hiding (size) import Data.Indexable import Data.Abelian import Data.SelectTree import Data.Typeable import Data.Map hiding (size) import Data.Data import Data.Generics.Uniplate.Data import Data.Accessor import Data.IORef import qualified Data.Binary as Binary import qualified Data.Text as T import Data.Version import qualified Data.Strict as St import Control.Monad.Reader import Control.Monad.State.Strict import Control.Monad.CatchState import Control.Concurrent.MVar import System.FilePath import Physics.Chipmunk as CM import Graphics.Qt as Qt import Sound.SFML import Utils import Base.Constants import Base.Configuration import Base.Grounds import Base.GameGrounds import Base.Pixmap import Base.Types.Events import Base.Types.LevelMetaData import StoryMode.Types -- * type aliases type ConfigurationReader = ReaderT Configuration IO type RM = ConfigurationReader type ConfigurationState = CatchState Configuration IO type M = ConfigurationState type GameMonad o = StateT GameState M o type RetryLevel = AppState data GameState = GameState { cmSpace :: Space, cameraStateRef :: IORef CameraState, scene :: Scene Object_, retryLevel :: RetryLevel } setScene :: Scene Object_ -> GameState -> GameState setScene scene (GameState space camRef _ retryLevel) = GameState space camRef scene retryLevel -- * from Base.Application data Application = Application { application :: Ptr QApplication, window :: Ptr MainWindow, keyPoller :: KeyPoller, autoUpdateVersion :: MVar UpdateVersions, storyModeAvailability :: MVar StoryModeAvailability, getMainMenu_ :: Application -> AppState, applicationPixmaps :: ApplicationPixmaps, applicationSounds :: ApplicationSounds, allSorts :: SelectTree Sort_ } getMainMenu :: Application -> AppState getMainMenu app = getMainMenu_ app app data UpdateVersions = UpdateVersions { gameNewVersion :: Maybe Version, storyModeNewVersion :: Either String (Maybe Version) } data StoryModeAvailability = NotAvailable | Buyable | Installed hasUpdates :: UpdateVersions -> Bool hasUpdates (UpdateVersions (Just _) _) = True hasUpdates (UpdateVersions _ (Right (Just _))) = True hasUpdates _ = False data AppState = AppState RenderableInstance (M AppState) | AppStateLooped RenderableInstance (M AppState) | NoGUIAppState (M AppState) | GameAppState RenderableInstance (GameMonad AppState) GameState | UnManagedAppState (M AppState) -- manages rendering by itself | FinalAppState type Parent = AppState type Play = Parent -> LevelFile -> AppState data ApplicationPixmaps = ApplicationPixmaps { menuBackground :: [Pixmap], menuBackgroundTransparent :: [Pixmap], alphaNumericFont :: Font, pixmapsDigitFont :: Font, headerCubePixmaps :: HeaderCubePixmaps, menuTitlePixmap :: Pixmap, pausePixmap :: Pixmap, successPixmap :: Pixmap, failurePixmap :: Pixmap } data Font = Font { colorVariants :: (Map Color ColorVariant) } -- | save pixmaps in one color on transparent background. data ColorVariant = ColorVariant { longest :: Int, -- length of the longest text for which a pixmap exists glyphs :: Map T.Text Pixmap, errorSymbol :: Pixmap } deriving Show -- | a letter with its graphical representation data Glyph = Glyph { character :: T.Text, glyphPixmap :: Pixmap } | ErrorGlyph {glyphPixmap :: Pixmap} deriving (Show) data HeaderCubePixmaps = HeaderCubePixmaps { startCube :: Pixmap, standardCube :: Pixmap, spaceCube :: Pixmap, endCube :: Pixmap } data ApplicationSounds = ApplicationSounds { menuSelectSound :: PolySound, menuConfirmSound :: PolySound, menuCancelSound :: PolySound, errorSound :: PolySound, failureSound :: PolySound, successSound :: PolySound } -- * Base.Renderable class Renderable r where render :: Ptr QPainter -> Application -> Configuration -> Size Double -> r -> IO (Size Double, IO ()) label :: r -> String -- for usage in menus select :: r -> r select = id deselect :: r -> r deselect = id data RenderableInstance = forall r . Renderable r => RenderableInstance r renderable :: Renderable r => r -> RenderableInstance renderable = RenderableInstance -- * from Game.Scene -- | representing the scene (both physical and graphical objects) during the game. -- A value of this type gets passed from the logic thread to the rendering thread data Scene object = Scene { levelFile :: LevelFile, spaceTime_ :: Seconds, objects_ :: GameGrounds object, lowerLimit_ :: Maybe CpFloat, batteryPower_ :: !(Pair Integer Integer), -- makes it possible to have REALLY BIG amounts of power :) batteryMap :: Map Shape (Index, Chipmunk), -- saves the batteries for every battery shape (needed for removal) switches_ :: !(Pair Int Int), contactRef :: !(ContactRef Contacts), contacts_ :: !Contacts, mode_ :: Mode } deriving Show spaceTime :: Accessor (Scene o) Seconds spaceTime = accessor spaceTime_ (\ a r -> r{spaceTime_ = a}) objects :: Accessor (Scene o) (GameGrounds o) objects = accessor objects_ (\ a r -> r{objects_ = a}) lowerLimit :: Accessor (Scene o) (Maybe CpFloat) lowerLimit = accessor lowerLimit_ (\ a r -> r{lowerLimit_ = a}) batteryPower :: Accessor (Scene o) (Pair Integer Integer) batteryPower = accessor batteryPower_ (\ a r -> r{batteryPower_ = a}) switches :: Accessor (Scene o) (Pair Int Int) switches = accessor switches_ (\ a r -> r{switches_ = a}) contacts :: Accessor (Scene o) Contacts contacts = accessor contacts_ (\ a r -> r{contacts_ = a}) mode :: Accessor (Scene o) Mode mode = accessor mode_ (\ a r -> r{mode_ = a}) -- * getter -- | returns the object currently controlled by the gamepad getControlled :: Scene o -> Maybe o getControlled s = s |> getControlledIndex |> fmap (\ i -> s ^. mainLayerObjectA i) -- | returns the controlled index in game mode getControlledIndex :: Scene o -> Maybe Index getControlledIndex scene = case scene ^. mode of NikkiMode{nikki} -> Just nikki TerminalMode{terminal} -> Just terminal RobotMode{robot} -> Just robot LevelFinished{} -> Nothing -- | accesses an object from the mainLayer mainLayerObjectA :: Index -> Accessor (Scene o) o mainLayerObjectA i = objects .> gameMainLayer .> indexA i data CameraState = CS Index Vector deriving Show data Contacts = Contacts { nikkiCollisions :: [NikkiCollision], nikkiTouchesDeadly :: !Bool, triggers :: Set Shape, terminals :: Set Shape, batteries :: Set Shape, fallingTiles :: Set Shape, nearestSign :: Maybe (Shape, CpFloat) } deriving Show data MyCollisionType = NikkiHeadCT | NikkiLegsCT | NikkiGhostCT | TileCT | TerminalCT | DeadlySolidCT | DeadlyPermeableCT | PermeableCT | RobotCT | TriggerCT | BatteryCT | SignCT | FallingTileCT deriving (Eq, Ord, Enum, Bounded, Show) instance PP MyCollisionType where pp = show data NikkiCollision = NikkiCollision { nikkiCollisionShape :: !Shape, nikkiCollisionAngle :: !Angle, nikkiCollisionPosition :: !Vector, nikkiCollisionType :: !MyCollisionType } deriving (Show) instance PP NikkiCollision where pp (NikkiCollision a b c d) = "NikkiCollision " ++ show a <~> pp b <~> pp c <~> pp d -- * mode for the game scene data Mode = NikkiMode { nikki :: Index } | TerminalMode { nikki :: Index, terminal :: Index } | RobotMode{ nikki :: Index, terminal :: Index, robot :: Index } | LevelFinished { levelScore :: Score, levelResult :: LevelResult } deriving Show mkLevelFinished :: Scene o -> LevelResult -> Mode mkLevelFinished scene result = LevelFinished (mkScore result (scene ^. spaceTime) (St.fst (scene ^. batteryPower))) result -- | returns, if Nikki is controlled currently isNikkiMode :: Mode -> Bool isNikkiMode NikkiMode{} = True -- | returns, if a robot is controlled currently isRobotMode :: Mode -> Bool isRobotMode RobotMode{} = True isRobotMode _ = False isTerminalMode :: Mode -> Bool isTerminalMode TerminalMode{} = True isTerminalMode _ = False isLevelFinishedMode :: Mode -> Bool isLevelFinishedMode LevelFinished{} = True isLevelFinishedMode _ = False isGameMode :: Mode -> Bool isGameMode = not . isLevelFinishedMode data LevelResult = Passed | Failed deriving (Eq, Ord, Show) -- | versioned type for scores data Score = Score_0 { scoreTime_ :: Seconds, scoreBatteryPower_ :: Integer } | Score_1_Tried -- played but not passed | Score_1_Passed { scoreTime_ :: Seconds, scoreBatteryPower_ :: Integer } deriving (Eq, Show) scoreTimeA :: Accessor Score Seconds scoreTimeA = accessor scoreTime_ (\ a r -> r{scoreTime_ = a}) scoreBatteryPowerA :: Accessor Score Integer scoreBatteryPowerA = accessor scoreBatteryPower_ (\ a r -> r{scoreBatteryPower_ = a}) toNewestScore :: Score -> Score toNewestScore (Score_0 time batteries) = Score_1_Passed time batteries toNewestScore x = x isPassedScore :: Score -> Bool isPassedScore Score_0{} = True isPassedScore Score_1_Tried{} = False isPassedScore Score_1_Passed{} = True instance Binary.Binary Score where put (Score_0 a b) = do Binary.putWord8 0 Binary.put a Binary.put b put Score_1_Tried = Binary.putWord8 1 put (Score_1_Passed a b) = do Binary.putWord8 2 Binary.put a Binary.put b get = toNewestScore <$> do i <- Binary.getWord8 case i of 0 -> Score_0 <$> Binary.get <*> Binary.get 1 -> return Score_1_Tried 2 -> Score_1_Passed <$> Binary.get <*> Binary.get mkScore :: LevelResult -> Seconds -> Integer -> Score mkScore Passed t = Score_1_Passed (roundTime t) where roundTime :: Seconds -> Seconds roundTime = (* (10 ^ timeDigits)) >>> ceiling >>> fromIntegral >>> (/ (10 ^ timeDigits)) mkScore Failed _ = const Score_1_Tried -- * EditorScene types data EditorScene sort = EditorScene { editorLevelFile :: LevelFile, cursor :: EditorPosition, cursorStep :: Maybe EditorPosition, -- if Nothing -> size of selected object availableSorts_ :: SelectTree sort, editorObjects_ :: Grounds (EditorObject sort), selectedLayer_ :: GroundsIndex, selected :: Maybe (GroundsIndex, Index), -- index of the object that is in the scene and currently under the cursor editorMode :: EditorMode, clipBoard :: [EditorObject sort], cachedTiles_ :: CachedTiles } deriving (Show, Typeable) editorObjects :: Accessor (EditorScene sort) (Grounds (EditorObject sort)) editorObjects = accessor editorObjects_ (\ a r -> r{editorObjects_ = a}) selectedLayer :: Accessor (EditorScene sort) GroundsIndex selectedLayer = accessor selectedLayer_ (\ a r -> r{selectedLayer_ = a}) availableSorts :: Accessor (EditorScene sort) (SelectTree sort) availableSorts = accessor availableSorts_ (\ a r -> r{availableSorts_ = a}) cachedTiles :: Accessor (EditorScene sort) CachedTiles cachedTiles = accessor cachedTiles_ (\ a r -> r{cachedTiles_ = a}) instance Show (EditorScene sort -> EditorPosition) where show _ = "<EditorScene -> EditorPosition>" type CachedTiles = Maybe [ShapeType] data EditorMode = NormalMode | ObjectEditMode { objectIndex :: Index } | SelectionMode { endPosition :: EditorPosition } deriving (Eq, Show, Typeable) toSelectionMode :: EditorScene s -> EditorScene s toSelectionMode scene = scene{editorMode = SelectionMode (cursor scene)} data EditorPosition = EditorPosition { editorX :: Double, editorY :: Double } deriving (Show, Read, Eq, Typeable, Data) instance Abelian EditorPosition where zero = EditorPosition 0 0 (EditorPosition a b) +~ (EditorPosition x y) = EditorPosition (a + x) (b + y) (EditorPosition a b) -~ (EditorPosition x y) = EditorPosition (a - x) (b - y) -- * Editor objects data EditorObject sort = EditorObject { editorSort :: sort, editorPosition_ :: EditorPosition, editorOEMState_ :: Maybe OEMState } deriving (Show, Functor) editorPosition :: Accessor (EditorObject sort) EditorPosition editorPosition = accessor editorPosition_ (\ a r -> r{editorPosition_ = a}) editorOEMState :: Accessor (EditorObject s) (Maybe OEMState) editorOEMState = accessor editorOEMState_ (\ a r -> r{editorOEMState_ = a}) -- | modifies all EditorPositions of the OEMState of EditorObjects modifyOEMEditorPositions :: (EditorPosition -> EditorPosition) -> EditorObject s -> EditorObject s modifyOEMEditorPositions f o@EditorObject{editorOEMState_ = Nothing} = o modifyOEMEditorPositions f o@EditorObject{editorOEMState_ = Just (OEMState state)} = editorOEMState ^= (Just $ OEMState $ transformBi f state) $ o -- * object edit mode class (Typeable a, Data a) => IsOEMState a where oemEnterMode :: Sort sort o => EditorScene sort -> a -> a oemUpdate :: EditorScene sort -> Button -> a -> OEMUpdateMonad a oemNormalize :: Sort sort o => EditorScene sort -> a -> a oemRender :: Sort sort o => Ptr QPainter -> Application -> Configuration -> EditorScene sort -> a -> IO () oemPickle :: a -> String -- phantom type oemHelp :: a -> String type OEMUpdateMonad a = Either OEMException a oemNothing :: OEMUpdateMonad a oemNothing = Left OEMNothing oemError :: OEMUpdateMonad a oemError = Left OEMError data OEMException = OEMNothing -- Nothing to be done, state is the same (help screen is shown?) | OEMError -- an error occured (emit an error sound) data OEMState = forall a . IsOEMState a => OEMState a deriving Typeable instance Show OEMState where show = const "<OEMState>" instance Data OEMState where gfoldl = oemStateDataInstanceError gunfold = oemStateDataInstanceError toConstr = oemStateDataInstanceError dataTypeOf = oemStateDataInstanceError oemStateDataInstanceError = error "don't use Data instance of OEMState" instance IsOEMState OEMState where oemEnterMode scene (OEMState a) = OEMState $ oemEnterMode scene a oemUpdate scene button (OEMState a) = fmap OEMState $ oemUpdate scene button a oemNormalize scene (OEMState a) = OEMState $ oemNormalize scene a oemRender ptr app config scene (OEMState a) = oemRender ptr app config scene a oemPickle (OEMState a) = oemPickle a oemHelp (OEMState a) = oemHelp a data OEMMethods = OEMMethods { oemInitialize :: EditorPosition -> OEMState, oemUnpickle :: String -> Maybe OEMState } -- * Objects newtype SortId = SortId {getSortId :: FilePath} deriving (Show, Read, Eq) data RenderMode = Iconified | InScene { offset :: Qt.Position Double } -- * Sort class -- | Class that every sort of objects has to implement. This is the interface between -- the game and the implemented objects. -- Minimal complete definition: 'sortId', 'size', 'sortRender', -- 'renderIconified', 'initialize', 'immutableCopy', 'chipmunks', 'renderObject' class (Show sort, Typeable sort, Show object, Typeable object) => Sort sort object | sort -> object, object -> sort where sortId :: sort -> SortId -- free memory for allocated resources freeSort :: sort -> IO () freeSort = const $ return () size :: sort -> Size Double -- Sorts that support an object edit mode have to return Just (initial, unpickle) here. objectEditMode :: sort -> Maybe OEMMethods objectEditMode _ = Nothing renderIconified :: sort -> Ptr QPainter -> IO () renderEditorObject :: Ptr QPainter -> Offset Double -> EditorObject sort -> IO () renderEditorObject ptr offset editorObject = do resetMatrix ptr translate ptr offset let sort = editorSort editorObject translate ptr (epToPosition (size sort) (editorObject ^. editorPosition)) renderIconified sort ptr -- if Nothing is passed as space, this should be an object -- that is not added to the chipmunk space (i.e. background tiles) initialize :: Application -> LevelFile -> Maybe Space -> sort -> EditorPosition -> Maybe OEMState -> CachedTiles -> RM object freeObject :: object -> IO () freeObject = const $ return () immutableCopy :: object -> IO object chipmunks :: object -> [Chipmunk] -- | only implemented in Nikki and robots getControlledChipmunk :: Scene Object_ -> object -> Chipmunk getControlledChipmunk scene o = error ("please implement getControlledChipmunk in: " ++ show o) startControl :: Seconds -> object -> object startControl now = id isUpdating :: object -> Bool -- phantom type update :: sort -> Application -> Configuration -> Space -> Scene Object_ -> Seconds -> Contacts -> (Bool, ControlData) -> Index -> object -> StateT (Scene Object_ -> Scene Object_) IO object update sort app config space scene now contacts cd i o = io $ updateNoSceneChange sort app config space scene now contacts cd o updateNoSceneChange :: sort -> Application -> Configuration -> Space -> Scene Object_ -> Seconds -> Contacts -> (Bool, ControlData) -> object -> IO object updateNoSceneChange _ _ _ _ _ _ _ _ o = return o renderObject :: Application -> Configuration -> object -> sort -> Ptr QPainter -> Offset Double -> Seconds -> IO [RenderPixmap] pushSceneChange :: (Scene Object_ -> Scene Object_) -> StateT (Scene Object_ -> Scene Object_) IO () pushSceneChange f = modify (>>> f) -- * position conversions -- from lower left to upper left epToPosition :: Size Double -> EditorPosition -> Qt.Position Double epToPosition size (EditorPosition x y) = Position x (y - height size) epToCenterPosition :: Size Double -> EditorPosition -> Qt.Position Double epToCenterPosition size ep = epToPosition size ep +~ fmap (/ 2) (size2position size) epToCenterVector :: Size Double -> EditorPosition -> Vector epToCenterVector size = position2vector . epToCenterPosition size editorComponentWise :: (Double -> Double -> Double) -> EditorPosition -> EditorPosition -> EditorPosition editorComponentWise (#) (EditorPosition a b) (EditorPosition x y) = EditorPosition (a # x) (b # y) -- * Sort class wrappers data Sort_ = forall sort object . (Sort sort object, Show sort, Typeable sort) => Sort_ sort | DummySort -- used if the wrapper object (Object_) will find the sort. deriving Typeable data Object_ = forall sort object . (Sort sort object, Show sort, Typeable sort, Show object, Typeable object) => Object_ sort object deriving (Typeable) instance Show Object_ where show (Object_ s o) = "Object_ (" ++ show o ++ ")" instance Show Sort_ where show (Sort_ s) = "Sort_ (" ++ show s ++ ")" instance Eq Sort_ where a == b = sortId a == sortId b instance Sort Sort_ Object_ where sortId (Sort_ s) = sortId s freeSort (Sort_ s) = freeSort s size (Sort_ s) = size s objectEditMode (Sort_ s) = objectEditMode s renderIconified (Sort_ s) = renderIconified s renderEditorObject ptr offset editorObject = case editorSort editorObject of (Sort_ innerSort) -> renderEditorObject ptr offset editorObject{editorSort = innerSort} initialize app file space (Sort_ sort) editorPosition state cachedTiles = Object_ sort <$> initialize app file space sort editorPosition state cachedTiles freeObject (Object_ _ o) = freeObject o immutableCopy (Object_ s o) = Object_ s <$> Base.Types.immutableCopy o chipmunks (Object_ _ o) = chipmunks o getControlledChipmunk scene (Object_ _ o) = getControlledChipmunk scene o startControl now (Object_ sort o) = Object_ sort $ startControl now o isUpdating (Object_ _ o) = isUpdating o update DummySort app controls space mode now contacts cd i (Object_ sort o) = Object_ sort <$> Base.Types.update sort app controls space mode now contacts cd i o updateNoSceneChange DummySort app controls space mode now contacts cd (Object_ sort o) = Object_ sort <$> updateNoSceneChange sort app controls space mode now contacts cd o renderObject = error "Don't use this function, use render_ instead (that's type safe)" sort_ :: Object_ -> Sort_ sort_ (Object_ sort _) = Sort_ sort -- * level files data LevelFile = StandardLevel { levelPath :: FilePath , levelPackage :: FilePath , levelFileName :: FilePath , levelMetaData_ :: LevelMetaData } | UserLevel { levelPath :: FilePath , levelPackage :: FilePath , levelFileName :: FilePath , levelMetaData_ :: LevelMetaData } | EpisodeLevel { levelEpisode :: Episode LevelFile , levelPath :: FilePath , levelPackage :: FilePath , levelFileName :: FilePath , levelMetaData_ :: LevelMetaData } | TemplateLevel {levelFilePath :: FilePath} | UnknownLevelType {levelFilePath :: FilePath} deriving (Show) type LevelUID = String -- | unique ID of a level levelUID :: LevelFile -> LevelUID levelUID (StandardLevel dir package file meta) = "standardLevels" <//> package <//> file levelUID (UserLevel dir package file meta) = "userLevels" <//> package <//> file levelUID (EpisodeLevel _ dir package file meta) = "storyModeLevels" <//> package <//> file levelUID (TemplateLevel path) = "templateLevels" <//> path levelUID (UnknownLevelType path) = "unknownLevels" <//> path getAbsoluteFilePath :: LevelFile -> FilePath getAbsoluteFilePath (TemplateLevel p) = p getAbsoluteFilePath (UnknownLevelType p) = p getAbsoluteFilePath x = levelPath x </> levelPackage x </> levelFileName x levelMetaData :: LevelFile -> LevelMetaData levelMetaData StandardLevel{..} = levelMetaData_ levelMetaData UserLevel{..} = levelMetaData_ levelMetaData EpisodeLevel{..} = levelMetaData_ levelMetaData file = LevelMetaData (guessName $ getAbsoluteFilePath file) Nothing Nothing Nothing Nothing
changlinli/nikki
src/Base/Types.hs
lgpl-3.0
23,044
0
20
5,266
6,153
3,302
2,851
548
4
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, UnicodeSyntax, FlexibleContexts #-} -- | The Sweetroll prelude == ClassyPrelude + more stuff. module Sweetroll.Prelude ( module X , module Sweetroll.Prelude ) where import RIO as X (HasLogFunc, HasCallStack, logDebug, logInfo, logWarn, logError, display, MonadThrow, throwM) import ClassyPrelude as X hiding (fromString, (<>)) import Magicbane as X import Control.Monad.Trans.Except as X (throwE) import Control.Lens as X hiding (Index, index, cons, snoc, uncons, unsnoc, (<.>), (.=), (|>), (<|), Context, Strict) import Text.XML (Document, Element) import qualified Data.Text import Data.Default as X import Data.Maybe (fromJust) import Data.List as X (nub) import Data.List.Split as X (splitOn) import Data.Char as X (isSpace, generalCategory, GeneralCategory(..)) import qualified Data.HashMap.Strict as HMS import Data.Aeson.Lens as X hiding (nonNull) type XDocument = Text.XML.Document type XElement = Text.XML.Element infixl 1 |> (|>) ∷ Monad μ ⇒ μ α → (α → β) → μ β (|>) = flip liftM firstStr v l = (v ^? l . _String) <|> (v ^? values . l . _String) <|> (v ^? l . values . _String) uriPathParts ∷ ConvertibleStrings Text α ⇒ URI → [α] uriPathParts = map cs . Data.Text.splitOn "/" . drop 1 . cs . uriPath orEmptyMaybe ∷ IsString α ⇒ Maybe α → α orEmptyMaybe = fromMaybe "" ensureArrayProp ∷ Text → Value → Value ensureArrayProp k (Object o) | HMS.member k o = Object o ensureArrayProp k (Object o) = Object $ HMS.insert k (Array empty) o ensureArrayProp _ v = v errWrongDomain ∷ ServantErr errWrongDomain = errText err400 "The target URI is not on this domain." errWrongPath ∷ ServantErr errWrongPath = errText err400 "The target URI is not a resource that exists on this domain." errNotFound ∷ ServantErr errNotFound = errText err404 "Not found" errNoURIInField ∷ LByteString → ServantErr errNoURIInField f = errText err400 $ "You didn't put a valid absolute URI in the '" ++ f ++ "' field of the www-form-urlencoded request body." guardJustP ∷ MonadThrow μ ⇒ ServantErr → Maybe α → μ α guardJustP _ (Just x) = return x guardJustP e Nothing = throwM e guardJustM ∷ MonadThrow μ ⇒ μ ServantErr → μ (Maybe α) → μ α guardJustM ea a = a >>= \x → case x of Just v → return v Nothing → throwM =<< ea guardJust ∷ MonadThrow μ ⇒ ServantErr → μ (Maybe α) → μ α guardJust e = guardJustM (return e) guardBool ∷ MonadThrow μ ⇒ ServantErr → Bool → μ () guardBool e x = unless x $ throwM e guardBoolM ∷ MonadThrow μ ⇒ μ ServantErr → Bool → μ () guardBoolM ea False = throwM =<< ea guardBoolM _ True = return () base ∷ ConvertibleStrings a String ⇒ Maybe a → URI base (Just x) = fromJust $ parseURI $ "https://" ++ cs x -- have to parse because it might have a port number base Nothing = URI "http:" (Just $ URIAuth "" "localhost" "") "" "" "" compareDomain ∷ URI → URI → Bool compareDomain x y = (uriRegName <$> uriAuthority x) == (uriRegName <$> uriAuthority y) ensureRightDomain ∷ MonadThrow μ ⇒ URI → URI → μ () ensureRightDomain x y = guardBool errWrongDomain $ compareDomain x y guardEntryNotFound ∷ MonadThrow μ ⇒ Maybe α → μ α guardEntryNotFound (Just obj) = return obj guardEntryNotFound Nothing = throwErrText err404 "Entry not found." withTrailingSlash ∷ Text → [Text] withTrailingSlash t = let t' = fromMaybe t (stripSuffix "/" t) in [ t', t' ++ "/" ]
myfreeweb/sweetroll
sweetroll-be/library/Sweetroll/Prelude.hs
unlicense
3,670
0
11
783
1,197
642
555
-1
-1
{-#LANGUAGE DeriveDataTypeable#-} module Data.P440.Domain.ZSO where import Data.P440.Domain.SimpleTypes import Data.P440.Domain.ComplexTypes import Data.P440.Domain.ComplexTypesZS import Data.Typeable (Typeable) import Data.Text (Text) -- 2.4 Запрос НО об остатках data Файл = Файл { идЭС :: GUID ,версПрог :: Text ,телОтпр :: Text ,должнОтпр :: Text ,фамОтпр :: Text ,запросОст :: ЗапросОст } deriving (Eq, Show, Typeable) data ЗапросОст = ЗапросОст { номЗапр :: Text ,стНКРФ :: Text ,видЗапр :: Text ,основЗапр :: Text ,типЗапр :: Text ,признЗапр :: Maybe Text ,датаПоСост :: Date ,датаПодп :: Date ,свНО :: СвНО ,свПл :: СвПл ,банкИлиУБР :: СвБанкИлиСвУБР ,счетИлиКЭСП :: СчетИлиКЭСП ,руководитель :: РукНО } deriving (Eq, Show, Typeable) data СчетИлиКЭСП = Счет [НомСч] | КЭСП [Text] deriving (Eq, Show, Typeable)
Macil-dev/440P-old
src/Data/P440/Domain/ZSO.hs
unlicense
1,262
61
8
294
634
339
295
33
0
module Kata02.Chop2 (chop) where import Data.List chop :: Int -> [Int] -> Int chop _ [] = -1 chop x xs = let indexedXs = zip xs [0..] in chop' x indexedXs chop' :: Int -> [(Int, Int)] -> Int chop' x [(y, i)] | x == y = i | otherwise = -1 chop' x xs | x <= y = chop' x first | otherwise = chop' x second where mid = length xs `quot` 2 (first, second) = splitAt mid xs (y, i) = last first
safwank/HaskellKata
src/Kata02/Chop2.hs
apache-2.0
425
0
10
127
229
118
111
17
1
{-# LANGUAGE OverloadedStrings #-} module Main ( main, ) where import Test.Framework (defaultMain) import RuleInfo.ExecutionRoot (fixFilePathFlags, fakeExecutionRoot) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit ((@?=)) main :: IO () main = defaultMain [ testCase "fixFilePathFlags" $ do let flags = [ "-package-db=foo/bar", "-pgmP", "some/path", "-optP-isystem", "-optPinclude/dir", "-optP-isystem", "without-optP", -- not prefixed with -optP; should not be modified "-some-flag=some-value", "-another-flag", "another value" ] fixFilePathFlags (fakeExecutionRoot "/root/path") flags @?= [ "-package-db=/root/path/foo/bar", "-pgmP", "/root/path/some/path", "-optP-isystem", "-optP/root/path/include/dir", "-optP-isystem", "without-optP", "-some-flag=some-value", "-another-flag", "another value" ] ]
google/hrepl
rule_info/RuleInfo/ExecutionRootTest.hs
apache-2.0
1,195
0
13
452
174
105
69
33
1
{-| Module : Core Description : Core namespace module. Copyright : (c) Nashwan Azhari, 2016 License : Apache 2.0 Maintainer : [email protected] Stability : experimental Portability : POSIX, Win32 Core contains the core components of the project. -} module Cloud.Haskzure.Core ( -- ** The AzureResource typeclass. AzureResource(..), -- ** The Resource ADT. Resource(..), -- ** Authentication data strutures and functions: Credentials(..), Token(..), getToken, createOrUpdate, get, delete ) where import Cloud.Haskzure.Core.Auth import Cloud.Haskzure.Core.AzureResource import Cloud.Haskzure.Core.Operations import Cloud.Haskzure.Core.Resource
aznashwan/haskzure
Cloud/Haskzure/Core.hs
apache-2.0
745
0
5
177
81
58
23
10
0
import Data.List (isSuffixOf) import Control.Applicative import Test.Framework (defaultMain, testGroup, Test) import Test.Framework.Providers.HUnit import Test.HUnit (assertFailure) import System.Directory import System.Exit (ExitCode(..)) import System.Process main :: IO () main = makeTests "test" >>= defaultMain -- Make a test out of those things which end in ".sh" and are executable -- Make a testgroup out of directories makeTests :: FilePath -> IO [Test] makeTests dir = do origDir <- getCurrentDirectory contents <- getDirectoryContents dir setCurrentDirectory dir retval <- mapM fileFunc contents setCurrentDirectory origDir return $ concat retval where fileFunc "." = return [] fileFunc ".." = return [] fileFunc f | ".sh" `isSuffixOf` f = do fullName <- canonicalizePath f isExecutable <- executable <$> getPermissions fullName let hunitTest = mkTest fullName return [testCase f hunitTest | isExecutable] fileFunc d = do fullName <- canonicalizePath d isSearchable <- searchable <$> getPermissions fullName if isSearchable then do subTests <- makeTests d return [testGroup d subTests] else return [] mkTest fullName = do execResult <- system fullName case execResult of ExitSuccess -> return () ExitFailure code -> assertFailure ("Failed with code " ++ show code)
fizbin/cabal-demo-backflip
test/BackflipShellTests.hs
apache-2.0
1,415
0
15
318
403
194
209
37
6
module Text.SRX ( parseSRX ) where import Control.Applicative ((<$>), (<*>)) import qualified Text.XML.PolySoup as Soup import Text.XML.PolySoup hiding (XmlParser, Parser) import qualified Data.SRX as S type Parser a = Soup.XmlParser String a type SRX = S.SRX String type Lang = S.Lang String type Rule = S.Rule String srxP :: Parser SRX srxP = tag "srx" `joinR` do cut (tag "header") bodyP bodyP :: Parser SRX bodyP = S.SRX <$> (tag "body" `joinR` (langsP <* mapRulesP)) langsP :: Parser [Lang] langsP = tag "languagerules" `joinR` many1 langP langP :: Parser Lang langP = (tag "languagerule" *> getAttr "languagerulename") `join` \name -> S.Lang name <$> many1 ruleP ruleP :: Parser Rule ruleP = (tag "rule" *> getAttr "break") `join` \break -> (S.Rule (break == "yes") <$> beforeP <*> afterP) beforeP :: Parser String beforeP = tag "beforebreak" `joinR` do maybe "" id <$> optional text afterP :: Parser String afterP = tag "afterbreak" `joinR` do maybe "" id <$> optional text mapRulesP :: Parser () mapRulesP = cut (tag "maprules") parseSRX :: String -> SRX parseSRX = parseXML srxP
kawu/tokenize
Text/SRX.hs
bsd-2-clause
1,130
0
12
219
434
236
198
34
1
module Database.SqlServer.Create.Database where import Database.SqlServer.Create.Identifier (RegularIdentifier) import Database.SqlServer.Create.Table (Table) import Database.SqlServer.Create.View (View) import Database.SqlServer.Create.Sequence (Sequence) import Database.SqlServer.Create.Procedure (Procedure) import Database.SqlServer.Create.User (User, Role) import Database.SqlServer.Create.FullTextCatalog (FullTextCatalog) import Database.SqlServer.Create.FullTextStopList (FullTextStopList) import Database.SqlServer.Create.Function (Function) import Database.SqlServer.Create.Credential (Credential) import Database.SqlServer.Create.MessageType (MessageType) import Database.SqlServer.Create.BrokerPriority (BrokerPriority) import Database.SqlServer.Create.PartitionFunction (PartitionFunction) import Database.SqlServer.Create.Contract (Contract) import Database.SqlServer.Create.Login (Login) import Database.SqlServer.Create.Certificate (Certificate) import Database.SqlServer.Create.Entity import Test.QuickCheck import Text.PrettyPrint hiding (render) data MasterKey = MasterKey instance Arbitrary MasterKey where arbitrary = return MasterKey renderMasterKey :: MasterKey -> Doc renderMasterKey _ = text "CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'weKKjwehg252t!!'" $+$ text "GO" data RenderOptions = RenderOptions { showTables :: Bool , showViews :: Bool , showSequences :: Bool , showProcedures :: Bool , showFunctions :: Bool , showUsers :: Bool , showRoles :: Bool , showFullTextCatalog :: Bool , showFullTextStopList :: Bool , showCredential :: Bool , showMessageType :: Bool , showBrokerPriority :: Bool , showPartitionFunction :: Bool , objectsPerType :: Int } deriving (Show) defaultRenderOptions :: RenderOptions defaultRenderOptions = RenderOptions True True True True True True True True True True True True True 10000000 data Database = Database { databaseName :: RegularIdentifier , tables :: [Table] , views :: [View] , sequences :: [Sequence] , procedures :: [Procedure] , functions :: [Function] , users :: [User] , roles :: [Role] , fullTextCatalogs :: [FullTextCatalog] , fullTextStopLists :: [FullTextStopList] , credentials :: [Credential] , messages :: [MessageType] , brokerPriorities :: [BrokerPriority] , partitionFunctions :: [PartitionFunction] , logins :: [Login] , contracts :: [Contract] , certificates :: [Certificate] , masterKey :: MasterKey } instance Entity Database where name = databaseName render = renderDatabase defaultRenderOptions -- Todo rename to renderentities renderNamedEntities :: Entity a => [a] -> Doc renderNamedEntities xs = vcat (map render xs) renderEntitiesIf :: Entity a => Bool -> [a] -> Doc renderEntitiesIf False _ = empty renderEntitiesIf True xs = renderNamedEntities xs renderDatabase :: RenderOptions -> Database -> Doc renderDatabase ro dd = text "USE master" $+$ text "GO" $+$ text "CREATE DATABASE" <+> dbName $+$ text "GO" $+$ text "USE" <+> dbName $+$ renderMasterKey (masterKey dd) $+$ renderEntitiesIf (showTables ro) (take n $ tables dd) $+$ renderEntitiesIf (showViews ro) (take n $ views dd) $+$ renderEntitiesIf (showSequences ro) (take n $ sequences dd) $+$ renderEntitiesIf (showProcedures ro) (take n $ procedures dd) $+$ renderEntitiesIf (showFunctions ro) (take n $ functions dd) $+$ renderEntitiesIf (showUsers ro) (take n $ users dd) $+$ renderEntitiesIf (showRoles ro) (take n $ roles dd) $+$ renderEntitiesIf (showFullTextCatalog ro) (take n $ fullTextCatalogs dd) $+$ renderEntitiesIf (showFullTextStopList ro) (take n $ fullTextStopLists dd) $+$ renderEntitiesIf (showCredential ro) (take n $ credentials dd) $+$ renderEntitiesIf (showMessageType ro) (take n $ messages dd) $+$ renderEntitiesIf (showBrokerPriority ro) (take n $ brokerPriorities dd) $+$ renderEntitiesIf (showPartitionFunction ro) (take n $ partitionFunctions dd) where dbName = renderName dd n = objectsPerType ro instance Arbitrary Database where arbitrary = Database <$> arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> infiniteListOf arbitrary <*> arbitrary instance Show Database where show = show . render
fffej/sql-server-gen
src/Database/SqlServer/Create/Database.hs
bsd-2-clause
4,702
0
25
757
1,293
705
588
118
1
module Database.VCache.Read ( readAddrIO , readRefctIO , withBytesIO ) where import Control.Monad import qualified Data.Map.Strict as Map import qualified Data.List as L import Control.Concurrent.MVar import Data.Word import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Alloc import Database.LMDB.Raw import Database.VCache.Types import Database.VCache.VGetInit import Database.VCache.VGetAux import Database.VCache.Refct -- | Parse contents at a given address. Returns both the value and the -- cache weight, or fails. This first tries reading the database, then -- falls back to reading from recent allocation frames. readAddrIO :: VSpace -> Address -> VGet a -> IO (a, Int) readAddrIO vc addr = withAddrValIO vc addr . readVal vc {-# INLINE readAddrIO #-} withAddrValIO :: VSpace -> Address -> (MDB_val -> IO a) -> IO a withAddrValIO vc addr action = alloca $ \ pAddr -> poke pAddr addr >> let vAddr = MDB_val { mv_data = castPtr pAddr , mv_size = fromIntegral (sizeOf addr) } in withRdOnlyTxn vc $ \ txn -> mdb_get' txn (vcache_db_memory vc) vAddr >>= \ mbData -> case mbData of Just vData -> action vData -- found data in database (ideal) Nothing -> -- since not in the database, try the allocator let ff = Map.lookup addr . alloc_list in readMVar (vcache_memory vc) >>= \ memory -> let ac = mem_alloc memory in case allocFrameSearch ff ac of Just an -> withByteStringVal (alloc_data an) action -- found data in allocator Nothing -> fail $ "VCache: address " ++ show addr ++ " is undefined!" {-# NOINLINE withAddrValIO #-} readVal :: VSpace -> VGet a -> MDB_val -> IO (a, Int) readVal vc p v = _vget (vgetFull p) s0 >>= retv where s0 = VGetS { vget_children = [] , vget_target = mv_data v , vget_limit = mv_data v `plusPtr` fromIntegral (mv_size v) , vget_space = vc } retv (VGetR result _) = return result retv (VGetE eMsg) = fail eMsg -- get the full value and weight vgetFull :: VGet a -> VGet (a, Int) vgetFull parser = do vgetInit w <- vgetWeight r <- parser assertDone return (r,w) assertDone :: VGet () assertDone = isEmpty >>= \ b -> unless b (fail emsg) where emsg = "VCache: failed to read full input" {-# INLINE assertDone #-} vgetWeight :: VGet Int vgetWeight = VGet $ \ s -> let nBytes = vget_limit s `minusPtr` vget_target s in let nRefs = L.length (vget_children s) in let w = cacheWeight nBytes nRefs in w `seq` return (VGetR w s) {-# INLINE vgetWeight #-} -- | Read a reference count for a given address. readRefctIO :: VSpace -> Address -> IO Int readRefctIO vc addr = alloca $ \ pAddr -> withRdOnlyTxn vc $ \ txn -> poke pAddr addr >> let vAddr = MDB_val { mv_data = castPtr pAddr , mv_size = fromIntegral (sizeOf addr) } in mdb_get' txn (vcache_db_refcts vc) vAddr >>= \ mbData -> maybe (return 0) readRefctBytes mbData -- | Zero-copy access to raw bytes for an address. withBytesIO :: VSpace -> Address -> (Ptr Word8 -> Int -> IO a) -> IO a withBytesIO vc addr action = withAddrValIO vc addr $ \ v -> action (mv_data v) (fromIntegral (mv_size v)) {-# INLINE withBytesIO #-}
bitemyapp/haskell-vcache
hsrc_lib/Database/VCache/Read.hs
bsd-2-clause
3,401
0
28
910
982
510
472
78
3
module Data.Parser.Grempa.Parser.Driver ( driver , resultDriver , ReductionTree ) where import Control.Applicative import Data.Dynamic import Data.List import Data.Maybe import Data.Parser.Grempa.Parser.Result import Data.Parser.Grempa.Parser.Table import qualified Data.Parser.Grempa.Grammar.Typed as T import Data.Parser.Grempa.Grammar.Token -- | Data type for reduction trees output by the driver data ReductionTree s = RTReduce RuleI ProdI [ReductionTree s] | RTTerm s deriving Show rtToTyped :: Token s => (s' -> s) -> ProdFunFun -> ReductionTree s' -> Dynamic rtToTyped unc _ (RTTerm s) = toDyn (unc s) rtToTyped unc funs (RTReduce r p tree) = applDynFun fun l where l = map (rtToTyped unc funs) tree fun = funs r p driver :: Token s => (ActionFun s, GotoFun s, StateI) -> [s] -> ParseResult s (ReductionTree s) driver (actionf, gotof, start) input = driver' [start] (map Tok input ++ [EOF]) [] [] (0 :: Integer) where driver' stack@(s:_) (a:rest) rt ests pos = case actionf s a of Shift t -> driver' (t : stack) rest (RTTerm (unTok a) : rt) [] (pos + 1) Reduce rule prod len es -> driver' (got : stack') (a : rest) rt' (es ++ ests) pos where stack'@(t:_) = drop len stack got = gotof t rule rt' = RTReduce rule prod (reverse $ take len rt) : drop len rt Accept -> Right $ head rt Error es -> Left $ ParseError (nub $ es ++ ests) pos driver' _ _ _ _ pos = Left $ InternalParserError pos type RTParseResult s = ParseResult s (ReductionTree s) resultDriver :: (Token s, Typeable a) => (s' -> s) -> ProdFunTable -> T.Grammar s a -> RTParseResult s' -> ParseResult s a resultDriver unc funs _ rt = fromJust <$> fromDynamic <$> rtToTyped unc (prodFunToFun funs) <$> either (Left . fmap unc) Right rt
ollef/Grempa
Data/Parser/Grempa/Parser/Driver.hs
bsd-3-clause
2,000
0
16
591
733
387
346
42
5
-- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- module Feldspar.Core.Frontend.Binding where import Language.Syntactic import Feldspar.Core.Constructs.Binding import Feldspar.Core.Constructs -- | Share an expression in the scope of a function share :: (Syntax a, Syntax b) => a -> (a -> b) -> b share = sugarSymC Let -- | Share the intermediate result when composing functions (.<) :: (Syntax b, Syntax c) => (b -> c) -> (a -> b) -> a -> c (.<) f g a = share (g a) f infixr 9 .< -- | Share an expression in the scope of a function ($<) :: (Syntax a, Syntax b) => (a -> b) -> a -> b ($<) = flip share infixr 0 $<
emwap/feldspar-language
src/Feldspar/Core/Frontend/Binding.hs
bsd-3-clause
2,169
0
9
411
229
144
85
12
1
{- | The `ArrowKleisli' type class allows for embedding monadic operations in Kleisli arrows. -} {-# LANGUAGE FlexibleInstances , FunctionalDependencies , MultiParamTypeClasses , TypeOperators #-} module Control.Arrow.Kleisli.Class where import Control.Arrow import Control.Category import Control.Monad.Trans import Prelude hiding (id, (.)) class (Monad m, Arrow arr) => ArrowKleisli m arr | arr -> m where arrM :: (a -> m b) -> a `arr` b instance Monad m => ArrowKleisli m (Kleisli m) where arrM f = Kleisli f constM :: ArrowKleisli m arr => m b -> a `arr` b constM a = arrM (const a) effect :: ArrowKleisli m arr => m () -> a `arr` a effect a = arrM (\b -> a >> return b) arrIO :: (MonadIO m, ArrowKleisli m arr) => (a -> IO b) -> a `arr` b arrIO f = arrM (liftIO . f)
silkapp/arrow-list
src/Control/Arrow/Kleisli/Class.hs
bsd-3-clause
794
4
10
162
286
153
133
20
1
{- Stroke.hs (adapted from stroke.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2006 <[email protected]> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE This program demonstrates some characters of a stroke (vector) font. The characters are represented by display lists, which are given numbers which correspond to the ASCII values of the characters. Use of callLists is demonstrated. -} import Data.List ( genericLength ) import Foreign.C.String ( castCharToCChar ) import Foreign.Marshal.Array ( withArray ) import Graphics.UI.GLUT import System.Exit ( exitWith, ExitCode(ExitSuccess) ) aData, eData, pData, rData, sData :: [[Vertex2 GLfloat]] aData = [ [ Vertex2 0 0, Vertex2 0 9, Vertex2 1 10, Vertex2 4 10, Vertex2 5 9, Vertex2 5 0 ], [ Vertex2 0 5, Vertex2 5 5 ] ] eData = [ [ Vertex2 5 0, Vertex2 0 0, Vertex2 0 10, Vertex2 5 10 ], [ Vertex2 0 5, Vertex2 4 5 ] ] pData = [ [ Vertex2 0 0, Vertex2 0 10, Vertex2 4 10, Vertex2 5 9, Vertex2 5 6, Vertex2 4 5, Vertex2 0 5 ] ] rData = [ [ Vertex2 0 0, Vertex2 0 10, Vertex2 4 10, Vertex2 5 9, Vertex2 5 6, Vertex2 4 5, Vertex2 0 5 ], [ Vertex2 3 5, Vertex2 5 0 ] ] sData = [ [ Vertex2 0 1, Vertex2 1 0, Vertex2 4 0, Vertex2 5 1, Vertex2 5 4, Vertex2 4 5, Vertex2 1 5, Vertex2 0 6, Vertex2 0 9, Vertex2 1 10, Vertex2 4 10, Vertex2 5 9 ] ] advance :: IO () advance = translate (Vector3 8 0 (0 :: GLfloat)) -- drawLetter renders a letter with line segments given by the list of line -- strips. drawLetter :: [[Vertex2 GLfloat]] -> IO () drawLetter lineStrips = do mapM_ (renderPrimitive LineStrip . mapM_ vertex) lineStrips advance charToGLubyte :: Char -> GLubyte charToGLubyte = fromIntegral . castCharToCChar myInit :: IO () myInit = do shadeModel $= Flat (base@(DisplayList b):_) <- genObjectNames 128 listBase $= base let charToDisplayList c = DisplayList (b + fromIntegral (charToGLubyte c)) mapM_ (\(c, d) -> defineList (charToDisplayList c) Compile d) [ ('A', drawLetter aData), ('E', drawLetter eData), ('P', drawLetter pData), ('R', drawLetter rData), ('S', drawLetter sData), (' ', advance) ] test1, test2 :: String test1 = "A SPARE SERAPE APPEARS AS" test2 = "APES PREPARE RARE PEPPERS" printStrokedString :: String -> IO () printStrokedString s = withArray (map charToGLubyte s) $ callLists (genericLength s) UnsignedByte display :: DisplayCallback display = do clear [ ColorBuffer ] -- resolve overloading, not needed in "real" programs let color3f = color :: Color3 GLfloat -> IO () scalef = scale :: GLfloat -> GLfloat -> GLfloat -> IO () translatef = translate :: Vector3 GLfloat -> IO () color3f (Color3 1 1 1) preservingMatrix $ do scalef 2 2 2 translatef (Vector3 10 30 0) printStrokedString test1 preservingMatrix $ do scalef 2 2 2 translatef (Vector3 10 13 0) printStrokedString test2 flush reshape :: ReshapeCallback reshape size@(Size w h) = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity ortho2D 0 (fromIntegral w) 0 (fromIntegral h) matrixMode $= Modelview 0 keyboard :: KeyboardMouseCallback keyboard (Char c) Down _ _ = case c of ' ' -> postRedisplay Nothing '\27' -> exitWith ExitSuccess _ -> return () keyboard _ _ _ _ = return () -- Main Loop: Open window with initial window size, title bar, RGBA display -- mode, and handle input events. main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode ] initialWindowSize $= Size 440 120 createWindow progName myInit reshapeCallback $= Just reshape keyboardMouseCallback $= Just keyboard displayCallback $= display mainLoop
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/examples/RedBook/Stroke.hs
bsd-3-clause
3,934
0
15
932
1,271
648
623
92
3
{-# LANGUAGE OverloadedStrings #-} module Rede.Research.Main(research) where import Control.Concurrent (forkIO) import Control.Concurrent.Chan import System.FilePath import qualified Data.ByteString as B import Data.ByteString.Char8 (pack) import Rede.MainLoop.ConfigHelp (getCertFilename, getMimicPostInterface, getMimicPostPort, configDir, getPrivkeyFilename) import Rede.MainLoop.OpenSSL_TLS (tlsServeWithALPN, FinishRequest(..)) import Rede.Research.ResearchWorker (runResearchWorker, spawnHarServer) import Rede.Http2.MakeAttendant (http2Attendant) import Rede.HarFiles.ServedEntry (ResolveCenter) research :: FilePath -> IO () research mimic_dir = do let mimic_config_dir = configDir mimic_dir url_chan <- newChan resolve_center_chan <- newChan finish_request_chan <- newChan forkIO $ spawnHarServer mimic_dir resolve_center_chan finish_request_chan publishUrlToCaptureWebserver mimic_dir mimic_config_dir url_chan resolve_center_chan finish_request_chan publishUrlToCaptureWebserver :: FilePath -> FilePath -> Chan B.ByteString -> Chan ResolveCenter -> Chan FinishRequest -> IO () publishUrlToCaptureWebserver mimic_dir mimic_config_dir url_chan resolve_center_chan finish_request_chan = do post_port <- getMimicPostPort mimic_config_dir iface <- getMimicPostInterface mimic_config_dir let priv_key_filename = getPrivkeyFilename mimic_config_dir cert_filename = getCertFilename mimic_config_dir research_dir = mimic_dir </> "hars/" http2worker <- runResearchWorker url_chan resolve_center_chan finish_request_chan research_dir (pack iface) tlsServeWithALPN cert_filename priv_key_filename iface [ ("h2-14", http2Attendant http2worker) ] post_port
loadimpact/http2-test
hs-src/Rede/Research/Main.hs
bsd-3-clause
2,309
0
11
800
369
195
174
48
1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module SPARC.Ppr ( pprNatCmmDecl, pprBasicBlock, pprData, pprInstr, pprFormat, pprImm, pprDataItem ) where #include "HsVersions.h" #include "nativeGen/NCG.h" import SPARC.Regs import SPARC.Instr import SPARC.Cond import SPARC.Imm import SPARC.AddrMode import SPARC.Base import Instruction import Reg import Format import PprBase import Cmm hiding (topInfoTable) import PprCmm() import CLabel import BlockId import Unique ( Uniquable(..), pprUnique ) import Outputable import Platform import FastString import Data.Word -- ----------------------------------------------------------------------------- -- Printing this stuff out pprNatCmmDecl :: NatCmmDecl CmmStatics Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionAlign section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = case topInfoTable proc of Nothing -> case blocks of [] -> -- special case for split markers: pprLabel lbl blocks -> -- special case for code without info table: pprSectionAlign (Section Text lbl) $$ pprLabel lbl $$ -- blocks guaranteed not null, so label needed vcat (map (pprBasicBlock top_info) blocks) Just (Statics info_lbl _) -> sdocWithPlatform $ \platform -> (if platformHasSubsectionsViaSymbols platform then pprSectionAlign dspSection $$ ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- See Note [Subsections Via Symbols] in X86/Ppr.hs text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) dspSection :: Section dspSection = Section Text $ panic "subsections-via-symbols doesn't combine with split-sections" pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = maybe_infotable $$ pprLabel (mkAsmTempLabel (getUnique blockid)) $$ vcat (map pprInstr instrs) where maybe_infotable = case mapLookup blockid info_env of Nothing -> empty Just (Statics info_lbl info) -> pprAlignForSection Text $$ vcat (map pprData info) $$ pprLabel info_lbl pprDatas :: CmmStatics -> SDoc pprDatas (Statics lbl dats) = vcat (pprLabel lbl : map pprData dats) pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprASCII str pprData (CmmUninitialised bytes) = text ".skip " <> int bytes pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = text ".global " <> ppr lbl pprTypeAndSizeDecl :: CLabel -> SDoc pprTypeAndSizeDecl lbl = sdocWithPlatform $ \platform -> if platformOS platform == OSLinux && externallyVisibleCLabel lbl then text ".type " <> ppr lbl <> ptext (sLit ", @object") else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeAndSizeDecl lbl $$ (ppr lbl <> char ':') pprASCII :: [Word8] -> SDoc pprASCII str = vcat (map do1 str) $$ do1 0 where do1 :: Word8 -> SDoc do1 w = text "\t.byte\t" <> int (fromIntegral w) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr -- | Pretty print a register. pprReg :: Reg -> SDoc pprReg reg = case reg of RegVirtual vr -> case vr of VirtualRegI u -> text "%vI_" <> pprUnique u VirtualRegHi u -> text "%vHi_" <> pprUnique u VirtualRegF u -> text "%vF_" <> pprUnique u VirtualRegD u -> text "%vD_" <> pprUnique u VirtualRegSSE u -> text "%vSSE_" <> pprUnique u RegReal rr -> case rr of RealRegSingle r1 -> pprReg_ofRegNo r1 RealRegPair r1 r2 -> text "(" <> pprReg_ofRegNo r1 <> vbar <> pprReg_ofRegNo r2 <> text ")" -- | Pretty print a register name, based on this register number. -- The definition has been unfolded so we get a jump-table in the -- object code. This function is called quite a lot when emitting -- the asm file.. -- pprReg_ofRegNo :: Int -> SDoc pprReg_ofRegNo i = ptext (case i of { 0 -> sLit "%g0"; 1 -> sLit "%g1"; 2 -> sLit "%g2"; 3 -> sLit "%g3"; 4 -> sLit "%g4"; 5 -> sLit "%g5"; 6 -> sLit "%g6"; 7 -> sLit "%g7"; 8 -> sLit "%o0"; 9 -> sLit "%o1"; 10 -> sLit "%o2"; 11 -> sLit "%o3"; 12 -> sLit "%o4"; 13 -> sLit "%o5"; 14 -> sLit "%o6"; 15 -> sLit "%o7"; 16 -> sLit "%l0"; 17 -> sLit "%l1"; 18 -> sLit "%l2"; 19 -> sLit "%l3"; 20 -> sLit "%l4"; 21 -> sLit "%l5"; 22 -> sLit "%l6"; 23 -> sLit "%l7"; 24 -> sLit "%i0"; 25 -> sLit "%i1"; 26 -> sLit "%i2"; 27 -> sLit "%i3"; 28 -> sLit "%i4"; 29 -> sLit "%i5"; 30 -> sLit "%i6"; 31 -> sLit "%i7"; 32 -> sLit "%f0"; 33 -> sLit "%f1"; 34 -> sLit "%f2"; 35 -> sLit "%f3"; 36 -> sLit "%f4"; 37 -> sLit "%f5"; 38 -> sLit "%f6"; 39 -> sLit "%f7"; 40 -> sLit "%f8"; 41 -> sLit "%f9"; 42 -> sLit "%f10"; 43 -> sLit "%f11"; 44 -> sLit "%f12"; 45 -> sLit "%f13"; 46 -> sLit "%f14"; 47 -> sLit "%f15"; 48 -> sLit "%f16"; 49 -> sLit "%f17"; 50 -> sLit "%f18"; 51 -> sLit "%f19"; 52 -> sLit "%f20"; 53 -> sLit "%f21"; 54 -> sLit "%f22"; 55 -> sLit "%f23"; 56 -> sLit "%f24"; 57 -> sLit "%f25"; 58 -> sLit "%f26"; 59 -> sLit "%f27"; 60 -> sLit "%f28"; 61 -> sLit "%f29"; 62 -> sLit "%f30"; 63 -> sLit "%f31"; _ -> sLit "very naughty sparc register" }) -- | Pretty print a format for an instruction suffix. pprFormat :: Format -> SDoc pprFormat x = ptext (case x of II8 -> sLit "ub" II16 -> sLit "uh" II32 -> sLit "" II64 -> sLit "d" FF32 -> sLit "" FF64 -> sLit "d" _ -> panic "SPARC.Ppr.pprFormat: no match") -- | Pretty print a format for an instruction suffix. -- eg LD is 32bit on sparc, but LDD is 64 bit. pprStFormat :: Format -> SDoc pprStFormat x = ptext (case x of II8 -> sLit "b" II16 -> sLit "h" II32 -> sLit "" II64 -> sLit "x" FF32 -> sLit "" FF64 -> sLit "d" _ -> panic "SPARC.Ppr.pprFormat: no match") -- | Pretty print a condition code. pprCond :: Cond -> SDoc pprCond c = ptext (case c of ALWAYS -> sLit "" NEVER -> sLit "n" GEU -> sLit "geu" LU -> sLit "lu" EQQ -> sLit "e" GTT -> sLit "g" GE -> sLit "ge" GU -> sLit "gu" LTT -> sLit "l" LE -> sLit "le" LEU -> sLit "leu" NE -> sLit "ne" NEG -> sLit "neg" POS -> sLit "pos" VC -> sLit "vc" VS -> sLit "vs") -- | Pretty print an address mode. pprAddr :: AddrMode -> SDoc pprAddr am = case am of AddrRegReg r1 (RegReal (RealRegSingle 0)) -> pprReg r1 AddrRegReg r1 r2 -> hcat [ pprReg r1, char '+', pprReg r2 ] AddrRegImm r1 (ImmInt i) | i == 0 -> pprReg r1 | not (fits13Bits i) -> largeOffsetError i | otherwise -> hcat [ pprReg r1, pp_sign, int i ] where pp_sign = if i > 0 then char '+' else empty AddrRegImm r1 (ImmInteger i) | i == 0 -> pprReg r1 | not (fits13Bits i) -> largeOffsetError i | otherwise -> hcat [ pprReg r1, pp_sign, integer i ] where pp_sign = if i > 0 then char '+' else empty AddrRegImm r1 imm -> hcat [ pprReg r1, char '+', pprImm imm ] -- | Pretty print an immediate value. pprImm :: Imm -> SDoc pprImm imm = case imm of ImmInt i -> int i ImmInteger i -> integer i ImmCLbl l -> ppr l ImmIndex l i -> ppr l <> char '+' <> int i ImmLit s -> s ImmConstantSum a b -> pprImm a <> char '+' <> pprImm b ImmConstantDiff a b -> pprImm a <> char '-' <> lparen <> pprImm b <> rparen LO i -> hcat [ text "%lo(", pprImm i, rparen ] HI i -> hcat [ text "%hi(", pprImm i, rparen ] -- these should have been converted to bytes and placed -- in the data section. ImmFloat _ -> text "naughty float immediate" ImmDouble _ -> text "naughty double immediate" -- | Pretty print a section \/ segment header. -- On SPARC all the data sections must be at least 8 byte aligned -- incase we store doubles in them. -- pprSectionAlign :: Section -> SDoc pprSectionAlign sec@(Section seg _) = sdocWithPlatform $ \platform -> pprSectionHeader platform sec $$ pprAlignForSection seg -- | Print appropriate alignment for the given section type. pprAlignForSection :: SectionType -> SDoc pprAlignForSection seg = ptext (case seg of Text -> sLit ".align 4" Data -> sLit ".align 8" ReadOnlyData -> sLit ".align 8" RelocatableReadOnlyData -> sLit ".align 8" UninitialisedData -> sLit ".align 8" ReadOnlyData16 -> sLit ".align 16" OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section") -- | Pretty print a data item. pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> vcat (ppr_item (cmmTypeFormat $ cmmLitType dflags lit) lit) where imm = litToImm lit ppr_item II8 _ = [text "\t.byte\t" <> pprImm imm] ppr_item II32 _ = [text "\t.long\t" <> pprImm imm] ppr_item FF32 (CmmFloat r _) = let bs = floatToBytes (fromRational r) in map (\b -> text "\t.byte\t" <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) = let bs = doubleToBytes (fromRational r) in map (\b -> text "\t.byte\t" <> pprImm (ImmInt b)) bs ppr_item II16 _ = [text "\t.short\t" <> pprImm imm] ppr_item II64 _ = [text "\t.quad\t" <> pprImm imm] ppr_item _ _ = panic "SPARC.Ppr.pprDataItem: no match" -- | Pretty print an instruction. pprInstr :: Instr -> SDoc -- nuke comments. pprInstr (COMMENT _) = empty pprInstr (DELTA d) = pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d))) -- Newblocks and LData should have been slurped out before producing the .s file. pprInstr (NEWBLOCK _) = panic "X86.Ppr.pprInstr: NEWBLOCK" pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" -- 64 bit FP loads are expanded into individual instructions in CodeGen.Expand pprInstr (LD FF64 _ reg) | RegReal (RealRegSingle{}) <- reg = panic "SPARC.Ppr: not emitting potentially misaligned LD FF64 instr" pprInstr (LD format addr reg) = hcat [ text "\tld", pprFormat format, char '\t', lbrack, pprAddr addr, pp_rbracket_comma, pprReg reg ] -- 64 bit FP storees are expanded into individual instructions in CodeGen.Expand pprInstr (ST FF64 reg _) | RegReal (RealRegSingle{}) <- reg = panic "SPARC.Ppr: not emitting potentially misaligned ST FF64 instr" -- no distinction is made between signed and unsigned bytes on stores for the -- Sparc opcodes (at least I cannot see any, and gas is nagging me --SOF), -- so we call a special-purpose pprFormat for ST.. pprInstr (ST format reg addr) = hcat [ text "\tst", pprStFormat format, char '\t', pprReg reg, pp_comma_lbracket, pprAddr addr, rbrack ] pprInstr (ADD x cc reg1 ri reg2) | not x && not cc && riZero ri = hcat [ text "\tmov\t", pprReg reg1, comma, pprReg reg2 ] | otherwise = pprRegRIReg (if x then sLit "addx" else sLit "add") cc reg1 ri reg2 pprInstr (SUB x cc reg1 ri reg2) | not x && cc && reg2 == g0 = hcat [ text "\tcmp\t", pprReg reg1, comma, pprRI ri ] | not x && not cc && riZero ri = hcat [ text "\tmov\t", pprReg reg1, comma, pprReg reg2 ] | otherwise = pprRegRIReg (if x then sLit "subx" else sLit "sub") cc reg1 ri reg2 pprInstr (AND b reg1 ri reg2) = pprRegRIReg (sLit "and") b reg1 ri reg2 pprInstr (ANDN b reg1 ri reg2) = pprRegRIReg (sLit "andn") b reg1 ri reg2 pprInstr (OR b reg1 ri reg2) | not b && reg1 == g0 = let doit = hcat [ text "\tmov\t", pprRI ri, comma, pprReg reg2 ] in case ri of RIReg rrr | rrr == reg2 -> empty _ -> doit | otherwise = pprRegRIReg (sLit "or") b reg1 ri reg2 pprInstr (ORN b reg1 ri reg2) = pprRegRIReg (sLit "orn") b reg1 ri reg2 pprInstr (XOR b reg1 ri reg2) = pprRegRIReg (sLit "xor") b reg1 ri reg2 pprInstr (XNOR b reg1 ri reg2) = pprRegRIReg (sLit "xnor") b reg1 ri reg2 pprInstr (SLL reg1 ri reg2) = pprRegRIReg (sLit "sll") False reg1 ri reg2 pprInstr (SRL reg1 ri reg2) = pprRegRIReg (sLit "srl") False reg1 ri reg2 pprInstr (SRA reg1 ri reg2) = pprRegRIReg (sLit "sra") False reg1 ri reg2 pprInstr (RDY rd) = text "\trd\t%y," <> pprReg rd pprInstr (WRY reg1 reg2) = text "\twr\t" <> pprReg reg1 <> char ',' <> pprReg reg2 <> char ',' <> text "%y" pprInstr (SMUL b reg1 ri reg2) = pprRegRIReg (sLit "smul") b reg1 ri reg2 pprInstr (UMUL b reg1 ri reg2) = pprRegRIReg (sLit "umul") b reg1 ri reg2 pprInstr (SDIV b reg1 ri reg2) = pprRegRIReg (sLit "sdiv") b reg1 ri reg2 pprInstr (UDIV b reg1 ri reg2) = pprRegRIReg (sLit "udiv") b reg1 ri reg2 pprInstr (SETHI imm reg) = hcat [ text "\tsethi\t", pprImm imm, comma, pprReg reg ] pprInstr NOP = text "\tnop" pprInstr (FABS format reg1 reg2) = pprFormatRegReg (sLit "fabs") format reg1 reg2 pprInstr (FADD format reg1 reg2 reg3) = pprFormatRegRegReg (sLit "fadd") format reg1 reg2 reg3 pprInstr (FCMP e format reg1 reg2) = pprFormatRegReg (if e then sLit "fcmpe" else sLit "fcmp") format reg1 reg2 pprInstr (FDIV format reg1 reg2 reg3) = pprFormatRegRegReg (sLit "fdiv") format reg1 reg2 reg3 pprInstr (FMOV format reg1 reg2) = pprFormatRegReg (sLit "fmov") format reg1 reg2 pprInstr (FMUL format reg1 reg2 reg3) = pprFormatRegRegReg (sLit "fmul") format reg1 reg2 reg3 pprInstr (FNEG format reg1 reg2) = pprFormatRegReg (sLit "fneg") format reg1 reg2 pprInstr (FSQRT format reg1 reg2) = pprFormatRegReg (sLit "fsqrt") format reg1 reg2 pprInstr (FSUB format reg1 reg2 reg3) = pprFormatRegRegReg (sLit "fsub") format reg1 reg2 reg3 pprInstr (FxTOy format1 format2 reg1 reg2) = hcat [ text "\tf", ptext (case format1 of II32 -> sLit "ito" FF32 -> sLit "sto" FF64 -> sLit "dto" _ -> panic "SPARC.Ppr.pprInstr.FxToY: no match"), ptext (case format2 of II32 -> sLit "i\t" II64 -> sLit "x\t" FF32 -> sLit "s\t" FF64 -> sLit "d\t" _ -> panic "SPARC.Ppr.pprInstr.FxToY: no match"), pprReg reg1, comma, pprReg reg2 ] pprInstr (BI cond b blockid) = hcat [ text "\tb", pprCond cond, if b then pp_comma_a else empty, char '\t', ppr (mkAsmTempLabel (getUnique blockid)) ] pprInstr (BF cond b blockid) = hcat [ text "\tfb", pprCond cond, if b then pp_comma_a else empty, char '\t', ppr (mkAsmTempLabel (getUnique blockid)) ] pprInstr (JMP addr) = text "\tjmp\t" <> pprAddr addr pprInstr (JMP_TBL op _ _) = pprInstr (JMP op) pprInstr (CALL (Left imm) n _) = hcat [ text "\tcall\t", pprImm imm, comma, int n ] pprInstr (CALL (Right reg) n _) = hcat [ text "\tcall\t", pprReg reg, comma, int n ] -- | Pretty print a RI pprRI :: RI -> SDoc pprRI (RIReg r) = pprReg r pprRI (RIImm r) = pprImm r -- | Pretty print a two reg instruction. pprFormatRegReg :: LitString -> Format -> Reg -> Reg -> SDoc pprFormatRegReg name format reg1 reg2 = hcat [ char '\t', ptext name, (case format of FF32 -> text "s\t" FF64 -> text "d\t" _ -> panic "SPARC.Ppr.pprFormatRegReg: no match"), pprReg reg1, comma, pprReg reg2 ] -- | Pretty print a three reg instruction. pprFormatRegRegReg :: LitString -> Format -> Reg -> Reg -> Reg -> SDoc pprFormatRegRegReg name format reg1 reg2 reg3 = hcat [ char '\t', ptext name, (case format of FF32 -> text "s\t" FF64 -> text "d\t" _ -> panic "SPARC.Ppr.pprFormatRegReg: no match"), pprReg reg1, comma, pprReg reg2, comma, pprReg reg3 ] -- | Pretty print an instruction of two regs and a ri. pprRegRIReg :: LitString -> Bool -> Reg -> RI -> Reg -> SDoc pprRegRIReg name b reg1 ri reg2 = hcat [ char '\t', ptext name, if b then text "cc\t" else char '\t', pprReg reg1, comma, pprRI ri, comma, pprReg reg2 ] {- pprRIReg :: LitString -> Bool -> RI -> Reg -> SDoc pprRIReg name b ri reg1 = hcat [ char '\t', ptext name, if b then text "cc\t" else char '\t', pprRI ri, comma, pprReg reg1 ] -} {- pp_ld_lbracket :: SDoc pp_ld_lbracket = text "\tld\t[" -} pp_rbracket_comma :: SDoc pp_rbracket_comma = text "]," pp_comma_lbracket :: SDoc pp_comma_lbracket = text ",[" pp_comma_a :: SDoc pp_comma_a = text ",a"
mettekou/ghc
compiler/nativeGen/SPARC/Ppr.hs
bsd-3-clause
19,049
0
18
6,238
5,588
2,742
2,846
443
65
module Events.SparkTree ( SparkTree, SparkNode, sparkTreeMaxDepth, emptySparkTree, eventsToSparkDurations, mkSparkTree, sparkProfile, ) where import qualified Events.SparkStats as SparkStats import qualified GHC.RTS.Events as GHCEvents import GHC.RTS.Events (Timestamp) import Control.Exception (assert) import Text.Printf -- import Debug.Trace -- | Sparks change state. Each state transition process has a duration. -- SparkDuration is a condensed description of such a process, -- containing a start time of the duration interval, -- spark stats that record the spark transition rate -- and the absolute number of sparks in the spark pool within the duration. data SparkDuration = SparkDuration { startT :: {-#UNPACK#-}!Timestamp, deltaC :: {-#UNPACK#-}!SparkStats.SparkStats } deriving Show -- | Calculates durations and maximal rendered values from the event log. -- Warning: cannot be applied to a suffix of the log (assumes start at time 0). eventsToSparkDurations :: [GHCEvents.Event] -> (Double, [SparkDuration]) eventsToSparkDurations es = let aux _startTime _startCounters [] = (0, []) aux startTime startCounters (event : events) = case GHCEvents.spec event of GHCEvents.SparkCounters crt dud ovf cnv fiz gcd rem -> let endTime = GHCEvents.time event endCounters = (crt, dud, ovf, cnv, fiz, gcd, rem) delta = SparkStats.create startCounters endCounters newMaxSparkPool = SparkStats.maxPool delta sd = SparkDuration { startT = startTime, deltaC = delta } (oldMaxSparkPool, l) = aux endTime endCounters events in (max oldMaxSparkPool newMaxSparkPool, sd : l) _otherEvent -> aux startTime startCounters events in aux 0 (0,0,0,0,0,0,0) es -- | We map the spark transition durations (intervals) onto a binary -- search tree, so that we can easily find the durations -- that correspond to a particular view of the timeline. -- Additionally, each node of the tree contains a summary -- of the information below it, so that we can render views at various -- levels of resolution. For example, if a tree node would represent -- less than one pixel on the display, there is no point is descending -- the tree further. data SparkTree = SparkTree {-#UNPACK#-}!Timestamp -- ^ start time of span represented by the tree {-#UNPACK#-}!Timestamp -- ^ end time of the span represented by the tree SparkNode deriving Show data SparkNode = SparkSplit {-#UNPACK#-}!Timestamp -- ^ time used to split the span into two parts SparkNode -- ^ the LHS split; all data lies completely between start and split SparkNode -- ^ the RHS split; all data lies completely between split and end {-#UNPACK#-}!SparkStats.SparkStats -- ^ aggregate of the spark stats within the span | SparkTreeLeaf {-#UNPACK#-}!SparkStats.SparkStats -- ^ the spark stats for the base duration | SparkTreeEmpty -- ^ represents a span that no data referts to, e.g., after the last GC deriving Show sparkTreeMaxDepth :: SparkTree -> Int sparkTreeMaxDepth (SparkTree _ _ t) = sparkNodeMaxDepth t sparkNodeMaxDepth :: SparkNode -> Int sparkNodeMaxDepth (SparkSplit _ lhs rhs _) = 1 + sparkNodeMaxDepth lhs `max` sparkNodeMaxDepth rhs sparkNodeMaxDepth _ = 1 emptySparkTree :: SparkTree emptySparkTree = SparkTree 0 0 SparkTreeEmpty -- | Create spark tree from spark durations. -- Note that the last event may be not a spark event, in which case -- there is no data about sparks for the last time interval -- (the subtree for the interval will have SparkTreeEmpty node). mkSparkTree :: [SparkDuration] -- ^ spark durations calculated from events -> Timestamp -- ^ end time of last event in the list -> SparkTree mkSparkTree es endTime = SparkTree s e $ -- trace (show tree) $ tree where tree = splitSparks es endTime (s, e) = if null es then (0, 0) else (startT (head es), endTime) -- | Construct spark tree, by recursively splitting time intervals.. -- We only split at spark transition duration boundaries; -- we never split a duration into multiple pieces. -- Therefore, the binary tree is only roughly split by time, -- the actual split depends on the distribution of sample points below it. splitSparks :: [SparkDuration] -> Timestamp -> SparkNode splitSparks [] !_endTime = SparkTreeEmpty splitSparks [e] !_endTime = SparkTreeLeaf (deltaC e) splitSparks es !endTime | null rhs = splitSparks es lhs_end | null lhs = error $ printf "splitSparks: null lhs: len = %d, startTime = %d, endTime = %d\n" (length es) startTime endTime ++ '\n' : show es | otherwise = -- trace (printf "len = %d, startTime = %d, endTime = %d\n" (length es) startTime endTime) $ assert (length lhs + length rhs == length es) $ SparkSplit (startT $ head rhs) ltree rtree (SparkStats.aggregate (subDelta rtree ++ subDelta ltree)) where -- | Integer division, rounding up. divUp :: Timestamp -> Timestamp -> Timestamp divUp n k = (n + k - 1) `div` k startTime = startT $ head es splitTime = startTime + (endTime - startTime) `divUp` 2 (lhs, lhs_end, rhs) = splitSparkList es [] splitTime 0 ltree = splitSparks lhs lhs_end rtree = splitSparks rhs endTime subDelta (SparkSplit _ _ _ delta) = [delta] subDelta (SparkTreeLeaf delta) = [delta] subDelta SparkTreeEmpty = [] splitSparkList :: [SparkDuration] -> [SparkDuration] -> Timestamp -> Timestamp -> ([SparkDuration], Timestamp, [SparkDuration]) splitSparkList [] acc !_tsplit !tmax = (reverse acc, tmax, []) splitSparkList [e] acc !_tsplit !tmax -- Just one event left: put it on the right. This ensures that we -- have at least one event on each side of the split. = (reverse acc, tmax, [e]) splitSparkList (e:es) acc !tsplit !tmax | startT e <= tsplit -- pick all durations that start at or before the split = splitSparkList es (e:acc) tsplit (max tmax (startT e)) | otherwise = (reverse acc, tmax, e:es) -- | For each timeslice, give the spark stats calculated for that interval. -- The spark stats are Approximated from the aggregated data -- at the level of the spark tree covering intervals of the size -- similar to the timeslice size. sparkProfile :: Timestamp -> Timestamp -> Timestamp -> SparkTree -> [SparkStats.SparkStats] sparkProfile slice start0 end0 t = {- trace (show flat) $ -} chopped where -- do an extra slice at both ends start = if start0 < slice then start0 else start0 - slice end = end0 + slice flat = flatten start t [] -- TODO: redefine chop so that it's obvious this error will not happen -- e.g., catch pathological cases, like a tree with only SparkTreeEmpty -- inside and/or make it tail-recursive instead of -- taking the 'previous' argument chopped0 = chop (error "Fatal error in sparkProfile.") [] start flat chopped | start0 < slice = SparkStats.initial : chopped0 | otherwise = chopped0 flatten :: Timestamp -> SparkTree -> [SparkTree] -> [SparkTree] flatten _start (SparkTree _s _e SparkTreeEmpty) rest = rest flatten start t@(SparkTree s e (SparkSplit split l r _)) rest | e <= start = rest | end <= s = rest | start >= split = flatten start (SparkTree split e r) rest | end <= split = flatten start (SparkTree s split l) rest | e - s > slice = flatten start (SparkTree s split l) $ flatten start (SparkTree split e r) rest -- A rule of thumb: if a node is narrower than slice, don't drill down, -- even if the node sits astride slice boundaries and so the readings -- for each of the two neigbouring slices will not be accurate -- (but for the pair as a whole, they will be). Smooths the curve down -- even more than averaging over the timeslice already does. | otherwise = t : rest flatten _start t@(SparkTree _s _e (SparkTreeLeaf _)) rest = t : rest chop :: SparkStats.SparkStats -> [SparkStats.SparkStats] -> Timestamp -> [SparkTree] -> [SparkStats.SparkStats] chop _previous sofar start1 _ts | start1 >= end = case sofar of _ : _ -> [SparkStats.aggregate sofar] [] -> [] chop _previous sofar _start1 [] -- data too short for the redrawn area | null sofar -- no data at all in the redrawn area = [] | otherwise = [SparkStats.aggregate sofar] chop previous sofar start1 (t : ts) | e <= start1 -- skipping data left of the slice = case sofar of _ : _ -> error "chop" [] -> chop previous sofar start1 ts | s >= start1 + slice -- postponing data right of the slice = let (c, p) = SparkStats.agEx sofar previous in c : chop p [] (start1 + slice) (t : ts) | e > start1 + slice = let (c, p) = SparkStats.agEx (created_in_this_slice t ++ sofar) previous in c : chop p [] (start1 + slice) (t : ts) | otherwise = chop previous (created_in_this_slice t ++ sofar) start1 ts where (s, e) | SparkTree s e _ <- t = (s, e) -- The common part of the slice and the duration. mi = min (start1 + slice) e ma = max start1 s common = if mi < ma then 0 else mi - ma -- Instead of drilling down the tree (unless it's a leaf), -- we approximate by taking a proportion of the aggregate value, -- depending on how much of the spark duration corresponding -- to the tree node is covered by our timeslice. proportion = if e > s then fromIntegral common / fromIntegral (e - s) else assert (e == s && common == 0) $ 0 -- Spark transitions in the tree are in units spark/duration. -- Here the numbers are rescaled so that the units are spark/ms. created_in_this_slice (SparkTree _ _ node) = case node of SparkTreeLeaf delta -> [SparkStats.rescale proportion delta] SparkTreeEmpty -> [] SparkSplit _ _ _ delta -> [SparkStats.rescale proportion delta]
dchagniot/threadscopeRestServer
src/Events/SparkTree.hs
bsd-3-clause
10,351
0
17
2,679
2,251
1,192
1,059
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Main where import Text.HSmarty import qualified Data.HashMap.Strict as HM import qualified Data.Text as T main :: IO () main = renderTemplate "test.tpl" $ HM.fromList [ ( "title", mkParam ("SomeTitle" :: T.Text)) , ( "list", mkParam (["a", "b"] :: [T.Text])) ]
agrafix/HSmarty
Example.hs
bsd-3-clause
342
0
12
84
103
63
40
10
1
-- | Defines an internal representation of Haskell data\/newtype definitions -- that correspond to the XML DTD types, and provides pretty-printers to -- convert these types into the 'Doc' type of "Text.PrettyPrint.HughesPJ". module Text.XML.HaXml.DtdToHaskell.TypeDef ( -- * Internal representation of types TypeDef(..) , Constructors , AttrFields , StructType(..) -- * Pretty-print a TypeDef , ppTypeDef , ppHName , ppXName , ppAName -- * Name mangling , Name(..) , name, name_, name_a, name_ac, name_f, mangle, manglef ) where import Char (isLower, isUpper, toLower, toUpper, isDigit) import List (intersperse) import Text.PrettyPrint.HughesPJ ---- Internal representation for typedefs ---- -- | Need to keep both the XML and Haskell versions of a name. data Name = Name { xName :: String -- ^ original XML name , hName :: String -- ^ mangled Haskell name } deriving Eq data TypeDef = DataDef Bool Name AttrFields Constructors -- ^ Bool for main\/aux. | EnumDef Name [Name] deriving Eq type Constructors = [(Name,[StructType])] type AttrFields = [(Name, StructType)] data StructType = Maybe StructType | Defaultable StructType String -- ^ String holds default value. | List StructType | List1 StructType -- ^ Non-empty lists. | Tuple [StructType] | OneOf [StructType] | Any -- ^ XML's contentspec allows ANY | String | Defined Name deriving Eq -- used for converting StructType (roughly) back to an XML content model instance Show StructType where showsPrec p (Maybe s) = showsPrec (p+1) s . showChar '?' showsPrec p (Defaultable s _) = shows s showsPrec p (List s) = showsPrec (p+1) s . showChar '*' showsPrec p (List1 s) = showsPrec (p+1) s . showChar '+' showsPrec p (Tuple ss) = showChar '(' . foldr1 (.) (intersperse (showChar ',') (map shows ss)) . showChar ')' showsPrec p (OneOf ss) = showChar '(' . foldr1 (.) (intersperse (showChar '|') (map shows ss)) . showChar ')' showsPrec p (Any) = showString "ANY" showsPrec p (String) = showString "#PCDATA" showsPrec p (Defined (Name n _)) = showString n ---- Pretty-printing typedefs ---- ppTypeDef :: TypeDef -> Doc -- no attrs, no constructors ppTypeDef (DataDef _ n [] []) = let name = ppHName n in text "data" <+> name <+> text "=" <+> name <+> text "\t\t" <> derives -- no attrs, single constructor ppTypeDef (DataDef _ n [] [c@(_,[_])]) = text "newtype" <+> ppHName n <+> text "=" <+> ppC c <+> text "\t\t" <> derives -- no attrs, multiple constrs ppTypeDef (DataDef _ n [] cs) = text "data" <+> ppHName n <+> ( text "=" <+> ppC (head cs) $$ vcat (map (\c-> text "|" <+> ppC c) (tail cs)) $$ derives ) -- nonzero attrs, no constructors ppTypeDef (DataDef _ n fs []) = let name = ppHName n in text "data" <+> name <+> text "=" <+> name $$ nest 4 ( text "{" <+> ppF (head fs) $$ vcat (map (\f-> text "," <+> ppF f) (tail fs)) $$ text "}" <+> derives ) -- nonzero attrs, one or more constrs ppTypeDef (DataDef _ n fs cs) = let attr = ppAName n in text "data" <+> ppHName n <+> ( text "=" <+> ppAC attr (head cs) $$ vcat (map (\c-> text "|" <+> ppAC attr c) (tail cs)) $$ derives ) $$ text "data" <+> attr <+> text "=" <+> attr $$ nest 4 ( text "{" <+> ppF (head fs) $$ vcat (map (\f-> text "," <+> ppF f) (tail fs)) $$ text "}" <+> derives ) -- enumerations (of attribute values) ppTypeDef (EnumDef n es) = text "data" <+> ppHName n <+> ( text "=" <+> fsep (intersperse (text " | ") (map ppHName es)) $$ derives ) ppST :: StructType -> Doc ppST (Defaultable st _) = parens (text "Defaultable" <+> ppST st) ppST (Maybe st) = parens (text "Maybe" <+> ppST st) ppST (List st) = text "[" <> ppST st <> text "]" ppST (List1 st) = parens (text "List1" <+> ppST st) ppST (Tuple sts) = parens (commaList (map ppST sts)) ppST (OneOf sts) = parens (text "OneOf" <> text (show (length sts)) <+> hsep (map ppST sts)) ppST String = text "String" ppST Any = text "ANYContent" ppST (Defined n) = ppHName n -- constructor and components ppC :: (Name,[StructType]) -> Doc ppC (n,sts) = ppHName n <+> fsep (map ppST sts) -- attribute (fieldname and type) ppF :: (Name,StructType) -> Doc ppF (n,st) = ppHName n <+> text "::" <+> ppST st -- constructor and components with initial attr-type ppAC :: Doc -> (Name,[StructType]) -> Doc ppAC atype (n,sts) = ppHName n <+> fsep (atype: map ppST sts) -- | Pretty print Haskell name. ppHName :: Name -> Doc ppHName (Name _ s) = text s -- | Pretty print XML name. ppXName :: Name -> Doc ppXName (Name s _) = text s -- | Pretty print Haskell attributes name. ppAName :: Name -> Doc ppAName (Name _ s) = text s <> text "_Attrs" derives = text "deriving" <+> parens (commaList (map text ["Eq","Show"])) ---- Some operations on Names ---- -- | Make a type name valid in both XML and Haskell. name :: String -> Name name n = Name { xName = n , hName = mangle n } -- | Append an underscore to the Haskell version of the name. name_ :: String -> Name name_ n = Name { xName = n , hName = mangle n ++ "_" } -- | Prefix an attribute enumeration type name with its containing element -- name. name_a :: String -> String -> Name name_a e n = Name { xName = n , hName = mangle e ++ "_" ++ map decolonify n } -- | Prefix an attribute enumeration constructor with its element-tag name, -- and its enumeration type name. name_ac :: String -> String -> String -> Name name_ac e t n = Name { xName = n , hName = mangle e ++ "_" ++ map decolonify t ++ "_" ++ map decolonify n } -- | Prefix a field name with its enclosing element name. name_f :: String -> String -> Name name_f e n = Name { xName = n , hName = manglef e ++ mangle n } ---- obsolete -- elementname_at :: String -> Name -- elementname_at n = Name n (mangle n ++ "_Attrs") -- | Convert an XML name to a Haskell conid. mangle :: String -> String mangle (n:ns) | isLower n = notPrelude (toUpper n: map decolonify ns) | isDigit n = 'I': n: map decolonify ns | otherwise = notPrelude (n: map decolonify ns) -- | Ensure a generated name does not conflict with a standard haskell one. notPrelude :: String -> String notPrelude "String" = "AString" notPrelude "Maybe" = "AMaybe" notPrelude "Either" = "AEither" notPrelude "Char" = "AChar" notPrelude "String" = "AString" notPrelude "Int" = "AInt" notPrelude "Integer" = "AInteger" notPrelude "Float" = "AFloat" notPrelude "Double" = "ADouble" notPrelude "List1" = "AList1" -- part of HaXml notPrelude "IO" = "AIO" notPrelude "IOError" = "AIOError" notPrelude "FilePath"= "AFilePath" notPrelude "Bool" = "ABool" notPrelude "Ordering"= "AOrdering" notPrelude "Eq" = "AEq" notPrelude "Ord" = "AOrd" notPrelude "Enum" = "AEnum" notPrelude "Bounded" = "ABounded" notPrelude "Functor" = "AFunctor" notPrelude "Monad" = "AMonad" notPrelude "Rational"= "ARational" notPrelude "Integral"= "AIntegral" notPrelude "Num" = "ANum" notPrelude "Real" = "AReal" notPrelude "RealFrac"= "ARealFrac" notPrelude "Floating"= "AFloating" notPrelude "RealFloat" = "ARealFloat" notPrelude "Fractional"= "AFractional" notPrelude "Read" = "ARead" notPrelude "Show" = "AShow" notPrelude "ReadS" = "AReadS" notPrelude "ShowS" = "AShowS" notPrelude n = n -- | Convert an XML name to a Haskell varid. manglef :: String -> String manglef (n:ns) | isUpper n = toLower n: map decolonify ns | isDigit n = '_': n: map decolonify ns | otherwise = n: map decolonify ns -- | Convert colon to prime, hyphen to underscore. decolonify :: Char -> Char decolonify ':' = '\'' -- TODO: turn namespaces into qualified identifiers decolonify '-' = '_' decolonify '.' = '_' decolonify c = c commaList = hcat . intersperse comma
FranklinChen/hugs98-plus-Sep2006
packages/HaXml/src/Text/XML/HaXml/DtdToHaskell/TypeDef.hs
bsd-3-clause
8,480
0
22
2,360
2,570
1,322
1,248
174
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Test.ZM.ADT.Tuple2.Ka5583bf3ad34 (Tuple2(..)) where import qualified Prelude(Eq,Ord,Show) import qualified GHC.Generics import qualified Flat import qualified Data.Model data Tuple2 a b = Tuple2 a b deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat) instance ( Data.Model.Model a,Data.Model.Model b ) => Data.Model.Model ( Tuple2 a b )
tittoassini/typed
test/Test/ZM/ADT/Tuple2/Ka5583bf3ad34.hs
bsd-3-clause
443
0
7
57
137
83
54
10
0
{-# LANGUAGE LambdaCase #-} module TopDown where import LambdaF import BruijnEnvironment import BruijnTerm as Lam hiding(Lambda,Appl,Let) import MTable(MTable) import Inprocess topDownTrans :: (context -> LamTermF () () Bound InProcess -> LamTermF () () Bound InProcess ) -> context -> MTable -> InProcess -> LamTerm () () Bound topDownTrans f context modifications = unfold go (context, modifications) where -- go :: context -> MTable -> LamTermF () Bound InProcess -> (LamTermF () Bound (LamTermF () Bound InProcess),(context,MTable)) go (context_, mod_) ast = (f context_ astF,(newContext,newMod)) where newContext = context --TODO updateContext ast (astF,newMod) = peek mod_ ast topDownTransM :: Monad m => (context -> LamTermF () () Bound InProcess -> m (LamTermF () () Bound InProcess)) -> context -> MTable -> InProcess -> m (LamTerm () () Bound) topDownTransM f context modifications = unfoldM go (context, modifications) where -- go :: context -> MTable -> LamTermF () Bound InProcess -> (LamTermF () Bound (LamTermF () Bound InProcess),(context,MTable)) go (context_, mod_) ast = do result <- f context_ astF return (result,(newContext,newMod)) where newContext = context --TODO updateContext ast (astF,newMod) = peek mod_ ast
kwibus/myLang
src/TopDown.hs
bsd-3-clause
1,317
0
13
261
377
203
174
19
1
-- This implements a simple `!echo` command that repeats back whatever follows -- the command. module Network.Ribot.Irc.Part.Echo ( echoPart , echoCommand ) where import Network.IRC.Bot.BotMonad (BotMonad(..), maybeZero) import Network.IRC.Bot.Commands (PrivMsg(..), replyTo, sendCommand) import Network.IRC.Bot.Log (LogLevel(Debug)) import Network.IRC.Bot.Parsec (botPrefix, parsecPart) import Text.Parsec (ParsecT, (<|>), anyChar, many1, space, string, try) -- This is the part to integrate into Ribot. echoPart :: BotMonad m => m () echoPart = parsecPart echoCommand -- This parses and handles the `!echo` command. echoCommand :: BotMonad m => ParsecT String () m () echoCommand = echo' <|> return () where echo' = do input <- try $ do botPrefix string "echo" space many1 anyChar target <- maybeZero =<< replyTo logM Debug $ "echo " ++ show target sendCommand $ PrivMsg Nothing [target] input
erochest/ribot
src/Network/Ribot/Irc/Part/Echo.hs
bsd-3-clause
1,089
0
13
318
268
151
117
21
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE RecordWildCards #-} module Control.Concurrent.STM.Connection ( Connection, new, close, recv, send, cram, bye, -- * Connection backend Backend(..), -- * Configuration Config(..), defaultConfig, -- * Exceptions Error(..), ) where import Control.Concurrent import Control.Concurrent.STM import Control.Exception import Control.Monad import Data.Default import Data.STM.Queue (Queue) import qualified Data.STM.Queue as Q import Data.Typeable (Typeable) data Connection r s = Connection { connOpen :: !(TVar Bool) -- ^ If 'True', the connection has not been 'close'd yet. -- If 'False', accessing the connection will throw -- 'ErrorConnectionClosed'. , connBackend :: !(Backend r s) , connRecv :: !(Half r) , connSend :: !(Half s) , connDone :: !(TVar Bool) -- ^ If 'True', the connection is done being used and the backend is done -- being closed. -- -- This does not imply that 'connOpen' is 'False'. Both 'connOpen' and -- 'connDone' will be 'True' if the connection is closed automatically. } instance Eq (Connection r s) where a == b = connOpen a == connOpen b data Half a = Half { queue :: !(Queue HalfTerminator a) , done :: !(TVar Bool) , thread :: !ThreadId } data HalfTerminator = HTEOF | HTError !SomeException -- | Wrap a connection handle so sending and receiving can be done with -- STM transactions. new :: Config -- ^ Queue size limits. Use 'defaultConfig' for defaults. -> Backend r s -- ^ Callbacks for accessing the underlying device. -> IO (Connection r s) new Config{..} connBackend = mask_ $ do conn_mv <- newEmptyTMVarIO let getConn = atomically $ readTMVar conn_mv connOpen <- newTVarIO True connRecv <- newHalf configRecvLimit $ getConn >>= recvLoop connSend <- newHalf configSendLimit $ getConn >>= sendLoop connDone <- newTVarIO False -- Automatically close the backend when we are done using it. _ <- forkIOWithUnmask $ \unmask -> (`finally` atomically (writeTVar connDone True)) $ unmask $ do waitHalf connRecv waitHalf connSend backendClose connBackend let !conn = Connection{..} atomically $ putTMVar conn_mv conn return conn newHalf :: Maybe Int -> IO HalfTerminator -> IO (Half a) newHalf limit work = do queue <- Q.newIO limit done <- newTVarIO False thread <- forkIOWithUnmask $ \unmask -> do t <- unmask work `catch` (return . HTError) atomically $ do _ <- Q.close queue t writeTVar done True return Half{..} waitHalf :: Half a -> IO () waitHalf Half{..} = atomically $ do d <- readTVar done if d then return () else retry killHalf :: Half a -> IO () killHalf = void . forkIO . killThread . thread recvLoop :: Connection r s -> IO HalfTerminator recvLoop Connection{connRecv = Half{..}, connBackend = Backend{..}} = loop where loop = do m <- backendRecv case m of Nothing -> return HTEOF Just r -> do res <- atomically $ Q.write queue r case res of Left t -> return t Right () -> loop sendLoop :: Connection r s -> IO HalfTerminator sendLoop Connection{connSend = Half{..}, connBackend = Backend{..}} = loop where loop = do res <- atomically $ Q.read queue case res of Left t -> do backendSend Nothing return t Right s -> do backendSend $ Just s loop -- | Close the connection. After this, 'recv' and 'send' will fail. -- -- 'close' will block until all queued data has been sent and the connection -- has been closed. If 'close' is interrupted, it will abandon any data still -- sitting in the send queue, and finish closing the connection in the -- background. close :: Connection r s -> IO () close Connection{..} = mask_ $ join $ atomically $ do b <- readTVar connOpen if b then do -- Mark the connection as closed so subsequent accesses to the -- 'Connection' object will fail. writeTVar connOpen False -- Close the recv and send queues. -- -- * The recv thread will terminate when it tries to queue a message. -- -- * The send thread will terminate *after* consuming remaining data -- in the send queue. _ <- Q.close (queue connRecv) $ HTError $ toException ThreadKilled _ <- Q.close (queue connSend) $ HTError $ toException ThreadKilled return $ do -- Kill the receive thread now, but let any pending sends -- flush out. Wait for closing to complete, but if interrupted, -- terminate the send thread early. killHalf connRecv waitDone `onException` killHalf connSend else -- Connection already being closed. Wait for it to finish closing. return waitDone where waitDone = atomically $ do d <- readTVar connDone if d then return () else retry checkOpen :: Connection r s -> String -> STM () checkOpen Connection{..} loc = do b <- readTVar connOpen when (not b) $ throwSTM $ ErrorConnectionClosed loc -- | Receive the next message from the connection. Return 'Nothing' on EOF. -- Throw an exception if the 'Connection' is closed, or if the underlying -- 'backendRecv' failed. -- -- This will block if no messages are available right now. recv :: Connection r s -> STM (Maybe r) recv conn@Connection{connRecv = Half{..}} = do checkOpen conn loc res <- Q.read queue case res of Right r -> return $ Just r Left HTEOF -> return Nothing Left (HTError ex) -> throwSTM ex where loc = "recv" -- | Send a message on the connection. Throw an exception if the -- 'Connection' is closed, or if a /previous/ 'backendSend' failed. -- -- This will block if the send queue is full. send :: Connection r s -> s -> STM () send conn@Connection{connSend = Half{..}} s = do checkOpen conn loc res <- Q.write queue s case res of Right () -> return () Left HTEOF -> throwSTM $ ErrorSentClose loc Left (HTError ex) -> throwSTM ex where loc = "send" -- | Like 'send', but never block, even if this causes the send queue to exceed -- 'configSendLimit'. cram :: Connection r s -> s -> STM () cram conn@Connection{connSend = Half{..}} s = do checkOpen conn loc res <- Q.cram queue s case res of Right () -> return () Left HTEOF -> throwSTM $ ErrorSentClose loc Left (HTError ex) -> throwSTM ex where loc = "cram" -- | Shut down the connection for sending, but keep the connection open so -- more data can be received. Subsequent calls to 'send' and 'cram' -- will fail. bye :: Connection r s -> STM () bye conn@Connection{connSend = Half{..}} = do checkOpen conn loc res <- Q.close queue HTEOF case res of Right () -> return () Left HTEOF -> return () Left (HTError ex) -> throwSTM ex where loc = "bye" ------------------------------------------------------------------------ -- Connection backends -- | -- Connection I\/O driver. -- -- 'backendSend' and 'backendRecv' will often be called at the same time, so -- they must not block each other. However, 'backendRecv' and 'backendSend' -- are each called in their own thread, so it is safe to use -- 'Data.IORef.IORef's to marshal state from call to call. data Backend r s = Backend { backendRecv :: !(IO (Maybe r)) -- ^ Receive the next message. Return 'Nothing' on EOF. , backendSend :: !(Maybe s -> IO ()) -- ^ Send (and flush) the given message. -- -- If 'Nothing' is given, shut down the underlying connection for -- sending, as 'backendSend' will not be called again. If your device -- does not support this, do nothing. , backendClose :: !(IO ()) -- ^ Close the device. 'backendSend' and 'backendRecv' are never -- called during or after this. -- -- 'backendClose' is called when the 'Connection' is done using the -- device, even if you don't use 'close'. } ------------------------------------------------------------------------ -- Configuration data Config = Config { configRecvLimit :: !(Maybe Int) -- ^ Default: @'Just' 10@ -- -- Number of messages that may sit in the receive queue before the -- 'Connection''s receiving thread blocks. Having a limit is -- recommended in case the client produces messages faster than your -- program consumes them. , configSendLimit :: !(Maybe Int) -- ^ Default: @'Just' 10@ -- -- Number of messages that may sit in the send queue before 'send' -- blocks. Having a limit is recommended if your program produces -- messages faster than they can be sent. } instance Default Config where def = defaultConfig defaultConfig :: Config defaultConfig = Config { configRecvLimit = Just 10 , configSendLimit = Just 10 } ------------------------------------------------------------------------ -- Exceptions data Error = ErrorConnectionClosed String -- ^ connection 'close'd | ErrorSentClose String -- ^ connection shut down for sending deriving Typeable instance Show Error where show err = case err of ErrorConnectionClosed loc -> loc ++ ": connection closed" ErrorSentClose loc -> loc ++ ": connection shut down for sending" instance Exception Error
joeyadams/hs-stm-connection
Control/Concurrent/STM/Connection.hs
bsd-3-clause
9,911
0
18
2,793
2,109
1,076
1,033
206
3
{------------------------------------------------------------------------------- DSem.VectorSpace.BowCached Bag-of-words distributional model (c) 2013 Jan Snajder <[email protected]> TODO: split into: Bow.Sparse Bow.Dense Bow.*.Cached -------------------------------------------------------------------------------} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module DSem.VectorSpace.BowCached ( module DSem.VectorSpace, Target, Context, Bow, ModelM, Vect, CacheStats (..), readModel, readMatrix, setCacheSize, getCacheStats) where import DSem.VectorSpace import qualified DSem.Vector.SparseVector as V import Control.Monad import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Map as M import qualified Data.IntMap as IM import qualified Data.BoundedMap as BM import Data.Maybe import Control.Monad.State.Strict import Control.Applicative import System.IO import qualified FileDB as DB type Word = T.Text -- TODO: convert to smallstring! type Target = Word type Context = Word type Vect = V.SparseVector type ModelM = ModelIO Bow type Contexts = IM.IntMap Context type Matrix = BM.BoundedMap Target Vect type TargetIndex = DB.Index -- from targets to fileseeks data CacheStats = CacheStats { hits :: !Int, misses :: !Int, unknowns :: !Int } deriving (Eq,Show,Read,Ord) data Bow = Bow { stats :: !CacheStats, handle :: !Handle, index :: !TargetIndex, matrix :: !Matrix, contexts :: Maybe Contexts } deriving (Show,Eq) defaultCacheSize = 512 incHits :: ModelM () incHits = modify $ \s -> let st = stats s in s { stats = st { hits = succ $ hits st }} incMisses :: ModelM () incMisses = modify $ \s -> let st = stats s in s { stats = st { misses = succ $ misses st }} incUnknowns :: ModelM () incUnknowns = modify $ \s -> let st = stats s in s { stats = st { unknowns = succ $ unknowns st }} getCacheStats :: ModelM CacheStats getCacheStats = gets stats instance Model ModelM Target Context Vect where getVector t = do m <- gets matrix case BM.lookup t m of Nothing -> do v <- readVector t if isJust v then do addVector t (fromJust v); incMisses else incUnknowns return v v -> do incHits; return v getDim = do t <- gets (M.size . index) c <- gets (IM.size . fromMaybe IM.empty . contexts) return (t,c) getContexts = gets (IM.elems . fromMaybe IM.empty . contexts) getTargets = gets (M.keys . index) setCacheSize :: Int -> ModelM () setCacheSize n = modify (\s -> s { matrix = BM.setBound n $ matrix s}) addVector :: Target -> Vect -> ModelM () addVector t v = modify (\s -> s { matrix = BM.insert t v $ matrix s} ) --addVector t v = modify (\s -> let m = matrix s in s `seq` m `seq` t `seq` v `seq` s { matrix = BM.insert t v m} ) readVector :: Target -> ModelM (Maybe Vect) readVector t = do h <- gets handle ti <- gets index case M.lookup t ti of Nothing -> return Nothing Just i -> do liftIO $ hSeek h AbsoluteSeek (toInteger i) Just . parseVector <$> liftIO (T.hGetLine h) {- nepotrebno? -- not good: mapM is not lazy... or something (?) -- not tail recursive! --cacheTargets :: [Target] -> ModelM Int --cacheTargets ts = length . filter isJust <$> mapM getVector ts cacheTargets :: [Target] -> ModelM Int cacheTargets = foldM (\n t -> do Just v <- getVector t; return (V.norm v `seq` n `seq` n + 1)) 0 -- the above forces the vector to be computed cacheAllTargets :: ModelM Int cacheAllTargets = getTargets >>= cacheTargets -} readContexts :: FilePath -> IO Contexts readContexts f = IM.fromList . zip [1..] . T.lines <$> T.readFile f readMatrix :: FilePath -> IO Bow readMatrix f = do h <- openFile f ReadMode ti <- DB.mkIndex h return $ Bow { matrix = BM.empty defaultCacheSize, handle = h, contexts = Nothing, index = ti, stats = CacheStats { hits = 0, misses = 0, unknowns = 0 } } readModel :: FilePath -> FilePath -> IO Bow readModel fm fc = do m <- readMatrix fm cs <- readContexts fc return $ m { contexts = Just cs } parseVector :: T.Text -> Vect parseVector = parse . T.words where parse (_:xs) = V.fromAssocList $ map parse2 xs parse _ = error "no parse" parse2 x = case T.split (==':') x of (c:f:_) -> (read $ T.unpack c, read $ T.unpack f) _ -> error "no parse" {- TODO: adapt and move to Bow uncached readMatrix :: FilePath -> IO Matrix readMatrix f = M.fromList . map (parse . words) . lines <$> readFile f where parse (t:xs) = let t' = B.fromString t xs' = V.fromAssocList $ map parse2 xs in t' `seq` xs' `seq` (t',xs') parse _ = error "no parse" parse2 x = let (c,_:f) = break (==':') x c' = c `seq` read c f' = f `seq` read f in c' `seq` f' `seq` (c',f') -}
jsnajder/dsem
src/DSem/VectorSpace/BowCached.hs
bsd-3-clause
5,065
4
18
1,325
1,342
707
635
121
3
module Win32Window where import StdDIS import Win32Types import GDITypes import Win32WinMessage ---------------------------------------------------------------- -- Window Class ---------------------------------------------------------------- -- The classname must not be deallocated until the corresponding class -- is deallocated. For this reason, we represent classnames by pointers -- and explicitly allocate the className. type ClassName = LPCTSTR -- Note: this is one of those rare functions which doesnt free all -- its String arguments. mkClassName :: String -> ClassName mkClassName gc_arg1 = unsafePerformIO( (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32Window_cpp_mkClassName arg1 >>= \ (gc_res1) -> (return (gc_res1))) primitive prim_Win32Window_cpp_mkClassName :: Addr -> IO (Addr) type ClassStyle = UINT cS_VREDRAW :: ClassStyle cS_VREDRAW = unsafePerformIO( prim_Win32Window_cpp_cS_VREDRAW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_VREDRAW :: IO (Word32) cS_HREDRAW :: ClassStyle cS_HREDRAW = unsafePerformIO( prim_Win32Window_cpp_cS_HREDRAW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_HREDRAW :: IO (Word32) cS_OWNDC :: ClassStyle cS_OWNDC = unsafePerformIO( prim_Win32Window_cpp_cS_OWNDC >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_OWNDC :: IO (Word32) cS_CLASSDC :: ClassStyle cS_CLASSDC = unsafePerformIO( prim_Win32Window_cpp_cS_CLASSDC >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_CLASSDC :: IO (Word32) cS_PARENTDC :: ClassStyle cS_PARENTDC = unsafePerformIO( prim_Win32Window_cpp_cS_PARENTDC >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_PARENTDC :: IO (Word32) cS_SAVEBITS :: ClassStyle cS_SAVEBITS = unsafePerformIO( prim_Win32Window_cpp_cS_SAVEBITS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_SAVEBITS :: IO (Word32) cS_DBLCLKS :: ClassStyle cS_DBLCLKS = unsafePerformIO( prim_Win32Window_cpp_cS_DBLCLKS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_DBLCLKS :: IO (Word32) cS_BYTEALIGNCLIENT :: ClassStyle cS_BYTEALIGNCLIENT = unsafePerformIO( prim_Win32Window_cpp_cS_BYTEALIGNCLIENT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_BYTEALIGNCLIENT :: IO (Word32) cS_BYTEALIGNWINDOW :: ClassStyle cS_BYTEALIGNWINDOW = unsafePerformIO( prim_Win32Window_cpp_cS_BYTEALIGNWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_BYTEALIGNWINDOW :: IO (Word32) cS_NOCLOSE :: ClassStyle cS_NOCLOSE = unsafePerformIO( prim_Win32Window_cpp_cS_NOCLOSE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_NOCLOSE :: IO (Word32) cS_GLOBALCLASS :: ClassStyle cS_GLOBALCLASS = unsafePerformIO( prim_Win32Window_cpp_cS_GLOBALCLASS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cS_GLOBALCLASS :: IO (Word32) type WNDCLASS = (ClassStyle, -- style HINSTANCE, -- hInstance MbHICON, -- hIcon MbHCURSOR, -- hCursor MbHBRUSH, -- hbrBackground MbLPCSTR, -- lpszMenuName ClassName) -- lpszClassName --ToDo! --To avoid confusion with NULL, WNDCLASS requires you to add 1 to a SystemColor --(which can be NULL) -- %fun mkMbHBRUSH :: SystemColor -> MbHBRUSH -- %code -- %result ((HBRUSH)($0+1)); marshall_wndClass_ :: WNDCLASS -> IO Addr marshall_wndClass_ gc_arg1 = case gc_arg1 of { (style,hInstance,hIcon,hCursor,hbrBackground,lpszMenuName,lpszClassName) -> (case hIcon of { Nothing -> (return (nullHANDLE)); (Just hIcon) -> (return ((hIcon))) }) >>= \ (hIcon) -> (case hCursor of { Nothing -> (return (nullHANDLE)); (Just hCursor) -> (return ((hCursor))) }) >>= \ (hCursor) -> (case hbrBackground of { Nothing -> (return (nullHANDLE)); (Just hbrBackground) -> (return ((hbrBackground))) }) >>= \ (hbrBackground) -> (case lpszMenuName of { Nothing -> (return (nullAddr)); (Just lpszMenuName) -> (return ((lpszMenuName))) }) >>= \ (lpszMenuName) -> prim_Win32Window_cpp_marshall_wndClass_ style hInstance hIcon hCursor hbrBackground lpszMenuName lpszClassName >>= \ (c,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (c))} primitive prim_Win32Window_cpp_marshall_wndClass_ :: Word32 -> Addr -> Addr -> Addr -> Addr -> Addr -> Addr -> IO (Addr,Int,Addr) registerClass :: WNDCLASS -> IO MbATOM registerClass gc_arg1 = (marshall_wndClass_ gc_arg1) >>= \ (arg1) -> prim_Win32Window_cpp_registerClass arg1 >>= \ (res1) -> (if 0 == (res1) then return Nothing else (return ((Just res1)))) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_registerClass :: Addr -> IO (Word32) unregisterClass :: ClassName -> HINSTANCE -> IO () unregisterClass arg1 arg2 = prim_Win32Window_cpp_unregisterClass arg1 arg2 primitive prim_Win32Window_cpp_unregisterClass :: Addr -> Addr -> IO () ---------------------------------------------------------------- -- Window Style ---------------------------------------------------------------- type WindowStyle = DWORD wS_OVERLAPPED :: WindowStyle wS_OVERLAPPED = unsafePerformIO( prim_Win32Window_cpp_wS_OVERLAPPED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_OVERLAPPED :: IO (Word32) wS_POPUP :: WindowStyle wS_POPUP = unsafePerformIO( prim_Win32Window_cpp_wS_POPUP >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_POPUP :: IO (Word32) wS_CHILD :: WindowStyle wS_CHILD = unsafePerformIO( prim_Win32Window_cpp_wS_CHILD >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_CHILD :: IO (Word32) wS_CLIPSIBLINGS :: WindowStyle wS_CLIPSIBLINGS = unsafePerformIO( prim_Win32Window_cpp_wS_CLIPSIBLINGS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_CLIPSIBLINGS :: IO (Word32) wS_CLIPCHILDREN :: WindowStyle wS_CLIPCHILDREN = unsafePerformIO( prim_Win32Window_cpp_wS_CLIPCHILDREN >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_CLIPCHILDREN :: IO (Word32) wS_VISIBLE :: WindowStyle wS_VISIBLE = unsafePerformIO( prim_Win32Window_cpp_wS_VISIBLE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_VISIBLE :: IO (Word32) wS_DISABLED :: WindowStyle wS_DISABLED = unsafePerformIO( prim_Win32Window_cpp_wS_DISABLED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_DISABLED :: IO (Word32) wS_MINIMIZE :: WindowStyle wS_MINIMIZE = unsafePerformIO( prim_Win32Window_cpp_wS_MINIMIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_MINIMIZE :: IO (Word32) wS_MAXIMIZE :: WindowStyle wS_MAXIMIZE = unsafePerformIO( prim_Win32Window_cpp_wS_MAXIMIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_MAXIMIZE :: IO (Word32) wS_CAPTION :: WindowStyle wS_CAPTION = unsafePerformIO( prim_Win32Window_cpp_wS_CAPTION >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_CAPTION :: IO (Word32) wS_BORDER :: WindowStyle wS_BORDER = unsafePerformIO( prim_Win32Window_cpp_wS_BORDER >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_BORDER :: IO (Word32) wS_DLGFRAME :: WindowStyle wS_DLGFRAME = unsafePerformIO( prim_Win32Window_cpp_wS_DLGFRAME >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_DLGFRAME :: IO (Word32) wS_VSCROLL :: WindowStyle wS_VSCROLL = unsafePerformIO( prim_Win32Window_cpp_wS_VSCROLL >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_VSCROLL :: IO (Word32) wS_HSCROLL :: WindowStyle wS_HSCROLL = unsafePerformIO( prim_Win32Window_cpp_wS_HSCROLL >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_HSCROLL :: IO (Word32) wS_SYSMENU :: WindowStyle wS_SYSMENU = unsafePerformIO( prim_Win32Window_cpp_wS_SYSMENU >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_SYSMENU :: IO (Word32) wS_THICKFRAME :: WindowStyle wS_THICKFRAME = unsafePerformIO( prim_Win32Window_cpp_wS_THICKFRAME >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_THICKFRAME :: IO (Word32) wS_MINIMIZEBOX :: WindowStyle wS_MINIMIZEBOX = unsafePerformIO( prim_Win32Window_cpp_wS_MINIMIZEBOX >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_MINIMIZEBOX :: IO (Word32) wS_MAXIMIZEBOX :: WindowStyle wS_MAXIMIZEBOX = unsafePerformIO( prim_Win32Window_cpp_wS_MAXIMIZEBOX >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_MAXIMIZEBOX :: IO (Word32) wS_GROUP :: WindowStyle wS_GROUP = unsafePerformIO( prim_Win32Window_cpp_wS_GROUP >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_GROUP :: IO (Word32) wS_TABSTOP :: WindowStyle wS_TABSTOP = unsafePerformIO( prim_Win32Window_cpp_wS_TABSTOP >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_TABSTOP :: IO (Word32) wS_OVERLAPPEDWINDOW :: WindowStyle wS_OVERLAPPEDWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_OVERLAPPEDWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_OVERLAPPEDWINDOW :: IO (Word32) wS_POPUPWINDOW :: WindowStyle wS_POPUPWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_POPUPWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_POPUPWINDOW :: IO (Word32) wS_CHILDWINDOW :: WindowStyle wS_CHILDWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_CHILDWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_CHILDWINDOW :: IO (Word32) wS_TILED :: WindowStyle wS_TILED = unsafePerformIO( prim_Win32Window_cpp_wS_TILED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_TILED :: IO (Word32) wS_ICONIC :: WindowStyle wS_ICONIC = unsafePerformIO( prim_Win32Window_cpp_wS_ICONIC >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_ICONIC :: IO (Word32) wS_SIZEBOX :: WindowStyle wS_SIZEBOX = unsafePerformIO( prim_Win32Window_cpp_wS_SIZEBOX >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_SIZEBOX :: IO (Word32) wS_TILEDWINDOW :: WindowStyle wS_TILEDWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_TILEDWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_TILEDWINDOW :: IO (Word32) type WindowStyleEx = DWORD wS_EX_DLGMODALFRAME :: WindowStyleEx wS_EX_DLGMODALFRAME = unsafePerformIO( prim_Win32Window_cpp_wS_EX_DLGMODALFRAME >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_DLGMODALFRAME :: IO (Word32) wS_EX_NOPARENTNOTIFY :: WindowStyleEx wS_EX_NOPARENTNOTIFY = unsafePerformIO( prim_Win32Window_cpp_wS_EX_NOPARENTNOTIFY >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_NOPARENTNOTIFY :: IO (Word32) wS_EX_TOPMOST :: WindowStyleEx wS_EX_TOPMOST = unsafePerformIO( prim_Win32Window_cpp_wS_EX_TOPMOST >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_TOPMOST :: IO (Word32) wS_EX_ACCEPTFILES :: WindowStyleEx wS_EX_ACCEPTFILES = unsafePerformIO( prim_Win32Window_cpp_wS_EX_ACCEPTFILES >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_ACCEPTFILES :: IO (Word32) wS_EX_TRANSPARENT :: WindowStyleEx wS_EX_TRANSPARENT = unsafePerformIO( prim_Win32Window_cpp_wS_EX_TRANSPARENT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_TRANSPARENT :: IO (Word32) wS_EX_MDICHILD :: WindowStyleEx wS_EX_MDICHILD = unsafePerformIO( prim_Win32Window_cpp_wS_EX_MDICHILD >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_MDICHILD :: IO (Word32) wS_EX_TOOLWINDOW :: WindowStyleEx wS_EX_TOOLWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_EX_TOOLWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_TOOLWINDOW :: IO (Word32) wS_EX_WINDOWEDGE :: WindowStyleEx wS_EX_WINDOWEDGE = unsafePerformIO( prim_Win32Window_cpp_wS_EX_WINDOWEDGE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_WINDOWEDGE :: IO (Word32) wS_EX_CLIENTEDGE :: WindowStyleEx wS_EX_CLIENTEDGE = unsafePerformIO( prim_Win32Window_cpp_wS_EX_CLIENTEDGE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_CLIENTEDGE :: IO (Word32) wS_EX_CONTEXTHELP :: WindowStyleEx wS_EX_CONTEXTHELP = unsafePerformIO( prim_Win32Window_cpp_wS_EX_CONTEXTHELP >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_CONTEXTHELP :: IO (Word32) wS_EX_RIGHT :: WindowStyleEx wS_EX_RIGHT = unsafePerformIO( prim_Win32Window_cpp_wS_EX_RIGHT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_RIGHT :: IO (Word32) wS_EX_LEFT :: WindowStyleEx wS_EX_LEFT = unsafePerformIO( prim_Win32Window_cpp_wS_EX_LEFT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_LEFT :: IO (Word32) wS_EX_RTLREADING :: WindowStyleEx wS_EX_RTLREADING = unsafePerformIO( prim_Win32Window_cpp_wS_EX_RTLREADING >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_RTLREADING :: IO (Word32) wS_EX_LTRREADING :: WindowStyleEx wS_EX_LTRREADING = unsafePerformIO( prim_Win32Window_cpp_wS_EX_LTRREADING >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_LTRREADING :: IO (Word32) wS_EX_LEFTSCROLLBAR :: WindowStyleEx wS_EX_LEFTSCROLLBAR = unsafePerformIO( prim_Win32Window_cpp_wS_EX_LEFTSCROLLBAR >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_LEFTSCROLLBAR :: IO (Word32) wS_EX_RIGHTSCROLLBAR :: WindowStyleEx wS_EX_RIGHTSCROLLBAR = unsafePerformIO( prim_Win32Window_cpp_wS_EX_RIGHTSCROLLBAR >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_RIGHTSCROLLBAR :: IO (Word32) wS_EX_CONTROLPARENT :: WindowStyleEx wS_EX_CONTROLPARENT = unsafePerformIO( prim_Win32Window_cpp_wS_EX_CONTROLPARENT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_CONTROLPARENT :: IO (Word32) wS_EX_STATICEDGE :: WindowStyleEx wS_EX_STATICEDGE = unsafePerformIO( prim_Win32Window_cpp_wS_EX_STATICEDGE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_STATICEDGE :: IO (Word32) wS_EX_APPWINDOW :: WindowStyleEx wS_EX_APPWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_EX_APPWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_APPWINDOW :: IO (Word32) wS_EX_OVERLAPPEDWINDOW :: WindowStyleEx wS_EX_OVERLAPPEDWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_EX_OVERLAPPEDWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_OVERLAPPEDWINDOW :: IO (Word32) wS_EX_PALETTEWINDOW :: WindowStyleEx wS_EX_PALETTEWINDOW = unsafePerformIO( prim_Win32Window_cpp_wS_EX_PALETTEWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_wS_EX_PALETTEWINDOW :: IO (Word32) cW_USEDEFAULT :: Pos cW_USEDEFAULT = unsafePerformIO( prim_Win32Window_cpp_cW_USEDEFAULT >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_cW_USEDEFAULT :: IO (Int) type Pos = Int type MbPos = Maybe Pos type WindowClosure = HWND -> WindowMessage -> WPARAM -> LPARAM -> IO LRESULT -- ?? setWindowClosure :: HWND -> WindowClosure -> IO () setWindowClosure hwnd gc_arg1 = (makeStablePtr gc_arg1) >>= \ closure -> prim_Win32Window_cpp_setWindowClosure hwnd closure primitive prim_Win32Window_cpp_setWindowClosure :: Addr -> StablePtr a2 -> IO () createWindow :: ClassName -> String -> WindowStyle -> Maybe Pos -> Maybe Pos -> Maybe Pos -> Maybe Pos -> MbHWND -> MbHMENU -> HINSTANCE -> WindowClosure -> IO HWND createWindow name gc_arg1 style x y width height hwndParent hmenu hinst gc_arg2 = (marshall_string_ gc_arg1) >>= \ (windowName) -> (case x of { Nothing -> (return (cW_USEDEFAULT)); (Just x) -> (return ((x))) }) >>= \ (x) -> (case y of { Nothing -> (return (cW_USEDEFAULT)); (Just y) -> (return ((y))) }) >>= \ (y) -> (case width of { Nothing -> (return (cW_USEDEFAULT)); (Just width) -> (return ((width))) }) >>= \ (width) -> (case height of { Nothing -> (return (cW_USEDEFAULT)); (Just height) -> (return ((height))) }) >>= \ (height) -> (case hwndParent of { Nothing -> (return (nullHANDLE)); (Just hwndParent) -> (return ((hwndParent))) }) >>= \ (hwndParent) -> (case hmenu of { Nothing -> (return (nullHANDLE)); (Just hmenu) -> (return ((hmenu))) }) >>= \ (hmenu) -> (makeStablePtr gc_arg2) >>= \ closure -> prim_Win32Window_cpp_createWindow name windowName style x y width height hwndParent hmenu hinst closure >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_createWindow :: Addr -> Addr -> Word32 -> Int -> Int -> Int -> Int -> Addr -> Addr -> Addr -> StablePtr a11 -> IO (Addr,Int,Addr) -- Freeing the title/window name has been reported -- to cause a crash, so let's not do it. -- %end free(windowName) createWindowEx :: WindowStyle -> ClassName -> String -> WindowStyle -> Maybe Pos -> Maybe Pos -> Maybe Pos -> Maybe Pos -> MbHWND -> MbHMENU -> HINSTANCE -> WindowClosure -> IO HWND createWindowEx estyle cls gc_arg1 wstyle x y nWidth nHeight hwndParent hmenu hinstance gc_arg2 = (marshall_string_ gc_arg1) >>= \ (wname) -> (case x of { Nothing -> (return (cW_USEDEFAULT)); (Just x) -> (return ((x))) }) >>= \ (x) -> (case y of { Nothing -> (return (cW_USEDEFAULT)); (Just y) -> (return ((y))) }) >>= \ (y) -> (case nWidth of { Nothing -> (return (cW_USEDEFAULT)); (Just nWidth) -> (return ((nWidth))) }) >>= \ (nWidth) -> (case nHeight of { Nothing -> (return (cW_USEDEFAULT)); (Just nHeight) -> (return ((nHeight))) }) >>= \ (nHeight) -> (case hwndParent of { Nothing -> (return (nullHANDLE)); (Just hwndParent) -> (return ((hwndParent))) }) >>= \ (hwndParent) -> (case hmenu of { Nothing -> (return (nullHANDLE)); (Just hmenu) -> (return ((hmenu))) }) >>= \ (hmenu) -> (makeStablePtr gc_arg2) >>= \ closure -> prim_Win32Window_cpp_createWindowEx estyle cls wname wstyle x y nWidth nHeight hwndParent hmenu hinstance closure >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_createWindowEx :: Word32 -> Addr -> Addr -> Word32 -> Int -> Int -> Int -> Int -> Addr -> Addr -> Addr -> StablePtr a12 -> IO (Addr,Int,Addr) -- see CreateWindow comment. -- %end free(wname) ---------------------------------------------------------------- defWindowProc :: MbHWND -> WindowMessage -> WPARAM -> LPARAM -> IO LRESULT defWindowProc arg1 arg2 arg3 gc_arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> case ( fromIntegral gc_arg1) of { arg4 -> prim_Win32Window_cpp_defWindowProc arg1 arg2 arg3 arg4 >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))} primitive prim_Win32Window_cpp_defWindowProc :: Addr -> Word32 -> Word32 -> Int -> IO (Int) ---------------------------------------------------------------- getClientRect :: HWND -> IO RECT getClientRect arg1 = prim_Win32Window_cpp_getClientRect arg1 >>= \ (gc_res2,gc_res4,gc_res6,gc_res8,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in let gc_res5 = ( fromIntegral (gc_res6)) in let gc_res7 = ( fromIntegral (gc_res8)) in (return ((gc_res1,gc_res3,gc_res5,gc_res7))) primitive prim_Win32Window_cpp_getClientRect :: Addr -> IO (Int,Int,Int,Int,Int,Addr) getWindowRect :: HWND -> IO RECT getWindowRect arg1 = prim_Win32Window_cpp_getWindowRect arg1 >>= \ (gc_res2,gc_res4,gc_res6,gc_res8,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in let gc_res5 = ( fromIntegral (gc_res6)) in let gc_res7 = ( fromIntegral (gc_res8)) in (return ((gc_res1,gc_res3,gc_res5,gc_res7))) primitive prim_Win32Window_cpp_getWindowRect :: Addr -> IO (Int,Int,Int,Int,Int,Addr) -- Should it be MbRECT instead? invalidateRect :: MbHWND -> MbLPRECT -> Bool -> IO () invalidateRect arg1 arg2 gc_arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> (case arg2 of { Nothing -> (return (nullAddr)); (Just arg2) -> (return ((arg2))) }) >>= \ (arg2) -> (marshall_bool_ gc_arg1) >>= \ (arg3) -> prim_Win32Window_cpp_invalidateRect arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_invalidateRect :: Addr -> Addr -> Int -> IO (Int,Addr) screenToClient :: HWND -> POINT -> IO POINT screenToClient arg1 gc_arg1 = case gc_arg1 of { (gc_arg2,gc_arg4) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> prim_Win32Window_cpp_screenToClient arg1 gc_arg3 gc_arg5 >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in (return ((gc_res1,gc_res3)))}}} primitive prim_Win32Window_cpp_screenToClient :: Addr -> Int -> Int -> IO (Int,Int,Int,Addr) clientToScreen :: HWND -> POINT -> IO POINT clientToScreen hwnd gc_arg1 = case gc_arg1 of { (gc_arg2,gc_arg4) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> prim_Win32Window_cpp_clientToScreen hwnd gc_arg3 gc_arg5 >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in (return ((gc_res1,gc_res3)))}}} primitive prim_Win32Window_cpp_clientToScreen :: Addr -> Int -> Int -> IO (Int,Int,Int,Addr) ---------------------------------------------------------------- -- Setting window text/label ---------------------------------------------------------------- -- For setting the title bar text. But inconvenient to make the LPCTSTR setWindowText :: HWND -> String -> IO () setWindowText arg1 gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg2) -> prim_Win32Window_cpp_setWindowText arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_setWindowText :: Addr -> Addr -> IO (Int,Addr) ---------------------------------------------------------------- -- Paint struct ---------------------------------------------------------------- type PAINTSTRUCT = ( HDC -- hdc , Bool -- fErase , RECT -- rcPaint ) type LPPAINTSTRUCT = Addr sizeofPAINTSTRUCT :: DWORD sizeofPAINTSTRUCT = unsafePerformIO( prim_Win32Window_cpp_sizeofPAINTSTRUCT >>= \ (gc_res1) -> (return (gc_res1))) primitive prim_Win32Window_cpp_sizeofPAINTSTRUCT :: IO (Word32) beginPaint :: HWND -> LPPAINTSTRUCT -> IO HDC beginPaint arg1 arg2 = prim_Win32Window_cpp_beginPaint arg1 arg2 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_beginPaint :: Addr -> Addr -> IO (Addr,Int,Addr) endPaint :: HWND -> LPPAINTSTRUCT -> IO () endPaint arg1 arg2 = prim_Win32Window_cpp_endPaint arg1 arg2 primitive prim_Win32Window_cpp_endPaint :: Addr -> Addr -> IO () -- Apparently always succeeds (return non-zero) ---------------------------------------------------------------- -- ShowWindow ---------------------------------------------------------------- type ShowWindowControl = DWORD sW_HIDE :: ShowWindowControl sW_HIDE = unsafePerformIO( prim_Win32Window_cpp_sW_HIDE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_HIDE :: IO (Word32) sW_SHOWNORMAL :: ShowWindowControl sW_SHOWNORMAL = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWNORMAL >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWNORMAL :: IO (Word32) sW_SHOWMINIMIZED :: ShowWindowControl sW_SHOWMINIMIZED = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWMINIMIZED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWMINIMIZED :: IO (Word32) sW_SHOWMAXIMIZED :: ShowWindowControl sW_SHOWMAXIMIZED = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWMAXIMIZED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWMAXIMIZED :: IO (Word32) sW_MAXIMIZE :: ShowWindowControl sW_MAXIMIZE = unsafePerformIO( prim_Win32Window_cpp_sW_MAXIMIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_MAXIMIZE :: IO (Word32) sW_SHOWNOACTIVATE :: ShowWindowControl sW_SHOWNOACTIVATE = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWNOACTIVATE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWNOACTIVATE :: IO (Word32) sW_SHOW :: ShowWindowControl sW_SHOW = unsafePerformIO( prim_Win32Window_cpp_sW_SHOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOW :: IO (Word32) sW_MINIMIZE :: ShowWindowControl sW_MINIMIZE = unsafePerformIO( prim_Win32Window_cpp_sW_MINIMIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_MINIMIZE :: IO (Word32) sW_SHOWMINNOACTIVE :: ShowWindowControl sW_SHOWMINNOACTIVE = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWMINNOACTIVE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWMINNOACTIVE :: IO (Word32) sW_SHOWNA :: ShowWindowControl sW_SHOWNA = unsafePerformIO( prim_Win32Window_cpp_sW_SHOWNA >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_SHOWNA :: IO (Word32) sW_RESTORE :: ShowWindowControl sW_RESTORE = unsafePerformIO( prim_Win32Window_cpp_sW_RESTORE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sW_RESTORE :: IO (Word32) showWindow :: HWND -> ShowWindowControl -> IO Bool showWindow arg1 arg2 = prim_Win32Window_cpp_showWindow arg1 arg2 >>= \ (res1) -> (unmarshall_bool_ res1) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_showWindow :: Addr -> Word32 -> IO (Int) ---------------------------------------------------------------- -- Misc ---------------------------------------------------------------- adjustWindowRect :: RECT -> WindowStyle -> Bool -> IO RECT adjustWindowRect gc_arg1 arg2 gc_arg11 = case gc_arg1 of { (gc_arg2,gc_arg4,gc_arg6,gc_arg8) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> case ( fromIntegral gc_arg6) of { gc_arg7 -> case ( fromIntegral gc_arg8) of { gc_arg9 -> (marshall_bool_ gc_arg11) >>= \ (arg3) -> prim_Win32Window_cpp_adjustWindowRect gc_arg3 gc_arg5 gc_arg7 gc_arg9 arg2 arg3 >>= \ (gc_res2,gc_res4,gc_res6,gc_res8,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in let gc_res5 = ( fromIntegral (gc_res6)) in let gc_res7 = ( fromIntegral (gc_res8)) in (return ((gc_res1,gc_res3,gc_res5,gc_res7)))}}}}} primitive prim_Win32Window_cpp_adjustWindowRect :: Int -> Int -> Int -> Int -> Word32 -> Int -> IO (Int,Int,Int,Int,Int,Addr) adjustWindowRectEx :: RECT -> WindowStyle -> Bool -> WindowStyleEx -> IO RECT adjustWindowRectEx gc_arg1 arg2 gc_arg11 arg4 = case gc_arg1 of { (gc_arg2,gc_arg4,gc_arg6,gc_arg8) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> case ( fromIntegral gc_arg6) of { gc_arg7 -> case ( fromIntegral gc_arg8) of { gc_arg9 -> (marshall_bool_ gc_arg11) >>= \ (arg3) -> prim_Win32Window_cpp_adjustWindowRectEx gc_arg3 gc_arg5 gc_arg7 gc_arg9 arg2 arg3 arg4 >>= \ (gc_res2,gc_res4,gc_res6,gc_res8,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in let gc_res5 = ( fromIntegral (gc_res6)) in let gc_res7 = ( fromIntegral (gc_res8)) in (return ((gc_res1,gc_res3,gc_res5,gc_res7)))}}}}} primitive prim_Win32Window_cpp_adjustWindowRectEx :: Int -> Int -> Int -> Int -> Word32 -> Int -> Word32 -> IO (Int,Int,Int,Int,Int,Addr) -- Win2K and later: -- %fun AllowSetForegroundWindow :: DWORD -> IO () -- % -- %dis animateWindowType x = dWORD x -- type AnimateWindowType = DWORD -- %const AnimateWindowType -- [ AW_SLIDE -- , AW_ACTIVATE -- , AW_BLEND -- , AW_HIDE -- , AW_CENTER -- , AW_HOR_POSITIVE -- , AW_HOR_NEGATIVE -- , AW_VER_POSITIVE -- , AW_VER_NEGATIVE -- ] -- Win98 or Win2K: -- %fun AnimateWindow :: HWND -> DWORD -> AnimateWindowType -> IO () -- %code BOOL success = AnimateWindow(arg1,arg2,arg3) -- %fail { !success } { ErrorWin("AnimateWindow") } anyPopup :: IO Bool anyPopup = prim_Win32Window_cpp_anyPopup >>= \ (res1) -> (unmarshall_bool_ res1) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_anyPopup :: IO (Int) arrangeIconicWindows :: HWND -> IO () arrangeIconicWindows arg1 = prim_Win32Window_cpp_arrangeIconicWindows arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_arrangeIconicWindows :: Addr -> IO (Int,Addr) beginDeferWindowPos :: Int -> IO HDWP beginDeferWindowPos arg1 = prim_Win32Window_cpp_beginDeferWindowPos arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_beginDeferWindowPos :: Int -> IO (Addr,Int,Addr) bringWindowToTop :: HWND -> IO () bringWindowToTop arg1 = prim_Win32Window_cpp_bringWindowToTop arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_bringWindowToTop :: Addr -> IO (Int,Addr) childWindowFromPoint :: HWND -> POINT -> IO MbHWND childWindowFromPoint hwnd gc_arg1 = case gc_arg1 of { (gc_arg2,gc_arg4) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> prim_Win32Window_cpp_childWindowFromPoint hwnd gc_arg3 gc_arg5 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (if nullHANDLE == (res1) then return Nothing else (return ((Just res1)))) >>= \ gc_res1 -> (return (gc_res1))}}} primitive prim_Win32Window_cpp_childWindowFromPoint :: Addr -> Int -> Int -> IO (Addr,Int,Addr) childWindowFromPointEx :: HWND -> POINT -> DWORD -> IO MbHWND childWindowFromPointEx hwnd gc_arg1 arg2 = case gc_arg1 of { (gc_arg2,gc_arg4) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> prim_Win32Window_cpp_childWindowFromPointEx hwnd gc_arg3 gc_arg5 arg2 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (if nullHANDLE == (res1) then return Nothing else (return ((Just res1)))) >>= \ gc_res1 -> (return (gc_res1))}}} primitive prim_Win32Window_cpp_childWindowFromPointEx :: Addr -> Int -> Int -> Word32 -> IO (Addr,Int,Addr) closeWindow :: HWND -> IO () closeWindow arg1 = prim_Win32Window_cpp_closeWindow arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_closeWindow :: Addr -> IO (Int,Addr) deferWindowPos :: HDWP -> HWND -> HWND -> Int -> Int -> Int -> Int -> SetWindowPosFlags -> IO HDWP deferWindowPos arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 = prim_Win32Window_cpp_deferWindowPos arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_deferWindowPos :: Addr -> Addr -> Addr -> Int -> Int -> Int -> Int -> Word32 -> IO (Addr,Int,Addr) destroyWindow :: HWND -> IO () destroyWindow arg1 = prim_Win32Window_cpp_destroyWindow arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_destroyWindow :: Addr -> IO (Int,Addr) endDeferWindowPos :: HDWP -> IO () endDeferWindowPos arg1 = prim_Win32Window_cpp_endDeferWindowPos arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_endDeferWindowPos :: Addr -> IO (Int,Addr) findWindow :: String -> String -> IO MbHWND findWindow gc_arg1 gc_arg2 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> prim_Win32Window_cpp_findWindow arg1 arg2 >>= \ (res1) -> (if nullHANDLE == (res1) then return Nothing else (return ((Just res1)))) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_findWindow :: Addr -> Addr -> IO (Addr) findWindowEx :: HWND -> HWND -> String -> String -> IO MbHWND findWindowEx arg1 arg2 gc_arg1 gc_arg2 = (marshall_string_ gc_arg1) >>= \ (arg3) -> (marshall_string_ gc_arg2) >>= \ (arg4) -> prim_Win32Window_cpp_findWindowEx arg1 arg2 arg3 arg4 >>= \ (res1) -> (if nullHANDLE == (res1) then return Nothing else (return ((Just res1)))) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_findWindowEx :: Addr -> Addr -> Addr -> Addr -> IO (Addr) flashWindow :: HWND -> Bool -> IO Bool flashWindow arg1 gc_arg1 = (marshall_bool_ gc_arg1) >>= \ (arg2) -> prim_Win32Window_cpp_flashWindow arg1 arg2 >>= \ (res1) -> (unmarshall_bool_ res1) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_flashWindow :: Addr -> Int -> IO (Int) -- No error code moveWindow :: HWND -> Int -> Int -> Int -> Int -> Bool -> IO () moveWindow arg1 arg2 arg3 arg4 arg5 gc_arg1 = (marshall_bool_ gc_arg1) >>= \ (arg6) -> prim_Win32Window_cpp_moveWindow arg1 arg2 arg3 arg4 arg5 arg6 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_moveWindow :: Addr -> Int -> Int -> Int -> Int -> Int -> IO (Int,Addr) getDesktopWindow :: IO HWND getDesktopWindow = prim_Win32Window_cpp_getDesktopWindow >>= \ (res1) -> (return (res1)) primitive prim_Win32Window_cpp_getDesktopWindow :: IO (Addr) getForegroundWindow :: IO HWND getForegroundWindow = prim_Win32Window_cpp_getForegroundWindow >>= \ (res1) -> (return (res1)) primitive prim_Win32Window_cpp_getForegroundWindow :: IO (Addr) getParent :: HWND -> IO HWND getParent arg1 = prim_Win32Window_cpp_getParent arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_getParent :: Addr -> IO (Addr,Int,Addr) getTopWindow :: HWND -> IO HWND getTopWindow arg1 = prim_Win32Window_cpp_getTopWindow arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_getTopWindow :: Addr -> IO (Addr,Int,Addr) type SetWindowPosFlags = UINT sWP_NOSIZE :: SetWindowPosFlags sWP_NOSIZE = unsafePerformIO( prim_Win32Window_cpp_sWP_NOSIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOSIZE :: IO (Word32) sWP_NOMOVE :: SetWindowPosFlags sWP_NOMOVE = unsafePerformIO( prim_Win32Window_cpp_sWP_NOMOVE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOMOVE :: IO (Word32) sWP_NOZORDER :: SetWindowPosFlags sWP_NOZORDER = unsafePerformIO( prim_Win32Window_cpp_sWP_NOZORDER >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOZORDER :: IO (Word32) sWP_NOREDRAW :: SetWindowPosFlags sWP_NOREDRAW = unsafePerformIO( prim_Win32Window_cpp_sWP_NOREDRAW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOREDRAW :: IO (Word32) sWP_NOACTIVATE :: SetWindowPosFlags sWP_NOACTIVATE = unsafePerformIO( prim_Win32Window_cpp_sWP_NOACTIVATE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOACTIVATE :: IO (Word32) sWP_FRAMECHANGED :: SetWindowPosFlags sWP_FRAMECHANGED = unsafePerformIO( prim_Win32Window_cpp_sWP_FRAMECHANGED >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_FRAMECHANGED :: IO (Word32) sWP_SHOWWINDOW :: SetWindowPosFlags sWP_SHOWWINDOW = unsafePerformIO( prim_Win32Window_cpp_sWP_SHOWWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_SHOWWINDOW :: IO (Word32) sWP_HIDEWINDOW :: SetWindowPosFlags sWP_HIDEWINDOW = unsafePerformIO( prim_Win32Window_cpp_sWP_HIDEWINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_HIDEWINDOW :: IO (Word32) sWP_NOCOPYBITS :: SetWindowPosFlags sWP_NOCOPYBITS = unsafePerformIO( prim_Win32Window_cpp_sWP_NOCOPYBITS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOCOPYBITS :: IO (Word32) sWP_NOOWNERZORDER :: SetWindowPosFlags sWP_NOOWNERZORDER = unsafePerformIO( prim_Win32Window_cpp_sWP_NOOWNERZORDER >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOOWNERZORDER :: IO (Word32) sWP_NOSENDCHANGING :: SetWindowPosFlags sWP_NOSENDCHANGING = unsafePerformIO( prim_Win32Window_cpp_sWP_NOSENDCHANGING >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOSENDCHANGING :: IO (Word32) sWP_DRAWFRAME :: SetWindowPosFlags sWP_DRAWFRAME = unsafePerformIO( prim_Win32Window_cpp_sWP_DRAWFRAME >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_DRAWFRAME :: IO (Word32) sWP_NOREPOSITION :: SetWindowPosFlags sWP_NOREPOSITION = unsafePerformIO( prim_Win32Window_cpp_sWP_NOREPOSITION >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_sWP_NOREPOSITION :: IO (Word32) ---------------------------------------------------------------- -- HDCs ---------------------------------------------------------------- type GetDCExFlags = DWORD dCX_WINDOW :: GetDCExFlags dCX_WINDOW = unsafePerformIO( prim_Win32Window_cpp_dCX_WINDOW >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_WINDOW :: IO (Word32) dCX_CACHE :: GetDCExFlags dCX_CACHE = unsafePerformIO( prim_Win32Window_cpp_dCX_CACHE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_CACHE :: IO (Word32) dCX_CLIPCHILDREN :: GetDCExFlags dCX_CLIPCHILDREN = unsafePerformIO( prim_Win32Window_cpp_dCX_CLIPCHILDREN >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_CLIPCHILDREN :: IO (Word32) dCX_CLIPSIBLINGS :: GetDCExFlags dCX_CLIPSIBLINGS = unsafePerformIO( prim_Win32Window_cpp_dCX_CLIPSIBLINGS >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_CLIPSIBLINGS :: IO (Word32) dCX_PARENTCLIP :: GetDCExFlags dCX_PARENTCLIP = unsafePerformIO( prim_Win32Window_cpp_dCX_PARENTCLIP >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_PARENTCLIP :: IO (Word32) dCX_EXCLUDERGN :: GetDCExFlags dCX_EXCLUDERGN = unsafePerformIO( prim_Win32Window_cpp_dCX_EXCLUDERGN >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_EXCLUDERGN :: IO (Word32) dCX_INTERSECTRGN :: GetDCExFlags dCX_INTERSECTRGN = unsafePerformIO( prim_Win32Window_cpp_dCX_INTERSECTRGN >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_INTERSECTRGN :: IO (Word32) dCX_LOCKWINDOWUPDATE :: GetDCExFlags dCX_LOCKWINDOWUPDATE = unsafePerformIO( prim_Win32Window_cpp_dCX_LOCKWINDOWUPDATE >>= \ (res1) -> (return (res1))) primitive prim_Win32Window_cpp_dCX_LOCKWINDOWUPDATE :: IO (Word32) -- apparently mostly fails if you use invalid hwnds getDCEx :: HWND -> HRGN -> GetDCExFlags -> IO HDC getDCEx arg1 arg2 arg3 = prim_Win32Window_cpp_getDCEx arg1 arg2 arg3 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_getDCEx :: Addr -> ForeignObj -> Word32 -> IO (Addr,Int,Addr) getDC :: MbHWND -> IO HDC getDC arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_getDC arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_getDC :: Addr -> IO (Addr,Int,Addr) getWindowDC :: MbHWND -> IO HDC getWindowDC arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_getWindowDC arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Window_cpp_getWindowDC :: Addr -> IO (Addr,Int,Addr) releaseDC :: MbHWND -> HDC -> IO () releaseDC arg1 arg2 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_releaseDC arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_releaseDC :: Addr -> Addr -> IO (Int,Addr) getDCOrgEx :: HDC -> IO POINT getDCOrgEx arg1 = prim_Win32Window_cpp_getDCOrgEx arg1 >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in (return ((gc_res1,gc_res3))) primitive prim_Win32Window_cpp_getDCOrgEx :: Addr -> IO (Int,Int,Int,Addr) ---------------------------------------------------------------- -- Caret ---------------------------------------------------------------- hideCaret :: HWND -> IO () hideCaret arg1 = prim_Win32Window_cpp_hideCaret arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_hideCaret :: Addr -> IO (Int,Addr) showCaret :: HWND -> IO () showCaret arg1 = prim_Win32Window_cpp_showCaret arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_showCaret :: Addr -> IO (Int,Addr) -- ToDo: allow arg2 to be NULL or {(HBITMAP)1} createCaret :: HWND -> HBITMAP -> MbINT -> MbINT -> IO () createCaret arg1 arg2 gc_arg1 gc_arg2 = (case gc_arg1 of { Nothing -> (return (0)); (Just gc_arg1) -> case ( fromIntegral gc_arg1) of { arg3 -> (return ((arg3)))} }) >>= \ (arg3) -> (case gc_arg2 of { Nothing -> (return (0)); (Just gc_arg2) -> case ( fromIntegral gc_arg2) of { arg4 -> (return ((arg4)))} }) >>= \ (arg4) -> prim_Win32Window_cpp_createCaret arg1 arg2 arg3 arg4 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_createCaret :: Addr -> Addr -> Int -> Int -> IO (Int,Addr) destroyCaret :: IO () destroyCaret = prim_Win32Window_cpp_destroyCaret >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_destroyCaret :: IO (Int,Addr) getCaretPos :: IO POINT getCaretPos = prim_Win32Window_cpp_getCaretPos >>= \ (gc_res2,gc_res4,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else let gc_res1 = ( fromIntegral (gc_res2)) in let gc_res3 = ( fromIntegral (gc_res4)) in (return ((gc_res1,gc_res3))) primitive prim_Win32Window_cpp_getCaretPos :: IO (Int,Int,Int,Addr) setCaretPos :: POINT -> IO () setCaretPos gc_arg1 = case gc_arg1 of { (gc_arg2,gc_arg4) -> case ( fromIntegral gc_arg2) of { gc_arg3 -> case ( fromIntegral gc_arg4) of { gc_arg5 -> prim_Win32Window_cpp_setCaretPos gc_arg3 gc_arg5 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (()))}}} primitive prim_Win32Window_cpp_setCaretPos :: Int -> Int -> IO (Int,Addr) -- The remarks on SetCaretBlinkTime are either highly risible or very sad - -- depending on whether you plan to use this function. ---------------------------------------------------------------- -- MSGs and event loops -- -- Note that the following functions have to be reentrant: -- -- DispatchMessage -- SendMessage -- UpdateWindow (I think) -- RedrawWindow (I think) -- -- The following dont have to be reentrant (according to documentation) -- -- GetMessage -- PeekMessage -- TranslateMessage -- -- For Hugs (and possibly NHC too?) this is no big deal. -- For GHC, you have to use casm_GC instead of casm. -- (It might be simpler to just put all this code in another -- file and build it with the appropriate command line option...) ---------------------------------------------------------------- -- type MSG = -- ( HWND -- hwnd; -- , UINT -- message; -- , WPARAM -- wParam; -- , LPARAM -- lParam; -- , DWORD -- time; -- , POINT -- pt; -- ) type LPMSG = Addr -- A NULL window requests messages for any window belonging to this thread. -- a "success" value of 0 indicates that WM_QUIT was received getMessage :: MbHWND -> IO LPMSG getMessage arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_getMessage arg1 >>= \ (gc_res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (gc_res1)) primitive prim_Win32Window_cpp_getMessage :: Addr -> IO (Addr,Int,Addr) getMessage2 :: MbHWND -> IO (LPMSG,Bool) getMessage2 arg1 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_getMessage2 arg1 >>= \ (gc_res1,gc_res3,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (unmarshall_bool_ gc_res3) >>= \ gc_res2 -> (return ((gc_res1,gc_res2))) primitive prim_Win32Window_cpp_getMessage2 :: Addr -> IO (Addr,Int,Int,Addr) -- A NULL window requests messages for any window belonging to this thread. -- Arguably the code block shouldn't be a 'safe' one, but it shouldn't really -- hurt. peekMessage :: MbHWND -> UINT -> UINT -> UINT -> IO LPMSG peekMessage arg1 arg2 arg3 arg4 = (case arg1 of { Nothing -> (return (nullHANDLE)); (Just arg1) -> (return ((arg1))) }) >>= \ (arg1) -> prim_Win32Window_cpp_peekMessage arg1 arg2 arg3 arg4 >>= \ (gc_res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (gc_res1)) primitive prim_Win32Window_cpp_peekMessage :: Addr -> Word32 -> Word32 -> Word32 -> IO (Addr,Int,Addr) -- Note: youre not supposed to call this if youre using accelerators translateMessage :: LPMSG -> IO BOOL translateMessage arg1 = prim_Win32Window_cpp_translateMessage arg1 >>= \ (res1) -> (unmarshall_bool_ res1) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Window_cpp_translateMessage :: Addr -> IO (Int) updateWindow :: HWND -> IO () updateWindow arg1 = prim_Win32Window_cpp_updateWindow arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32Window_cpp_updateWindow :: Addr -> IO (Int,Addr) -- Return value of DispatchMessage is usually ignored dispatchMessage :: LPMSG -> IO LONG dispatchMessage arg1 = prim_Win32Window_cpp_dispatchMessage arg1 >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1)) primitive prim_Win32Window_cpp_dispatchMessage :: Addr -> IO (Int) sendMessage :: HWND -> WindowMessage -> WPARAM -> LPARAM -> IO LRESULT sendMessage arg1 arg2 arg3 gc_arg1 = case ( fromIntegral gc_arg1) of { arg4 -> prim_Win32Window_cpp_sendMessage arg1 arg2 arg3 arg4 >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))} primitive prim_Win32Window_cpp_sendMessage :: Addr -> Word32 -> Word32 -> Int -> IO (Int) ---------------------------------------------------------------- -- ToDo: figure out reentrancy stuff -- ToDo: catch error codes -- -- ToDo: how to send HWND_BROADCAST to PostMessage -- %fun PostMessage :: MbHWND -> WindowMessage -> WPARAM -> LPARAM -> IO () -- %fun PostQuitMessage :: Int -> IO () -- %fun PostThreadMessage :: DWORD -> WindowMessage -> WPARAM -> LPARAM -> IO () -- %fun InSendMessage :: IO Bool ---------------------------------------------------------------- -- End ---------------------------------------------------------------- needPrims_hugs 2
OS2World/DEV-UTIL-HUGS
libraries/win32/Win32Window.hs
bsd-3-clause
50,850
552
38
8,247
14,572
8,000
6,572
-1
-1
-- | -- Module : Network.SMTP.Types -- License : BSD-style -- -- Maintainer : Nicolas DI PRIMA <[email protected]> -- Stability : experimental -- Portability : unknown -- module Network.SMTP.Types ( -- * Mail Storage User MailStorageUser(..) -- * ClientState , ClientConnectionState(..) , SMTPType(..) -- * Authentification , UserName , Password , AuthType(..) -- * SMTP Commands -- ** Command , Command(..) , showCommand -- ** SMTP extensions , ESMTPKeyWord , ESMTPValue , ESMTPParameters , MailParameters , RcptParameters -- * SMTP Responses , Response(..) , ResponseCode(..) ) where import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.ByteString.Char8 as BC import Data.Maild.Email ------------------------------------------------------------------------------ -- Mail Storage Users -- ------------------------------------------------------------------------------ -- | describe a user data MailStorageUser = MailStorageUser { emails :: [EmailAddress] -- ^ the list of email address owned , firstName :: String -- ^ user's firstname , lastName :: String -- ^ user's lastname , userDigest :: String -- ^ user's digest } deriving (Show, Eq) -- | SMTP or EMSTP protocol data SMTPType = SMTP | ESMTP deriving (Show, Eq) -- | contains all the needed data to receive/forward emails data ClientConnectionState = ClientConnectionState { domainClient :: Maybe Domain -- ^ the domain name of the client , identified :: Maybe MailStorageUser -- ^ if the user has been identified , smtpType :: Maybe SMTPType , smtpMail :: Email -- ^ the email } deriving (Show, Eq) ------------------------------------------------------------------------------ -- Authentifications -- ------------------------------------------------------------------------------ -- | user's name type UserName = BC.ByteString -- | user's digest type Password = BC.ByteString -- | type of authentification implemented data AuthType = PLAIN | LOGIN | CRAM_MD5 deriving (Read, Show, Eq) showAuthType :: AuthType -> String showAuthType t = case t of PLAIN -> "PLAIN" LOGIN -> "LOGIN" CRAM_MD5 -> "CRAM-MD5" ------------------------------------------------------------------------------ -- Commands -- ------------------------------------------------------------------------------ -- | A ESMTP key word type ESMTPKeyWord = String -- | A ESMTPValue type ESMTPValue = String -- | A ESMTPParameter collection type ESMTPParameters = Map ESMTPKeyWord (Maybe ESMTPValue) -- | the MAIL command may receive parameters type MailParameters = ESMTPParameters -- | the RCTP command may receive parameters type RcptParameters = ESMTPParameters -- | (E)SMTP commands data Command = HELO String | EHLO String | MAIL ReversePath MailParameters | RCPT ForwardPath RcptParameters | DATA | EXPN String | VRFY String | HELP (Maybe String) | AUTH AuthType (Maybe String) | NOOP (Maybe String) | RSET | QUIT | INVALCMD String -- ^ use to know if the command is not supported | TIMEOUT -- ^ use to raise an error in case of a timeout deriving (Show, Eq) showCommand :: Command -> String showCommand cmd = case cmd of HELO dom -> "HELO " ++ dom EHLO dom -> "EHLO " ++ dom MAIL rp mp -> "MAIL FROM:" ++ (maybe "<>" showPath rp) ++ (showParameters' $ Map.toList mp) RCPT rp mp -> "RCPT TO:" ++ (showPath rp) ++ (showParameters' $ Map.toList mp) DATA -> "DATA" EXPN exp -> "EXPN " ++ exp VRFY str -> "VRFY " ++ str HELP mcmd -> "HELP" ++ (maybe [] (\t -> " " ++ t) mcmd) AUTH t ms -> "AUTH " ++ (showAuthType t) ++ (maybe [] (\s -> " " ++ s) ms) NOOP ms -> "NOOP" ++ (maybe [] (\s -> " " ++ s) ms) RSET -> "RSET" QUIT -> "QUIT" INVALCMD s -> s TIMEOUT -> "" where showParameters' :: [(String, Maybe String)] -> String showParameters' [] = [] showParameters' xs = showParameters xs showParameters :: [(String, Maybe String)] -> String showParameters [] = [] showParameters [(k, mv)] = case mv of Just v -> k ++ "=" ++ v Nothing -> k showParameters (x:xs) = (showParameters [x]) ++ " " ++ (showParameters xs) ------------------------------------------------------------------------------ -- Response -- ------------------------------------------------------------------------------ -- | Non-exautive list of possible response code data ResponseCode = RC500SyntaxCommandError | RC501SyntaxParameterError | RC502CommandNotImplemented | RC503BadSequenceOfCommand | RC504ParameterNotImplemented | RC211SystemStatus | RC214Help | RC220ServiceReady | RC221ServiceClosingChannel | RC421ServiceNotAvailable | RC250Ok | RC251UserNotLocalButTry | RC252CannotVRFYUser | RC455ServerUnableToAccParrameters | RC555FromOrToError | RC450MailActionRejectedMailboxUnavailable | RC550ActionRejectedMailboxUnavailable | RC451ActionAborted | RC551UserNotLocalFail | RC452ActionRejectedSystemStorage | RC552MailActionAbbortedSystemStorage | RC553ActionRejectedMailboxNotAllowed | RC354StartMailInput | RC554Failed deriving (Show, Read, Eq) -- | As described in a RFC5321, a response is a CODE with message -- see section 4.2.1 data Response = Response { code :: Either Int ResponseCode , message :: BC.ByteString , endOfResponse :: Bool } deriving (Show)
NicolasDP/maild
Network/SMTP/Types.hs
bsd-3-clause
5,966
2
13
1,585
1,116
653
463
127
18
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Copyright : (c) Edward Kmett 2011-2015 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Text.Trifecta.Parser ( Parser(..) , manyAccum , race -- * Feeding a parser more more input , Step(..) , feed , starve , stepParser , stepResult , stepIt -- * Parsing , parseFromFile , parseFromFileEx , parseString , parseByteString , parseTest ) where import Control.Applicative as Alternative import Control.Lens ((%~), (&)) import Control.Monad (MonadPlus(..), ap, join) import Control.Monad.IO.Class import Data.ByteString as Strict hiding (empty, snoc) import Data.ByteString.UTF8 as UTF8 import Data.Maybe (isJust) import Data.Semigroup import Data.Semigroup.Reducer -- import Data.Sequence as Seq hiding (empty) import Data.Set as Set hiding (empty, toList) import System.IO import Text.Parser.Combinators import Text.Parser.Char import Text.Parser.LookAhead import Text.Parser.Token import Text.PrettyPrint.ANSI.Leijen as Pretty hiding (line, (<>), (<$>), empty) import Text.Trifecta.Combinators import Text.Trifecta.Instances () import Text.Trifecta.Rendering import Text.Trifecta.Result import Text.Trifecta.Rope import Text.Trifecta.Delta as Delta import Text.Trifecta.Util.It newtype Parser a = Parser { unparser :: forall r. (a -> Err -> It Rope r) -> (Err -> It Rope r) -> (a -> Set String -> Delta -> ByteString -> It Rope r) -> -- committed success (Delta -> ErrInfo -> Err -> It Rope r) -> -- committed err Delta -> ByteString -> It Rope r } instance Functor Parser where fmap f (Parser m) = Parser $ \ eo ee co -> m (eo . f) ee (co . f) {-# INLINE fmap #-} a <$ Parser m = Parser $ \ eo ee co -> m (\_ -> eo a) ee (\_ -> co a) {-# INLINE (<$) #-} instance Applicative Parser where pure a = Parser $ \ eo _ _ _ _ _ -> eo a mempty {-# INLINE pure #-} (<*>) = ap {-# INLINE (<*>) #-} instance Alternative Parser where empty = Parser $ \_ ee _ _ _ _ -> ee mempty {-# INLINE empty #-} Parser m <|> Parser n = Parser $ \ eo ee co ce d bs -> m eo (\e -> n (\a e' -> eo a (e <> e')) (\e' -> ee (e <> e')) co ce d bs) co ce d bs {-# INLINE (<|>) #-} many p = Prelude.reverse <$> manyAccum (:) p {-# INLINE many #-} some p = (:) <$> p <*> Alternative.many p instance Semigroup a => Semigroup (Parser a) where (<>) = liftA2 (<>) {-# INLINE (<>) #-} instance Monoid a => Monoid (Parser a) where mappend = liftA2 mappend {-# INLINE mappend #-} mempty = pure mempty {-# INLINE mempty #-} instance Monad Parser where return a = Parser $ \ eo _ _ _ _ _ -> eo a mempty {-# INLINE return #-} Parser m >>= k = Parser $ \ eo ee co ce d bs -> m (\a e -> unparser (k a) (\b e' -> eo b (e <> e')) (\e' -> ee (e <> e')) co ce d bs) ee (\a es d' bs' -> unparser (k a) (\b e' -> co b (es <> _expected e') d' bs') (\e -> let errDoc = explain (renderingCaret d' bs') e { _expected = _expected e <> es } errDelta = _finalDeltas e in ce d' (ErrInfo errDoc (d' : errDelta)) e ) co ce d' bs') ce d bs {-# INLINE (>>=) #-} (>>) = (*>) {-# INLINE (>>) #-} fail s = Parser $ \ _ ee _ _ _ _ -> ee (failed s) {-# INLINE fail #-} instance MonadPlus Parser where mzero = empty {-# INLINE mzero #-} mplus = (<|>) {-# INLINE mplus #-} manyAccum :: (a -> [a] -> [a]) -> Parser a -> Parser [a] manyAccum f (Parser p) = Parser $ \eo _ co ce d bs -> let walk xs x es d' bs' = p (manyErr d' bs') (\e -> co (f x xs) (_expected e <> es) d' bs') (walk (f x xs)) ce d' bs' manyErr d' bs' _ e = ce d' (ErrInfo errDoc [d']) e where errDoc = explain (renderingCaret d' bs') (e <> failed "'many' applied to a parser that accepted an empty string") in p (manyErr d bs) (eo []) (walk []) ce d bs liftIt :: It Rope a -> Parser a liftIt m = Parser $ \ eo _ _ _ _ _ -> do a <- m eo a mempty {-# INLINE liftIt #-} instance Parsing Parser where try (Parser m) = Parser $ \ eo ee co _ -> m eo ee co (\_ _ _ -> ee mempty) {-# INLINE try #-} Parser m <?> nm = Parser $ \ eo ee -> m (\a e -> eo a (if isJust (_reason e) then e { _expected = Set.singleton nm } else e)) (\e -> ee e { _expected = Set.singleton nm }) {-# INLINE (<?>) #-} skipMany p = () <$ manyAccum (\_ _ -> []) p {-# INLINE skipMany #-} unexpected s = Parser $ \ _ ee _ _ _ _ -> ee $ failed $ "unexpected " ++ s {-# INLINE unexpected #-} eof = notFollowedBy anyChar <?> "end of input" {-# INLINE eof #-} notFollowedBy p = try (optional p >>= maybe (pure ()) (unexpected . show)) {-# INLINE notFollowedBy #-} race :: Parser a -> Parser a race (Parser m) = Parser $ \eo ee co ce -> m eo ee co $ \d ei err -> ee $ mempty & expected %~ Set.union (_expected err) & finalDeltas %~ (++) (_errDeltas ei) {-# INLINE race #-} instance Errable Parser where raiseErr e = Parser $ \ _ ee _ _ _ _ -> ee e {-# INLINE raiseErr #-} instance LookAheadParsing Parser where lookAhead (Parser m) = Parser $ \eo ee _ -> m eo ee (\a _ _ _ -> eo a mempty) {-# INLINE lookAhead #-} instance CharParsing Parser where satisfy f = Parser $ \ _ ee co _ d bs -> case UTF8.uncons $ Strict.drop (fromIntegral (columnByte d)) bs of Nothing -> ee (failed "unexpected EOF") Just (c, xs) | not (f c) -> ee mempty | Strict.null xs -> let !ddc = d <> delta c in join $ fillIt (co c mempty ddc (if c == '\n' then mempty else bs)) (co c mempty) ddc | otherwise -> co c mempty (d <> delta c) bs {-# INLINE satisfy #-} instance TokenParsing Parser instance DeltaParsing Parser where line = Parser $ \eo _ _ _ _ bs -> eo bs mempty {-# INLINE line #-} position = Parser $ \eo _ _ _ d _ -> eo d mempty {-# INLINE position #-} rend = Parser $ \eo _ _ _ d bs -> eo (rendered d bs) mempty {-# INLINE rend #-} slicedWith f p = do m <- position a <- p r <- position f a <$> liftIt (sliceIt m r) {-# INLINE slicedWith #-} instance MarkParsing Delta Parser where mark = position {-# INLINE mark #-} release d' = Parser $ \_ ee co _ d bs -> do mbs <- rewindIt d' case mbs of Just bs' -> co () mempty d' bs' Nothing | bytes d' == bytes (rewind d) + fromIntegral (Strict.length bs) -> if near d d' then co () mempty d' bs else co () mempty d' mempty | otherwise -> ee mempty data Step a = StepDone !Rope a | StepFail !Rope ErrInfo | StepCont !Rope (Result a) (Rope -> Step a) instance Show a => Show (Step a) where showsPrec d (StepDone r a) = showParen (d > 10) $ showString "StepDone " . showsPrec 11 r . showChar ' ' . showsPrec 11 a showsPrec d (StepFail r xs) = showParen (d > 10) $ showString "StepFail " . showsPrec 11 r . showChar ' ' . showsPrec 11 xs showsPrec d (StepCont r fin _) = showParen (d > 10) $ showString "StepCont " . showsPrec 11 r . showChar ' ' . showsPrec 11 fin . showString " ..." instance Functor Step where fmap f (StepDone r a) = StepDone r (f a) fmap _ (StepFail r xs) = StepFail r xs fmap f (StepCont r z k) = StepCont r (fmap f z) (fmap f . k) feed :: Reducer t Rope => t -> Step r -> Step r feed t (StepDone r a) = StepDone (snoc r t) a feed t (StepFail r xs) = StepFail (snoc r t) xs feed t (StepCont r _ k) = k (snoc r t) {-# INLINE feed #-} starve :: Step a -> Result a starve (StepDone _ a) = Success a starve (StepFail _ xs) = Failure xs starve (StepCont _ z _) = z {-# INLINE starve #-} stepResult :: Rope -> Result a -> Step a stepResult r (Success a) = StepDone r a stepResult r (Failure xs) = StepFail r xs {-# INLINE stepResult #-} stepIt :: It Rope a -> Step a stepIt = go mempty where go r (Pure a) = StepDone r a go r (It a k) = StepCont r (pure a) $ \s -> go s (k s) {-# INLINE stepIt #-} data Stepping a = EO a Err | EE Err | CO a (Set String) Delta ByteString | CE Delta ErrInfo Err stepParser :: Parser a -> Delta -> ByteString -> Step a stepParser (Parser p) d0 bs0 = go mempty $ p eo ee co ce d0 bs0 where eo a e = Pure (EO a e) ee e = Pure (EE e) co a es d bs = Pure (CO a es d bs) ce d errInf e = Pure (CE d errInf e) go r (Pure (EO a _)) = StepDone r a go r (Pure (EE e)) = StepFail r $ let errDoc = explain (renderingCaret d0 bs0) e in ErrInfo errDoc (_finalDeltas e) go r (Pure (CO a _ _ _)) = StepDone r a go r (Pure (CE _ ei _)) = StepFail r ei go r (It ma k) = StepCont r (case ma of EO a _ -> Success a EE e -> Failure $ ErrInfo (explain (renderingCaret d0 bs0) e) (d0 : _finalDeltas e) CO a _ _ _ -> Success a CE _ ei _ -> Failure ei ) (go <*> k) {-# INLINE stepParser #-} -- | @parseFromFile p filePath@ runs a parser @p@ on the -- input read from @filePath@ using 'ByteString.readFile'. All diagnostic messages -- emitted over the course of the parse attempt are shown to the user on the console. -- -- > main = do -- > result <- parseFromFile numbers "digits.txt" -- > case result of -- > Nothing -> return () -- > Just a -> print $ sum a parseFromFile :: MonadIO m => Parser a -> String -> m (Maybe a) parseFromFile p fn = do result <- parseFromFileEx p fn case result of Success a -> return (Just a) Failure xs -> do liftIO $ displayIO stdout $ renderPretty 0.8 80 $ (_errDoc xs) <> linebreak return Nothing -- | @parseFromFileEx p filePath@ runs a parser @p@ on the -- input read from @filePath@ using 'ByteString.readFile'. Returns all diagnostic messages -- emitted over the course of the parse and the answer if the parse was successful. -- -- > main = do -- > result <- parseFromFileEx (many number) "digits.txt" -- > case result of -- > Failure xs -> displayLn xs -- > Success a -> print (sum a) -- > parseFromFileEx :: MonadIO m => Parser a -> String -> m (Result a) parseFromFileEx p fn = do s <- liftIO $ Strict.readFile fn return $ parseByteString p (Directed (UTF8.fromString fn) 0 0 0 0) s -- | @parseByteString p delta i@ runs a parser @p@ on @i@. parseByteString :: Parser a -> Delta -> UTF8.ByteString -> Result a parseByteString p d inp = starve $ feed inp $ stepParser (release d *> p) mempty mempty parseString :: Parser a -> Delta -> String -> Result a parseString p d inp = starve $ feed inp $ stepParser (release d *> p) mempty mempty parseTest :: (MonadIO m, Show a) => Parser a -> String -> m () parseTest p s = case parseByteString p mempty (UTF8.fromString s) of Failure xs -> liftIO $ displayIO stdout $ renderPretty 0.8 80 $ (_errDoc xs) <> linebreak -- TODO: retrieve columns Success a -> liftIO (print a)
mikeplus64/trifecta
src/Text/Trifecta/Parser.hs
bsd-3-clause
11,602
0
22
3,191
4,300
2,210
2,090
265
8
module Sharc.Instruments.Flute (flute) where import Sharc.Types flute :: Instr flute = Instr "flute_vibrato" "Flute" (Legend "McGill" "2" "1") (Range (InstrRange (HarmonicFreq 1 (Pitch 261.62 48 "c4")) (Pitch 261.62 48 "c4") (Amplitude 9079.92 (HarmonicFreq 13 (Pitch 698.456 65 "f5")) 0.11)) (InstrRange (HarmonicFreq 12 (Pitch 9967.3 68 "g#5")) (Pitch 2093.0 84 "c7") (Amplitude 466.16 (HarmonicFreq 1 (Pitch 466.164 58 "a#4")) 6413.0))) [note0 ,note1 ,note2 ,note3 ,note4 ,note5 ,note6 ,note7 ,note8 ,note9 ,note10 ,note11 ,note12 ,note13 ,note14 ,note15 ,note16 ,note17 ,note18 ,note19 ,note20 ,note21 ,note22 ,note23 ,note24 ,note25 ,note26 ,note27 ,note28 ,note29 ,note30 ,note31 ,note32 ,note33 ,note34 ,note35 ,note36] note0 :: Note note0 = Note (Pitch 261.626 48 "c4") 1 (Range (NoteRange (NoteRangeAmplitude 9680.16 37 0.22) (NoteRangeHarmonicFreq 1 261.62)) (NoteRange (NoteRangeAmplitude 523.25 2 2957.0) (NoteRangeHarmonicFreq 37 9680.16))) [Harmonic 1 2.613 983.6 ,Harmonic 2 (-0.878) 2957.0 ,Harmonic 3 2.019 1419.21 ,Harmonic 4 (-2.39) 790.14 ,Harmonic 5 0.891 1128.71 ,Harmonic 6 2.883 427.98 ,Harmonic 7 (-2.134) 290.77 ,Harmonic 8 0.139 486.62 ,Harmonic 9 3.074 221.42 ,Harmonic 10 3.047 75.69 ,Harmonic 11 1.022 102.28 ,Harmonic 12 (-1.293) 34.48 ,Harmonic 13 (-2.222) 21.73 ,Harmonic 14 (-0.322) 11.8 ,Harmonic 15 2.75 8.98 ,Harmonic 16 (-1.271) 9.9 ,Harmonic 17 1.399 7.3 ,Harmonic 18 (-2.865) 3.75 ,Harmonic 19 (-0.296) 5.11 ,Harmonic 20 1.888 10.63 ,Harmonic 21 (-1.334) 4.51 ,Harmonic 22 0.153 1.32 ,Harmonic 23 1.794 1.57 ,Harmonic 24 (-1.562) 3.24 ,Harmonic 25 1.624 1.8 ,Harmonic 26 (-1.613) 6.28 ,Harmonic 27 1.401 3.66 ,Harmonic 28 (-2.39) 5.5 ,Harmonic 29 1.248 2.91 ,Harmonic 30 (-0.461) 2.34 ,Harmonic 31 (-2.357) 1.54 ,Harmonic 32 0.375 0.62 ,Harmonic 33 2.268 1.01 ,Harmonic 34 (-2.992) 1.25 ,Harmonic 35 (-0.58) 0.37 ,Harmonic 36 2.888 1.13 ,Harmonic 37 1.164 0.22] note1 :: Note note1 = Note (Pitch 277.183 49 "c#4") 2 (Range (NoteRange (NoteRangeAmplitude 8592.67 31 0.41) (NoteRangeHarmonicFreq 1 277.18)) (NoteRange (NoteRangeAmplitude 554.36 2 3478.0) (NoteRangeHarmonicFreq 35 9701.4))) [Harmonic 1 (-0.418) 1231.99 ,Harmonic 2 (-1.332) 3478.0 ,Harmonic 3 (-1.682) 1246.74 ,Harmonic 4 (-3.057) 843.53 ,Harmonic 5 2.847 1248.37 ,Harmonic 6 1.694 171.14 ,Harmonic 7 (-1.019) 240.19 ,Harmonic 8 (-2.31) 421.03 ,Harmonic 9 (-3.077) 143.93 ,Harmonic 10 (-1.344) 22.99 ,Harmonic 11 1.825 32.43 ,Harmonic 12 1.052 40.4 ,Harmonic 13 0.418 8.46 ,Harmonic 14 (-1.523) 15.19 ,Harmonic 15 (-1.963) 10.35 ,Harmonic 16 2.908 9.4 ,Harmonic 17 2.542 7.31 ,Harmonic 18 0.894 5.94 ,Harmonic 19 1.865 3.28 ,Harmonic 20 (-0.601) 4.14 ,Harmonic 21 0.354 1.09 ,Harmonic 22 (-1.305) 3.12 ,Harmonic 23 (-3.019) 2.91 ,Harmonic 24 1.417 1.57 ,Harmonic 25 0.985 3.98 ,Harmonic 26 1.43 0.49 ,Harmonic 27 (-1.366) 2.57 ,Harmonic 28 (-1.257) 0.55 ,Harmonic 29 (-3.098) 4.88 ,Harmonic 30 0.298 2.41 ,Harmonic 31 (-0.366) 0.41 ,Harmonic 32 (-0.606) 0.9 ,Harmonic 33 (-1.727) 1.29 ,Harmonic 34 (-3.071) 4.39 ,Harmonic 35 3.096 1.27] note2 :: Note note2 = Note (Pitch 293.665 50 "d4") 3 (Range (NoteRange (NoteRangeAmplitude 8222.62 28 0.58) (NoteRangeHarmonicFreq 1 293.66)) (NoteRange (NoteRangeAmplitude 587.33 2 5270.0) (NoteRangeHarmonicFreq 33 9690.94))) [Harmonic 1 (-2.148) 2971.72 ,Harmonic 2 1.478 5270.0 ,Harmonic 3 0.48 1008.52 ,Harmonic 4 2.243 941.55 ,Harmonic 5 0.164 1658.88 ,Harmonic 6 (-0.981) 37.81 ,Harmonic 7 (-1.904) 260.72 ,Harmonic 8 1.871 116.74 ,Harmonic 9 (-0.482) 73.68 ,Harmonic 10 (-2.309) 74.05 ,Harmonic 11 1.761 72.56 ,Harmonic 12 (-2.06) 7.97 ,Harmonic 13 7.7e-2 9.16 ,Harmonic 14 (-2.976) 10.6 ,Harmonic 15 1.727 10.45 ,Harmonic 16 3.131 1.86 ,Harmonic 17 2.432 6.3 ,Harmonic 18 2.761 9.37 ,Harmonic 19 0.839 4.06 ,Harmonic 20 (-2.56) 2.03 ,Harmonic 21 2.996 6.45 ,Harmonic 22 (-3.018) 3.76 ,Harmonic 23 2.329 2.43 ,Harmonic 24 (-1.578) 3.64 ,Harmonic 25 (-2.924) 6.59 ,Harmonic 26 1.39 3.89 ,Harmonic 27 (-0.84) 1.71 ,Harmonic 28 2.702 0.58 ,Harmonic 29 1.19 3.4 ,Harmonic 30 1.54 2.32 ,Harmonic 31 (-2.641) 2.17 ,Harmonic 32 2.165 4.44 ,Harmonic 33 1.732 2.71] note3 :: Note note3 = Note (Pitch 311.127 51 "d#4") 4 (Range (NoteRange (NoteRangeAmplitude 5600.28 18 0.8) (NoteRangeHarmonicFreq 1 311.12)) (NoteRange (NoteRangeAmplitude 622.25 2 4666.0) (NoteRangeHarmonicFreq 31 9644.93))) [Harmonic 1 2.946 3366.87 ,Harmonic 2 0.713 4666.0 ,Harmonic 3 (-1.467) 931.67 ,Harmonic 4 1.151 1009.54 ,Harmonic 5 (-2.64) 716.99 ,Harmonic 6 (-0.522) 205.57 ,Harmonic 7 2.152 9.82 ,Harmonic 8 0.689 108.8 ,Harmonic 9 (-2.676) 12.38 ,Harmonic 10 (-2.532) 8.12 ,Harmonic 11 (-7.9e-2) 25.55 ,Harmonic 12 2.708 22.36 ,Harmonic 13 0.391 21.07 ,Harmonic 14 (-1.657) 1.12 ,Harmonic 15 (-1.67) 4.99 ,Harmonic 16 2.335 5.73 ,Harmonic 17 (-1.567) 2.04 ,Harmonic 18 (-0.91) 0.8 ,Harmonic 19 2.639 1.1 ,Harmonic 20 0.696 3.57 ,Harmonic 21 2.361 2.87 ,Harmonic 22 (-0.742) 7.04 ,Harmonic 23 (-3.123) 9.01 ,Harmonic 24 0.438 2.17 ,Harmonic 25 0.788 1.7 ,Harmonic 26 2.413 4.2 ,Harmonic 27 1.024 4.43 ,Harmonic 28 (-1.882) 2.83 ,Harmonic 29 1.024 1.72 ,Harmonic 30 2.261 1.26 ,Harmonic 31 (-1.87) 2.07] note4 :: Note note4 = Note (Pitch 329.628 52 "e4") 5 (Range (NoteRange (NoteRangeAmplitude 6262.93 19 0.66) (NoteRangeHarmonicFreq 1 329.62)) (NoteRange (NoteRangeAmplitude 659.25 2 4388.0) (NoteRangeHarmonicFreq 30 9888.84))) [Harmonic 1 (-1.172) 3280.12 ,Harmonic 2 (-1.62) 4388.0 ,Harmonic 3 (-2.014) 1204.04 ,Harmonic 4 2.676 978.06 ,Harmonic 5 0.253 346.33 ,Harmonic 6 (-0.948) 168.02 ,Harmonic 7 (-2.973) 421.69 ,Harmonic 8 (-2.976) 35.6 ,Harmonic 9 (-0.3) 3.38 ,Harmonic 10 (-1.122) 46.75 ,Harmonic 11 (-2.607) 25.89 ,Harmonic 12 2.81 9.7 ,Harmonic 13 0.639 4.19 ,Harmonic 14 (-0.886) 2.86 ,Harmonic 15 (-1.23) 6.11 ,Harmonic 16 (-2.06) 8.57 ,Harmonic 17 1.447 1.04 ,Harmonic 18 0.996 0.93 ,Harmonic 19 6.0e-2 0.66 ,Harmonic 20 (-1.567) 2.15 ,Harmonic 21 0.765 5.02 ,Harmonic 22 1.008 2.41 ,Harmonic 23 (-0.654) 1.72 ,Harmonic 24 (-1.758) 0.98 ,Harmonic 25 (-0.47) 2.58 ,Harmonic 26 0.663 4.78 ,Harmonic 27 0.111 3.41 ,Harmonic 28 (-2.807) 1.08 ,Harmonic 29 1.85 3.23 ,Harmonic 30 0.698 1.2] note5 :: Note note5 = Note (Pitch 349.228 53 "f4") 6 (Range (NoteRange (NoteRangeAmplitude 5238.42 15 1.29) (NoteRangeHarmonicFreq 1 349.22)) (NoteRange (NoteRangeAmplitude 349.22 1 4816.0) (NoteRangeHarmonicFreq 28 9778.38))) [Harmonic 1 (-1.576) 4816.0 ,Harmonic 2 (-1.781) 3902.84 ,Harmonic 3 (-2.615) 581.58 ,Harmonic 4 0.348 712.1 ,Harmonic 5 (-1.072) 1121.24 ,Harmonic 6 (-2.853) 198.24 ,Harmonic 7 0.794 90.95 ,Harmonic 8 3.0 31.53 ,Harmonic 9 3.062 8.56 ,Harmonic 10 1.981 17.6 ,Harmonic 11 (-0.152) 8.74 ,Harmonic 12 (-1.656) 12.24 ,Harmonic 13 (-1.861) 9.51 ,Harmonic 14 (-0.534) 3.26 ,Harmonic 15 (-2.677) 1.29 ,Harmonic 16 2.605 3.29 ,Harmonic 17 2.288 2.11 ,Harmonic 18 0.606 7.53 ,Harmonic 19 (-1.1e-2) 2.46 ,Harmonic 20 (-2.664) 4.2 ,Harmonic 21 2.912 8.3 ,Harmonic 22 0.981 5.12 ,Harmonic 23 (-0.67) 4.79 ,Harmonic 24 (-2.229) 4.51 ,Harmonic 25 2.096 3.07 ,Harmonic 26 0.287 1.5 ,Harmonic 27 (-0.893) 2.82 ,Harmonic 28 (-1.913) 1.78] note6 :: Note note6 = Note (Pitch 369.994 54 "f#4") 7 (Range (NoteRange (NoteRangeAmplitude 9619.84 26 1.31) (NoteRangeHarmonicFreq 1 369.99)) (NoteRange (NoteRangeAmplitude 369.99 1 4336.0) (NoteRangeHarmonicFreq 26 9619.84))) [Harmonic 1 2.315 4336.0 ,Harmonic 2 (-0.511) 4223.74 ,Harmonic 3 1.232 578.52 ,Harmonic 4 2.526 935.1 ,Harmonic 5 0.335 310.03 ,Harmonic 6 1.942 130.91 ,Harmonic 7 (-2.751) 126.87 ,Harmonic 8 (-0.501) 94.7 ,Harmonic 9 1.018 53.16 ,Harmonic 10 (-2.718) 44.84 ,Harmonic 11 (-0.218) 25.54 ,Harmonic 12 1.779 12.33 ,Harmonic 13 (-2.459) 8.55 ,Harmonic 14 (-0.772) 10.14 ,Harmonic 15 1.911 7.54 ,Harmonic 16 (-1.646) 4.91 ,Harmonic 17 1.674 5.62 ,Harmonic 18 (-2.238) 6.36 ,Harmonic 19 (-0.405) 6.0 ,Harmonic 20 2.788 3.61 ,Harmonic 21 (-1.395) 6.75 ,Harmonic 22 2.338 3.24 ,Harmonic 23 1.862 7.68 ,Harmonic 24 (-0.22) 5.73 ,Harmonic 25 2.501 4.17 ,Harmonic 26 (-0.767) 1.31] note7 :: Note note7 = Note (Pitch 391.995 55 "g4") 8 (Range (NoteRange (NoteRangeAmplitude 7447.9 19 0.53) (NoteRangeHarmonicFreq 1 391.99)) (NoteRange (NoteRangeAmplitude 391.99 1 4930.0) (NoteRangeHarmonicFreq 25 9799.87))) [Harmonic 1 2.067 4930.0 ,Harmonic 2 (-5.6e-2) 3719.05 ,Harmonic 3 1.418 777.19 ,Harmonic 4 2.868 969.72 ,Harmonic 5 (-0.926) 563.63 ,Harmonic 6 1.818 375.99 ,Harmonic 7 (-2.764) 61.75 ,Harmonic 8 2.249 44.39 ,Harmonic 9 1.332 32.09 ,Harmonic 10 (-1.676) 19.04 ,Harmonic 11 0.8 11.48 ,Harmonic 12 (-3.091) 12.15 ,Harmonic 13 (-0.932) 11.55 ,Harmonic 14 1.19 6.45 ,Harmonic 15 (-1.051) 3.18 ,Harmonic 16 (-1.535) 0.66 ,Harmonic 17 (-2.575) 5.08 ,Harmonic 18 1.483 2.68 ,Harmonic 19 (-0.495) 0.53 ,Harmonic 20 (-2.434) 4.72 ,Harmonic 21 (-2.935) 3.67 ,Harmonic 22 1.21 2.75 ,Harmonic 23 (-2.914) 3.33 ,Harmonic 24 1.023 2.12 ,Harmonic 25 1.357 1.67] note8 :: Note note8 = Note (Pitch 415.305 56 "g#4") 9 (Range (NoteRange (NoteRangeAmplitude 9136.71 22 1.28) (NoteRangeHarmonicFreq 1 415.3)) (NoteRange (NoteRangeAmplitude 415.3 1 4028.0) (NoteRangeHarmonicFreq 23 9552.01))) [Harmonic 1 (-1.732) 4028.0 ,Harmonic 2 (-1.638) 1913.7 ,Harmonic 3 1.285 259.05 ,Harmonic 4 (-1.004) 736.43 ,Harmonic 5 (-1.836) 370.07 ,Harmonic 6 0.187 81.01 ,Harmonic 7 1.763 58.64 ,Harmonic 8 (-0.965) 59.02 ,Harmonic 9 (-2.802) 16.39 ,Harmonic 10 1.858 6.08 ,Harmonic 11 (-0.173) 7.78 ,Harmonic 12 (-1.62) 5.12 ,Harmonic 13 (-2.959) 6.23 ,Harmonic 14 2.607 2.06 ,Harmonic 15 (-0.166) 3.05 ,Harmonic 16 (-0.229) 1.56 ,Harmonic 17 3.115 5.37 ,Harmonic 18 1.454 3.91 ,Harmonic 19 (-0.811) 2.9 ,Harmonic 20 (-2.845) 3.27 ,Harmonic 21 2.109 2.33 ,Harmonic 22 (-1.74) 1.28 ,Harmonic 23 (-1.58) 1.68] note9 :: Note note9 = Note (Pitch 440.0 57 "a4") 10 (Range (NoteRange (NoteRangeAmplitude 7480.0 17 0.75) (NoteRangeHarmonicFreq 1 440.0)) (NoteRange (NoteRangeAmplitude 440.0 1 4561.0) (NoteRangeHarmonicFreq 22 9680.0))) [Harmonic 1 2.167 4561.0 ,Harmonic 2 0.411 3295.16 ,Harmonic 3 0.716 637.36 ,Harmonic 4 3.011 762.84 ,Harmonic 5 (-1.028) 482.85 ,Harmonic 6 (-1.497) 113.66 ,Harmonic 7 (-2.834) 41.9 ,Harmonic 8 (-1.209) 55.56 ,Harmonic 9 2.184 24.53 ,Harmonic 10 (-1.619) 17.3 ,Harmonic 11 (-0.127) 9.16 ,Harmonic 12 2.162 10.63 ,Harmonic 13 (-2.193) 5.42 ,Harmonic 14 2.578 3.49 ,Harmonic 15 (-2.062) 3.75 ,Harmonic 16 (-0.965) 1.16 ,Harmonic 17 (-3.008) 0.75 ,Harmonic 18 (-1.069) 1.07 ,Harmonic 19 1.906 4.3 ,Harmonic 20 0.307 0.89 ,Harmonic 21 (-2.583) 2.05 ,Harmonic 22 0.228 0.79] note10 :: Note note10 = Note (Pitch 466.164 58 "a#4") 11 (Range (NoteRange (NoteRangeAmplitude 6060.13 13 1.49) (NoteRangeHarmonicFreq 1 466.16)) (NoteRange (NoteRangeAmplitude 466.16 1 6413.0) (NoteRangeHarmonicFreq 21 9789.44))) [Harmonic 1 (-2.062) 6413.0 ,Harmonic 2 (-1.399) 4098.45 ,Harmonic 3 (-2.292) 673.33 ,Harmonic 4 (-0.591) 1508.45 ,Harmonic 5 (-1.444) 151.25 ,Harmonic 6 1.47 137.58 ,Harmonic 7 0.541 47.66 ,Harmonic 8 (-1.774) 65.95 ,Harmonic 9 2.553 27.54 ,Harmonic 10 0.233 13.02 ,Harmonic 11 (-0.86) 17.45 ,Harmonic 12 1.897 7.39 ,Harmonic 13 2.621 1.49 ,Harmonic 14 0.647 5.9 ,Harmonic 15 (-1.75) 4.82 ,Harmonic 16 (-3.087) 5.88 ,Harmonic 17 2.028 14.77 ,Harmonic 18 6.2e-2 10.07 ,Harmonic 19 (-2.129) 8.41 ,Harmonic 20 2.883 4.49 ,Harmonic 21 1.049 2.48] note11 :: Note note11 = Note (Pitch 493.883 59 "b4") 12 (Range (NoteRange (NoteRangeAmplitude 6420.47 13 1.72) (NoteRangeHarmonicFreq 1 493.88)) (NoteRange (NoteRangeAmplitude 493.88 1 5168.0) (NoteRangeHarmonicFreq 20 9877.66))) [Harmonic 1 (-1.742) 5168.0 ,Harmonic 2 (-1.494) 4385.69 ,Harmonic 3 1.498 1120.91 ,Harmonic 4 0.28 731.42 ,Harmonic 5 (-2.753) 336.81 ,Harmonic 6 2.715 99.07 ,Harmonic 7 0.886 94.38 ,Harmonic 8 (-1.896) 45.32 ,Harmonic 9 2.705 23.49 ,Harmonic 10 1.455 10.32 ,Harmonic 11 (-0.815) 9.32 ,Harmonic 12 (-1.809) 7.09 ,Harmonic 13 2.754 1.72 ,Harmonic 14 1.804 7.63 ,Harmonic 15 (-1.17) 5.65 ,Harmonic 16 (-2.746) 9.01 ,Harmonic 17 2.178 4.85 ,Harmonic 18 (-0.614) 1.75 ,Harmonic 19 (-2.805) 2.87 ,Harmonic 20 3.042 1.88] note12 :: Note note12 = Note (Pitch 523.251 60 "c5") 13 (Range (NoteRange (NoteRangeAmplitude 8895.26 17 2.8) (NoteRangeHarmonicFreq 1 523.25)) (NoteRange (NoteRangeAmplitude 523.25 1 6412.0) (NoteRangeHarmonicFreq 18 9418.51))) [Harmonic 1 (-1.881) 6412.0 ,Harmonic 2 (-1.777) 2984.17 ,Harmonic 3 (-0.545) 717.38 ,Harmonic 4 (-1.734) 852.73 ,Harmonic 5 (-0.754) 151.4 ,Harmonic 6 (-0.559) 56.41 ,Harmonic 7 (-2.951) 12.28 ,Harmonic 8 2.029 37.88 ,Harmonic 9 0.461 22.51 ,Harmonic 10 (-0.806) 3.03 ,Harmonic 11 (-0.637) 3.89 ,Harmonic 12 1.396 4.09 ,Harmonic 13 0.187 8.02 ,Harmonic 14 2.885 9.92 ,Harmonic 15 2.265 8.82 ,Harmonic 16 0.271 5.68 ,Harmonic 17 2.758 2.8 ,Harmonic 18 1.873 2.89] note13 :: Note note13 = Note (Pitch 554.365 61 "c#5") 14 (Range (NoteRange (NoteRangeAmplitude 9424.2 17 0.27) (NoteRangeHarmonicFreq 1 554.36)) (NoteRange (NoteRangeAmplitude 554.36 1 3925.0) (NoteRangeHarmonicFreq 17 9424.2))) [Harmonic 1 (-1.49) 3925.0 ,Harmonic 2 (-2.05) 1245.36 ,Harmonic 3 (-1.894) 239.12 ,Harmonic 4 (-2.887) 284.85 ,Harmonic 5 1.64 33.17 ,Harmonic 6 (-0.788) 36.69 ,Harmonic 7 2.486 13.13 ,Harmonic 8 (-0.558) 10.02 ,Harmonic 9 (-2.347) 7.89 ,Harmonic 10 0.387 1.72 ,Harmonic 11 (-1.643) 3.17 ,Harmonic 12 (-9.7e-2) 1.61 ,Harmonic 13 (-2.208) 0.47 ,Harmonic 14 (-0.893) 1.35 ,Harmonic 15 (-0.443) 0.55 ,Harmonic 16 (-0.258) 1.36 ,Harmonic 17 0.911 0.27] note14 :: Note note14 = Note (Pitch 587.33 62 "d5") 15 (Range (NoteRange (NoteRangeAmplitude 9397.28 16 1.04) (NoteRangeHarmonicFreq 1 587.33)) (NoteRange (NoteRangeAmplitude 587.33 1 5363.0) (NoteRangeHarmonicFreq 16 9397.28))) [Harmonic 1 (-1.643) 5363.0 ,Harmonic 2 2.181 882.58 ,Harmonic 3 (-0.943) 642.1 ,Harmonic 4 (-3.7e-2) 226.53 ,Harmonic 5 (-1.992) 74.0 ,Harmonic 6 0.737 7.68 ,Harmonic 7 (-1.538) 20.45 ,Harmonic 8 2.181 11.34 ,Harmonic 9 (-0.708) 9.2 ,Harmonic 10 0.399 1.56 ,Harmonic 11 1.584 3.55 ,Harmonic 12 (-0.302) 3.55 ,Harmonic 13 1.982 2.07 ,Harmonic 14 (-0.208) 2.39 ,Harmonic 15 2.258 2.21 ,Harmonic 16 (-0.751) 1.04] note15 :: Note note15 = Note (Pitch 622.254 63 "d#5") 16 (Range (NoteRange (NoteRangeAmplitude 8089.3 13 0.67) (NoteRangeHarmonicFreq 1 622.25)) (NoteRange (NoteRangeAmplitude 622.25 1 4994.0) (NoteRangeHarmonicFreq 15 9333.81))) [Harmonic 1 (-1.573) 4994.0 ,Harmonic 2 2.739 614.22 ,Harmonic 3 (-1.768) 541.82 ,Harmonic 4 (-2.719) 134.58 ,Harmonic 5 (-2.634) 18.86 ,Harmonic 6 1.89 44.3 ,Harmonic 7 (-1.05) 13.06 ,Harmonic 8 2.186 13.26 ,Harmonic 9 (-1.177) 7.09 ,Harmonic 10 2.79 4.43 ,Harmonic 11 1.815 6.26 ,Harmonic 12 (-0.641) 2.7 ,Harmonic 13 (-2.2) 0.67 ,Harmonic 14 (-0.372) 1.25 ,Harmonic 15 (-0.821) 2.6] note16 :: Note note16 = Note (Pitch 659.255 64 "e5") 17 (Range (NoteRange (NoteRangeAmplitude 6592.55 10 0.78) (NoteRangeHarmonicFreq 1 659.25)) (NoteRange (NoteRangeAmplitude 659.25 1 3797.0) (NoteRangeHarmonicFreq 15 9888.82))) [Harmonic 1 1.503 3797.0 ,Harmonic 2 1.403 271.99 ,Harmonic 3 0.939 203.56 ,Harmonic 4 1.957 19.28 ,Harmonic 5 1.795 49.8 ,Harmonic 6 1.051 9.03 ,Harmonic 7 1.186 9.85 ,Harmonic 8 1.974 3.98 ,Harmonic 9 (-2.65) 3.56 ,Harmonic 10 (-2.918) 0.78 ,Harmonic 11 (-1.334) 1.36 ,Harmonic 12 (-1.606) 1.86 ,Harmonic 13 (-2.316) 3.93 ,Harmonic 14 1.248 0.8 ,Harmonic 15 (-1.462) 2.26] note17 :: Note note17 = Note (Pitch 698.456 65 "f5") 18 (Range (NoteRange (NoteRangeAmplitude 9079.92 13 0.11) (NoteRangeHarmonicFreq 1 698.45)) (NoteRange (NoteRangeAmplitude 698.45 1 4476.0) (NoteRangeHarmonicFreq 14 9778.38))) [Harmonic 1 (-1.362) 4476.0 ,Harmonic 2 2.765 1424.38 ,Harmonic 3 (-1.232) 418.71 ,Harmonic 4 1.919 59.43 ,Harmonic 5 (-0.568) 50.49 ,Harmonic 6 (-1.874) 15.98 ,Harmonic 7 1.916 13.39 ,Harmonic 8 (-1.153) 4.99 ,Harmonic 9 (-1.969) 4.73 ,Harmonic 10 2.596 2.55 ,Harmonic 11 0.678 3.84 ,Harmonic 12 (-1.548) 6.86 ,Harmonic 13 (-0.767) 0.11 ,Harmonic 14 (-0.531) 1.01] note18 :: Note note18 = Note (Pitch 739.989 66 "f#5") 19 (Range (NoteRange (NoteRangeAmplitude 5919.91 8 1.11) (NoteRangeHarmonicFreq 1 739.98)) (NoteRange (NoteRangeAmplitude 739.98 1 4475.0) (NoteRangeHarmonicFreq 13 9619.85))) [Harmonic 1 (-1.737) 4475.0 ,Harmonic 2 1.055 304.98 ,Harmonic 3 (-1.724) 309.23 ,Harmonic 4 1.986 44.63 ,Harmonic 5 (-1.246) 55.52 ,Harmonic 6 2.903 12.01 ,Harmonic 7 0.363 19.53 ,Harmonic 8 (-2.712) 1.11 ,Harmonic 9 1.097 3.44 ,Harmonic 10 (-2.048) 7.45 ,Harmonic 11 0.174 5.63 ,Harmonic 12 (-1.229) 8.73 ,Harmonic 13 0.286 8.2] note19 :: Note note19 = Note (Pitch 783.991 67 "g5") 20 (Range (NoteRange (NoteRangeAmplitude 8623.9 11 2.07) (NoteRangeHarmonicFreq 1 783.99)) (NoteRange (NoteRangeAmplitude 783.99 1 4304.0) (NoteRangeHarmonicFreq 12 9407.89))) [Harmonic 1 1.508 4304.0 ,Harmonic 2 (-0.75) 329.98 ,Harmonic 3 1.436 419.64 ,Harmonic 4 1.779 30.68 ,Harmonic 5 (-2.93) 33.73 ,Harmonic 6 (-1.72) 2.8 ,Harmonic 7 (-1.049) 15.84 ,Harmonic 8 (-3.041) 4.66 ,Harmonic 9 2.774 10.0 ,Harmonic 10 2.251 5.66 ,Harmonic 11 2.3 2.07 ,Harmonic 12 (-2.637) 6.78] note20 :: Note note20 = Note (Pitch 830.609 68 "g#5") 21 (Range (NoteRange (NoteRangeAmplitude 9967.3 12 2.67) (NoteRangeHarmonicFreq 1 830.6)) (NoteRange (NoteRangeAmplitude 830.6 1 3628.0) (NoteRangeHarmonicFreq 12 9967.3))) [Harmonic 1 (-1.536) 3628.0 ,Harmonic 2 2.189 893.64 ,Harmonic 3 (-1.913) 559.79 ,Harmonic 4 (-1.795) 100.0 ,Harmonic 5 1.357 62.94 ,Harmonic 6 (-0.205) 20.49 ,Harmonic 7 2.895 5.03 ,Harmonic 8 2.239 3.6 ,Harmonic 9 (-9.6e-2) 6.73 ,Harmonic 10 (-0.849) 9.01 ,Harmonic 11 1.858 7.42 ,Harmonic 12 (-0.175) 2.67] note21 :: Note note21 = Note (Pitch 880.0 69 "a5") 22 (Range (NoteRange (NoteRangeAmplitude 7040.0 8 4.16) (NoteRangeHarmonicFreq 1 880.0)) (NoteRange (NoteRangeAmplitude 880.0 1 5280.0) (NoteRangeHarmonicFreq 10 8800.0))) [Harmonic 1 (-1.793) 5280.0 ,Harmonic 2 1.04 793.54 ,Harmonic 3 (-1.444) 752.79 ,Harmonic 4 (-0.866) 126.83 ,Harmonic 5 (-2.219) 67.7 ,Harmonic 6 0.889 25.4 ,Harmonic 7 (-0.78) 18.25 ,Harmonic 8 (-1.001) 4.16 ,Harmonic 9 (-0.184) 22.15 ,Harmonic 10 3.141 8.51] note22 :: Note note22 = Note (Pitch 932.328 70 "a#5") 23 (Range (NoteRange (NoteRangeAmplitude 5593.96 6 5.34) (NoteRangeHarmonicFreq 1 932.32)) (NoteRange (NoteRangeAmplitude 932.32 1 4055.0) (NoteRangeHarmonicFreq 10 9323.27))) [Harmonic 1 1.578 4055.0 ,Harmonic 2 1.582 644.76 ,Harmonic 3 (-1.0e-3) 231.29 ,Harmonic 4 1.34 47.45 ,Harmonic 5 1.501 18.44 ,Harmonic 6 2.033 5.34 ,Harmonic 7 (-1.074) 10.8 ,Harmonic 8 (-0.691) 9.67 ,Harmonic 9 (-1.441) 17.4 ,Harmonic 10 (-0.258) 8.34] note23 :: Note note23 = Note (Pitch 987.767 71 "b5") 24 (Range (NoteRange (NoteRangeAmplitude 8889.9 9 3.58) (NoteRangeHarmonicFreq 1 987.76)) (NoteRange (NoteRangeAmplitude 987.76 1 4758.0) (NoteRangeHarmonicFreq 9 8889.9))) [Harmonic 1 1.281 4758.0 ,Harmonic 2 1.505 594.64 ,Harmonic 3 0.92 297.49 ,Harmonic 4 2.004 24.94 ,Harmonic 5 1.778 29.76 ,Harmonic 6 (-2.952) 10.45 ,Harmonic 7 (-0.296) 8.44 ,Harmonic 8 (-2.439) 11.8 ,Harmonic 9 (-2.137) 3.58] note24 :: Note note24 = Note (Pitch 1046.5 72 "c6") 25 (Range (NoteRange (NoteRangeAmplitude 6279.0 6 1.66) (NoteRangeHarmonicFreq 1 1046.5)) (NoteRange (NoteRangeAmplitude 1046.5 1 4291.0) (NoteRangeHarmonicFreq 9 9418.5))) [Harmonic 1 (-1.62) 4291.0 ,Harmonic 2 (-2.308) 103.03 ,Harmonic 3 1.921 144.55 ,Harmonic 4 (-2.284) 4.04 ,Harmonic 5 2.704 19.76 ,Harmonic 6 2.767 1.66 ,Harmonic 7 (-2.248) 18.59 ,Harmonic 8 1.343 9.1 ,Harmonic 9 (-1.905) 8.12] note25 :: Note note25 = Note (Pitch 1108.73 73 "c#6") 26 (Range (NoteRange (NoteRangeAmplitude 8869.84 8 9.82) (NoteRangeHarmonicFreq 1 1108.73)) (NoteRange (NoteRangeAmplitude 1108.73 1 3610.0) (NoteRangeHarmonicFreq 8 8869.84))) [Harmonic 1 1.371 3610.0 ,Harmonic 2 1.124 404.42 ,Harmonic 3 0.471 214.83 ,Harmonic 4 1.001 38.31 ,Harmonic 5 0.638 10.47 ,Harmonic 6 (-2.298) 13.31 ,Harmonic 7 2.727 18.02 ,Harmonic 8 2.561 9.82] note26 :: Note note26 = Note (Pitch 1174.66 74 "d6") 27 (Range (NoteRange (NoteRangeAmplitude 9397.28 8 6.52) (NoteRangeHarmonicFreq 1 1174.66)) (NoteRange (NoteRangeAmplitude 1174.66 1 2784.0) (NoteRangeHarmonicFreq 8 9397.28))) [Harmonic 1 1.368 2784.0 ,Harmonic 2 0.961 497.78 ,Harmonic 3 (-0.948) 72.11 ,Harmonic 4 0.804 48.11 ,Harmonic 5 (-1.243) 13.68 ,Harmonic 6 2.38 21.48 ,Harmonic 7 2.591 17.42 ,Harmonic 8 2.917 6.52] note27 :: Note note27 = Note (Pitch 1244.51 75 "d#6") 28 (Range (NoteRange (NoteRangeAmplitude 9956.08 8 9.88) (NoteRangeHarmonicFreq 1 1244.51)) (NoteRange (NoteRangeAmplitude 1244.51 1 2853.0) (NoteRangeHarmonicFreq 8 9956.08))) [Harmonic 1 (-1.535) 2853.0 ,Harmonic 2 2.219 369.94 ,Harmonic 3 (-2.081) 128.53 ,Harmonic 4 (-2.883) 45.86 ,Harmonic 5 1.748 18.2 ,Harmonic 6 (-1.17) 24.02 ,Harmonic 7 (-2.927) 12.67 ,Harmonic 8 (-0.158) 9.88] note28 :: Note note28 = Note (Pitch 1318.51 76 "e6") 29 (Range (NoteRange (NoteRangeAmplitude 6592.55 5 8.85) (NoteRangeHarmonicFreq 1 1318.51)) (NoteRange (NoteRangeAmplitude 1318.51 1 4725.0) (NoteRangeHarmonicFreq 7 9229.57))) [Harmonic 1 (-1.781) 4725.0 ,Harmonic 2 1.331 327.59 ,Harmonic 3 3.141 104.99 ,Harmonic 4 1.193 41.12 ,Harmonic 5 (-0.406) 8.85 ,Harmonic 6 3.14 19.12 ,Harmonic 7 (-1.242) 14.0] note29 :: Note note29 = Note (Pitch 1396.91 77 "f6") 30 (Range (NoteRange (NoteRangeAmplitude 6984.55 5 6.21) (NoteRangeHarmonicFreq 1 1396.91)) (NoteRange (NoteRangeAmplitude 1396.91 1 4792.0) (NoteRangeHarmonicFreq 7 9778.37))) [Harmonic 1 1.413 4792.0 ,Harmonic 2 0.699 107.16 ,Harmonic 3 1.814 91.22 ,Harmonic 4 2.168 32.58 ,Harmonic 5 (-1.444) 6.21 ,Harmonic 6 0.265 24.76 ,Harmonic 7 1.7 10.7] note30 :: Note note30 = Note (Pitch 1479.98 78 "f#6") 31 (Range (NoteRange (NoteRangeAmplitude 5919.92 4 7.52) (NoteRangeHarmonicFreq 1 1479.98)) (NoteRange (NoteRangeAmplitude 1479.98 1 5119.0) (NoteRangeHarmonicFreq 6 8879.88))) [Harmonic 1 1.244 5119.0 ,Harmonic 2 0.821 216.49 ,Harmonic 3 0.755 121.38 ,Harmonic 4 (-0.834) 7.52 ,Harmonic 5 3.01 27.89 ,Harmonic 6 (-2.435) 27.08] note31 :: Note note31 = Note (Pitch 1567.98 79 "g6") 32 (Range (NoteRange (NoteRangeAmplitude 6271.92 4 3.13) (NoteRangeHarmonicFreq 1 1567.98)) (NoteRange (NoteRangeAmplitude 1567.98 1 5896.0) (NoteRangeHarmonicFreq 6 9407.88))) [Harmonic 1 1.411 5896.0 ,Harmonic 2 (-1.463) 59.77 ,Harmonic 3 (-2.941) 101.66 ,Harmonic 4 (-2.986) 3.13 ,Harmonic 5 0.594 49.24 ,Harmonic 6 1.791 12.19] note32 :: Note note32 = Note (Pitch 1661.22 80 "g#6") 33 (Range (NoteRange (NoteRangeAmplitude 6644.88 4 10.98) (NoteRangeHarmonicFreq 1 1661.22)) (NoteRange (NoteRangeAmplitude 1661.22 1 3350.0) (NoteRangeHarmonicFreq 5 8306.1))) [Harmonic 1 1.234 3350.0 ,Harmonic 2 (-0.823) 250.03 ,Harmonic 3 1.899 292.56 ,Harmonic 4 2.955 10.98 ,Harmonic 5 (-6.4e-2) 15.62] note33 :: Note note33 = Note (Pitch 1760.0 81 "a6") 34 (Range (NoteRange (NoteRangeAmplitude 8800.0 5 49.74) (NoteRangeHarmonicFreq 1 1760.0)) (NoteRange (NoteRangeAmplitude 1760.0 1 3073.0) (NoteRangeHarmonicFreq 5 8800.0))) [Harmonic 1 1.151 3073.0 ,Harmonic 2 2.18 210.88 ,Harmonic 3 7.5e-2 155.57 ,Harmonic 4 2.35 53.67 ,Harmonic 5 1.653 49.74] note34 :: Note note34 = Note (Pitch 1864.66 82 "a#6") 35 (Range (NoteRange (NoteRangeAmplitude 9323.3 5 28.66) (NoteRangeHarmonicFreq 1 1864.66)) (NoteRange (NoteRangeAmplitude 1864.66 1 5847.0) (NoteRangeHarmonicFreq 5 9323.3))) [Harmonic 1 1.496 5847.0 ,Harmonic 2 4.8e-2 586.31 ,Harmonic 3 0.337 134.92 ,Harmonic 4 2.072 106.1 ,Harmonic 5 1.755 28.66] note35 :: Note note35 = Note (Pitch 1975.53 83 "b6") 36 (Range (NoteRange (NoteRangeAmplitude 9877.65 5 26.77) (NoteRangeHarmonicFreq 1 1975.53)) (NoteRange (NoteRangeAmplitude 1975.53 1 3562.0) (NoteRangeHarmonicFreq 5 9877.65))) [Harmonic 1 (-1.803) 3562.0 ,Harmonic 2 (-1.127) 482.52 ,Harmonic 3 1.929 196.8 ,Harmonic 4 0.394 61.9 ,Harmonic 5 0.198 26.77] note36 :: Note note36 = Note (Pitch 2093.0 84 "c7") 37 (Range (NoteRange (NoteRangeAmplitude 8372.0 4 33.27) (NoteRangeHarmonicFreq 1 2093.0)) (NoteRange (NoteRangeAmplitude 2093.0 1 5076.0) (NoteRangeHarmonicFreq 4 8372.0))) [Harmonic 1 (-1.833) 5076.0 ,Harmonic 2 (-1.66) 155.5 ,Harmonic 3 (-1.518) 215.08 ,Harmonic 4 (-0.722) 33.27]
anton-k/sharc-timbre
src/Sharc/Instruments/Flute.hs
bsd-3-clause
29,360
0
15
8,834
10,802
5,587
5,215
1,035
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Blaze.ByteString.Builder.Html.Utf8 -- Copyright : (c) 2010 Jasper Van der Jeugt & Simon Meier -- License : BSD3-style (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Stability : experimental -- Portability : tested on GHC only -- -- 'Write's and 'Builder's for serializing HTML escaped and UTF-8 encoded -- characters. -- -- This module is used by both the 'blaze-html' and the \'hamlet\' HTML -- templating libraries. If the 'Builder' from 'blaze-builder' replaces the -- 'Data.Binary.Builder' implementation, this module will most likely keep its -- place, as it provides a set of very specialized functions. module Blaze.ByteString.Builder.Html.Utf8 ( module Blaze.ByteString.Builder.Char.Utf8 -- * Writing HTML escaped and UTF-8 encoded characters to a buffer , writeHtmlEscapedChar -- * Creating Builders from HTML escaped and UTF-8 encoded characters , fromHtmlEscapedChar , fromHtmlEscapedString , fromHtmlEscapedShow , fromHtmlEscapedText , fromHtmlEscapedLazyText ) where import Data.ByteString.Char8 () -- for the 'IsString' instance of bytesrings import qualified Data.Text as TS import qualified Data.Text.Lazy as TL import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Internal import Blaze.ByteString.Builder.Char.Utf8 -- | Write a HTML escaped and UTF-8 encoded Unicode character to a bufffer. -- writeHtmlEscapedChar :: Char -> Write writeHtmlEscapedChar c0 = boundedWrite 6 (io c0) -- WARNING: Don't forget to change the bound if you change the bytestrings. where io '<' = getPoke $ writeByteString "&lt;" io '>' = getPoke $ writeByteString "&gt;" io '&' = getPoke $ writeByteString "&amp;" io '"' = getPoke $ writeByteString "&quot;" io '\'' = getPoke $ writeByteString "&#39;" io c = getPoke $ writeChar c {-# INLINE writeHtmlEscapedChar #-} -- | /O(1)./ Serialize a HTML escaped Unicode character using the UTF-8 -- encoding. -- fromHtmlEscapedChar :: Char -> Builder fromHtmlEscapedChar = fromWriteSingleton writeHtmlEscapedChar -- | /O(n)/. Serialize a HTML escaped Unicode 'String' using the UTF-8 -- encoding. -- fromHtmlEscapedString :: String -> Builder fromHtmlEscapedString = fromWriteList writeHtmlEscapedChar -- | /O(n)/. Serialize a value by 'Show'ing it and then, HTML escaping and -- UTF-8 encoding the resulting 'String'. -- fromHtmlEscapedShow :: Show a => a -> Builder fromHtmlEscapedShow = fromHtmlEscapedString . show -- | /O(n)/. Serialize a HTML escaped strict Unicode 'TS.Text' value using the -- UTF-8 encoding. -- fromHtmlEscapedText :: TS.Text -> Builder fromHtmlEscapedText = fromHtmlEscapedString . TS.unpack -- | /O(n)/. Serialize a HTML escaped Unicode 'TL.Text' using the UTF-8 encoding. -- fromHtmlEscapedLazyText :: TL.Text -> Builder fromHtmlEscapedLazyText = fromHtmlEscapedString . TL.unpack
meiersi/blaze-builder
Blaze/ByteString/Builder/Html/Utf8.hs
bsd-3-clause
2,954
0
8
517
346
211
135
36
6
{-# LANGUAGE ExistentialQuantification #-} module System.IO.Log where newtype Logger = forall o. Output o => Logger { loggerOutput :: MVar (BufferedOutput o) , loggerPrefix :: Bytes -> IO Builder , loggerNoDebug :: Bool , loggerAutoFlush :: Bool } newLogger :: Output o => o -> Int -> Bool -> IO Logger changeDefaultLogger :: Logger -> IO () getDefaultLogger :: IO Logger -------------------------------------------------------------------------------- defaultLogger :: IORef Logger debug :: Text -> IO () info :: Text -> IO () warn :: Text -> IO () fatal :: Text -> IO () debug_ :: Logger -> Text -> IO () info_ :: Logger -> Text -> IO () warn_ :: Logger -> Text -> IO () fatal_ :: Logger -> Text -> IO ()
winterland1989/stdio
System/IO/Log.hs
bsd-3-clause
752
37
6
167
239
127
112
-1
-1
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module SPARC.CodeGen.Base ( InstrBlock, CondCode(..), ChildCode64(..), Amode(..), Register(..), setSizeOfRegister, getRegisterReg, mangleIndexTree ) where import SPARC.Instr import SPARC.Cond import SPARC.AddrMode import SPARC.Regs import Size import Reg import CodeGen.Platform import DynFlags import Cmm import PprCmmExpr () import Platform import Outputable import OrdList -------------------------------------------------------------------------------- -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal yields the insns in the correct order. -- type InstrBlock = OrdList Instr -- | Condition codes passed up the tree. -- data CondCode = CondCode Bool Cond InstrBlock -- | a.k.a "Register64" -- Reg is the lower 32-bit temporary which contains the result. -- Use getHiVRegFromLo to find the other VRegUnique. -- -- Rules of this simplified insn selection game are therefore that -- the returned Reg may be modified -- data ChildCode64 = ChildCode64 InstrBlock Reg -- | Holds code that references a memory address. data Amode = Amode -- the AddrMode we can use in the instruction -- that does the real load\/store. AddrMode -- other setup code we have to run first before we can use the -- above AddrMode. InstrBlock -------------------------------------------------------------------------------- -- | Code to produce a result into a register. -- If the result must go in a specific register, it comes out as Fixed. -- Otherwise, the parent can decide which register to put it in. -- data Register = Fixed Size Reg InstrBlock | Any Size (Reg -> InstrBlock) -- | Change the size field in a Register. setSizeOfRegister :: Register -> Size -> Register setSizeOfRegister reg size = case reg of Fixed _ reg code -> Fixed size reg code Any _ codefn -> Any size codefn -------------------------------------------------------------------------------- -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> CmmReg -> Reg getRegisterReg _ (CmmLocal (LocalReg u pk)) = RegVirtual $ mkVirtualReg u (cmmTypeSize pk) getRegisterReg platform (CmmGlobal mid) = case globalRegMaybe platform mid of Just reg -> RegReal reg Nothing -> pprPanic "SPARC.CodeGen.Base.getRegisterReg: global is in memory" (ppr $ CmmGlobal mid) -- Expand CmmRegOff. ToDo: should we do it this way around, or convert -- CmmExprs into CmmRegOff? mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr mangleIndexTree dflags (CmmRegOff reg off) = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)] where width = typeWidth (cmmRegType dflags reg) mangleIndexTree _ _ = panic "SPARC.CodeGen.Base.mangleIndexTree: no match"
ekmett/ghc
compiler/nativeGen/SPARC/CodeGen/Base.hs
bsd-3-clause
3,249
48
11
631
514
294
220
59
2
{- Defines the most basic Type Class used by this library to define data that is either Graph or DiGraph. A lot of functionality is implemented for GraphDataSets and then reused by both Graph and DiGraph -} module PolyGraph.ReadOnly ( GraphDataSet(..) , defaultVertexCount , GMorphism (..) , fGMorphism , isValidGraphDataSet ) where import Data.List (nub) import qualified Data.Foldable as F import qualified Data.Maybe as M -- | GraphDataSet thinks of vertices (v) and edges (e) as two arbitrary types -- Incidence function is defined on Graph or DiGraph level. -- Foldable constraint does not imply any adjacency friendly folds. -- It simply means that the content of edges and isolatedVertices can be -- discovered independently of traversing the graph itself. class (Eq v, Foldable t) => GraphDataSet g v e t | g -> t, g -> v, g -> e where isolatedVertices :: g -> t v edges :: g -> t e -- | edge count eCount :: g -> Int eCount g = length . edges $ g -- | vertex count that uses edge to vertex resolver vCount :: (e -> (v,v)) -> g -> Int vCount = defaultVertexCount -- | property helper isValidGraphDataSet :: forall g v e t . GraphDataSet g v e t => (e -> (v,v)) ->g -> Bool isValidGraphDataSet resolveE g = let isolatedVs = isolatedVertices g findVMatch :: e -> Bool findVMatch e = let (v1,v2) = resolveE e in (F.elem v1 isolatedVs) || (F.elem v2 isolatedVs) in M.isNothing $ F.find findVMatch (edges g) ---------------------------------------------------------- -- Note GMoriphism can be used with Graphs or DiGraphs -- -- Definition is has not type contraint on e -- -- -- -- morphism properties are defined in GraphProperties -- -- DiGraph.Properties modules separately -- ---------------------------------------------------------- data GMorphism v0 e0 v1 e1 = GMorphism { vTrans :: v0 -> v1, eTrans :: e0 -> e1 } fGMorphism :: forall v0 v1 f . (Functor f) => (v0 -> v1) -> GMorphism v0 (f v0) v1 (f v1) fGMorphism fn = GMorphism { vTrans = fn, eTrans = fmap fn } -- other helper functions -- defaultVertexCount :: forall g v e t. (GraphDataSet g v e t) => (e -> (v,v)) -> g -> Int defaultVertexCount f g = let isolatedVCount = length . isolatedVertices $ g appendVertices :: e -> [v] -> [v] appendVertices e list = let (v1, v2) = f e in v1 : v2 : list nonIsolatedVCount = length . nub $ foldr appendVertices [] (edges g) in isolatedVCount + nonIsolatedVCount
rpeszek/GraphPlay
src/PolyGraph/ReadOnly.hs
bsd-3-clause
2,774
0
14
825
631
357
274
-1
-1
{-# LANGUAGE FlexibleContexts #-} {- | Module : Data.Graph.Inductive.Query.Properties Description : Properties for Query modules Copyright : (c) Ivan Lazar Miljenovic License : BSD3 Maintainer : [email protected] Rather than having an individual module of properties for each `Data.Graph.Inductive.Query.*` module, this combines all such properties and tests into one module. -} module Data.Graph.Inductive.Query.Properties where import Data.Graph.Inductive.Arbitrary import Data.Graph.Inductive.Example (clr595, vor) import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree (Gr) import Data.Graph.Inductive.Proxy import Data.Graph.Inductive.Query import Test.Hspec (Spec, describe, it, shouldBe, shouldMatchList, shouldSatisfy) import Test.QuickCheck import Control.Applicative ((<*>)) import Control.Arrow (second) import Data.List (delete, sort, unfoldr) import qualified Data.Set as S -- ----------------------------------------------------------------------------- -- Articulation Points -- | Deleting the articulation points should increase the number of -- components. test_ap :: (ArbGraph gr) => Proxy (gr a b) -> Undirected gr a b -> Property test_ap _ ug = not (isEmpty g) ==> null points || noComponents (delNodes points g) > noComponents g where g = toBaseGraph ug points = ap g -- ----------------------------------------------------------------------------- -- BCC -- | Test that the bi-connected components are indeed composed solely -- from the original graph (and comprise the entire original graph). test_bcc :: (ArbGraph gr, Ord a, Ord b) => Proxy (gr a b) -> UConnected gr a b -> Bool test_bcc _ cg = sort (concatMap labEdges bgs) == sort (labEdges g) -- Don't test labNodes as a node -- may be repeated in multiple -- bi-connected components. where g = connGraph cg bgs = bcc g -- ----------------------------------------------------------------------------- -- BFS test_bfs :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr a b -> Bool test_bfs _ cg = sort (bfs (connNode cg) g) == sort (nodes g) where g = connGraph cg test_level :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr a b -> Bool test_level _ cg = sort expect == sort (level cn g) where g = connGraph cg cn = connNode cg vs = delete cn (nodes g) expect = (cn,0) : map (flip (,) 1) vs -- esp tested as part of test_sp -- ----------------------------------------------------------------------------- -- DFS -- TODO: flesh out -- | The 'components' function should never return an empty list, and -- none of its sub-lists should be empty (unless the graph is -- empty). All nodes in the graph should be in precisely one of the -- components. test_components :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr a b -> Bool test_components _ cg = all (not . null) cs && sort (concat cs) == sort (nodes g) where g = connGraph cg cs = components g -- | The strongly connected components should be a partitioning of the -- nodes of a graph. test_scc :: (Graph gr) => Proxy (gr a b) -> gr a b -> Bool test_scc _ g = sort (concat (scc g)) == sort (nodes g) -- | Every node in an undirected connected graph should be reachable. test_reachable :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr a b -> Property test_reachable _ cg = not (isEmpty g) ==> sort (reachable v g) == sort (nodes g) where g = connGraph cg v = node' . fst . matchAny $ g -- | The nodes of the condensation should be exactly the connected -- components, and the edges of the condensation should correspond -- exactly to the edges between the connected components. test_condensation :: (Graph gr) => Proxy (gr a b) -> gr a b -> Bool test_condensation _ g = sort sccs == sort (map snd $ labNodes cdg) && and [ or [ hasEdge g (v,w) == hasEdge cdg (cv,cw) | v <- sccv, w <- sccw ] | (cv,sccv) <- labNodes cdg , (cw,sccw) <- labNodes cdg , cv /= cw ] where sccs = scc g cdg = condensation g -- ----------------------------------------------------------------------------- -- Dominators test_dom :: Spec test_dom = it "dom" $ sortIt (dom domGraph 1) `shouldMatchList` [ (1, [1]) , (2, [1,2]) , (3, [1,2,3]) , (4, [1,2,4]) , (5, [1,2,5]) , (6, [1,2,6]) ] where sortIt = map (second sort) test_iDom :: Spec test_iDom = it "iDom" $ iDom domGraph 1 `shouldMatchList` [(2,1),(3,2),(4,2),(5,2),(6,2)] -- Taken from <https://en.wikipedia.org/wiki/Dominator_%28graph_theory%29> domGraph :: Gr () () domGraph = mkUGraph [1..6] [ (1,2) , (2,3) , (2,4) , (2,6) , (3,5) , (4,5) , (5,2) ] -- ----------------------------------------------------------------------------- -- GVD test_voronoiSet :: Spec test_voronoiSet = describe "voronoiSet" $ do describe "inwards" $ do it "with root node" (voronoiSet 4 vd `shouldMatchList` [1,2,4]) it "other node" (voronoiSet 1 vd `shouldSatisfy` null) describe "outwards" $ do it "with root node" (voronoiSet 4 vd0 `shouldMatchList` [2,4,6,7]) it "other node" (voronoiSet 1 vd0 `shouldSatisfy` null) test_nearestNode :: Spec test_nearestNode = describe "nearestNode" $ do describe "inwards" $ do it "reachable" (nearestNode 6 vd `shouldBe` Just 5) it "unreachable" (nearestNode 7 vd `shouldBe` Nothing) describe "outwards" $ do it "reachable" (nearestNode 6 vd0 `shouldBe` Just 4) it "unreachable" (nearestNode 1 vd0 `shouldBe` Nothing) test_nearestDist :: Spec test_nearestDist = describe "nearestDist" $ do describe "inwards" $ do it "root" (nearestDist 4 vd `shouldBe` Just 0) it "reachable" (nearestDist 1 vd `shouldBe` Just 3) it "unreachable" (nearestDist 7 vd `shouldBe` Nothing) describe "outwards" $ do it "root" (nearestDist 5 vd0 `shouldBe` Just 0) it "reachable" (nearestDist 7 vd0 `shouldBe` Just 4) it "unreachable" (nearestDist 1 vd0 `shouldBe` Nothing) test_nearestPath :: Spec test_nearestPath = describe "nearestPath" $ do describe "inwards" $ do it "reachable" (nearestPath 1 vd `shouldBe` Just [1,4]) it "unreachable" (nearestPath 7 vd `shouldBe` Nothing) describe "outwards" $ do it "reachable" (nearestPath 7 vd0 `shouldBe` Just [7,6,4]) it "unreachable" (nearestPath 1 vd0 `shouldBe` Nothing) vd :: Voronoi Int vd = gvdIn [4,5] vor vd0 :: Voronoi Int vd0 = gvdOut [4,5] vor -- ----------------------------------------------------------------------------- -- Indep -- TODO: how to prove that the found independent set is /maximal/? -- | Make sure the size of independent sets is indeed accurate. test_indepSize :: (ArbGraph gr) => Proxy (gr a b) -> gr a b -> Bool test_indepSize _ ag = uncurry ((==) . length) (indepSize g) where g = toBaseGraph ag -- | Is this really an independent set? test_indep :: (ArbGraph gr) => Proxy (gr a b) -> gr a b -> Bool test_indep _ ag = and . unfoldr checkSet . S.fromList $ indep g where g = toBaseGraph ag checkSet = fmap checkVal . S.minView checkVal (v,ws) = (S.null (S.fromList (neighbors g v) `S.intersection` ws), ws) -- ----------------------------------------------------------------------------- -- MaxFlow2 -- As it is difficult to generate a suitable arbitrary graph for which -- there /is/ a valid flow, we instead use unit tests based upon the -- examples in the source code. -- | Maximum flow of 2000 exampleNetwork1 :: Network exampleNetwork1 = emap (flip (,) 0 . fromIntegral) exampleFlowGraph1 -- | Taken from "Introduction to Algorithms" (Cormen, Leiserson, Rivest). -- This network has a maximum flow of 23 exampleNetwork2 :: Network -- Names of nodes in "Introduction to Algorithms": -- 1: s -- 2: v1 -- 3: v2 -- 4: v3 -- 5: v4 -- 6: t exampleNetwork2 = nemap (const ()) (flip (,) 0 . fromIntegral) clr595 clr595_network :: Network clr595_network = maxFlowgraph clr595' 1 6 where clr595' = nemap (const ()) fromIntegral clr595 test_maxFlow2_with :: String -> (Network -> Node -> Node -> (Network,Double)) -> Spec test_maxFlow2_with nm f = it nm $ do snd (f exampleNetwork1 1 4) `shouldBe` 2000 snd (f exampleNetwork2 1 6) `shouldBe` 23 test_maxFlow2 :: Spec test_maxFlow2 = describe "MaxFlow2" $ do test_maxFlow2_with "ekSimple" ekSimple test_maxFlow2_with "ekFused" ekFused test_maxFlow2_with "ekList" ekList -- ----------------------------------------------------------------------------- -- MaxFlow -- TODO: test other exported functions. exampleFlowGraph1 :: Gr () Int exampleFlowGraph1 = mkGraph [ (1,()), (2,()), (3,()), (4,()) ] [ (1,2,(1000)), (1,3,(1000)) , (2,3,(1)), (2,4,(1000)), (3,4,(1000)) ] test_maxFlow :: Spec test_maxFlow = it "maxFlow" $ do maxFlow exampleFlowGraph1 1 4 `shouldBe` 2000 maxFlow clr595 1 6 `shouldBe` 23 -- ----------------------------------------------------------------------------- -- MST -- | A minimum spanning tree of a connected, undirected graph should -- cover all nodes, and all edges in the tree should be present in -- the original graph. test_msTree :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr () Int -> Bool test_msTree _ cg = ns == mstNs && S.isSubsetOf mstEs es where g = connGraph cg -- a Connected graph is always non-empty mst = map unLPath (msTree g) ns = S.fromList (nodes g) es = S.fromList (labEdges g) mstNs = S.unions (map (S.fromList . map fst) mst) mstEs = S.unions (map (S.fromList . (zipWith toE <*> tail)) mst) toE (w,l) (v,_) = (v,w,l) -- ----------------------------------------------------------------------------- -- SP test_sp :: (ArbGraph gr) => Proxy (gr a b) -> UConnected gr () (Positive Int) -> Bool test_sp _ cg = all test_p (map unLPath (msTree g)) where -- Use Positive to avoid problems with distances containing -- negative lengths. g = emap getPositive (connGraph cg) gCon = emap (const 1) g `asTypeOf` g test_p p = length p >= len_gCon -- Length-based test && length (esp v w gCon) == len_gCon && sum (map snd p) >= spLength v w g -- Weighting-based test where v = fst (head p) w = fst (last p) len_gCon = length (sp v w gCon) -- ----------------------------------------------------------------------------- -- TransClos test_trc :: (ArbGraph gr, Eq (BaseGraph gr a ())) => Proxy (gr a b) -> UConnected (SimpleGraph gr) a () -> Bool test_trc _ cg = gReach == trc g where g = connGraph cg lns = labNodes g gReach = (`asTypeOf` g) . insEdges [(v,w,()) | (v,_) <- lns, (w,_) <- lns] $ mkGraph lns [] -- ----------------------------------------------------------------------------- -- Utility functions type UConnected gr a b = Connected (Undirected gr) a b
scolobb/fgl
test/Data/Graph/Inductive/Query/Properties.hs
bsd-3-clause
11,776
0
17
3,151
3,401
1,819
1,582
172
1
module Main ( main ) where import Test.Framework (defaultMain) import qualified Crawler.Tests main :: IO () main = defaultMain [ Crawler.Tests.uriHostTests , Crawler.Tests.addTrailingSlashTests , Crawler.Tests.removeWWWTests , Crawler.Tests.sameDomainTests , Crawler.Tests.addRootToRelativeTests , Crawler.Tests.localLinksTests , Crawler.Tests.pageAssetsTests , Crawler.Tests.visitPageTests ]
mavenraven/digital-ocean-crawler
tests/TestSuite.hs
bsd-3-clause
440
0
7
83
91
57
34
14
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-unused-imports#-} module Data.KeyStore.Sections ( SECTIONS(..) , Code(..) , Sections(..) , SectionType(..) , KeyData(..) , KeyDataMode(..) , KeyPredicate , RetrieveDg(..) , initialise , rotate , rotateIfChanged , rotate_ , retrieve , signKeystore , verifyKeystore , noKeys , allKeys , listKeys , keyPrededicate , keyHelp , sectionHelp , secretKeySummary , publicKeySummary , locateKeys , keyName , keyName_ , passwordName , mkSection ) where import Data.KeyStore.IO import Data.KeyStore.KS import qualified Data.Text as T import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.Aeson as A import qualified Data.HashMap.Strict as HM import qualified Data.Vector as V import qualified Data.Map as Map import Data.API.Types import Data.Maybe import Data.List import Data.Char import Data.Ord import Data.String import Data.Monoid import Control.Lens(over) import Control.Applicative import Control.Monad import Text.Printf import System.FilePath import Safe data SECTIONS h s k = SECTIONS class (Bounded a,Enum a,Eq a, Ord a,Show a) => Code a where encode :: a -> String decode :: String -> Maybe a decode s = listToMaybe [ k | k<-[minBound..maxBound], encode k==s ] -- | This class describes the relationship between the host-id, section-id -- and key-id types used to build a hierarchical deployment model for a -- keystore. A minimal instance would have to define hostDeploySection. -- The deploy example program contains a fairly thorough example of this -- class being used to implement a quite realitic deploymrnt scenario. class (Code h, Code s, Code k) => Sections h s k | s -> h, k -> h , h -> s, k -> s , s -> k, h -> k where hostDeploySection :: h -> s -- ^ the deployment section: for a given host, -- the starting section for locating the keys -- during a deployment ('higher'/closer sections -- taking priority) sectionType :: s -> SectionType -- ^ whether the section holds the top key for the -- keystore (i.e., keystore master key), the signing key -- for the keystore or is a normal section containing -- deployment keys superSections :: s -> [s] -- ^ the sections that get a copy of the master -- for this section (making all of its keys -- available to them); N.B., the graph formed by this -- this relationship over the sections must be acyclic keyIsHostIndexed :: k -> Maybe (h->Bool) -- ^ if the key is host-indexed then the predicate -- specifies the hosts that use this key keyIsInSection :: k -> s -> Bool -- ^ specifies which sections a key is resident in getKeyData :: Maybe h -> s -> k -> IO KeyData -- ^ loads the data for a particular key getKeyDataWithMode :: Maybe h -> s -> k -> IO (KeyDataMode,KeyData) -- ^ loads the data for a particular key, returning mode sectionSettings :: Maybe s -> IO Settings -- ^ loads the setting for a given settings describeKey :: k -> String -- ^ describes the key (for the ks help command) describeSection :: s -> String -- ^ describes the section (for the ks help command) sectionPWEnvVar :: s -> EnvVar -- ^ secifies the environment variable containing the -- ^ master password/provate key for for the given section sectionType = const ST_keys superSections = const [] keyIsHostIndexed = const Nothing keyIsInSection = const $ const True getKeyData mb s k = snd <$> getKeyDataWithMode mb s k getKeyDataWithMode Nothing s = get_kd $ encode s getKeyDataWithMode (Just h) _ = get_kd $ encode h sectionSettings = const $ return mempty describeKey k = "The '" ++ encode k ++ "' key." describeSection s = "The '" ++ encode s ++ "' Section." sectionPWEnvVar = EnvVar . T.pack . ("KEY_pw_" ++) . encode -- | Sections are used to hold the top (master) key for the keystore, -- its signing key, or deployment keys data SectionType = ST_top | ST_signing | ST_keys deriving (Show,Eq,Ord) -- | A key is triple containing some (plain-text) identity information for the -- key, some comment text and the secret text to be encrypted. Note that -- the keystore doesn't rely on this information but merely stores it. (They -- can be empty.) The identity field will often be used to storte the key's -- identity within the system that generates and uses it, ofor example. data KeyData = KeyData { kd_identity :: Identity , kd_comment :: Comment , kd_secret :: B.ByteString } deriving (Show,Eq) data KeyDataMode = KDM_static | KDM_random deriving (Bounded,Enum,Eq,Ord,Show) -- | One, many or all of the keys in a store may be rotated at a time. -- we use one of these to specify which keys are to be rotated. type KeyPredicate h s k = Maybe h -> s -> k -> Bool -- | Requests to retrieve a key from the staor can fail for various reasons. type Retrieve a = Either RetrieveDg a -- | This type specifies the reasons that an attempt to access a key from the -- store has failed. This kind of failure suggests an inconsistent model -- and will be raised regardless of which keys have been stored in the store. data RetrieveDg = RDG_key_not_reachable | RDG_no_such_host_key deriving (Show,Eq,Ord) -- | Here we create the store and rotate in a buch of keys. N.B. All of the -- section passwords must be bound in the process environment before calling -- procedure. initialise :: Sections h s k => CtxParams -> KeyPredicate h s k -> IO () initialise cp kp = do stgs <- setSettingsOpt opt__sections_fix True <$> scs kp Nothing newKeyStore (the_keystore cp) stgs ic <- instanceCtx cp mapM_ (mks kp ic) [minBound..maxBound] rotate ic kp map _key_name <$> keys ic >>= mapM_ (keyInfo ic) where scs :: Sections h s k => KeyPredicate h s k -> Maybe s -> IO Settings scs = const sectionSettings mks :: Sections h s k => KeyPredicate h s k -> IC -> s -> IO () mks = const mkSection -- | Rotate in a set of keys specified by the predicate. rotate :: Sections h s k => IC -> KeyPredicate h s k -> IO () rotate ic = rotate_ ic Nothing False -- | Rotate in a set of keys specified by the predicate, rotating each key only -- if it has changed: NB the check is contingent on the secret text being -- accessible; if the secret text is not accessible then the rotation will happen. rotateIfChanged :: Sections h s k => IC -> KeyPredicate h s k -> IO () rotateIfChanged ic = rotate_ ic Nothing True -- | Rotate in a set of keys specified by the predicate with the first argument -- controlling whether to squash duplicate rotations rotate_ :: Sections h s k => IC -> Maybe KeyDataMode -> Bool -> KeyPredicate h s k -> IO () rotate_ ic mb ch kp = reformat ic' $ sequence_ [ rotate' mb ch ic mb_h s k | (mb_h,s,k)<-listKeys kp ] where ic' = kp_RFT kp ic -- | Retrieve the keys for a given host from the store. Note that the whole history for the given key is returned. -- Note also that the secret text may not be present if it is not accessible (depnding upon hwich section passwords -- are correctly bound in the process environment). Note also that the 'Retrieve' diagnostic should not fail if a -- coherent model has been ddefined for 'Sections'. retrieve :: Sections h s k => IC -> h -> k -> IO (Retrieve [Key]) retrieve ic h k = reformat ic' $ either (return . Left) (\nm->Right <$> locate_keys ic' nm) $ keyName h k where ic' = h_RFT h ic -- | Sign the keystore. (Requites the password for the signing section to be correctly -- bound in the environment) signKeystore :: Sections h s k => IC -> SECTIONS h s k -> IO B.ByteString signKeystore ic scn = reformat ic' $ B.readFile (the_keystore $ ic_ctx_params ic) >>= sign_ ic (sgn_nme $ signing_key scn) where ic' = scn_RFT scn ic -- Verify that the signature for a keystore matches the keystore. verifyKeystore :: Sections h s k => IC -> SECTIONS h s k -> B.ByteString -> IO Bool verifyKeystore ic scn sig = reformat ic' $ B.readFile (the_keystore $ ic_ctx_params ic) >>= flip (verify_ ic) sig where ic' = scn_RFT scn ic -- | A predicate specifying all of the keys in the store. noKeys :: KeyPredicate h s k noKeys _ _ _ = False -- | A predicate specifying none of the keys in the keystore. allKeys :: KeyPredicate h s k allKeys _ _ _ = True -- | List all of the keys specified by a KeyPredicate listKeys :: Sections h s k => KeyPredicate h s k -> [(Maybe h,s,k)] listKeys kp = [ trp | trp@(mb_h,s,k)<-host_keys++non_host_keys, kp mb_h s k ] where host_keys = [ (Just h ,s,k) | k<-[minBound..maxBound], Just isp<-[keyIsHostIndexed k], h<-[minBound..maxBound], isp h, let s = key_section h k ] non_host_keys = [ (Nothing,s,k) | k<-[minBound..maxBound], Nothing <-[keyIsHostIndexed k], s<-[minBound..maxBound], keyIsInSection k s ] -- | A utility for specifing a slice of the keys in the store, optionally specifying -- host section and key that should belong to the slice. (If the host is specified then -- the resulting predicate will only include host-indexed keys belonging to the -- given host.) keyPrededicate :: Sections h s k => Maybe h -> Maybe s -> Maybe k -> KeyPredicate h s k keyPrededicate mbh mbs mbk mbh_ s k = h_ok && s_ok && k_ok where h_ok = maybe True (\h->maybe False (h==) mbh_) mbh s_ok = maybe True (s==) mbs k_ok = maybe True (k==) mbk -- Generate some help text for the keys. If no key is specified then they are -- merely listed, otherwise the help for the given key is listed. keyHelp :: Sections h s k => Maybe k -> T.Text keyHelp x@Nothing = T.unlines $ map (T.pack . encode) [minBound..maxBound `asTypeOf` fromJust x ] keyHelp (Just k) = T.unlines $ map T.pack $ (map f $ concat [ [ (,) (encode k) "" ] , [ (,) " hosts:" hln | Just hln <- [mb_hln] ] , [ (,) " sections:" sln | Nothing <- [mb_hln] ] ]) ++ "" : map (" "++) (lines $ describeKey k) ++ [""] where mb_hln = fmt <$> keyIsHostIndexed k sln = fmt $ keyIsInSection k f = uncurry $ printf "%-10s %s" -- Generate some help text for the sectionss. If no section is specified then they are -- merely listed, otherwise the help for the given section is listed. sectionHelp :: Sections h s k => Maybe s -> IO T.Text sectionHelp x@Nothing = return $ T.unlines $ map (T.pack . encode) [minBound..maxBound `asTypeOf` fromJust x ] sectionHelp (Just s) = do stgs <- sectionSettings $ Just s return $ T.unlines $ map T.pack $ (map f $ concat [ [ (,) (encode s) typ ] , [ (,) " p/w env var:" env ] , [ (,) " hosts:" hln ] , [ (,) " super sections:" sln ] , [ (,) " under sections:" uln ] , [ (,) " keys:" kln ] , [ (,) " settings" "" ] ]) ++ fmt_s stgs ++ "" : map (" "++) (lines $ describeSection s) ++ [""] where typ = case sectionType s of ST_top -> "(top)" ST_signing -> "(signing)" ST_keys -> "(keys)" env = "$" ++ T.unpack (_EnvVar $ sectionPWEnvVar s) hln = unwords $ nub [ encode h | h<-[minBound..maxBound], hostDeploySection h==s ] sln = unwords $ map encode $ superSections s uln = unwords $ map encode $ [ s_ | s_<-[minBound..maxBound], s `elem` superSections s_ ] kln = fmt $ flip keyIsInSection s f = uncurry $ printf "%-20s %s" fmt_s stgs = map (" "++) $ lines $ LBS.unpack $ A.encode $ A.Object $ _Settings stgs -- | List a shell script for establishing all of the keys in the environment. NB For this -- to work the password for the top section (or the passwords for all of the sections -- must be bound if the store does not maintain a top key). secretKeySummary :: Sections h s k => IC -> SECTIONS h s k -> IO T.Text secretKeySummary ic scn = reformat ic' $ T.unlines <$> mapM f (sections scn) where f s = do sec <- T.pack . B.unpack <$> (showSecret ic False $ passwordName s) return $ T.concat ["export ",_EnvVar $ sectionPWEnvVar s,"=",sec] ic' = scn_RFT scn ic -- | List a shell script for storing the public signing key for the store. publicKeySummary :: Sections h s k => IC -> SECTIONS h s k -> FilePath -> IO T.Text publicKeySummary ic scn fp = reformat ic' $ f <$> showPublic ic True (sgn_nme $ signing_key scn) where f b = T.pack $ "echo '" ++ B.unpack b ++ "' >" ++ fp ++ "\n" ic' = scn_RFT scn ic -- | List all of the keys that have the given name as their prefix. If the -- generic name of a key is given then it will list the complete history for -- the key, the current (or most recent) entry first. locateKeys :: Sections h s k => IC -> SECTIONS h s k -> Name -> IO [Key] locateKeys ic scn nm = locate_keys ic' nm where ic' = scn_RFT scn ic locate_keys :: Sections h s k => REFORMAT h s k -> Name -> IO [Key] locate_keys ic' nm = reformat ic' $ sortBy (flip $ comparing _key_name) . filter yup <$> keys ic where yup = isp . _key_name isp nm' = nm_s `isPrefixOf` _name nm' nm_s = _name nm ic = _REFORMAT ic' -- | Return the generic name for a given key thst is used by the specified -- host, returning a failure diagnostic if the host does not have such a key -- on the given Section model. keyName :: Sections h s k => h -> k -> Retrieve Name keyName h k = do mb_h <- case keyIsHostIndexed k of Nothing -> return Nothing Just hp | hp h -> return $ Just h | otherwise -> Left RDG_no_such_host_key s <- keySection h k return $ keyName_ mb_h s k -- | Basic function for generating a key name from the host (if it is -- host indexex), section name and key id. keyName_ :: Sections h s k => Maybe h -> s -> k -> Name keyName_ mb_h s k = name' $ encode s ++ "/" ++ encode k ++ hst_sfx ++ "/" where hst_sfx = maybe "" (\h -> "/" ++ encode h) mb_h -- a wrapper on keySection used internally in functional contexts key_section :: Sections h s k => h -> k -> s key_section h k = either oops id $ keySection h k where oops dg = error $ "key_section: " ++ encode h ++ ": " ++ encode k ++ ": " ++ show dg -- | Return the section that a host stores a given key in, returning a -- failure diagnostic if the host does not keep such a key in the given -- 'Section' model. keySection :: Sections h s k => h -> k -> Retrieve s keySection h k = maybe (Left RDG_key_not_reachable) return $ listToMaybe $ filter (keyIsInSection k) $ lower_sections $ hostDeploySection h -- | The name of the key that stores the password for a given sections. passwordName :: Sections h s k => s -> Name passwordName s = name' $ "/pw/" ++ encode s fmt :: Code a => (a->Bool) -> String fmt p = unwords [ encode h | h<-[minBound..maxBound], p h ] rotate' :: Sections h s k => Maybe KeyDataMode -> Bool -> IC -> Maybe h -> s -> k -> IO () rotate' mb ch ic mb_h s k = do (kdm,kd@KeyData{..}) <- getKeyDataWithMode mb_h s k -- if the KeyDataMode is specified but does not match the key's mode then squash the rotation case maybe True (==kdm) mb of True -> do -- iff ch then compare the new value with the old ok <- case ch of True -> do -- if key has not changed, or the secret text is not available -- then squash the rotation mbkds <- map key2KeyData <$> locateKeys ic (mks k) g_nm case mbkds of Just kd':_ | kd==kd' -> return False -- the key has not changes Nothing :_ -> return False -- secret not accessible to compare _ -> return True False -> return True when ok $ do n_nm <- unique_nme ic g_nm putStrLn $ "rotating: " ++ _name n_nm createKey ic n_nm kd_comment kd_identity Nothing $ Just kd_secret False -> return () where g_nm = keyName_ mb_h s k mks :: k -> SECTIONS h s k mks = const SECTIONS lower_sections :: Sections h s k => s -> [s] lower_sections s0 = s0 : concat [ s:lower_sections s | s<-[minBound..maxBound], s0 `elem` superSections s ] mkSection :: Sections h s k => IC -> s -> IO () mkSection ic s = do mk_section ic s case sectionType s of ST_top -> return () ST_signing -> add_signing ic s ST_keys -> return () mk_section :: Sections h s k => IC -> s -> IO () mk_section ic s = do add_password ic s add_save_key ic s add_trigger ic s mapM_ (backup_password ic s) $ superSections s add_signing :: Sections h s k => IC -> s -> IO () add_signing ic s = createRSAKeyPair ic (sgn_nme s) cmt "" [pw_sg] where cmt = Comment $ T.pack $ "signing key" pw_sg = safeguard [passwordName s] add_password :: Sections h s k => IC -> s -> IO () add_password ic s = createKey ic nm cmt ide (Just ev) Nothing where cmt = Comment $ T.pack $ "password for " ++ encode s ide = "" ev = sectionPWEnvVar s nm = passwordName s add_save_key :: Sections h s k => IC -> s -> IO () add_save_key ic s = createRSAKeyPair ic nm cmt ide [pw_sg] where nm = sve_nme s cmt = Comment $ T.pack $ "save key for " ++ encode s ide = "" pw_sg = safeguard [passwordName s] add_trigger :: Sections h s k => IC -> s -> IO () add_trigger ic s = do stgs <- (bu_settings s <>) <$> sectionSettings (Just s) addTrigger' ic tid pat stgs where tid = TriggerID $ T.pack $ encode s pat = scn_pattern s bu_settings :: Sections h s k => s -> Settings bu_settings s = Settings $ HM.fromList [ ("backup.keys" , A.Array $ V.singleton $ A.String $ T.pack $ _name $ sve_nme s ) ] signing_key :: Sections h s k => SECTIONS h s k -> s signing_key _ = maybe oops id $ listToMaybe [ s_ | s_<-[minBound..maxBound], sectionType s_ == ST_signing ] where oops = error "signing_key: there is no signing key!" sections :: Sections h s k => SECTIONS h s k -> [s] sections _ = [minBound..maxBound] backup_password :: Sections h s k => IC -> s -> s -> IO () backup_password ic s sv_s = secureKey ic (passwordName s) $ safeguard [sve_nme sv_s] sgn_nme :: Sections h s k => s -> Name sgn_nme s = name' $ encode s ++ "/keystore_signing_key" sve_nme :: Sections h s k => s -> Name sve_nme s = name' $ "/save/" ++ encode s scn_pattern :: Sections h s k => s -> Pattern scn_pattern s = pattern $ "^" ++ encode s ++ "/.*" unique_nme :: IC -> Name -> IO Name unique_nme ic nm = do nms <- filter isp . map _key_name <$> keys ic return $ unique_nme' nms nm where isp nm' = _name nm `isPrefixOf` _name nm' unique_nme' :: [Name] -> Name -> Name unique_nme' nms nm0 = headNote "unique_name'" c_nms where c_nms = [ nm | i<-[length nms+1..], let nm=nname i nm0, nm `notElem` nms ] nname :: Int -> Name -> Name nname i nm_ = name' $ _name nm_ ++ printf "%03d" i the_keystore :: CtxParams -> FilePath the_keystore = maybe "keystore.json" id . cp_store get_kd :: Sections h s k => String -> k -> IO (KeyDataMode,KeyData) get_kd sd k = do ide <- B.readFile $ fp "_id" cmt <- B.readFile $ fp "_cmt" sec <- B.readFile $ fp "" return ( KDM_static , KeyData { kd_identity = Identity $ T.pack $ B.unpack ide , kd_comment = Comment $ T.pack $ B.unpack cmt , kd_secret = sec } ) where fp sfx = sd </> encode k ++ sfx -------------------------------------------------------------------------------- -- -- Reformating the KeyStore Names to Allow Prefixes (#3) -- -------------------------------------------------------------------------------- reformat :: Sections h s k => REFORMAT h s k -> IO a -> IO a reformat rft@(REFORMAT ic) p = reformat_ic (encoding rft) ic >> p -- Proxy city! data REFORMAT h s k = REFORMAT { _REFORMAT :: IC } data CODE a = CODE scn_RFT :: SECTIONS h s k -> IC -> REFORMAT h s k kp_RFT :: KeyPredicate h s k -> IC -> REFORMAT h s k h_RFT :: h -> IC -> REFORMAT h s k scn_RFT _ ic = REFORMAT ic kp_RFT _ ic = REFORMAT ic h_RFT _ ic = REFORMAT ic reformat_ic :: Encoding -> IC -> IO () reformat_ic enc ic = do (ctx,st) <- getCtxState ic putCtxState ic ctx $ st { st_keystore = reformat_keystore enc $ st_keystore st } reformat_keystore :: Encoding -> KeyStore -> KeyStore reformat_keystore enc ks = case getSettingsOpt opt__sections_fix $ _cfg_settings $ _ks_config ks of True -> ks False -> over ks_config (reformat_config enc) $ over ks_keymap (reformat_key_map enc) ks reformat_config :: Encoding -> Configuration -> Configuration reformat_config enc = over cfg_settings (setSettingsOpt opt__sections_fix True) . over cfg_settings (reformat_settings enc) . over cfg_triggers (reformat_triggers enc) reformat_triggers :: Encoding -> TriggerMap -> TriggerMap reformat_triggers enc = Map.map $ over trg_pattern (reformat_pattern enc) . over trg_settings (reformat_settings enc) reformat_settings :: Encoding -> Settings -> Settings reformat_settings enc stgs = case getSettingsOpt' opt__backup_keys stgs of Nothing -> stgs Just nms -> setSettingsOpt opt__backup_keys (map (reformat_name enc) nms) stgs reformat_pattern :: Encoding -> Pattern -> Pattern reformat_pattern enc pat = maybe oops id $ run_munch (m_pattern enc) $ _pat_string pat where oops = error $ "reformat_pattern: bad pattern format: " ++ _pat_string pat reformat_key_map :: Encoding -> KeyMap -> KeyMap reformat_key_map enc km = Map.fromList [ (reformat_name enc nm,r_ky ky) | (nm,ky)<-Map.toList km ] where r_ky = over key_name (reformat_name enc) . over key_secret_copies (reformat_ecm enc) reformat_ecm :: Encoding -> EncrypedCopyMap -> EncrypedCopyMap reformat_ecm enc ecm = Map.fromList [ (reformat_sg enc sg,r_ec ec) | (sg,ec)<-Map.toList ecm ] where r_ec = over ec_safeguard (reformat_sg enc) reformat_sg :: Encoding -> Safeguard -> Safeguard reformat_sg enc = safeguard . map (reformat_name enc) . safeguardKeys reformat_name :: Encoding -> Name -> Name reformat_name enc nm = maybe oops id $ run_munch (m_name enc) $ _name nm where oops = error $ "reformat_name: bad name format: " ++ _name nm m_pattern :: Encoding -> Munch Pattern m_pattern enc = do munch_ "^" s <- enc_s enc munch_ "_.*" return $ fromString $ "^" ++ s ++ "/.*" m_name, m_save, m_pw, m_section :: Encoding -> Munch Name m_name enc = m_save enc <|> m_pw enc <|> m_section enc m_save enc = do munch_ "save_" s <- enc_s enc return $ name' $ "/save/" ++ s m_pw enc = do munch_ "pw_" s <- enc_s enc return $ name' $ "/pw/" ++ s m_section enc = do s <- enc_s enc m_section_signing enc s <|> m_section_key enc s m_section_key, m_section_signing :: Encoding -> String -> Munch Name m_section_signing _ s = do munch_ "_keystore_signing_key" return $ name' $ s ++ "/keystore_signing_key" m_section_key enc s = do munch_ "_" k <- enc_k enc m_section_key_host enc s k <|> m_section_key_vrn enc s k m_section_key_vrn, m_section_key_host :: Encoding -> String -> String -> Munch Name m_section_key_vrn _ s k = do munch_ "_" v <- munch_vrn return $ name' $ s ++"/" ++ k ++ "/" ++ v m_section_key_host enc s k = do munch_ "_" h <- enc_h enc munch_ "_" v <- munch_vrn return $ name' $ s ++"/" ++ k ++ "/" ++ h ++ "/" ++ v munch_vrn :: Munch String munch_vrn = do c1 <- munch1 isDigit c2 <- munch1 isDigit c3 <- munch1 isDigit return [c1,c2,c3] -- Capturing the host, section and key encodings in a nice convenient -- monotype that we can pass around. data Encoding = Encoding { enc_h, enc_s, enc_k :: Munch String } encoding :: Sections h s k => REFORMAT h s k -> Encoding encoding rft = Encoding { enc_h = code_m $ host_c rft , enc_s = code_m $ section_c rft , enc_k = code_m $ key_c rft } where host_c :: Sections h s k => REFORMAT h s k -> CODE h host_c _ = CODE section_c :: Sections h s k => REFORMAT h s k -> CODE s section_c _ = CODE key_c :: Sections h s k => REFORMAT h s k -> CODE k key_c _ = CODE code_m :: Code a => CODE a -> Munch String code_m c = foldr (<|>) empty $ [ munch $ encode x | x<-bds c ] where bds :: Code a => CODE a -> [a] bds _ = [minBound..maxBound] -- our Munch Monad newtype Munch a = Munch { _Munch :: String -> Maybe (a,String) } instance Functor Munch where fmap f m = m >>= \x -> return $ f x instance Applicative Munch where pure = return (<*>) = ap instance Alternative Munch where empty = Munch $ const Nothing (<|>) x y = Munch $ \s -> _Munch x s <|> _Munch y s instance Monad Munch where return x = Munch $ \s -> Just (x,s) (>>=) m f = Munch $ \s -> _Munch m s >>= \(x,s') -> _Munch (f x) s' run_munch :: Munch a -> String -> Maybe a run_munch (Munch f) str = case f str of Just (x,"") -> Just x _ -> Nothing munch1 :: (Char->Bool) -> Munch Char munch1 p = Munch $ \str -> case str of c:t | p c -> Just (c,t) _ -> Nothing munch_ :: String -> Munch () munch_ s = const () <$> munch s munch :: String -> Munch String munch str_p = Munch $ \str -> case str_p `isPrefixOf` str of True -> Just (str_p,drop (length str_p) str) False -> Nothing -------------------------------------------------------------------------------- key2KeyData :: Key -> Maybe KeyData key2KeyData Key{..} = f <$> _key_clear_text where f (ClearText(Binary bs)) = KeyData { kd_identity = _key_identity , kd_comment = _key_comment , kd_secret = bs } name' :: String -> Name name' = either (error.show) id . name
cdornan/keystore
src/Data/KeyStore/Sections.hs
bsd-3-clause
27,172
45
24
7,567
8,039
4,077
3,962
476
5
{-# LANGUAGE OverloadedStrings #-} module Main where import Fragnix.ModuleDeclarations ( parse,moduleDeclarationsWithEnvironment,moduleSymbols) import Fragnix.Declaration (writeDeclarations) import Fragnix.DeclarationLocalSlices (declarationLocalSlices) import Fragnix.HashLocalSlices (hashLocalSlices,replaceSliceID) import Fragnix.Slice (Slice(Slice),writeSlice) import Fragnix.LocalSlice (LocalSliceID(LocalSliceID)) import Fragnix.Environment (loadEnvironment) import Fragnix.SliceSymbols (updateEnvironment,lookupLocalIDs) import Fragnix.SliceCompiler (writeSlicesModules,invokeGHC) import Fragnix.Paths (slicesPath,builtinEnvironmentPath,compilationunitsPath,declarationsPath) import Test.Tasty (testGroup,TestTree) import Test.Tasty.Golden (goldenVsFileDiff) import Test.Tasty.Golden.Manage (defaultMain) import Language.Haskell.Exts (prettyPrint) import Language.Haskell.Names (symbolName) import Data.Text as Text (append) import Control.Monad (forM_,forM,when) import qualified Data.Map as Map (toList) import Data.Foldable (toList) import System.Exit (ExitCode(ExitSuccess,ExitFailure)) import System.Directory (getDirectoryContents,removeDirectoryRecursive,doesDirectoryExist) import System.FilePath ((</>),takeExtension) main :: IO () main = do packagenames <- getDirectoryContents examplePackageFolder >>= return . filter (not . (=='.') . head) quicknames <- getDirectoryContents exampleQuickFolder >>= return . filter (not . (=='.') . head) defaultMain (testGroup "tests" [ testGroup "packages" (map (testCase examplePackageFolder) packagenames), testGroup "quick" (map (testCase exampleQuickFolder) quicknames)]) examplePackageFolder :: FilePath examplePackageFolder = "tests/packages" exampleQuickFolder :: FilePath exampleQuickFolder = "tests/quick" testCase :: FilePath -> String -> TestTree testCase folder testname = goldenVsFileDiff testname (\ref new -> ["diff", "-u", ref, new]) (folder </> testname </> "golden") (folder </> testname </> "out") (testModules (folder </> testname)) testModules :: FilePath -> IO () testModules folder = do modulefilenames <- getDirectoryContents folder >>= return . filter (\filename -> takeExtension filename == ".hs") let modulepaths = map (\filename -> folder </> filename) modulefilenames builtinEnvironment <- loadEnvironment builtinEnvironmentPath modules <- forM modulepaths parse let declarations = moduleDeclarationsWithEnvironment builtinEnvironment modules writeDeclarations declarationsPath declarations let (localSlices, symbolLocalIDs) = declarationLocalSlices declarations let (localSliceIDMap, slices) = hashLocalSlices localSlices let symbolSliceIDs = lookupLocalIDs symbolLocalIDs localSliceIDMap forM_ slices (\slice -> writeSlice slicesPath slice) let environment = updateEnvironment symbolSliceIDs (moduleSymbols builtinEnvironment modules) moduleSymbolResults = do (moduleName,symbols) <- Map.toList environment return (prettyPrint moduleName ++ " " ++ unwords (map (prettyPrint . symbolName) symbols)) sliceModuleDirectoryExists <- doesDirectoryExist compilationunitsPath when sliceModuleDirectoryExists (removeDirectoryRecursive compilationunitsPath) let sliceIDs = [sliceID | Slice sliceID _ _ _ _ <- toList slices] writeSlicesModules sliceIDs exitCodes <- forM sliceIDs (\sliceID -> do invokeGHC [sliceID]) let successes = length [() | ExitSuccess <- exitCodes] failures = length [() | ExitFailure _ <- exitCodes] let localSlices = map (replaceSliceID (\sliceID -> LocalSliceID (Text.append "T" sliceID))) slices let (_, rehashedLocalSlices) = hashLocalSlices localSlices let rehashedSlicesEqual = rehashedLocalSlices == slices let result = unlines ([ "Successes: " ++ show successes, "Failures: " ++ show failures, "Rehashing: " ++ show rehashedSlicesEqual] ++ moduleSymbolResults) writeFile (folder </> "out") result
phischu/fragnix
tests-src/Main.hs
bsd-3-clause
4,102
0
19
681
1,115
588
527
80
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.GA.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Lang import Duckling.Resolve import Duckling.Time.Corpus import Duckling.TimeGrain.Types hiding (add) import Duckling.Testing.Types hiding (examples) corpus :: Corpus corpus = (testContext {lang = GA}, allExamples) allExamples :: [Example] allExamples = concat [ examples (datetime (2013, 2, 12, 4, 30, 0) Second) [ "anois" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "inniu" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "inné" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "arú inné" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "amárach" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "arú amárach" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "dé luain" , "an luan" , "an luan seo" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "an luan seo chugainn" , "an luan seo atá ag teacht" , "dé luain seo chugainn" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "18/2/2013" ] ]
rfranek/duckling
Duckling/Time/GA/Corpus.hs
bsd-3-clause
1,690
0
10
555
453
277
176
36
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>Teknologi deteksi | Ekstensi ZAP</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Isi</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/wappalyzer/src/main/javahelp/org/zaproxy/zap/extension/wappalyzer/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
974
80
66
160
415
210
205
-1
-1
{-# LANGUAGE BangPatterns #-} ------------------------------------------------------------------------------ -- | -- Module : Blaze.ByteString.Builder.Enumerator -- Copyright : (c) 2010 Simon Meier -- License : BSD3 -- -- Maintainer : Simon Meier <[email protected]> -- Stability : Experimental -- Portability : Tested on GHC only -- -- Infrastructure and enumeratees for the incremental execution of builders and -- passing on of the filled chunks as bytestrings to an inner iteratee. -- -- Note that the @Buffer@ code is likely to move/change in order to -- reconciliate it with the rest of the blaze-builder library. -- ------------------------------------------------------------------------------ module Blaze.ByteString.Builder.Enumerator ( -- * Buffers Buffer -- ** Status information , freeSize , sliceSize , bufferSize -- ** Creation and modification , allocBuffer , reuseBuffer , nextSlice -- ** Conversion to bytestings , unsafeFreezeBuffer , unsafeFreezeNonEmptyBuffer -- * Buffer allocation strategies , BufferAllocStrategy , allNewBuffersStrategy , reuseBufferStrategy -- * Enumeratees from builders to bytestrings , builderToByteString , unsafeBuilderToByteString , builderToByteStringWith ) where import qualified Data.ByteString as S import Data.Enumerator hiding (map) import Data.Monoid import Control.Monad.IO.Class import Blaze.ByteString.Builder.Internal import Blaze.ByteString.Builder.Internal.Types import Blaze.ByteString.Builder.Internal.Buffer ------------------------------------------------------------------------------ -- Enumeratees for converting builders incrementally to bytestrings ------------------------------------------------------------------------------ -- Simple default instances --------------------------- -- | Incrementally execute builders and pass on the filled chunks as -- bytestrings. builderToByteString :: MonadIO m => Enumeratee Builder S.ByteString m a builderToByteString = builderToByteStringWith (allNewBuffersStrategy defaultBufferSize) -- | Incrementally execute builders on the given buffer and pass on the filled -- chunks as bytestrings. Note that, if the given buffer is too small for the -- execution of a build step, a larger one will be allocated. -- -- WARNING: This enumeratee yields bytestrings that are NOT -- referentially transparent. Their content will be overwritten as soon -- as control is returned from the inner iteratee! unsafeBuilderToByteString :: MonadIO m => IO Buffer -- action yielding the inital buffer. -> Enumeratee Builder S.ByteString m a unsafeBuilderToByteString = builderToByteStringWith . reuseBufferStrategy -- | An enumeratee that incrementally executes builders and passes on the -- filled chunks as bytestrings to an inner iteratee. -- -- INV: All bytestrings passed to the inner iteratee are non-empty. -- -- based on the enumeratee code by Michael Snoyman <[email protected]> -- builderToByteStringWith :: MonadIO m => BufferAllocStrategy -> Enumeratee Builder S.ByteString m a builderToByteStringWith (ioBuf0, nextBuf) step0 = do loop ioBuf0 step0 where loop ioBuf = checkDone $ continue . step ioBuf step :: MonadIO m => IO (Buffer) -> (Stream S.ByteString -> Iteratee S.ByteString m b) -> Stream Builder -> Iteratee Builder m (Step S.ByteString m b) step ioBuf k EOF = do buf <- liftIO ioBuf case unsafeFreezeNonEmptyBuffer buf of Nothing -> yield (Continue k) EOF Just bs -> k (Chunks [bs]) >>== flip yield EOF step ioBuf k0 (Chunks xs) = go (unBuilder (mconcat xs) (buildStep finalStep)) ioBuf k0 where finalStep !(BufRange pf _) = return $ Done pf () go bStep ioBuf k = do !buf <- liftIO ioBuf signal <- liftIO (execBuildStep bStep buf) case signal of Done op' _ -> continue $ step (return (updateEndOfSlice buf op')) k BufferFull minSize op' bStep' -> do let buf' = updateEndOfSlice buf op' {-# INLINE cont #-} cont k' = do -- sequencing the computation of the next buffer -- construction here ensures that the reference to the -- foreign pointer `fp` is lost as soon as possible. ioBuf' <- liftIO $ nextBuf minSize buf' go bStep' ioBuf' k' case unsafeFreezeNonEmptyBuffer buf' of Nothing -> cont k Just bs -> k (Chunks [bs]) >>== \step' -> case step' of Continue k' -> cont k' _ -> return step' -- FIXME: Check that we don't loose any input here! InsertByteString op' bs bStep' -> do let buf' = updateEndOfSlice buf op' bsk = maybe id (:) $ unsafeFreezeNonEmptyBuffer buf' k (Chunks (bsk [bs])) >>== \step' -> case step' of Continue k' -> do ioBuf' <- liftIO $ nextBuf 1 buf' go bStep' ioBuf' k' _ -> return step' -- FIXME: Check that we don't loose any input here! {- Old testing code: main :: IO () main = main1 >> main2 >> main3 main1 :: IO () main1 = do builder <- fromLazyByteString `fmap` L.readFile "test-input" withBinaryFile "test-output1" WriteMode $ \h -> run_ (go h builder) where go h builder = enumList 1 [builder] $$ joinI $ blaze $$ iterHandle h main2 :: IO () main2 = withBinaryFile "test-output2" WriteMode $ \h -> run_ (go h) where go h = enumFile "test-input" $$ joinI $ E.map fromByteString $$ joinI $ blaze $$ iterHandle h main3 :: IO () main3 = withBinaryFile "test-output3" WriteMode $ \h -> run_ (go h) where go h = enumList 1 (map S.singleton $ concat $ replicate 1000 [65..90]) $$ joinI $ E.map (mconcat . map fromWord8 . S.unpack) $$ joinI $ blaze $$ iterHandle h -}
sol/blaze-builder-enumerator
Blaze/ByteString/Builder/Enumerator.hs
bsd-3-clause
6,351
0
23
1,829
878
463
415
76
8
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Ros.Nav_msgs.OccupancyGrid where import qualified Prelude as P import Prelude ((.), (+), (*)) import qualified Data.Typeable as T import Control.Applicative import Ros.Internal.RosBinary import Ros.Internal.Msg.MsgInfo import qualified GHC.Generics as G import qualified Data.Default.Generics as D import Ros.Internal.Msg.HeaderSupport import qualified Data.Int as Int import qualified Data.Vector.Storable as V import qualified Ros.Nav_msgs.MapMetaData as MapMetaData import qualified Ros.Std_msgs.Header as Header import Lens.Family.TH (makeLenses) import Lens.Family (view, set) data OccupancyGrid = OccupancyGrid { _header :: Header.Header , _info :: MapMetaData.MapMetaData , __data :: V.Vector Int.Int8 } deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic) $(makeLenses ''OccupancyGrid) instance RosBinary OccupancyGrid where put obj' = put (_header obj') *> put (_info obj') *> put (__data obj') get = OccupancyGrid <$> get <*> get <*> get putMsg = putStampedMsg instance HasHeader OccupancyGrid where getSequence = view (header . Header.seq) getFrame = view (header . Header.frame_id) getStamp = view (header . Header.stamp) setSequence = set (header . Header.seq) instance MsgInfo OccupancyGrid where sourceMD5 _ = "3381f2d731d4076ec5c71b0759edbe4e" msgTypeName _ = "nav_msgs/OccupancyGrid" instance D.Default OccupancyGrid
acowley/roshask
msgs/Nav_msgs/Ros/Nav_msgs/OccupancyGrid.hs
bsd-3-clause
1,614
1
10
315
411
243
168
38
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.GenerateCredentialReport -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Generates a credential report for the AWS account. For more information -- about the credential report, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html Getting Credential Reports> in the /Using IAM/ -- guide. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateCredentialReport.html> module Network.AWS.IAM.GenerateCredentialReport ( -- * Request GenerateCredentialReport -- ** Request constructor , generateCredentialReport -- * Response , GenerateCredentialReportResponse -- ** Response constructor , generateCredentialReportResponse -- ** Response lenses , gcrrDescription , gcrrState ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.IAM.Types import qualified GHC.Exts data GenerateCredentialReport = GenerateCredentialReport deriving (Eq, Ord, Read, Show, Generic) -- | 'GenerateCredentialReport' constructor. generateCredentialReport :: GenerateCredentialReport generateCredentialReport = GenerateCredentialReport data GenerateCredentialReportResponse = GenerateCredentialReportResponse { _gcrrDescription :: Maybe Text , _gcrrState :: Maybe ReportStateType } deriving (Eq, Read, Show) -- | 'GenerateCredentialReportResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'gcrrDescription' @::@ 'Maybe' 'Text' -- -- * 'gcrrState' @::@ 'Maybe' 'ReportStateType' -- generateCredentialReportResponse :: GenerateCredentialReportResponse generateCredentialReportResponse = GenerateCredentialReportResponse { _gcrrState = Nothing , _gcrrDescription = Nothing } -- | Information about the credential report. gcrrDescription :: Lens' GenerateCredentialReportResponse (Maybe Text) gcrrDescription = lens _gcrrDescription (\s a -> s { _gcrrDescription = a }) -- | Information about the state of the credential report. gcrrState :: Lens' GenerateCredentialReportResponse (Maybe ReportStateType) gcrrState = lens _gcrrState (\s a -> s { _gcrrState = a }) instance ToPath GenerateCredentialReport where toPath = const "/" instance ToQuery GenerateCredentialReport where toQuery = const mempty instance ToHeaders GenerateCredentialReport instance AWSRequest GenerateCredentialReport where type Sv GenerateCredentialReport = IAM type Rs GenerateCredentialReport = GenerateCredentialReportResponse request = post "GenerateCredentialReport" response = xmlResponse instance FromXML GenerateCredentialReportResponse where parseXML = withElement "GenerateCredentialReportResult" $ \x -> GenerateCredentialReportResponse <$> x .@? "Description" <*> x .@? "State"
romanb/amazonka
amazonka-iam/gen/Network/AWS/IAM/GenerateCredentialReport.hs
mpl-2.0
3,769
0
11
711
409
248
161
52
1
module Unifier.Restricted ( Unifier.Restricted.unify , Unifier.Restricted.subsumes , runErrorT2 , WithEnv ) where import Unifier.Unifier import Control.Unification import Control.Unification.IntVar import Control.Unification.Types import Control.Monad.Except type Failure = UFailure T IntVar type Type = UTerm T IntVar type WithEnv a = IntBindingT T a type WithExcept = ExceptT Failure unify :: Monad a => Type -> Type -> WithExcept (WithEnv a) Type unify = Control.Unification.unify subsumes :: Monad a => Type -> Type -> WithExcept (WithEnv a) Bool subsumes = Control.Unification.subsumes runErrorT2 :: WithExcept m a -> m (Either Failure a) runErrorT2 = runExceptT
kayuri/HNC
Unifier/Restricted.hs
lgpl-3.0
680
4
10
103
209
116
93
20
1
module Stream where import Prelude hiding (map,(!!)) import Nat data Stream a = Cons a (Stream a) map :: (a -> b) -> Stream a -> Stream b map f (Cons a s) = Cons (f a) (map f s) (!!) :: Stream a -> Nat -> a (Cons a _) !! Zero = a (Cons _ s) !! (Succ n) = s !! n nats :: Stream Nat nats = Zero `Cons` map Succ nats
beni55/hermit
examples/fib-stream/Stream.hs
bsd-2-clause
323
0
8
85
192
102
90
11
1
import StackTest import Control.Monad import System.Directory import System.FilePath {-# ANN module "HLint: ignore Use unless" #-} main :: IO () main = if isWindows then logInfo "Disabled on Windows (see https://github.com/commercialhaskell/stack/issues/1337#issuecomment-166118678)" else do stack ["new", "1234a-4b-b4-abc-12b34"] doesExist "./1234a-4b-b4-abc-12b34/stack.yaml" stackErr ["new", "1234-abc"] doesNotExist "./1234-abc/stack.yaml" doesNotExist "./1234-abc" stackErr ["new", "1-abc"] stackErr ["new", "44444444444444"] stackErr ["new", "abc-1"] stackErr ["new", "444-ば日本-4本"] unless isMacOSX $ stack ["new", "ば日本-4本"] stack ["new", "אבהץש"] stack ["new", "ΔΘΩϬ"] doesExist "./ΔΘΩϬ/stack.yaml" doesExist "./ΔΘΩϬ/ΔΘΩϬ.cabal"
anton-dessiatov/stack
test/integration/tests/1336-1337-new-package-names/Main.hs
bsd-3-clause
961
0
10
262
191
93
98
24
2
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="en-GB"> <title>All In One Notes Add-On</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
denniskniep/zap-extensions
addOns/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help/helpset.hs
apache-2.0
981
81
68
172
427
218
209
-1
-1
{-# LANGUAGE NoImplicitPrelude, TypeInType, PolyKinds, DataKinds, ScopedTypeVariables, TypeFamilies, UndecidableInstances #-} module T15666 where import Data.Kind(Type) data PolyType k (t :: k) type Wrap (t :: k) = PolyType k t type Unwrap pt = (GetType pt :: GetKind pt) type family GetKind (pt :: Type) :: Type where GetKind (PolyType k t) = k type family GetType (pt :: Type) :: k where GetType (PolyType k t) = t data Composite :: a -> b -> Type type family RecursiveWrap expr where RecursiveWrap (Composite a b) = Wrap (Composite (Unwrap (RecursiveWrap a)) (Unwrap (RecursiveWrap b))) RecursiveWrap x = Wrap x
sdiehl/ghc
testsuite/tests/dependent/should_compile/T15666.hs
bsd-3-clause
645
11
11
130
222
122
100
-1
-1
module MoveDef.Demote where toplevel :: Integer -> Integer toplevel x = c * x -- c,d :: Integer c = 7 d = 9
RefactoringTools/HaRe
test/testdata/MoveDef/Demote.hs
bsd-3-clause
112
0
5
28
38
22
16
5
1
{-# LANGUAGE FlexibleInstances #-} -- | Monadic front-end to Text.PrettyPrint module Language.Haskell.TH.PprLib ( -- * The document type Doc, -- Abstract, instance of Show PprM, -- * Primitive Documents empty, semi, comma, colon, dcolon, space, equals, arrow, lparen, rparen, lbrack, rbrack, lbrace, rbrace, -- * Converting values into documents text, char, ptext, int, integer, float, double, rational, -- * Wrapping documents in delimiters parens, brackets, braces, quotes, doubleQuotes, -- * Combining documents (<>), (<+>), hcat, hsep, ($$), ($+$), vcat, sep, cat, fsep, fcat, nest, hang, punctuate, -- * Predicates on documents isEmpty, to_HPJ_Doc, pprName, pprName' ) where import Language.Haskell.TH.Syntax (Name(..), showName', NameFlavour(..), NameIs(..)) import qualified Text.PrettyPrint as HPJ import Control.Monad (liftM, liftM2, ap) import Language.Haskell.TH.Lib.Map ( Map ) import qualified Language.Haskell.TH.Lib.Map as Map ( lookup, insert, empty ) infixl 6 <> infixl 6 <+> infixl 5 $$, $+$ -- --------------------------------------------------------------------------- -- The interface -- The primitive Doc values instance Show Doc where show d = HPJ.render (to_HPJ_Doc d) isEmpty :: Doc -> PprM Bool; -- ^ Returns 'True' if the document is empty empty :: Doc; -- ^ An empty document semi :: Doc; -- ^ A ';' character comma :: Doc; -- ^ A ',' character colon :: Doc; -- ^ A ':' character dcolon :: Doc; -- ^ A "::" string space :: Doc; -- ^ A space character equals :: Doc; -- ^ A '=' character arrow :: Doc; -- ^ A "->" string lparen :: Doc; -- ^ A '(' character rparen :: Doc; -- ^ A ')' character lbrack :: Doc; -- ^ A '[' character rbrack :: Doc; -- ^ A ']' character lbrace :: Doc; -- ^ A '{' character rbrace :: Doc; -- ^ A '}' character text :: String -> Doc ptext :: String -> Doc char :: Char -> Doc int :: Int -> Doc integer :: Integer -> Doc float :: Float -> Doc double :: Double -> Doc rational :: Rational -> Doc parens :: Doc -> Doc; -- ^ Wrap document in @(...)@ brackets :: Doc -> Doc; -- ^ Wrap document in @[...]@ braces :: Doc -> Doc; -- ^ Wrap document in @{...}@ quotes :: Doc -> Doc; -- ^ Wrap document in @\'...\'@ doubleQuotes :: Doc -> Doc; -- ^ Wrap document in @\"...\"@ -- Combining @Doc@ values (<>) :: Doc -> Doc -> Doc; -- ^Beside hcat :: [Doc] -> Doc; -- ^List version of '<>' (<+>) :: Doc -> Doc -> Doc; -- ^Beside, separated by space hsep :: [Doc] -> Doc; -- ^List version of '<+>' ($$) :: Doc -> Doc -> Doc; -- ^Above; if there is no -- overlap it \"dovetails\" the two ($+$) :: Doc -> Doc -> Doc; -- ^Above, without dovetailing. vcat :: [Doc] -> Doc; -- ^List version of '$$' cat :: [Doc] -> Doc; -- ^ Either hcat or vcat sep :: [Doc] -> Doc; -- ^ Either hsep or vcat fcat :: [Doc] -> Doc; -- ^ \"Paragraph fill\" version of cat fsep :: [Doc] -> Doc; -- ^ \"Paragraph fill\" version of sep nest :: Int -> Doc -> Doc; -- ^ Nested -- GHC-specific ones. hang :: Doc -> Int -> Doc -> Doc; -- ^ @hang d1 n d2 = sep [d1, nest n d2]@ punctuate :: Doc -> [Doc] -> [Doc] -- ^ @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@ -- --------------------------------------------------------------------------- -- The "implementation" type State = (Map Name Name, Int) data PprM a = PprM { runPprM :: State -> (a, State) } pprName :: Name -> Doc pprName = pprName' Alone pprName' :: NameIs -> Name -> Doc pprName' ni n@(Name o (NameU _)) = PprM $ \s@(fm, i) -> let (n', s') = case Map.lookup n fm of Just d -> (d, s) Nothing -> let n'' = Name o (NameU i) in (n'', (Map.insert n n'' fm, i + 1)) in (HPJ.text $ showName' ni n', s') pprName' ni n = text $ showName' ni n {- instance Show Name where show (Name occ (NameU u)) = occString occ ++ "_" ++ show (I# u) show (Name occ NameS) = occString occ show (Name occ (NameG ns m)) = modString m ++ "." ++ occString occ data Name = Name OccName NameFlavour data NameFlavour | NameU Int# -- A unique local name -} to_HPJ_Doc :: Doc -> HPJ.Doc to_HPJ_Doc d = fst $ runPprM d (Map.empty, 0) instance Functor PprM where fmap = liftM instance Applicative PprM where pure x = PprM $ \s -> (x, s) (<*>) = ap instance Monad PprM where m >>= k = PprM $ \s -> let (x, s') = runPprM m s in runPprM (k x) s' type Doc = PprM HPJ.Doc -- The primitive Doc values isEmpty = liftM HPJ.isEmpty empty = return HPJ.empty semi = return HPJ.semi comma = return HPJ.comma colon = return HPJ.colon dcolon = return $ HPJ.text "::" space = return HPJ.space equals = return HPJ.equals arrow = return $ HPJ.text "->" lparen = return HPJ.lparen rparen = return HPJ.rparen lbrack = return HPJ.lbrack rbrack = return HPJ.rbrack lbrace = return HPJ.lbrace rbrace = return HPJ.rbrace text = return . HPJ.text ptext = return . HPJ.ptext char = return . HPJ.char int = return . HPJ.int integer = return . HPJ.integer float = return . HPJ.float double = return . HPJ.double rational = return . HPJ.rational parens = liftM HPJ.parens brackets = liftM HPJ.brackets braces = liftM HPJ.braces quotes = liftM HPJ.quotes doubleQuotes = liftM HPJ.doubleQuotes -- Combining @Doc@ values (<>) = liftM2 (HPJ.<>) hcat = liftM HPJ.hcat . sequence (<+>) = liftM2 (HPJ.<+>) hsep = liftM HPJ.hsep . sequence ($$) = liftM2 (HPJ.$$) ($+$) = liftM2 (HPJ.$+$) vcat = liftM HPJ.vcat . sequence cat = liftM HPJ.cat . sequence sep = liftM HPJ.sep . sequence fcat = liftM HPJ.fcat . sequence fsep = liftM HPJ.fsep . sequence nest n = liftM (HPJ.nest n) hang d1 n d2 = do d1' <- d1 d2' <- d2 return (HPJ.hang d1' n d2') -- punctuate uses the same definition as Text.PrettyPrint punctuate _ [] = [] punctuate p (d:ds) = go d ds where go d' [] = [d'] go d' (e:es) = (d' <> p) : go e es
olsner/ghc
libraries/template-haskell/Language/Haskell/TH/PprLib.hs
bsd-3-clause
6,652
0
20
2,067
1,790
1,038
752
142
2
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ko-KR"> <title>Selenium add-on</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kamiNaranjo/zap-extensions
src/org/zaproxy/zap/extension/selenium/resources/help_ko_KR/helpset_ko_KR.hs
apache-2.0
961
79
67
157
413
209
204
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PatternGuards #-} -- | A type class 'ModSubst' for objects which can have 'ModuleSubst' -- applied to them. -- -- See also <https://github.com/ezyang/ghc-proposals/blob/backpack/proposals/0000-backpack.rst> module Distribution.Backpack.ModSubst ( ModSubst(..), ) where import Prelude () import Distribution.Compat.Prelude hiding (mod) import Distribution.ModuleName import Distribution.Backpack import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set -- | Applying module substitutions to semantic objects. class ModSubst a where -- In notation, substitution is postfix, which implies -- putting it on the right hand side, but for partial -- application it's more convenient to have it on the left -- hand side. modSubst :: OpenModuleSubst -> a -> a instance ModSubst OpenModule where modSubst subst (OpenModule cid mod_name) = OpenModule (modSubst subst cid) mod_name modSubst subst mod@(OpenModuleVar mod_name) | Just mod' <- Map.lookup mod_name subst = mod' | otherwise = mod instance ModSubst OpenUnitId where modSubst subst (IndefFullUnitId cid insts) = IndefFullUnitId cid (modSubst subst insts) modSubst _subst uid = uid instance ModSubst (Set ModuleName) where modSubst subst reqs = Set.union (Set.difference reqs (Map.keysSet subst)) (openModuleSubstFreeHoles subst) -- Substitutions are functorial. NB: this means that -- there is an @instance 'ModSubst' 'ModuleSubst'@! instance ModSubst a => ModSubst (Map k a) where modSubst subst = fmap (modSubst subst) instance ModSubst a => ModSubst [a] where modSubst subst = fmap (modSubst subst) instance ModSubst a => ModSubst (k, a) where modSubst subst (x,y) = (x, modSubst subst y)
themoritz/cabal
Cabal/Distribution/Backpack/ModSubst.hs
bsd-3-clause
1,831
0
11
350
420
226
194
31
0
-- buffer ends in 0xF0 ð
ml9951/ghc
testsuite/tests/parser/unicode/utf8_005.hs
bsd-3-clause
24
0
4
5
5
2
3
-1
-1
{-# LANGUAGE FlexibleContexts #-} module AI.Visualizations ( networkHistogram , weightList , biasList ) where import AI.Layer import AI.Network import AI.Network.FeedForwardNetwork import AI.Neuron import Numeric.LinearAlgebra import Data.Foldable (foldMap) import GHC.Float import Graphics.Histogram import AI.Trainer weightList :: FeedForwardNetwork -> [Double] weightList n = concat $ map (toList . flatten . weightMatrix) (layers n) biasList :: FeedForwardNetwork -> [Double] biasList n = concat $ map (toList . biasVector) (layers n) networkHistogram :: FilePath -> (FeedForwardNetwork -> [Double]) -> FeedForwardNetwork -> IO () networkHistogram filename listFunction n = do let hist = histogram binSturges (listFunction n) plot filename hist return ()
qzchenwl/LambdaNet
AI/Visualizations.hs
mit
882
0
12
220
237
127
110
23
1
module Tests.IRC.Commands where import IRC.Commands (respond') import IRC.Parser (Message(..), Sender(..)) import Config (Config(..), defaultConfig) import Test.HUnit (Test(..), (~=?)) respondTest :: Test respondTest = TestLabel "respond" $ TestList [ respond' testMsg "test reply" defaultConfig ~=? ("test location", "asdf: test reply") ] where testMsg = Message { location = "test location" , sender = Sender { IRC.Parser.nick = "asdf" } }
jdiez17/HaskellHawk
Tests/IRC/Commands.hs
mit
506
0
10
123
144
89
55
11
1
module Handler.EditoSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getEditoR" $ do error "Spec not implemented: getEditoR"
swamp-agr/carbuyer-advisor
test/Handler/EditoSpec.hs
mit
171
0
11
39
44
23
21
6
1
{-# LANGUAGE OverloadedStrings , DeriveGeneric #-} module Tach.Transformable.Types.Transform where import GHC.Generics
smurphy8/tach
core-types/tach-transformable-types/src/Tach/Transformable/Types/Transform.hs
mit
122
0
4
14
14
10
4
3
0
{- | Module : Xcode.FileEncoding License : MIT Maintainer : [email protected] Stability : unstable Portability : portable A file encoding -} module Xcode.FileEncoding ( FileEncoding( .. ) ) where -- | An Xcode file encoding -- Encodings taken from NSString.h data FileEncoding = ASCII | NEXTSTEP | JapaneseEUC | UTF8 | ISOLatin1 | Symbol | NonLossyASCII | ShiftJIS | ISOLatin2 | Unicode | WindowsCP1251 | WindowsCP1252 | WindowsCP1253 | WindowsCP1254 | WindowsCP1250 | ISO2022JP | MacOSRoman | UTF16 | UTF16BigEndian | UTF16LittleEndian | UTF32 | UTF32BigEndian | UTF32LittleEndian | Proprietary
shlevy/xcode-types
src/Xcode/FileEncoding.hs
mit
674
0
5
168
94
63
31
26
0
myDrop n xs = if n <= 0 || null xs then xs else myDrop (n-1)(tail xs)
rglew/rwh
ch2/myDrop.hs
mit
99
0
8
46
48
24
24
3
2
import Data.List (sort) import Control.Applicative import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString as B main = do input <- B.readFile "input.txt" let presents = case parsePresents input of Right (p) -> p Left (err) -> error ("Parse error: " ++ err) print . sum . map required_ribbon $ presents required_paper present = let areas = sides present in sum areas + minimum areas sides (Present l w h) = [l*w, l*w, l*h, l*h, w*h, w*h] required_ribbon present = smallest_perimeter present + volume present smallest_perimeter (Present l w h) = (*2) . sum . take 2 . sort $ [l,w,h] volume (Present l w h) = l*w*h data Present = Present Int Int Int parsePresents :: B.ByteString -> Either String [Present] parsePresents = A.parseOnly (presents <* A.skipMany A.endOfLine <* A.endOfInput) presents :: A.Parser [Present] presents = present `A.sepBy` A.endOfLine present :: A.Parser Present present = do l <- A.decimal A.char 'x' w <- A.decimal A.char 'x' h <- A.decimal return $ Present l w h
devonhollowood/adventofcode
2015/day2/day2.hs
mit
1,110
0
15
255
467
238
229
29
2
sumDigits acc 0 = acc sumDigits acc n = sumDigits (acc+d) n' where (n', d) = quotRem n 10 main = print $ maximum $ map (sumDigits 0) [a^b | a<-[1..99], b<-[1..99]]
dpieroux/euler
0/0056.hs
mit
166
0
10
34
109
56
53
3
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module with producer properties types and functions. ----------------------------------------------------------------------------- module Kafka.Producer.ProducerProperties ( ProducerProperties(..) , brokersList , setCallback , logLevel , compression , topicCompression , sendTimeout , statisticsInterval , extraProps , suppressDisconnectLogs , extraTopicProps , debugOptions , module Kafka.Producer.Callbacks ) where import Data.Text (Text) import qualified Data.Text as Text import Control.Monad (MonadPlus(mplus)) import Data.Map (Map) import qualified Data.Map as M import Data.Semigroup as Sem import Kafka.Internal.Setup (KafkaConf(..), Callback(..)) import Kafka.Types (KafkaDebug(..), Timeout(..), KafkaCompressionCodec(..), KafkaLogLevel(..), BrokerAddress(..), kafkaDebugToText, kafkaCompressionCodecToText, Millis(..)) import Kafka.Producer.Callbacks -- | Properties to create 'Kafka.Producer.Types.KafkaProducer'. data ProducerProperties = ProducerProperties { ppKafkaProps :: Map Text Text , ppTopicProps :: Map Text Text , ppLogLevel :: Maybe KafkaLogLevel , ppCallbacks :: [Callback] } instance Sem.Semigroup ProducerProperties where (ProducerProperties k1 t1 ll1 cb1) <> (ProducerProperties k2 t2 ll2 cb2) = ProducerProperties (M.union k2 k1) (M.union t2 t1) (ll2 `mplus` ll1) (cb1 `mplus` cb2) {-# INLINE (<>) #-} -- | /Right biased/ so we prefer newer properties over older ones. instance Monoid ProducerProperties where mempty = ProducerProperties { ppKafkaProps = M.empty , ppTopicProps = M.empty , ppLogLevel = Nothing , ppCallbacks = [] } {-# INLINE mempty #-} mappend = (Sem.<>) {-# INLINE mappend #-} -- | Set the <https://kafka.apache.org/documentation/#bootstrap.servers list of brokers> to contact to connect to the Kafka cluster. brokersList :: [BrokerAddress] -> ProducerProperties brokersList bs = let bs' = Text.intercalate "," (unBrokerAddress <$> bs) in extraProps $ M.fromList [("bootstrap.servers", bs')] -- | Set the producer callback. -- -- For examples of use, see: -- -- * 'errorCallback' -- * 'logCallback' -- * 'statsCallback' setCallback :: Callback -> ProducerProperties setCallback cb = mempty { ppCallbacks = [cb] } -- | Sets the logging level. -- Usually is used with 'debugOptions' to configure which logs are needed. logLevel :: KafkaLogLevel -> ProducerProperties logLevel ll = mempty { ppLogLevel = Just ll } -- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md compression.codec> for the producer. compression :: KafkaCompressionCodec -> ProducerProperties compression c = extraProps $ M.singleton "compression.codec" (kafkaCompressionCodecToText c) -- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md#topic-configuration-properties compression.codec> for the topic. topicCompression :: KafkaCompressionCodec -> ProducerProperties topicCompression c = extraTopicProps $ M.singleton "compression.codec" (kafkaCompressionCodecToText c) -- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md#topic-configuration-properties message.timeout.ms>. sendTimeout :: Timeout -> ProducerProperties sendTimeout (Timeout t) = extraTopicProps $ M.singleton "message.timeout.ms" (Text.pack $ show t) -- | Set the <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md statistics.interval.ms> for the producer. statisticsInterval :: Millis -> ProducerProperties statisticsInterval (Millis t) = extraProps $ M.singleton "statistics.interval.ms" (Text.pack $ show t) -- | Any configuration options that are supported by /librdkafka/. -- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md here> extraProps :: Map Text Text -> ProducerProperties extraProps m = mempty { ppKafkaProps = m } -- | Suppresses producer disconnects logs. -- -- It might be useful to turn this off when interacting with brokers -- with an aggressive connection.max.idle.ms value. suppressDisconnectLogs :: ProducerProperties suppressDisconnectLogs = extraProps $ M.fromList [("log.connection.close", "false")] -- | Any *topic* configuration options that are supported by /librdkafka/. -- The full list can be found <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md#topic-configuration-properties here> extraTopicProps :: Map Text Text -> ProducerProperties extraTopicProps m = mempty { ppTopicProps = m } -- | Sets <https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md debug> features for the producer -- Usually is used with 'logLevel'. debugOptions :: [KafkaDebug] -> ProducerProperties debugOptions [] = extraProps M.empty debugOptions d = let points = Text.intercalate "," (kafkaDebugToText <$> d) in extraProps $ M.fromList [("debug", points)]
haskell-works/kafka-client
src/Kafka/Producer/ProducerProperties.hs
mit
5,129
0
11
825
870
508
362
74
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} module Devel ( devel , DevelOpts(..) , DevelTermOpt(..) , defaultDevelOpts ) where import qualified Distribution.Compiler as D import qualified Distribution.ModuleName as D import qualified Distribution.PackageDescription as D import qualified Distribution.PackageDescription.Parse as D import qualified Distribution.Simple.Configure as D import qualified Distribution.Simple.Program as D import qualified Distribution.Simple.Utils as D import qualified Distribution.Verbosity as D import Control.Applicative ((<$>), (<*>)) import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (MVar, newEmptyMVar, takeMVar, tryPutMVar) import Control.Concurrent.Async (race_) import qualified Control.Exception as Ex import Control.Monad (forever, unless, void, when, forM) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.State (evalStateT, get) import qualified Data.IORef as I import qualified Data.ByteString.Lazy as LB import Data.Char (isNumber, isUpper) import qualified Data.List as L import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Set as Set import System.Directory import System.Environment (getEnvironment) import System.Exit (ExitCode (..), exitFailure, exitSuccess) import System.FilePath (dropExtension, splitDirectories, takeExtension, (</>)) import System.FSNotify import System.IO (Handle) import System.IO.Error (isDoesNotExistError) import System.Posix.Types (EpochTime) import System.PosixCompat.Files (getFileStatus, modificationTime) import System.Process (ProcessHandle, createProcess, env, getProcessExitCode, proc, readProcess, system, terminateProcess) import System.Timeout (timeout) import Build (getDeps, isNewerThan, recompDeps) import GhcBuild (buildPackage, getBuildFlags, getPackageArgs) import qualified Config as GHC import Data.Streaming.Network (bindPortTCP) import Network (withSocketsDo) import Network.HTTP.Conduit (conduitManagerSettings, newManager) import Data.Default.Class (def) #if MIN_VERSION_http_client(0,4,7) import Network.HTTP.Client (managerSetProxy, noProxy) #endif import Network.HTTP.ReverseProxy (ProxyDest (ProxyDest), waiProxyToSettings, wpsTimeout, wpsOnExc) import qualified Network.HTTP.ReverseProxy as ReverseProxy import Network.HTTP.Types (status200, status503) import Network.Socket (sClose) import Network.Wai (responseLBS, requestHeaders) import Network.Wai.Parse (parseHttpAccept) import Network.Wai.Handler.Warp (run, defaultSettings, setPort) import Network.Wai.Handler.WarpTLS (runTLS, tlsSettingsMemory) import SrcLoc (Located) import Data.FileEmbed (embedFile) lockFile :: FilePath lockFile = "yesod-devel/devel-terminate" writeLock :: DevelOpts -> IO () writeLock opts = do createDirectoryIfMissing True "yesod-devel" writeFile lockFile "" createDirectoryIfMissing True "dist" -- for compatibility with old devel.hs writeFile "dist/devel-terminate" "" removeLock :: DevelOpts -> IO () removeLock opts = do removeFileIfExists lockFile removeFileIfExists "dist/devel-terminate" -- for compatibility with old devel.hs data DevelTermOpt = TerminateOnEnter | TerminateOnlyInterrupt deriving (Show, Eq) data DevelOpts = DevelOpts { isCabalDev :: Bool , forceCabal :: Bool , verbose :: Bool , eventTimeout :: Int -- negative value for no timeout , successHook :: Maybe String , failHook :: Maybe String , buildDir :: Maybe String , develPort :: Int , develTlsPort :: Int , proxyTimeout :: Int , useReverseProxy :: Bool , terminateWith :: DevelTermOpt -- Support for GHC_PACKAGE_PATH wrapping , develConfigOpts :: [String] , develEnv :: Maybe [(String, String)] } deriving (Show, Eq) getBuildDir :: DevelOpts -> String getBuildDir opts = fromMaybe "dist" (buildDir opts) defaultDevelOpts :: DevelOpts defaultDevelOpts = DevelOpts { isCabalDev = False , forceCabal = False , verbose = False , eventTimeout = -1 , successHook = Nothing , failHook = Nothing , buildDir = Nothing , develPort = 3000 , develTlsPort = 3443 , proxyTimeout = 10 , useReverseProxy = True , terminateWith = TerminateOnEnter } cabalProgram :: DevelOpts -> FilePath cabalProgram opts | isCabalDev opts = "cabal-dev" | otherwise = "cabal" -- | Run a reverse proxy from port 3000 to 3001. If there is no response on -- 3001, give an appropriate message to the user. reverseProxy :: DevelOpts -> I.IORef Int -> IO () reverseProxy opts iappPort = do #if MIN_VERSION_http_client(0,4,7) manager <- newManager $ managerSetProxy noProxy conduitManagerSettings #else manager <- newManager conduitManagerSettings #endif let refreshHtml = LB.fromChunks $ return $(embedFile "refreshing.html") let onExc _ req | maybe False (("application/json" `elem`) . parseHttpAccept) (lookup "accept" $ requestHeaders req) = return $ responseLBS status503 [ ("Retry-After", "1") ] "{\"message\":\"Recompiling\"}" | otherwise = return $ responseLBS status200 [ ("content-type", "text/html") , ("Refresh", "1") ] refreshHtml let proxyApp = waiProxyToSettings (const $ do appPort <- liftIO $ I.readIORef iappPort return $ ReverseProxy.WPRProxyDest $ ProxyDest "127.0.0.1" appPort) def { wpsOnExc = \e req f -> onExc e req >>= f , wpsTimeout = if proxyTimeout opts == 0 then Nothing else Just (1000000 * proxyTimeout opts) } manager runProxyTls port app = do let cert = $(embedFile "certificate.pem") key = $(embedFile "key.pem") tlsSettings = tlsSettingsMemory cert key runTLS tlsSettings (setPort port defaultSettings) app httpProxy = run (develPort opts) proxyApp httpsProxy = runProxyTls (develTlsPort opts) proxyApp putStrLn "Application can be accessed at:\n" putStrLn $ "http://127.0.0.1:" ++ show (develPort opts) putStrLn $ "https://127.0.0.1:" ++ show (develTlsPort opts) putStrLn $ "If you wish to test https capabilities, you should set the following variable:" putStrLn $ " export APPROOT=https://127.0.0.1:" ++ show (develTlsPort opts) putStrLn "" loop (race_ httpProxy httpsProxy) `Ex.catch` \e -> do print (e :: Ex.SomeException) exitFailure Ex.throwIO e -- heh, just for good measure where loop proxies = forever $ do void proxies putStrLn $ "Reverse proxy stopped, but it shouldn't" threadDelay 1000000 putStrLn $ "Restarting reverse proxies" checkPort :: Int -> IO Bool checkPort p = do es <- Ex.try $ bindPortTCP p "*4" case es of Left (_ :: Ex.IOException) -> return False Right s -> do sClose s return True getPort :: DevelOpts -> Int -> IO Int getPort opts _ | not (useReverseProxy opts) = return $ develPort opts getPort _ p0 = loop p0 where loop p = do avail <- checkPort p if avail then return p else loop (succ p) unlessM :: Monad m => m Bool -> m () -> m () unlessM c a = c >>= \res -> unless res a devel :: DevelOpts -> [String] -> IO () devel opts passThroughArgs = withSocketsDo $ withManager $ \manager -> do unlessM (checkPort $ develPort opts) $ error "devel port unavailable" iappPort <- getPort opts 17834 >>= I.newIORef when (useReverseProxy opts) $ void $ forkIO $ reverseProxy opts iappPort develHsPath <- checkDevelFile writeLock opts let (terminator, after) = case terminateWith opts of TerminateOnEnter -> ("Press ENTER", void getLine) TerminateOnlyInterrupt -> -- run for one year ("Interrupt", threadDelay $ 1000 * 1000 * 60 * 60 * 24 * 365) putStrLn $ "Yesod devel server. " ++ terminator ++ " to quit" void $ forkIO $ do filesModified <- newEmptyMVar void $ forkIO $ void $ watchTree manager "." (const True) (\_ -> void (tryPutMVar filesModified ())) evalStateT (mainOuterLoop develHsPath iappPort filesModified) Map.empty after writeLock opts exitSuccess where bd = getBuildDir opts -- outer loop re-reads the cabal file mainOuterLoop develHsPath iappPort filesModified = do ghcVer <- liftIO ghcVersion #if MIN_VERSION_Cabal(1,20,0) cabal <- liftIO $ D.tryFindPackageDesc "." #else cabal <- liftIO $ D.findPackageDesc "." #endif gpd <- liftIO $ D.readPackageDescription D.normal cabal ldar <- liftIO lookupLdAr (hsSourceDirs, _) <- liftIO $ checkCabalFile gpd liftIO $ removeFileIfExists (bd </> "setup-config") c <- liftIO $ configure opts passThroughArgs if c then do -- these files contain the wrong data after the configure step, -- remove them to force a cabal build first liftIO $ mapM_ removeFileIfExists [ "yesod-devel/ghcargs.txt" , "yesod-devel/arargs.txt" , "yesod-devel/ldargs.txt" ] rebuild <- liftIO $ mkRebuild ghcVer cabal opts ldar mainInnerLoop develHsPath iappPort hsSourceDirs filesModified cabal rebuild else do liftIO (threadDelay 5000000) mainOuterLoop develHsPath iappPort filesModified -- inner loop rebuilds after files change mainInnerLoop develHsPath iappPort hsSourceDirs filesModified cabal rebuild = go where go = do _ <- recompDeps hsSourceDirs list <- liftIO $ getFileList hsSourceDirs [cabal] success <- liftIO rebuild pkgArgs <- liftIO (ghcPackageArgs opts) let devArgs = pkgArgs ++ [develHsPath] let loop list0 = do (haskellFileChanged, list1) <- liftIO $ watchForChanges filesModified hsSourceDirs [cabal] list0 (eventTimeout opts) anyTouched <- recompDeps hsSourceDirs unless (anyTouched || haskellFileChanged) $ loop list1 if not success then liftIO $ do putStrLn "\x1b[1;31mBuild failure, pausing...\x1b[0m" runBuildHook $ failHook opts else do liftIO $ runBuildHook $ successHook opts liftIO $ removeLock opts liftIO $ putStrLn $ if verbose opts then "Starting development server: runghc " ++ L.unwords devArgs else "Starting development server..." env0 <- liftIO getEnvironment -- get a new port for the new process to listen on appPort <- liftIO $ I.readIORef iappPort >>= getPort opts . (+ 1) liftIO $ I.writeIORef iappPort appPort (_,_,_,ph) <- liftIO $ createProcess (proc "runghc" devArgs) { env = Just $ Map.toList $ Map.insert "PORT" (show appPort) $ Map.insert "DISPLAY_PORT" (show $ develPort opts) $ Map.fromList env0 } derefMap <- get watchTid <- liftIO . forkIO . try_ $ flip evalStateT derefMap $ do loop list liftIO $ do putStrLn "Stopping development server..." writeLock opts threadDelay 1000000 putStrLn "Terminating development server..." terminateProcess ph ec <- liftIO $ waitForProcess' ph liftIO $ putStrLn $ "Exit code: " ++ show ec liftIO $ Ex.throwTo watchTid (userError "process finished") loop list n <- liftIO $ cabal `isNewerThan` (bd </> "setup-config") if n then mainOuterLoop develHsPath iappPort filesModified else go runBuildHook :: Maybe String -> IO () runBuildHook (Just s) = do ret <- system s case ret of ExitFailure _ -> putStrLn ("Error executing hook: " ++ s) _ -> return () runBuildHook Nothing = return () {- run `cabal configure' with our wrappers -} configure :: DevelOpts -> [String] -> IO Bool configure opts extraArgs = checkExit =<< createProcess (proc (cabalProgram opts) $ [ "configure" , "-flibrary-only" , "--disable-tests" , "--disable-benchmarks" , "-fdevel" , "--disable-library-profiling" , "--with-ld=yesod-ld-wrapper" , "--with-ghc=yesod-ghc-wrapper" , "--with-ar=yesod-ar-wrapper" , "--with-hc-pkg=ghc-pkg" ] ++ develConfigOpts opts ++ extraArgs ) { env = develEnv opts } removeFileIfExists :: FilePath -> IO () removeFileIfExists file = removeFile file `Ex.catch` handler where handler :: IOError -> IO () handler e | isDoesNotExistError e = return () | otherwise = Ex.throw e mkRebuild :: String -> FilePath -> DevelOpts -> (FilePath, FilePath) -> IO (IO Bool) mkRebuild ghcVer cabalFile opts (ldPath, arPath) | GHC.cProjectVersion /= ghcVer = failWith "Yesod has been compiled with a different GHC version, please reinstall yesod-bin" | forceCabal opts = return (rebuildCabal opts) | otherwise = return $ do ns <- mapM (cabalFile `isNewerThan`) [ "yesod-devel/ghcargs.txt", "yesod-devel/arargs.txt", "yesod-devel/ldargs.txt" ] if or ns then rebuildCabal opts else do bf <- getBuildFlags rebuildGhc bf ldPath arPath rebuildGhc :: [Located String] -> FilePath -> FilePath -> IO Bool rebuildGhc bf ld ar = do putStrLn "Rebuilding application... (using GHC API)" buildPackage bf ld ar rebuildCabal :: DevelOpts -> IO Bool rebuildCabal opts = do putStrLn $ "Rebuilding application... (using " ++ cabalProgram opts ++ ")" checkExit =<< createProcess (proc (cabalProgram opts) args) { env = develEnv opts } where args | verbose opts = [ "build" ] | otherwise = [ "build", "-v0" ] try_ :: forall a. IO a -> IO () try_ x = void (Ex.try x :: IO (Either Ex.SomeException a)) type FileList = Map.Map FilePath EpochTime getFileList :: [FilePath] -> [FilePath] -> IO FileList getFileList hsSourceDirs extraFiles = do (files, deps) <- getDeps hsSourceDirs let files' = extraFiles ++ files ++ map fst (Map.toList deps) fmap Map.fromList $ forM files' $ \f -> do efs <- Ex.try $ getFileStatus f return $ case efs of Left (_ :: Ex.SomeException) -> (f, 0) Right fs -> (f, modificationTime fs) -- | Returns @True@ if a .hs file changed. watchForChanges :: MVar () -> [FilePath] -> [FilePath] -> FileList -> Int -> IO (Bool, FileList) watchForChanges filesModified hsSourceDirs extraFiles list t = do newList <- getFileList hsSourceDirs extraFiles if list /= newList then do let haskellFileChanged = not $ Map.null $ Map.filterWithKey isHaskell $ Map.differenceWith compareTimes newList list `Map.union` Map.differenceWith compareTimes list newList return (haskellFileChanged, newList) else timeout (1000000*t) (takeMVar filesModified) >> watchForChanges filesModified hsSourceDirs extraFiles list t where compareTimes x y | x == y = Nothing | otherwise = Just x isHaskell filename _ = takeExtension filename `elem` [".hs", ".lhs", ".hsc", ".cabal"] checkDevelFile :: IO FilePath checkDevelFile = loop paths where paths = ["app/devel.hs", "devel.hs", "src/devel.hs"] loop [] = failWith $ "file devel.hs not found, checked: " ++ show paths loop (x:xs) = do e <- doesFileExist x if e then return x else loop xs checkCabalFile :: D.GenericPackageDescription -> IO ([FilePath], D.Library) checkCabalFile gpd = case D.condLibrary gpd of Nothing -> failWith "incorrect cabal file, no library" Just ct -> case lookupDevelLib gpd ct of Nothing -> failWith "no development flag found in your configuration file. Expected a 'library-only' flag or the older 'devel' flag" Just dLib -> do let hsSourceDirs = D.hsSourceDirs . D.libBuildInfo $ dLib fl <- getFileList hsSourceDirs [] let unlisted = checkFileList fl dLib unless (null unlisted) $ do putStrLn "WARNING: the following source files are not listed in exposed-modules or other-modules:" mapM_ putStrLn unlisted when ("Application" `notElem` (map (last . D.components) $ D.exposedModules dLib)) $ putStrLn "WARNING: no exposed module Application" return (hsSourceDirs, dLib) failWith :: String -> IO a failWith msg = do putStrLn $ "ERROR: " ++ msg exitFailure checkFileList :: FileList -> D.Library -> [FilePath] checkFileList fl lib = filter (not . isSetup) . filter isUnlisted . filter isSrcFile $ sourceFiles where al = allModules lib -- a file is only a possible 'module file' if all path pieces start with a capital letter sourceFiles = filter isSrcFile . map fst . Map.toList $ fl isSrcFile file = let dirs = filter (/=".") $ splitDirectories file in all (isUpper . head) dirs && (takeExtension file `elem` [".hs", ".lhs"]) isUnlisted file = not (toModuleName file `Set.member` al) toModuleName = L.intercalate "." . filter (/=".") . splitDirectories . dropExtension isSetup "Setup.hs" = True isSetup "./Setup.hs" = True isSetup "Setup.lhs" = True isSetup "./Setup.lhs" = True isSetup _ = False allModules :: D.Library -> Set.Set String allModules lib = Set.fromList $ map toString $ D.exposedModules lib ++ (D.otherModules . D.libBuildInfo) lib where toString = L.intercalate "." . D.components ghcVersion :: IO String ghcVersion = fmap getNumber $ readProcess "runghc" ["--numeric-version", "0"] [] where getNumber = filter (\x -> isNumber x || x == '.') ghcPackageArgs :: DevelOpts -> IO [String] ghcPackageArgs opts = getBuildFlags >>= getPackageArgs (buildDir opts) lookupDevelLib :: D.GenericPackageDescription -> D.CondTree D.ConfVar c a -> Maybe a lookupDevelLib gpd ct | found = Just (D.condTreeData ct) | otherwise = Nothing where flags = map (unFlagName . D.flagName) $ D.genPackageFlags gpd unFlagName (D.FlagName x) = x found = any (`elem` ["library-only", "devel"]) flags -- location of `ld' and `ar' programs lookupLdAr :: IO (FilePath, FilePath) lookupLdAr = do mla <- lookupLdAr' case mla of Nothing -> failWith "Cannot determine location of `ar' or `ld' program" Just la -> return la lookupLdAr' :: IO (Maybe (FilePath, FilePath)) lookupLdAr' = do #if MIN_VERSION_Cabal(1,22,0) (_, _, pgmc) <- D.configCompilerEx (Just D.GHC) Nothing Nothing D.defaultProgramConfiguration D.silent #else (_, pgmc) <- D.configCompiler (Just D.GHC) Nothing Nothing D.defaultProgramConfiguration D.silent #endif pgmc' <- D.configureAllKnownPrograms D.silent pgmc return $ (,) <$> look D.ldProgram pgmc' <*> look D.arProgram pgmc' where look pgm pdb = fmap D.programPath (D.lookupProgram pgm pdb) -- | nonblocking version of @waitForProcess@ waitForProcess' :: ProcessHandle -> IO ExitCode waitForProcess' pid = go where go = do mec <- getProcessExitCode pid case mec of Just ec -> return ec Nothing -> threadDelay 100000 >> go -- | wait for process started by @createProcess@, return True for ExitSuccess checkExit :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO Bool checkExit (_,_,_,h) = (==ExitSuccess) <$> waitForProcess' h
andrewthad/yesod
yesod-bin/Devel.hs
mit
23,164
0
24
8,277
5,374
2,759
2,615
434
6
-- | -- Module : PhantomPhases.Typechecker -- Copyright : © 2019 Elias Castegren and Kiko Fernandez-Reyes -- License : MIT -- -- Stability : experimental -- Portability : portable -- -- This module includes everything you need to get started type checking -- a program. To build the Abstract Syntax Tree (AST), please import and build -- the AST from "PhantomPhases.AST". -- -- The main entry point to the type checker is the combinator 'tcProgram', which -- takes an AST and returns either an error, or the typed program with the current 'Phase'. -- By 'Phase' we mean that the type checker statically guarantees that all AST -- nodes have been visited during the type checking phase. -- For example, for the following program (using a made up syntax): -- -- > -- > class C -- > val f: Foo -- > -- -- should be parsed to generate this AST: -- -- > testClass1 = -- > ClassDef {cname = "C" -- > ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}] -- > ,methods = []} -- > -- -- To type check the AST, run the 'tcProgram' combinator as follows: -- -- > tcProgram testClass1 -- -- {-# LANGUAGE NamedFieldPuns, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, RankNTypes, DataKinds, GADTs #-} module PhantomPhases.Typechecker where import Data.Map as Map hiding (foldl, map, null, (\\)) import Data.List as List import Text.Printf (printf) import Control.Monad import Control.Monad.Reader import Control.Monad.Except import PhantomPhases.AST -- | Declaration of a type checking errors data TCError where -- | Declaration of two classes with the same name DuplicateClassError :: Name -> TCError -- | Reference of a class that does not exists UnknownClassError :: Name -> TCError -- | Reference of a field that does not exists UnknownFieldError :: Name -> TCError -- | Reference of a method that does not exists UnknownMethodError :: Name -> TCError -- | Unbound variable UnboundVariableError :: Name -> TCError -- | Type mismatch error, the first @Type@ refers to the formal type argument, -- the second @Type@ refers to the actual type argument. TypeMismatchError :: Type 'Checked -> Type 'Checked -> TCError -- | Immutable field error, used when someone violates immutability ImmutableFieldError :: Expr 'Checked -> TCError -- | Error to indicate that a one cannot assign a value to expression @Expr@ NonLValError :: Expr 'Checked -> TCError -- | Error indicating that the return type cannot be @Null@ PrimitiveNullError :: Type 'Checked -> TCError -- | Used to indicate that @Type p@ is not of a class type NonClassTypeError :: Type p -> TCError -- | Expecting a function (arrow) type but got another type instead. NonArrowTypeError :: Type 'Checked -> TCError -- | Tried to call a constructor outside of instantiation ConstructorCallError :: Type 'Checked -> TCError -- | Cannot infer type of @Expr@ UninferrableError :: Expr 'Parsed -> TCError instance Show TCError where show (DuplicateClassError c) = printf "Duplicate declaration of class '%s'" c show (UnknownClassError c) = printf "Unknown class '%s'" c show (UnknownFieldError f) = printf "Unknown field '%s'" f show (UnknownMethodError m) = printf "Unknown method '%s'" m show (UnboundVariableError x) = printf "Unbound variable '%s'" x show (TypeMismatchError actual expected) = printf "Type '%s' does not match expected type '%s'" (show actual) (show expected) show (ImmutableFieldError e) = printf "Cannot write to immutable field '%s'" (show e) show (NonLValError e) = printf "Cannot assign to expression '%s'" (show e) show (PrimitiveNullError t) = printf "Type '%s' cannot be null" (show t) show (NonClassTypeError t) = printf "Expected class type, got '%s'" (show t) show (NonArrowTypeError t) = printf "Expected function type, got '%s'" (show t) show (ConstructorCallError t) = printf "Tried to call constructor of class '%s' outside of instantiation" (show t) show (UninferrableError e) = printf "Cannot infer the type of '%s'" (show e) -- | Environment method entry. Contains method parameters and types. -- The 'MethodEntry' is created during the 'generateEnvironment' function, which -- creates an Environment (symbol's table). After the 'MethodEntry' -- has been created, it can be queried via helper functions, e.g., -- @'findMethod' ty m@. data MethodEntry = MethodEntry {meparams :: [Param 'Checked] ,metype :: Type 'Checked } -- |Environment field entry. Contains class' fields parameters and types. data FieldEntry = FieldEntry {femod :: Mod ,fetype :: Type 'Checked } -- |Environment class entry. Contains fields parameters and methods. data ClassEntry = ClassEntry {cefields :: Map Name FieldEntry ,cemethods :: Map Name MethodEntry } -- | Environment. The 'Env' is used during type checking, and is updated as -- the type checker runs. Most likely, one uses the 'Reader' monad to hide details -- of how the environment is updated, via the common 'local' function. data Env = Env {ctable :: Map Name ClassEntry ,vartable :: Map Name (Type 'Checked) ,constructor :: Bool} -- | Conditionally update the environment to track if we are in a -- constructor method. setConstructor :: Name -> Env -> Env setConstructor m env = env{constructor = isConstructorName m} -- | Helper function to lookup a class given a 'Name' and an 'Env'. Usually -- it relies on the 'Reader' monad, so that passing the 'Env' can be omitted. -- For example: -- -- > findClass :: Type p1 -> TypecheckM ClassEntry -- > findClass (ClassType c) = do -- > cls <- asks $ lookupClass c -- > case cls of -- > Just cdef -> return cdef -- > Nothing -> tcError $ UnknownClassError c -- > findClass ty = tcError $ NonClassTypeError ty -- -- In this function ('findClass'), the 'Reader' function 'asks' will inject -- the 'Reader' monad as the last argument. More details in the paper. lookupClass :: Name -> Env -> Maybe ClassEntry lookupClass c Env{ctable} = Map.lookup c ctable -- | Look up a variable by its 'Name' in the 'Env', returning an option type -- indicating whether the variable was found or not. lookupVar :: Name -> Env -> Maybe (Type 'Checked) lookupVar x Env{vartable} = Map.lookup x vartable -- | Find a class declaration by its 'Type' findClass :: Type p -> TypecheckM ClassEntry findClass (ClassType c) = do cls <- asks $ lookupClass c case cls of Just cdef -> return cdef Nothing -> throwError $ UnknownClassError c findClass ty = throwError $ NonClassTypeError ty -- | Find a method declaration by its 'Type' and method name @m@ findMethod :: Type p1 -> Name -> TypecheckM MethodEntry findMethod ty m = do ClassEntry{cemethods} <- findClass ty case Map.lookup m cemethods of Just entry -> return entry Nothing -> throwError $ UnknownMethodError m -- | Find a field declaration by its 'Type' (@ty@) and field name @f@ findField :: Type p1 -> Name -> TypecheckM FieldEntry findField ty f = do ClassEntry{cefields} <- findClass ty case Map.lookup f cefields of Just entry -> return entry Nothing -> throwError $ UnknownFieldError f -- | Find a variable in the environment by its name @x@ findVar :: Name -> TypecheckM (Type 'Checked) findVar x = do result <- asks $ lookupVar x case result of Just t -> return t Nothing -> throwError $ UnboundVariableError x -- | Environment generation from a parsed AST program. generateEnvironment :: Program 'Parsed -> Except TCError Env generateEnvironment (Program classes) = do classEntries <- mapM precheckClass classes let cnames = map cname classes duplicates = cnames \\ nub cnames unless (null duplicates) $ throwError $ DuplicateClassError (head duplicates) return $ Env {ctable = Map.fromList $ zip cnames classEntries ,vartable = Map.empty ,constructor = False} where precheckClass :: ClassDef 'Parsed -> Except TCError ClassEntry precheckClass ClassDef {fields, methods} = do fields' <- mapM precheckField fields methods' <- mapM precheckMethod methods return ClassEntry {cefields = Map.fromList $ zip (map fname fields) fields' ,cemethods = Map.fromList $ zip (map mname methods) methods'} precheckField :: FieldDef 'Parsed -> Except TCError FieldEntry precheckField FieldDef {ftype, fmod} = do ftype' <- precheckType ftype return FieldEntry {femod = fmod ,fetype = ftype' } precheckParam :: Param 'Parsed -> Except TCError (Param 'Checked) precheckParam Param {ptype, pname} = do ptype' <- precheckType ptype return Param {pname ,ptype = ptype'} precheckMethod :: MethodDef 'Parsed -> Except TCError MethodEntry precheckMethod MethodDef {mparams, mtype} = do mtype' <- precheckType mtype mparams' <- mapM precheckParam mparams return $ MethodEntry {meparams = mparams' ,metype = mtype'} precheckType :: Type 'Parsed -> Except TCError (Type 'Checked) precheckType (ClassType c) = do unless (any ((== c) . cname) classes) $ throwError $ UnknownClassError c return $ ClassType c precheckType IntType = return IntType precheckType BoolType = return BoolType precheckType UnitType = return UnitType precheckType (Arrow ts t) = do ts' <- mapM precheckType ts t' <- precheckType t return $ Arrow ts' t' -- | Add a variable name and its type to the environment 'Env'. addVariable :: Name -> Type 'Checked -> Env -> Env addVariable x t env@Env{vartable} = env{vartable = Map.insert x t vartable} -- | Add a list of parameters, 'Param', to the environment. addParameters :: [Param 'Checked] -> Env -> Env addParameters params env = foldl addParameter env params where addParameter env (Param name ty) = addVariable name ty env -- |The type checking monad. The type checking monad is the stacking -- of the 'Reader' and 'Exception' monads. type TypecheckM a = forall m. (MonadReader Env m, MonadError TCError m) => m a -- | Main entry point of the type checker. This function type checks an AST -- returning either an error or a well-typed program. For instance, -- assuming the following made up language: -- > -- > class C -- > val f: Foo -- > -- -- it should be parsed to generate the following AST: -- -- > testClass1 = -- > ClassDef {cname = "C" -- > ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}] -- > ,methods = []} -- > -- -- To type check the AST, run the 'tcProgram' combinator as follows: -- -- > tcProgram testClass1 -- tcProgram :: Program 'Parsed -> Either TCError (Program 'Checked) tcProgram p = do env <- runExcept $ generateEnvironment p let exceptM = runReaderT (typecheck p) env runExcept exceptM -- | The type class defines how to type check an AST node. class Typecheckable a where -- | Type check the well-formedness of an AST node. typecheck :: a 'Parsed -> TypecheckM (a 'Checked) -- Type checking the well-formedness of types instance Typecheckable Type where typecheck (ClassType c) = do _ <- findClass (ClassType c) return $ ClassType c typecheck IntType = return IntType typecheck BoolType = return BoolType typecheck UnitType = return UnitType typecheck (Arrow ts t) = do ts' <- mapM typecheck ts t' <- typecheck t return $ Arrow ts' t' instance Typecheckable Program where typecheck (Program classes) = Program <$> (mapM typecheck classes) instance Typecheckable ClassDef where typecheck ClassDef{cname, fields, methods} = do fields' <- local (addVariable thisName (ClassType cname)) $ mapM typecheck fields methods' <- local (addVariable thisName (ClassType cname)) $ mapM typecheck methods return $ ClassDef {fields = fields' ,cname ,methods = methods'} instance Typecheckable FieldDef where typecheck fdef@FieldDef{ftype} = do ftype' <- typecheck ftype return fdef{ftype = ftype'} instance Typecheckable Param where typecheck param@(Param {ptype}) = do ptype' <- typecheck ptype return param{ptype = ptype'} instance Typecheckable MethodDef where typecheck MethodDef {mname, mparams, mbody, mtype} = do -- typecheck the well-formedness of types of method parameters mparams' <- mapM typecheck mparams mtype' <- typecheck mtype -- extend environment with method parameters and typecheck body mbody' <- local (addParameters mparams' . setConstructor mname) $ hasType mbody mtype' return $ MethodDef {mname ,mparams = mparams' ,mtype = mtype' ,mbody = mbody'} instance Typecheckable Expr where typecheck BoolLit {bval} = return $ BoolLit (Just BoolType) bval typecheck IntLit {ival} = return $ IntLit (Just IntType) ival typecheck (Lambda {params, body}) = do params' <- mapM typecheck params body' <- local (addParameters params') $ typecheck body let parameterTypes = map ptype params' bodyType = getType body' funType = Arrow parameterTypes bodyType return $ Lambda {etype = Just funType ,params = params' ,body = body'} typecheck (VarAccess {name}) = do ty <- findVar name return $ VarAccess {etype = Just ty ,name} typecheck (FieldAccess {target, name}) = do target' <- typecheck target let targetType = getType target' FieldEntry {fetype} <- findField targetType name return $ FieldAccess{target = target' ,etype = Just fetype ,name } typecheck (Assignment {lhs, rhs}) = do lhs' <- typecheck lhs unless (isLVal lhs') $ throwError $ NonLValError lhs' let lType = getType lhs' rhs' <- hasType rhs lType checkMutability lhs' return $ Assignment {etype = Just UnitType ,lhs = lhs' ,rhs = rhs'} where checkMutability e@FieldAccess{target, name} = do FieldEntry {femod} <- findField (getType target) name inConstructor <- asks constructor unless (femod == Var || inConstructor && isThisAccess target) $ throwError $ ImmutableFieldError e checkMutability _ = return () typecheck New {ty, args} = do ty' <- typecheck ty MethodEntry {meparams, metype} <- findMethod ty' "init" let paramTypes = map ptype meparams args' <- zipWithM hasType args paramTypes return New {etype = Just ty' ,ty = ty' ,args = args'} typecheck MethodCall {target, name, args} = do target' <- typecheck target let targetType = getType target' when (isConstructorName name) $ throwError $ ConstructorCallError targetType MethodEntry {meparams, metype} <- findMethod targetType name let paramTypes = map ptype meparams args' <- zipWithM hasType args paramTypes return MethodCall {target = target' ,etype = Just metype ,name ,args = args'} typecheck (FunctionCall {target, args}) = do target' <- typecheck target let targetType = getType target' unless (isArrowType targetType) $ throwError $ NonArrowTypeError targetType let paramTypes = tparams targetType resultType = tresult targetType args' <- zipWithM hasType args paramTypes return $ FunctionCall {etype = Just resultType ,target = target' ,args = args'} typecheck (BinOp {op, lhs, rhs}) = do lhs' <- hasType lhs IntType rhs' <- hasType rhs IntType return $ BinOp {etype = Just IntType ,op ,lhs = lhs' ,rhs = rhs'} typecheck (Cast {body, ty}) = do ty' <- typecheck ty body' <- hasType body ty' return $ Cast {etype = Just ty' ,body = body' ,ty = ty'} typecheck (If {cond, thn, els}) = do cond' <- hasType cond BoolType thn' <- typecheck thn let thnType = getType thn' els' <- hasType els thnType return $ If {etype = Just thnType ,cond = cond' ,thn = thn' ,els = els'} typecheck (Let {name, val, body}) = do val' <- typecheck val let ty = getType val' body' <- local (addVariable name ty) $ typecheck body let bodyType = getType body' return $ Let{etype = Just bodyType ,name ,val = val' ,body = body'} typecheck e = throwError $ UninferrableError e -- | This combinator is used whenever a certain type is expected. This function -- is quite important. Here follows an example: -- -- > doTypecheck MethodDef {mname, mparams, mbody, mtype} = do -- > (mparams', mtype') <- forkM typecheck mparams <&> -- > typecheck mtype -- > -- extend environment with method parameters and typecheck body -- > mbody' <- local (addParameters mparams') $ hasType mbody mtype' -- -- in the last line we are type checking a method declaration, and -- it is statically known what should be the return type of the function body. In these -- cases, one should use the 'hasType' combinator. -- hasType :: Expr 'Parsed -> Type 'Checked -> TypecheckM (Expr 'Checked) hasType Null{} expected = do unless (isClassType expected) $ throwError $ PrimitiveNullError expected return $ Null {etype = Just expected} hasType e expected = do e' <- typecheck e let eType = getType e' unless (eType == expected) $ throwError $ TypeMismatchError eType expected return $ setType expected e' -- | Class definition for didactic purposes. This AST represents the following -- class, which is named @C@, contains an immutable field @f@ of type @Foo@: -- -- > class C: -- > val f: Foo -- -- This class is ill-typed, as there is no declaration of @Foo@ anywhere. -- To check how to type checker catches this error, run: -- -- > tcProgram (Program [testClass1]) -- testClass1 = ClassDef {cname = "C" ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}] ,methods = []} -- | Test program with a class, field, method, and variable access. The class @Bar@ -- does not exist in the environment. The variable access is unbound. -- -- This program is the AST equivalent of the following syntax: -- -- > class D -- > val g: Bar -- > def m(): Int -- > x -- testClass2 = ClassDef {cname = "D" ,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "Bar"}] ,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]} -- | Test program with a two classes, field, method, and variable access. The class -- declaration are duplicated. -- -- This program is the AST equivalent of the following syntax: -- -- > class D -- > val g: Bar -- > def m(): Int -- > x -- > -- > class D -- > val g: Bar -- > def m(): Int -- > x -- testClass3 = [ClassDef {cname = "D" ,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "D"}] ,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]}, ClassDef {cname = "D" ,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "D"}] ,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]}] --testProgram :: Program 'Parsed 'Parsed testProgram = Program [testClass1, testClass2] testValidProgram = Program testClass3
kikofernandez/kikofernandez.github.io
files/monadic-typechecker/typechecker/src/PhantomPhases/Typechecker.hs
mit
20,026
0
16
5,102
4,513
2,341
2,172
-1
-1
module Problem005 (answer) where answer :: Int answer = floor(2**4) * floor(3**2) * 5 * 7 * 11 * 13 * 17 * 19 -- just see the decomposition in prime factors of [1..20] -- and then pick the highest power for each factor
geekingfrog/project-euler
Problem005.hs
gpl-3.0
221
0
14
46
69
38
31
3
1
module FOOL.TPTP where import FOOL.AST data TPTP = TPTP [Sentence] data Sentence = TypeD Name FOOLTerm | Axiom Name FOOLTerm | Conj Name FOOLTerm deriving (Eq) type Name = String {- misc -} isOfType :: Name -> FOOLTerm -> Sentence isOfType = TypeD
emptylambda/BLT
src/FOOL/TPTP.hs
gpl-3.0
286
0
7
81
80
47
33
10
1
fac 0 = 1 fac n = n * fac (n-1) main = print ( fac 10 )
forflo/snippetbin
haskell/first.hs
gpl-3.0
56
0
8
18
45
22
23
3
1
import Control.Exception(Exception,catch,displayException,throwIO) import Control.Monad(foldM) import qualified Data.ByteString import Data.String(fromString) import System.Directory(removeFile,getCurrentDirectory,getTemporaryDirectory) import System.Environment(getArgs,getProgName) import System.Exit(exitFailure) import System.FilePath(combine,replaceExtension,takeExtension,takeFileName) import System.Posix(getProcessID) import System.Process(callProcess) import qualified LLVM.AST import LLVM.Context(Context,withContext) import LLVM.IRBuilder.Module(ModuleBuilder,buildModule) import LLVM.Module(File(File),Module,moduleLLVMAssembly,withModuleFromAST,withModuleFromBitcode,withModuleFromLLVMAssembly,writeLLVMAssemblyToFile,writeBitcodeToFile,writeTargetAssemblyToFile,writeObjectToFile) import LLVM.Target(TargetMachine,withHostTargetMachine) import qualified AST.AST import AST.Parse(parse) import CodeGen.CodeGen(codeGen) newtype CompileException = CompileException String deriving Show instance Exception CompileException where displayException (CompileException msg) = msg dgolFileToModule :: [String] -> Context -> FilePath -> (Module -> IO a) -> IO a dgolFileToModule libs context file process = do src <- readFile file dir <- getCurrentDirectory ast <- either (throwIO . CompileException . (file++) . (':':)) return $ parse file dir src let mbuilder = codeGen ast libs let mod = buildModule (fromString $ takeFileName file) mbuilder withModuleFromAST context mod { LLVM.AST.moduleSourceFileName = fromString file } process llFileToModule :: Context -> FilePath -> (Module -> IO a) -> IO a llFileToModule context file process = withModuleFromLLVMAssembly context (File (fromString file)) process bcFileToModule :: Context -> FilePath -> (Module -> IO a) -> IO a bcFileToModule context file process = withModuleFromBitcode context (File (fromString file)) process moduleToLL :: FilePath -> Module -> IO () moduleToLL file m = writeLLVMAssemblyToFile (File file) m moduleToBC :: FilePath -> Module -> IO () moduleToBC file m = writeBitcodeToFile (File file) m moduleToAsm :: FilePath -> Module -> IO () moduleToAsm file m = do withHostTargetMachine (\ targetMachine -> writeTargetAssemblyToFile targetMachine (File file) m) moduleToObj :: FilePath -> Module -> IO () moduleToObj file m = do withHostTargetMachine (\ targetMachine -> writeObjectToFile targetMachine (File file) m) usage :: IO a usage = do progName <- getProgName putStrLn "Usage:" putStr progName putStrLn " (-o BINFILE | -c | -s | -ll | -bc) [-L=LIB ...] FILE FILE ..." putStrLn "" putStrLn "Example:" putStr progName putStrLn " -o HELLO -L=IO HELLO.DGOL" exitFailure data OutputOption = BinFile String | ObjFile | AsmFile | LLFile | BCFile parseArgs :: IO (OutputOption,[String],[FilePath]) parseArgs = do args <- getArgs maybe usage return $ p Nothing [] [] args where p _ _ [] [] = Nothing p _ _ _ ["-o"] = Nothing p Nothing libs files ("-o":out:args) = p (Just $ BinFile out) libs files args p Nothing libs [] ("-c":args) = p (Just ObjFile) libs [] args p Nothing libs [] ("-s":args) = p (Just AsmFile) libs [] args p Nothing libs [] ("-ll":args) = p (Just LLFile) libs [] args p Nothing libs [] ("-bc":args) = p (Just BCFile) libs [] args p out libs files (('-':'L':'=':lib@_):args) = p out (libs ++ [lib]) files args p Nothing libs [] (file:args) = p (Just $ BinFile "a.out") libs [file] args p (Just _) _ _ ("-o":args) = Nothing p (Just _) _ _ ("-c":args) = Nothing p (Just _) _ _ ("-s":args) = Nothing p (Just _) _ _ ("-ll":args) = Nothing p (Just _) _ _ ("-bc":args) = Nothing p (Just out) libs files (arg:args) = p (Just out) libs (files ++ [arg]) args p (Just out) libs files [] = Just (out,libs,files) processFiles :: OutputOption -> [String] -> [FilePath] -> IO () processFiles (BinFile f) libs files = do pid <- getProcessID tmpDir <- getTemporaryDirectory (tmpObjFiles,objFiles,_) <- foldM (makeTmpObjFiles (combine tmpDir $ show pid) libs) ([],[],1) files callProcess "cc" (["-o",f] ++ tmpObjFiles ++ objFiles) mapM_ removeFile tmpObjFiles processFiles outputOption libs files = do mapM_ (withContext . processFile outputOption libs) files processFile :: OutputOption -> [String] -> FilePath -> Context -> IO () processFile ObjFile libs file context | takeExtension file == ".DGOL" = dgolFileToModule libs context file $ moduleToObj (replaceExtension file ".o") | takeExtension file == ".ll" = llFileToModule context file $ moduleToObj (replaceExtension file ".o") | takeExtension file == ".bc" = bcFileToModule context file $ moduleToObj (replaceExtension file ".o") | otherwise = return () processFile AsmFile libs file context | takeExtension file == ".DGOL" = dgolFileToModule libs context file $ moduleToAsm (replaceExtension file ".s") | takeExtension file == ".ll" = llFileToModule context file $ moduleToAsm (replaceExtension file ".s") | takeExtension file == ".bc" = bcFileToModule context file $ moduleToAsm (replaceExtension file ".s") | otherwise = return () processFile BCFile libs file context | takeExtension file == ".DGOL" = dgolFileToModule libs context file $ moduleToBC (replaceExtension file ".bc") | otherwise = return () processFile LLFile libs file context | takeExtension file == ".DGOL" = dgolFileToModule libs context file $ moduleToLL (replaceExtension file ".ll") | otherwise = return () makeTmpObjFiles :: FilePath -> [String] -> ([FilePath],[FilePath],Int) -> FilePath -> IO ([FilePath],[FilePath],Int) makeTmpObjFiles tmpFileBase libs (tmpObjFiles,objFiles,index) file = withContext mkTmpObj where mkTmpObj context | takeExtension file == ".DGOL" = do let tmpObjFile = tmpFileBase ++ "." ++ show index ++ ".o" dgolFileToModule libs context file $ moduleToObj tmpObjFile return (tmpObjFile:tmpObjFiles,objFiles,index+1) | takeExtension file == ".ll" = do let tmpObjFile = tmpFileBase ++ "." ++ show index ++ ".o" llFileToModule context file $ moduleToObj tmpObjFile return (tmpObjFile:tmpObjFiles,objFiles,index+1) | takeExtension file == ".bc" = do let tmpObjFile = tmpFileBase ++ "." ++ show index ++ ".o" bcFileToModule context file $ moduleToObj tmpObjFile return (tmpObjFile:tmpObjFiles,objFiles,index+1) | takeExtension file `elem` [".s",".o",".a"] = return (tmpObjFiles,file:objFiles,index+1) | otherwise = return (tmpObjFiles,objFiles,index+1) compileError :: CompileException -> IO a compileError e = do putStrLn $ displayException e exitFailure main :: IO () main = do (outputOption,libs,files) <- parseArgs catch (processFiles outputOption libs files) compileError ll :: [String] -> FilePath -> IO () ll libs file = do withContext (\ context -> do dgolFileToModule libs context file (\ m -> do llcode <- moduleLLVMAssembly m Data.ByteString.putStr llcode)) p :: FilePath -> IO () p file = do src <- readFile file dir <- getCurrentDirectory print $ parse file dir src m :: [String] -> FilePath -> IO LLVM.AST.Module m libs file = do src <- readFile file dir <- getCurrentDirectory ast <- either (throwIO . CompileException . (file++) . (':':)) return $ parse file dir src return $ buildModule (fromString $ takeFileName file) (codeGen ast libs)
qpliu/esolang
DGOL/hs/compiler/DGOLC.hs
gpl-3.0
7,584
0
18
1,468
2,816
1,411
1,405
152
16
module Editor.CodeEdit.DefinitionEdit(make, makeParts, addJumps) where import Control.Arrow (second) import Control.Monad (liftM) import Data.List.Utils (atPred, pairList) import Data.Monoid (Monoid(..)) import Data.Store.IRef (IRef) import Data.Store.Transaction (Transaction) import Data.Vector.Vector2 (Vector2(..)) import Editor.Anchors (ViewTag) import Editor.CTransaction (CTransaction, TWidget, transaction, getP) import Editor.CodeEdit.ExpressionEdit.ExpressionMaker(ExpressionEditMaker) import Editor.MonadF (MonadF) import Graphics.UI.Bottle.Widget (Widget) import Graphics.UI.Bottle.Widgets.Grid (GridElement) import qualified Data.List as List import qualified Data.Store.Property as Property import qualified Data.Store.Transaction as Transaction import qualified Editor.BottleWidgets as BWidgets import qualified Editor.CodeEdit.Ancestry as Ancestry import qualified Editor.CodeEdit.ExpressionEdit.FuncEdit as FuncEdit import qualified Editor.CodeEdit.Sugar as Sugar import qualified Editor.Config as Config import qualified Editor.Data as Data import qualified Editor.WidgetIds as WidgetIds import qualified Graphics.UI.Bottle.Direction as Direction import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.Bottle.Widgets.Box as Box import qualified Graphics.UI.Bottle.Widgets.FocusDelegator as FocusDelegator data Side = LHS | RHS deriving (Show, Eq) makeNameEdit :: Monad m => IRef a -> TWidget t m makeNameEdit definitionI = BWidgets.wrapDelegated FocusDelegator.NotDelegating (BWidgets.setTextColor Config.definitionColor . BWidgets.makeNameEdit Config.unnamedStr definitionI) $ WidgetIds.fromIRef definitionI makeLHSEdit :: MonadF m => ExpressionEditMaker m -> Ancestry.ExpressionAncestry m -> IRef a -> [Sugar.FuncParam m] -> TWidget ViewTag m makeLHSEdit makeExpressionEdit ancestry definitionI params = do nameEdit <- makeNameEdit definitionI liftM (BWidgets.gridHSpaced . List.transpose . map pairList . ((nameEdit, nameTypeFiller) :)) . mapM (FuncEdit.makeParamEdit makeExpressionEdit ancestry) $ params where -- no type for def name (yet): nameTypeFiller = BWidgets.spaceWidget -- from lhs->rhs and vice-versa: addJumps :: [(Maybe Side, Box.BoxElement f)] -> [(Maybe Side, Graphics.UI.Bottle.Widgets.Grid.GridElement f)] addJumps defKBoxElements = addEventMap LHS RHS "right-hand side" Config.jumpToRhsKeys Direction.fromLeft . addEventMap RHS LHS "left-hand side" Config.jumpToLhsKeys Direction.fromRight $ defKBoxElements where addEventMap srcSide destSide doc keys dir = atPred (== Just srcSide) (addJumpsTo doc keys dir $ Box.getElement (Just destSide) defKBoxElements) addJumpsTo doc keys dir = Box.atBoxElementSdwd . Widget.atSdwdEventMap . flip mappend . jumpToExpressionEventMap doc keys dir jumpToExpressionEventMap doc keys dir destElement = maybe mempty (makeJumpForEnter doc keys dir destElement) . Widget.sdwdMaybeEnter $ Box.boxElementSdwd destElement makeJumpForEnter doc keys dir destElement enter = E.fromEventTypes keys ("Jump to "++doc) . Widget.enterResultEvent . enter . dir $ Box.boxElementRect destElement makeParts :: MonadF m => ExpressionEditMaker m -> Ancestry.ExpressionAncestry m -> IRef a -> Sugar.ExpressionRef m -> CTransaction ViewTag m [(Maybe Side, Widget (Transaction ViewTag m))] makeParts makeExpressionEdit ancestry definitionI exprRef = do exprI <- getP $ Sugar.rExpressionPtr exprRef let sExpr = Sugar.rExpression exprRef func = case sExpr of Sugar.ExpressionFunc x -> x _ -> Sugar.Func [] exprRef lhsEdit <- makeLHSEdit makeExpressionEdit ancestry definitionI $ Sugar.fParams func equals <- BWidgets.makeLabel "=" (WidgetIds.fromIRef definitionI) rhsEdit <- makeExpressionEdit (Ancestry.AncestryItemLambda (Ancestry.LambdaParent func exprI) : ancestry) (Sugar.fBody func) return $ zipWith (second . Widget.align . (`Vector2` 0.5)) [1, 0.5, 0.5, 0.5, 0] [(Just LHS, lhsEdit) ,(Nothing, BWidgets.spaceWidget) ,(Nothing, equals) ,(Nothing, BWidgets.spaceWidget) ,(Just RHS, rhsEdit) ] make :: MonadF m => ExpressionEditMaker m -> IRef Data.Definition -> TWidget ViewTag m make makeExpressionEdit definitionI = do sExpr <- transaction $ Sugar.convertExpression exprPtr liftM ( Box.toWidget . (Box.atBoxContent . fmap) addJumps . BWidgets.hboxK ) $ makeParts makeExpressionEdit [] definitionI sExpr where exprPtr = Property.composeLabel Data.defBody Data.atDefBody (Transaction.fromIRef definitionI)
nimia/bottle
codeedit/Editor/CodeEdit/DefinitionEdit.hs
gpl-3.0
4,713
0
15
764
1,322
722
600
113
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Games.Achievements.UpdateMultiple -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates multiple achievements for the currently authenticated player. -- -- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.achievements.updateMultiple@. module Network.Google.Resource.Games.Achievements.UpdateMultiple ( -- * REST Resource AchievementsUpdateMultipleResource -- * Creating a Request , achievementsUpdateMultiple , AchievementsUpdateMultiple -- * Request Lenses , aumConsistencyToken , aumPayload ) where import Network.Google.Games.Types import Network.Google.Prelude -- | A resource alias for @games.achievements.updateMultiple@ method which the -- 'AchievementsUpdateMultiple' request conforms to. type AchievementsUpdateMultipleResource = "games" :> "v1" :> "achievements" :> "updateMultiple" :> QueryParam "consistencyToken" (Textual Int64) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] AchievementUpdateMultipleRequest :> Post '[JSON] AchievementUpdateMultipleResponse -- | Updates multiple achievements for the currently authenticated player. -- -- /See:/ 'achievementsUpdateMultiple' smart constructor. data AchievementsUpdateMultiple = AchievementsUpdateMultiple' { _aumConsistencyToken :: !(Maybe (Textual Int64)) , _aumPayload :: !AchievementUpdateMultipleRequest } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AchievementsUpdateMultiple' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aumConsistencyToken' -- -- * 'aumPayload' achievementsUpdateMultiple :: AchievementUpdateMultipleRequest -- ^ 'aumPayload' -> AchievementsUpdateMultiple achievementsUpdateMultiple pAumPayload_ = AchievementsUpdateMultiple' { _aumConsistencyToken = Nothing , _aumPayload = pAumPayload_ } -- | The last-seen mutation timestamp. aumConsistencyToken :: Lens' AchievementsUpdateMultiple (Maybe Int64) aumConsistencyToken = lens _aumConsistencyToken (\ s a -> s{_aumConsistencyToken = a}) . mapping _Coerce -- | Multipart request metadata. aumPayload :: Lens' AchievementsUpdateMultiple AchievementUpdateMultipleRequest aumPayload = lens _aumPayload (\ s a -> s{_aumPayload = a}) instance GoogleRequest AchievementsUpdateMultiple where type Rs AchievementsUpdateMultiple = AchievementUpdateMultipleResponse type Scopes AchievementsUpdateMultiple = '["https://www.googleapis.com/auth/games", "https://www.googleapis.com/auth/plus.login"] requestClient AchievementsUpdateMultiple'{..} = go _aumConsistencyToken (Just AltJSON) _aumPayload gamesService where go = buildClient (Proxy :: Proxy AchievementsUpdateMultipleResource) mempty
rueshyna/gogol
gogol-games/gen/Network/Google/Resource/Games/Achievements/UpdateMultiple.hs
mpl-2.0
3,784
0
14
805
413
245
168
66
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Compute.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Compute.Types.Sum where import Network.Google.Prelude -- | Defines the maintenance behavior for this instance. For standard -- instances, the default behavior is MIGRATE. For preemptible instances, -- the default and only possible behavior is TERMINATE. For more -- information, see Setting Instance Scheduling Options. data SchedulingOnHostMaintenance = Migrate -- ^ @MIGRATE@ | Terminate -- ^ @TERMINATE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SchedulingOnHostMaintenance instance FromHttpApiData SchedulingOnHostMaintenance where parseQueryParam = \case "MIGRATE" -> Right Migrate "TERMINATE" -> Right Terminate x -> Left ("Unable to parse SchedulingOnHostMaintenance from: " <> x) instance ToHttpApiData SchedulingOnHostMaintenance where toQueryParam = \case Migrate -> "MIGRATE" Terminate -> "TERMINATE" instance FromJSON SchedulingOnHostMaintenance where parseJSON = parseJSONText "SchedulingOnHostMaintenance" instance ToJSON SchedulingOnHostMaintenance where toJSON = toJSONText -- | Defines how target utilization value is expressed for a Stackdriver -- Monitoring metric. Either GAUGE, DELTA_PER_SECOND, or DELTA_PER_MINUTE. -- If not specified, the default is GAUGE. data AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType = DeltaPerMinute -- ^ @DELTA_PER_MINUTE@ | DeltaPerSecond -- ^ @DELTA_PER_SECOND@ | Gauge -- ^ @GAUGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType instance FromHttpApiData AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType where parseQueryParam = \case "DELTA_PER_MINUTE" -> Right DeltaPerMinute "DELTA_PER_SECOND" -> Right DeltaPerSecond "GAUGE" -> Right Gauge x -> Left ("Unable to parse AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType from: " <> x) instance ToHttpApiData AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType where toQueryParam = \case DeltaPerMinute -> "DELTA_PER_MINUTE" DeltaPerSecond -> "DELTA_PER_SECOND" Gauge -> "GAUGE" instance FromJSON AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType where parseJSON = parseJSONText "AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType" instance ToJSON AutoscalingPolicyCustomMetricUtilizationUtilizationTargetType where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data OperationWarningsItemCode = CleanupFailed -- ^ @CLEANUP_FAILED@ | DeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | DiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | FieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | InjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | NextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | NextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | NextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | NextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | NextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | NotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | NoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | RequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | ResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | SingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | Unreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OperationWarningsItemCode instance FromHttpApiData OperationWarningsItemCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right CleanupFailed "DEPRECATED_RESOURCE_USED" -> Right DeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right DiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right FieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right InjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right NextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right NextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right NextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right NextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right NextHopNotRunning "NOT_CRITICAL_ERROR" -> Right NotCriticalError "NO_RESULTS_ON_PAGE" -> Right NoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right RequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right ResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right SingleInstancePropertyTemplate "UNREACHABLE" -> Right Unreachable x -> Left ("Unable to parse OperationWarningsItemCode from: " <> x) instance ToHttpApiData OperationWarningsItemCode where toQueryParam = \case CleanupFailed -> "CLEANUP_FAILED" DeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" DiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" FieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" InjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" NextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" NextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" NextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" NextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" NextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" NotCriticalError -> "NOT_CRITICAL_ERROR" NoResultsOnPage -> "NO_RESULTS_ON_PAGE" RequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" ResourceNotDeleted -> "RESOURCE_NOT_DELETED" SingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" Unreachable -> "UNREACHABLE" instance FromJSON OperationWarningsItemCode where parseJSON = parseJSONText "OperationWarningsItemCode" instance ToJSON OperationWarningsItemCode where toJSON = toJSONText -- | The protocol this BackendService uses to communicate with backends. -- Possible values are HTTP, HTTPS, HTTP2, TCP and SSL. The default is -- HTTP. For internal load balancing, the possible values are TCP and UDP, -- and the default is TCP. data BackendServiceProtocol = HTTP -- ^ @HTTP@ | HTTPS -- ^ @HTTPS@ | SSL -- ^ @SSL@ | TCP -- ^ @TCP@ | Udp -- ^ @UDP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable BackendServiceProtocol instance FromHttpApiData BackendServiceProtocol where parseQueryParam = \case "HTTP" -> Right HTTP "HTTPS" -> Right HTTPS "SSL" -> Right SSL "TCP" -> Right TCP "UDP" -> Right Udp x -> Left ("Unable to parse BackendServiceProtocol from: " <> x) instance ToHttpApiData BackendServiceProtocol where toQueryParam = \case HTTP -> "HTTP" HTTPS -> "HTTPS" SSL -> "SSL" TCP -> "TCP" Udp -> "UDP" instance FromJSON BackendServiceProtocol where parseJSON = parseJSONText "BackendServiceProtocol" instance ToJSON BackendServiceProtocol where toJSON = toJSONText -- | Specifies the type of the disk, either SCRATCH or PERSISTENT. If not -- specified, the default is PERSISTENT. data AttachedDiskType = Persistent -- ^ @PERSISTENT@ | Scratch -- ^ @SCRATCH@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AttachedDiskType instance FromHttpApiData AttachedDiskType where parseQueryParam = \case "PERSISTENT" -> Right Persistent "SCRATCH" -> Right Scratch x -> Left ("Unable to parse AttachedDiskType from: " <> x) instance ToHttpApiData AttachedDiskType where toQueryParam = \case Persistent -> "PERSISTENT" Scratch -> "SCRATCH" instance FromJSON AttachedDiskType where parseJSON = parseJSONText "AttachedDiskType" instance ToJSON AttachedDiskType where toJSON = toJSONText -- | Specifies the type of proxy header to append before sending data to the -- backend, either NONE or PROXY_V1. The default is NONE. data TargetSSLProxyProxyHeader = None -- ^ @NONE@ | ProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetSSLProxyProxyHeader instance FromHttpApiData TargetSSLProxyProxyHeader where parseQueryParam = \case "NONE" -> Right None "PROXY_V1" -> Right ProxyV1 x -> Left ("Unable to parse TargetSSLProxyProxyHeader from: " <> x) instance ToHttpApiData TargetSSLProxyProxyHeader where toQueryParam = \case None -> "NONE" ProxyV1 -> "PROXY_V1" instance FromJSON TargetSSLProxyProxyHeader where parseJSON = parseJSONText "TargetSSLProxyProxyHeader" instance ToJSON TargetSSLProxyProxyHeader where toJSON = toJSONText -- | Instances in which state should be returned. Valid options are: \'ALL\', -- \'RUNNING\'. By default, it lists all instances. data RegionInstanceGroupsListInstancesRequestInstanceState = All -- ^ @ALL@ | Running -- ^ @RUNNING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RegionInstanceGroupsListInstancesRequestInstanceState instance FromHttpApiData RegionInstanceGroupsListInstancesRequestInstanceState where parseQueryParam = \case "ALL" -> Right All "RUNNING" -> Right Running x -> Left ("Unable to parse RegionInstanceGroupsListInstancesRequestInstanceState from: " <> x) instance ToHttpApiData RegionInstanceGroupsListInstancesRequestInstanceState where toQueryParam = \case All -> "ALL" Running -> "RUNNING" instance FromJSON RegionInstanceGroupsListInstancesRequestInstanceState where parseJSON = parseJSONText "RegionInstanceGroupsListInstancesRequestInstanceState" instance ToJSON RegionInstanceGroupsListInstancesRequestInstanceState where toJSON = toJSONText -- | The type of the image used to create this disk. The default and only -- value is RAW data ImageSourceType = Raw -- ^ @RAW@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ImageSourceType instance FromHttpApiData ImageSourceType where parseQueryParam = \case "RAW" -> Right Raw x -> Left ("Unable to parse ImageSourceType from: " <> x) instance ToHttpApiData ImageSourceType where toQueryParam = \case Raw -> "RAW" instance FromJSON ImageSourceType where parseJSON = parseJSONText "ImageSourceType" instance ToJSON ImageSourceType where toJSON = toJSONText -- | Type of session affinity to use. The default is NONE. When the load -- balancing scheme is EXTERNAL, can be NONE, CLIENT_IP, or -- GENERATED_COOKIE. When the load balancing scheme is INTERNAL, can be -- NONE, CLIENT_IP, CLIENT_IP_PROTO, or CLIENT_IP_PORT_PROTO. When the -- protocol is UDP, this field is not used. data BackendServiceSessionAffinity = BSSAClientIP -- ^ @CLIENT_IP@ | BSSAClientIPPortProto -- ^ @CLIENT_IP_PORT_PROTO@ | BSSAClientIPProto -- ^ @CLIENT_IP_PROTO@ | BSSAGeneratedCookie -- ^ @GENERATED_COOKIE@ | BSSANone -- ^ @NONE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable BackendServiceSessionAffinity instance FromHttpApiData BackendServiceSessionAffinity where parseQueryParam = \case "CLIENT_IP" -> Right BSSAClientIP "CLIENT_IP_PORT_PROTO" -> Right BSSAClientIPPortProto "CLIENT_IP_PROTO" -> Right BSSAClientIPProto "GENERATED_COOKIE" -> Right BSSAGeneratedCookie "NONE" -> Right BSSANone x -> Left ("Unable to parse BackendServiceSessionAffinity from: " <> x) instance ToHttpApiData BackendServiceSessionAffinity where toQueryParam = \case BSSAClientIP -> "CLIENT_IP" BSSAClientIPPortProto -> "CLIENT_IP_PORT_PROTO" BSSAClientIPProto -> "CLIENT_IP_PROTO" BSSAGeneratedCookie -> "GENERATED_COOKIE" BSSANone -> "NONE" instance FromJSON BackendServiceSessionAffinity where parseJSON = parseJSONText "BackendServiceSessionAffinity" instance ToJSON BackendServiceSessionAffinity where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data ForwardingRulesScopedListWarningCode = FRSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | FRSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | FRSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | FRSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | FRSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | FRSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | FRSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | FRSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | FRSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | FRSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | FRSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | FRSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | FRSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | FRSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | FRSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | FRSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ForwardingRulesScopedListWarningCode instance FromHttpApiData ForwardingRulesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right FRSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right FRSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right FRSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right FRSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right FRSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right FRSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right FRSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right FRSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right FRSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right FRSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right FRSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right FRSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right FRSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right FRSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right FRSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right FRSLWCUnreachable x -> Left ("Unable to parse ForwardingRulesScopedListWarningCode from: " <> x) instance ToHttpApiData ForwardingRulesScopedListWarningCode where toQueryParam = \case FRSLWCCleanupFailed -> "CLEANUP_FAILED" FRSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" FRSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" FRSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" FRSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" FRSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" FRSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" FRSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" FRSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" FRSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" FRSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" FRSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" FRSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" FRSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" FRSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" FRSLWCUnreachable -> "UNREACHABLE" instance FromJSON ForwardingRulesScopedListWarningCode where parseJSON = parseJSONText "ForwardingRulesScopedListWarningCode" instance ToJSON ForwardingRulesScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data OperationsScopedListWarningCode = OSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | OSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | OSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | OSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | OSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | OSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | OSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | OSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | OSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | OSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | OSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | OSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | OSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | OSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | OSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | OSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OperationsScopedListWarningCode instance FromHttpApiData OperationsScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right OSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right OSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right OSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right OSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right OSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right OSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right OSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right OSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right OSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right OSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right OSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right OSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right OSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right OSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right OSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right OSLWCUnreachable x -> Left ("Unable to parse OperationsScopedListWarningCode from: " <> x) instance ToHttpApiData OperationsScopedListWarningCode where toQueryParam = \case OSLWCCleanupFailed -> "CLEANUP_FAILED" OSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" OSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" OSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" OSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" OSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" OSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" OSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" OSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" OSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" OSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" OSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" OSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" OSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" OSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" OSLWCUnreachable -> "UNREACHABLE" instance FromJSON OperationsScopedListWarningCode where parseJSON = parseJSONText "OperationsScopedListWarningCode" instance ToJSON OperationsScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data DisksScopedListWarningCode = DSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | DSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | DSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | DSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | DSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | DSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | DSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | DSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | DSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | DSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | DSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | DSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | DSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | DSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | DSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | DSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DisksScopedListWarningCode instance FromHttpApiData DisksScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right DSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right DSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right DSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right DSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right DSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right DSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right DSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right DSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right DSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right DSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right DSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right DSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right DSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right DSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right DSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right DSLWCUnreachable x -> Left ("Unable to parse DisksScopedListWarningCode from: " <> x) instance ToHttpApiData DisksScopedListWarningCode where toQueryParam = \case DSLWCCleanupFailed -> "CLEANUP_FAILED" DSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" DSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" DSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" DSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" DSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" DSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" DSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" DSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" DSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" DSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" DSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" DSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" DSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" DSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" DSLWCUnreachable -> "UNREACHABLE" instance FromJSON DisksScopedListWarningCode where parseJSON = parseJSONText "DisksScopedListWarningCode" instance ToJSON DisksScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data InstanceGroupManagersScopedListWarningCode = IGMSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | IGMSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | IGMSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | IGMSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | IGMSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | IGMSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | IGMSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | IGMSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | IGMSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | IGMSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | IGMSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | IGMSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | IGMSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | IGMSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | IGMSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | IGMSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstanceGroupManagersScopedListWarningCode instance FromHttpApiData InstanceGroupManagersScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right IGMSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right IGMSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right IGMSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right IGMSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right IGMSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right IGMSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right IGMSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right IGMSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right IGMSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right IGMSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right IGMSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right IGMSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right IGMSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right IGMSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right IGMSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right IGMSLWCUnreachable x -> Left ("Unable to parse InstanceGroupManagersScopedListWarningCode from: " <> x) instance ToHttpApiData InstanceGroupManagersScopedListWarningCode where toQueryParam = \case IGMSLWCCleanupFailed -> "CLEANUP_FAILED" IGMSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" IGMSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" IGMSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" IGMSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" IGMSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" IGMSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" IGMSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" IGMSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" IGMSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" IGMSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" IGMSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" IGMSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" IGMSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" IGMSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" IGMSLWCUnreachable -> "UNREACHABLE" instance FromJSON InstanceGroupManagersScopedListWarningCode where parseJSON = parseJSONText "InstanceGroupManagersScopedListWarningCode" instance ToJSON InstanceGroupManagersScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data TargetPoolsScopedListWarningCode = TPSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | TPSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | TPSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | TPSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | TPSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | TPSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | TPSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | TPSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | TPSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | TPSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | TPSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | TPSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | TPSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | TPSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | TPSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | TPSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetPoolsScopedListWarningCode instance FromHttpApiData TargetPoolsScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right TPSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right TPSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right TPSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right TPSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right TPSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right TPSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right TPSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right TPSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right TPSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right TPSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right TPSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right TPSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right TPSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right TPSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right TPSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right TPSLWCUnreachable x -> Left ("Unable to parse TargetPoolsScopedListWarningCode from: " <> x) instance ToHttpApiData TargetPoolsScopedListWarningCode where toQueryParam = \case TPSLWCCleanupFailed -> "CLEANUP_FAILED" TPSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" TPSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" TPSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" TPSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" TPSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" TPSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" TPSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" TPSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" TPSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" TPSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" TPSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" TPSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" TPSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" TPSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" TPSLWCUnreachable -> "UNREACHABLE" instance FromJSON TargetPoolsScopedListWarningCode where parseJSON = parseJSONText "TargetPoolsScopedListWarningCode" instance ToJSON TargetPoolsScopedListWarningCode where toJSON = toJSONText -- | Specifies the type of proxy header to append before sending data to the -- backend, either NONE or PROXY_V1. The default is NONE. data SSLHealthCheckProxyHeader = SHCPHNone -- ^ @NONE@ | SHCPHProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SSLHealthCheckProxyHeader instance FromHttpApiData SSLHealthCheckProxyHeader where parseQueryParam = \case "NONE" -> Right SHCPHNone "PROXY_V1" -> Right SHCPHProxyV1 x -> Left ("Unable to parse SSLHealthCheckProxyHeader from: " <> x) instance ToHttpApiData SSLHealthCheckProxyHeader where toQueryParam = \case SHCPHNone -> "NONE" SHCPHProxyV1 -> "PROXY_V1" instance FromJSON SSLHealthCheckProxyHeader where parseJSON = parseJSONText "SSLHealthCheckProxyHeader" instance ToJSON SSLHealthCheckProxyHeader where toJSON = toJSONText -- | [Output Only] The status of the VPN gateway. data TargetVPNGatewayStatus = Creating -- ^ @CREATING@ | Deleting -- ^ @DELETING@ | Failed -- ^ @FAILED@ | Ready -- ^ @READY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetVPNGatewayStatus instance FromHttpApiData TargetVPNGatewayStatus where parseQueryParam = \case "CREATING" -> Right Creating "DELETING" -> Right Deleting "FAILED" -> Right Failed "READY" -> Right Ready x -> Left ("Unable to parse TargetVPNGatewayStatus from: " <> x) instance ToHttpApiData TargetVPNGatewayStatus where toQueryParam = \case Creating -> "CREATING" Deleting -> "DELETING" Failed -> "FAILED" Ready -> "READY" instance FromJSON TargetVPNGatewayStatus where parseJSON = parseJSONText "TargetVPNGatewayStatus" instance ToJSON TargetVPNGatewayStatus where toJSON = toJSONText -- | [Output Only] The status of the snapshot. This can be CREATING, -- DELETING, FAILED, READY, or UPLOADING. data SnapshotStatus = SSCreating -- ^ @CREATING@ | SSDeleting -- ^ @DELETING@ | SSFailed -- ^ @FAILED@ | SSReady -- ^ @READY@ | SSUploading -- ^ @UPLOADING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SnapshotStatus instance FromHttpApiData SnapshotStatus where parseQueryParam = \case "CREATING" -> Right SSCreating "DELETING" -> Right SSDeleting "FAILED" -> Right SSFailed "READY" -> Right SSReady "UPLOADING" -> Right SSUploading x -> Left ("Unable to parse SnapshotStatus from: " <> x) instance ToHttpApiData SnapshotStatus where toQueryParam = \case SSCreating -> "CREATING" SSDeleting -> "DELETING" SSFailed -> "FAILED" SSReady -> "READY" SSUploading -> "UPLOADING" instance FromJSON SnapshotStatus where parseJSON = parseJSONText "SnapshotStatus" instance ToJSON SnapshotStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data TargetInstancesScopedListWarningCode = TISLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | TISLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | TISLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | TISLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | TISLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | TISLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | TISLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | TISLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | TISLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | TISLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | TISLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | TISLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | TISLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | TISLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | TISLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | TISLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetInstancesScopedListWarningCode instance FromHttpApiData TargetInstancesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right TISLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right TISLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right TISLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right TISLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right TISLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right TISLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right TISLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right TISLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right TISLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right TISLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right TISLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right TISLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right TISLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right TISLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right TISLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right TISLWCUnreachable x -> Left ("Unable to parse TargetInstancesScopedListWarningCode from: " <> x) instance ToHttpApiData TargetInstancesScopedListWarningCode where toQueryParam = \case TISLWCCleanupFailed -> "CLEANUP_FAILED" TISLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" TISLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" TISLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" TISLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" TISLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" TISLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" TISLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" TISLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" TISLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" TISLWCNotCriticalError -> "NOT_CRITICAL_ERROR" TISLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" TISLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" TISLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" TISLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" TISLWCUnreachable -> "UNREACHABLE" instance FromJSON TargetInstancesScopedListWarningCode where parseJSON = parseJSONText "TargetInstancesScopedListWarningCode" instance ToJSON TargetInstancesScopedListWarningCode where toJSON = toJSONText -- | The type of supported feature. Currenty only VIRTIO_SCSI_MULTIQUEUE is -- supported. For newer Windows images, the server might also populate this -- property with the value WINDOWS to indicate that this is a Windows -- image. This value is purely informational and does not enable or disable -- any features. data GuestOSFeatureType = FeatureTypeUnspecified -- ^ @FEATURE_TYPE_UNSPECIFIED@ | VirtioScsiMultiQueue -- ^ @VIRTIO_SCSI_MULTIQUEUE@ | Windows -- ^ @WINDOWS@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable GuestOSFeatureType instance FromHttpApiData GuestOSFeatureType where parseQueryParam = \case "FEATURE_TYPE_UNSPECIFIED" -> Right FeatureTypeUnspecified "VIRTIO_SCSI_MULTIQUEUE" -> Right VirtioScsiMultiQueue "WINDOWS" -> Right Windows x -> Left ("Unable to parse GuestOSFeatureType from: " <> x) instance ToHttpApiData GuestOSFeatureType where toQueryParam = \case FeatureTypeUnspecified -> "FEATURE_TYPE_UNSPECIFIED" VirtioScsiMultiQueue -> "VIRTIO_SCSI_MULTIQUEUE" Windows -> "WINDOWS" instance FromJSON GuestOSFeatureType where parseJSON = parseJSONText "GuestOSFeatureType" instance ToJSON GuestOSFeatureType where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data RouteWarningsItemCode = RWICCleanupFailed -- ^ @CLEANUP_FAILED@ | RWICDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | RWICDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | RWICFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | RWICInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | RWICNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | RWICNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | RWICNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | RWICNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | RWICNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | RWICNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | RWICNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | RWICRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | RWICResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | RWICSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | RWICUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RouteWarningsItemCode instance FromHttpApiData RouteWarningsItemCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right RWICCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right RWICDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right RWICDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right RWICFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right RWICInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right RWICNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right RWICNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right RWICNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right RWICNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right RWICNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right RWICNotCriticalError "NO_RESULTS_ON_PAGE" -> Right RWICNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right RWICRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right RWICResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right RWICSingleInstancePropertyTemplate "UNREACHABLE" -> Right RWICUnreachable x -> Left ("Unable to parse RouteWarningsItemCode from: " <> x) instance ToHttpApiData RouteWarningsItemCode where toQueryParam = \case RWICCleanupFailed -> "CLEANUP_FAILED" RWICDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" RWICDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" RWICFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" RWICInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" RWICNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" RWICNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" RWICNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" RWICNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" RWICNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" RWICNotCriticalError -> "NOT_CRITICAL_ERROR" RWICNoResultsOnPage -> "NO_RESULTS_ON_PAGE" RWICRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" RWICResourceNotDeleted -> "RESOURCE_NOT_DELETED" RWICSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" RWICUnreachable -> "UNREACHABLE" instance FromJSON RouteWarningsItemCode where parseJSON = parseJSONText "RouteWarningsItemCode" instance ToJSON RouteWarningsItemCode where toJSON = toJSONText -- | [Output Only] An indicator whether storageBytes is in a stable state or -- it is being adjusted as a result of shared storage reallocation. This -- status can either be UPDATING, meaning the size of the snapshot is being -- updated, or UP_TO_DATE, meaning the size of the snapshot is up-to-date. data SnapshotStorageBytesStatus = Updating -- ^ @UPDATING@ | UpToDate -- ^ @UP_TO_DATE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SnapshotStorageBytesStatus instance FromHttpApiData SnapshotStorageBytesStatus where parseQueryParam = \case "UPDATING" -> Right Updating "UP_TO_DATE" -> Right UpToDate x -> Left ("Unable to parse SnapshotStorageBytesStatus from: " <> x) instance ToHttpApiData SnapshotStorageBytesStatus where toQueryParam = \case Updating -> "UPDATING" UpToDate -> "UP_TO_DATE" instance FromJSON SnapshotStorageBytesStatus where parseJSON = parseJSONText "SnapshotStorageBytesStatus" instance ToJSON SnapshotStorageBytesStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data AddressesScopedListWarningCode = ASLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | ASLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | ASLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | ASLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | ASLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | ASLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | ASLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | ASLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | ASLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | ASLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | ASLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | ASLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | ASLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | ASLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | ASLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | ASLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AddressesScopedListWarningCode instance FromHttpApiData AddressesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right ASLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right ASLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right ASLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right ASLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right ASLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right ASLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right ASLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right ASLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right ASLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right ASLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right ASLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right ASLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right ASLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right ASLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right ASLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right ASLWCUnreachable x -> Left ("Unable to parse AddressesScopedListWarningCode from: " <> x) instance ToHttpApiData AddressesScopedListWarningCode where toQueryParam = \case ASLWCCleanupFailed -> "CLEANUP_FAILED" ASLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" ASLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" ASLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" ASLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" ASLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" ASLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" ASLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" ASLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" ASLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" ASLWCNotCriticalError -> "NOT_CRITICAL_ERROR" ASLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" ASLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" ASLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" ASLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" ASLWCUnreachable -> "UNREACHABLE" instance FromJSON AddressesScopedListWarningCode where parseJSON = parseJSONText "AddressesScopedListWarningCode" instance ToJSON AddressesScopedListWarningCode where toJSON = toJSONText -- | [Output Only] The status of the image. An image can be used to create -- other resources, such as instances, only after the image has been -- successfully created and the status is set to READY. Possible values are -- FAILED, PENDING, or READY. data ImageStatus = ISFailed -- ^ @FAILED@ | ISPending -- ^ @PENDING@ | ISReady -- ^ @READY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ImageStatus instance FromHttpApiData ImageStatus where parseQueryParam = \case "FAILED" -> Right ISFailed "PENDING" -> Right ISPending "READY" -> Right ISReady x -> Left ("Unable to parse ImageStatus from: " <> x) instance ToHttpApiData ImageStatus where toQueryParam = \case ISFailed -> "FAILED" ISPending -> "PENDING" ISReady -> "READY" instance FromJSON ImageStatus where parseJSON = parseJSONText "ImageStatus" instance ToJSON ImageStatus where toJSON = toJSONText -- | Health state of the instance. data HealthStatusHealthState = Healthy -- ^ @HEALTHY@ | Unhealthy -- ^ @UNHEALTHY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable HealthStatusHealthState instance FromHttpApiData HealthStatusHealthState where parseQueryParam = \case "HEALTHY" -> Right Healthy "UNHEALTHY" -> Right Unhealthy x -> Left ("Unable to parse HealthStatusHealthState from: " <> x) instance ToHttpApiData HealthStatusHealthState where toQueryParam = \case Healthy -> "HEALTHY" Unhealthy -> "UNHEALTHY" instance FromJSON HealthStatusHealthState where parseJSON = parseJSONText "HealthStatusHealthState" instance ToJSON HealthStatusHealthState where toJSON = toJSONText -- | The deprecation state of this resource. This can be DEPRECATED, -- OBSOLETE, or DELETED. Operations which create a new resource using a -- DEPRECATED resource will return successfully, but with a warning -- indicating the deprecated resource and recommending its replacement. -- Operations which use OBSOLETE or DELETED resources will be rejected and -- result in an error. data DeprecationStatusState = Deleted -- ^ @DELETED@ | Deprecated -- ^ @DEPRECATED@ | Obsolete -- ^ @OBSOLETE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DeprecationStatusState instance FromHttpApiData DeprecationStatusState where parseQueryParam = \case "DELETED" -> Right Deleted "DEPRECATED" -> Right Deprecated "OBSOLETE" -> Right Obsolete x -> Left ("Unable to parse DeprecationStatusState from: " <> x) instance ToHttpApiData DeprecationStatusState where toQueryParam = \case Deleted -> "DELETED" Deprecated -> "DEPRECATED" Obsolete -> "OBSOLETE" instance FromJSON DeprecationStatusState where parseJSON = parseJSONText "DeprecationStatusState" instance ToJSON DeprecationStatusState where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data RoutersScopedListWarningCode = RSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | RSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | RSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | RSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | RSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | RSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | RSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | RSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | RSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | RSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | RSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | RSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | RSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | RSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | RSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | RSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RoutersScopedListWarningCode instance FromHttpApiData RoutersScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right RSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right RSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right RSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right RSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right RSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right RSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right RSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right RSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right RSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right RSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right RSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right RSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right RSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right RSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right RSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right RSLWCUnreachable x -> Left ("Unable to parse RoutersScopedListWarningCode from: " <> x) instance ToHttpApiData RoutersScopedListWarningCode where toQueryParam = \case RSLWCCleanupFailed -> "CLEANUP_FAILED" RSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" RSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" RSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" RSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" RSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" RSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" RSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" RSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" RSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" RSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" RSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" RSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" RSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" RSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" RSLWCUnreachable -> "UNREACHABLE" instance FromJSON RoutersScopedListWarningCode where parseJSON = parseJSONText "RoutersScopedListWarningCode" instance ToJSON RoutersScopedListWarningCode where toJSON = toJSONText -- | [Output Only] The current action that the managed instance group has -- scheduled for the instance. Possible values: - NONE The instance is -- running, and the managed instance group does not have any scheduled -- actions for this instance. - CREATING The managed instance group is -- creating this instance. If the group fails to create this instance, it -- will try again until it is successful. - CREATING_WITHOUT_RETRIES The -- managed instance group is attempting to create this instance only once. -- If the group fails to create this instance, it does not try again and -- the group\'s targetSize value is decreased instead. - RECREATING The -- managed instance group is recreating this instance. - DELETING The -- managed instance group is permanently deleting this instance. - -- ABANDONING The managed instance group is abandoning this instance. The -- instance will be removed from the instance group and from any target -- pools that are associated with this group. - RESTARTING The managed -- instance group is restarting the instance. - REFRESHING The managed -- instance group is applying configuration changes to the instance without -- stopping it. For example, the group can update the target pool list for -- an instance without stopping that instance. data ManagedInstanceCurrentAction = MICAAbandoning -- ^ @ABANDONING@ | MICACreating -- ^ @CREATING@ | MICACreatingWithoutRetries -- ^ @CREATING_WITHOUT_RETRIES@ | MICADeleting -- ^ @DELETING@ | MICANone -- ^ @NONE@ | MICARecreating -- ^ @RECREATING@ | MICARefreshing -- ^ @REFRESHING@ | MICARestarting -- ^ @RESTARTING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ManagedInstanceCurrentAction instance FromHttpApiData ManagedInstanceCurrentAction where parseQueryParam = \case "ABANDONING" -> Right MICAAbandoning "CREATING" -> Right MICACreating "CREATING_WITHOUT_RETRIES" -> Right MICACreatingWithoutRetries "DELETING" -> Right MICADeleting "NONE" -> Right MICANone "RECREATING" -> Right MICARecreating "REFRESHING" -> Right MICARefreshing "RESTARTING" -> Right MICARestarting x -> Left ("Unable to parse ManagedInstanceCurrentAction from: " <> x) instance ToHttpApiData ManagedInstanceCurrentAction where toQueryParam = \case MICAAbandoning -> "ABANDONING" MICACreating -> "CREATING" MICACreatingWithoutRetries -> "CREATING_WITHOUT_RETRIES" MICADeleting -> "DELETING" MICANone -> "NONE" MICARecreating -> "RECREATING" MICARefreshing -> "REFRESHING" MICARestarting -> "RESTARTING" instance FromJSON ManagedInstanceCurrentAction where parseJSON = parseJSONText "ManagedInstanceCurrentAction" instance ToJSON ManagedInstanceCurrentAction where toJSON = toJSONText -- | NAT option controlling how IPs are NAT\'ed to the instance. Currently -- only NO_NAT (default value) is supported. data TargetInstanceNATPolicy = NoNAT -- ^ @NO_NAT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetInstanceNATPolicy instance FromHttpApiData TargetInstanceNATPolicy where parseQueryParam = \case "NO_NAT" -> Right NoNAT x -> Left ("Unable to parse TargetInstanceNATPolicy from: " <> x) instance ToHttpApiData TargetInstanceNATPolicy where toQueryParam = \case NoNAT -> "NO_NAT" instance FromJSON TargetInstanceNATPolicy where parseJSON = parseJSONText "TargetInstanceNATPolicy" instance ToJSON TargetInstanceNATPolicy where toJSON = toJSONText -- | The type of configuration. The default and only option is -- ONE_TO_ONE_NAT. data AccessConfigType = OneToOneNAT -- ^ @ONE_TO_ONE_NAT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccessConfigType instance FromHttpApiData AccessConfigType where parseQueryParam = \case "ONE_TO_ONE_NAT" -> Right OneToOneNAT x -> Left ("Unable to parse AccessConfigType from: " <> x) instance ToHttpApiData AccessConfigType where toQueryParam = \case OneToOneNAT -> "ONE_TO_ONE_NAT" instance FromJSON AccessConfigType where parseJSON = parseJSONText "AccessConfigType" instance ToJSON AccessConfigType where toJSON = toJSONText data BackendServiceLoadBalancingScheme = External -- ^ @EXTERNAL@ | Internal -- ^ @INTERNAL@ | InvalidLoadBalancingScheme -- ^ @INVALID_LOAD_BALANCING_SCHEME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable BackendServiceLoadBalancingScheme instance FromHttpApiData BackendServiceLoadBalancingScheme where parseQueryParam = \case "EXTERNAL" -> Right External "INTERNAL" -> Right Internal "INVALID_LOAD_BALANCING_SCHEME" -> Right InvalidLoadBalancingScheme x -> Left ("Unable to parse BackendServiceLoadBalancingScheme from: " <> x) instance ToHttpApiData BackendServiceLoadBalancingScheme where toQueryParam = \case External -> "EXTERNAL" Internal -> "INTERNAL" InvalidLoadBalancingScheme -> "INVALID_LOAD_BALANCING_SCHEME" instance FromJSON BackendServiceLoadBalancingScheme where parseJSON = parseJSONText "BackendServiceLoadBalancingScheme" instance ToJSON BackendServiceLoadBalancingScheme where toJSON = toJSONText -- | [Output Only] The status of the operation, which can be one of the -- following: PENDING, RUNNING, or DONE. data OperationStatus = OSDone -- ^ @DONE@ | OSPending -- ^ @PENDING@ | OSRunning -- ^ @RUNNING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OperationStatus instance FromHttpApiData OperationStatus where parseQueryParam = \case "DONE" -> Right OSDone "PENDING" -> Right OSPending "RUNNING" -> Right OSRunning x -> Left ("Unable to parse OperationStatus from: " <> x) instance ToHttpApiData OperationStatus where toQueryParam = \case OSDone -> "DONE" OSPending -> "PENDING" OSRunning -> "RUNNING" instance FromJSON OperationStatus where parseJSON = parseJSONText "OperationStatus" instance ToJSON OperationStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data TargetVPNGatewaysScopedListWarningCode = TVGSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | TVGSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | TVGSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | TVGSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | TVGSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | TVGSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | TVGSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | TVGSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | TVGSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | TVGSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | TVGSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | TVGSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | TVGSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | TVGSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | TVGSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | TVGSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetVPNGatewaysScopedListWarningCode instance FromHttpApiData TargetVPNGatewaysScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right TVGSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right TVGSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right TVGSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right TVGSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right TVGSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right TVGSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right TVGSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right TVGSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right TVGSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right TVGSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right TVGSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right TVGSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right TVGSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right TVGSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right TVGSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right TVGSLWCUnreachable x -> Left ("Unable to parse TargetVPNGatewaysScopedListWarningCode from: " <> x) instance ToHttpApiData TargetVPNGatewaysScopedListWarningCode where toQueryParam = \case TVGSLWCCleanupFailed -> "CLEANUP_FAILED" TVGSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" TVGSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" TVGSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" TVGSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" TVGSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" TVGSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" TVGSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" TVGSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" TVGSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" TVGSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" TVGSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" TVGSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" TVGSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" TVGSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" TVGSLWCUnreachable -> "UNREACHABLE" instance FromJSON TargetVPNGatewaysScopedListWarningCode where parseJSON = parseJSONText "TargetVPNGatewaysScopedListWarningCode" instance ToJSON TargetVPNGatewaysScopedListWarningCode where toJSON = toJSONText -- | [Output Only] The status of disk creation. data DiskStatus = DSCreating -- ^ @CREATING@ | DSFailed -- ^ @FAILED@ | DSReady -- ^ @READY@ | DSRestoring -- ^ @RESTORING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DiskStatus instance FromHttpApiData DiskStatus where parseQueryParam = \case "CREATING" -> Right DSCreating "FAILED" -> Right DSFailed "READY" -> Right DSReady "RESTORING" -> Right DSRestoring x -> Left ("Unable to parse DiskStatus from: " <> x) instance ToHttpApiData DiskStatus where toQueryParam = \case DSCreating -> "CREATING" DSFailed -> "FAILED" DSReady -> "READY" DSRestoring -> "RESTORING" instance FromJSON DiskStatus where parseJSON = parseJSONText "DiskStatus" instance ToJSON DiskStatus where toJSON = toJSONText -- | [Output Only] The status of the instance. This field is empty when the -- instance does not exist. data ManagedInstanceInstanceStatus = MIISProvisioning -- ^ @PROVISIONING@ | MIISRunning -- ^ @RUNNING@ | MIISStaging -- ^ @STAGING@ | MIISStopped -- ^ @STOPPED@ | MIISStopping -- ^ @STOPPING@ | MIISSuspended -- ^ @SUSPENDED@ | MIISSuspending -- ^ @SUSPENDING@ | MIISTerminated -- ^ @TERMINATED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ManagedInstanceInstanceStatus instance FromHttpApiData ManagedInstanceInstanceStatus where parseQueryParam = \case "PROVISIONING" -> Right MIISProvisioning "RUNNING" -> Right MIISRunning "STAGING" -> Right MIISStaging "STOPPED" -> Right MIISStopped "STOPPING" -> Right MIISStopping "SUSPENDED" -> Right MIISSuspended "SUSPENDING" -> Right MIISSuspending "TERMINATED" -> Right MIISTerminated x -> Left ("Unable to parse ManagedInstanceInstanceStatus from: " <> x) instance ToHttpApiData ManagedInstanceInstanceStatus where toQueryParam = \case MIISProvisioning -> "PROVISIONING" MIISRunning -> "RUNNING" MIISStaging -> "STAGING" MIISStopped -> "STOPPED" MIISStopping -> "STOPPING" MIISSuspended -> "SUSPENDED" MIISSuspending -> "SUSPENDING" MIISTerminated -> "TERMINATED" instance FromJSON ManagedInstanceInstanceStatus where parseJSON = parseJSONText "ManagedInstanceInstanceStatus" instance ToJSON ManagedInstanceInstanceStatus where toJSON = toJSONText -- | Specifies the type of proxy header to append before sending data to the -- backend, either NONE or PROXY_V1. The default is NONE. data HTTPHealthCheckProxyHeader = HTTPHCPHNone -- ^ @NONE@ | HTTPHCPHProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable HTTPHealthCheckProxyHeader instance FromHttpApiData HTTPHealthCheckProxyHeader where parseQueryParam = \case "NONE" -> Right HTTPHCPHNone "PROXY_V1" -> Right HTTPHCPHProxyV1 x -> Left ("Unable to parse HTTPHealthCheckProxyHeader from: " <> x) instance ToHttpApiData HTTPHealthCheckProxyHeader where toQueryParam = \case HTTPHCPHNone -> "NONE" HTTPHCPHProxyV1 -> "PROXY_V1" instance FromJSON HTTPHealthCheckProxyHeader where parseJSON = parseJSONText "HTTPHealthCheckProxyHeader" instance ToJSON HTTPHealthCheckProxyHeader where toJSON = toJSONText -- | The mode in which to attach this disk, either READ_WRITE or READ_ONLY. -- If not specified, the default is to attach the disk in READ_WRITE mode. data AttachedDiskMode = ReadOnly -- ^ @READ_ONLY@ | ReadWrite -- ^ @READ_WRITE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AttachedDiskMode instance FromHttpApiData AttachedDiskMode where parseQueryParam = \case "READ_ONLY" -> Right ReadOnly "READ_WRITE" -> Right ReadWrite x -> Left ("Unable to parse AttachedDiskMode from: " <> x) instance ToHttpApiData AttachedDiskMode where toQueryParam = \case ReadOnly -> "READ_ONLY" ReadWrite -> "READ_WRITE" instance FromJSON AttachedDiskMode where parseJSON = parseJSONText "AttachedDiskMode" instance ToJSON AttachedDiskMode where toJSON = toJSONText -- | [Output Only] Status of the region, either UP or DOWN. data RegionStatus = Down -- ^ @DOWN@ | UP -- ^ @UP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RegionStatus instance FromHttpApiData RegionStatus where parseQueryParam = \case "DOWN" -> Right Down "UP" -> Right UP x -> Left ("Unable to parse RegionStatus from: " <> x) instance ToHttpApiData RegionStatus where toQueryParam = \case Down -> "DOWN" UP -> "UP" instance FromJSON RegionStatus where parseJSON = parseJSONText "RegionStatus" instance ToJSON RegionStatus where toJSON = toJSONText -- | The new type of proxy header to append before sending data to the -- backend. NONE or PROXY_V1 are allowed. data TargetSSLProxiesSetProxyHeaderRequestProxyHeader = TSPSPHRPHNone -- ^ @NONE@ | TSPSPHRPHProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetSSLProxiesSetProxyHeaderRequestProxyHeader instance FromHttpApiData TargetSSLProxiesSetProxyHeaderRequestProxyHeader where parseQueryParam = \case "NONE" -> Right TSPSPHRPHNone "PROXY_V1" -> Right TSPSPHRPHProxyV1 x -> Left ("Unable to parse TargetSSLProxiesSetProxyHeaderRequestProxyHeader from: " <> x) instance ToHttpApiData TargetSSLProxiesSetProxyHeaderRequestProxyHeader where toQueryParam = \case TSPSPHRPHNone -> "NONE" TSPSPHRPHProxyV1 -> "PROXY_V1" instance FromJSON TargetSSLProxiesSetProxyHeaderRequestProxyHeader where parseJSON = parseJSONText "TargetSSLProxiesSetProxyHeaderRequestProxyHeader" instance ToJSON TargetSSLProxiesSetProxyHeaderRequestProxyHeader where toJSON = toJSONText -- | [Output Only] The status of the VPN tunnel. data VPNTunnelStatus = VTSAllocatingResources -- ^ @ALLOCATING_RESOURCES@ | VTSAuthorizationError -- ^ @AUTHORIZATION_ERROR@ | VTSDeprovisioning -- ^ @DEPROVISIONING@ | VTSEstablished -- ^ @ESTABLISHED@ | VTSFailed -- ^ @FAILED@ | VTSFirstHandshake -- ^ @FIRST_HANDSHAKE@ | VTSNegotiationFailure -- ^ @NEGOTIATION_FAILURE@ | VTSNetworkError -- ^ @NETWORK_ERROR@ | VTSNoIncomingPackets -- ^ @NO_INCOMING_PACKETS@ | VTSProvisioning -- ^ @PROVISIONING@ | VTSRejected -- ^ @REJECTED@ | VTSWaitingForFullConfig -- ^ @WAITING_FOR_FULL_CONFIG@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable VPNTunnelStatus instance FromHttpApiData VPNTunnelStatus where parseQueryParam = \case "ALLOCATING_RESOURCES" -> Right VTSAllocatingResources "AUTHORIZATION_ERROR" -> Right VTSAuthorizationError "DEPROVISIONING" -> Right VTSDeprovisioning "ESTABLISHED" -> Right VTSEstablished "FAILED" -> Right VTSFailed "FIRST_HANDSHAKE" -> Right VTSFirstHandshake "NEGOTIATION_FAILURE" -> Right VTSNegotiationFailure "NETWORK_ERROR" -> Right VTSNetworkError "NO_INCOMING_PACKETS" -> Right VTSNoIncomingPackets "PROVISIONING" -> Right VTSProvisioning "REJECTED" -> Right VTSRejected "WAITING_FOR_FULL_CONFIG" -> Right VTSWaitingForFullConfig x -> Left ("Unable to parse VPNTunnelStatus from: " <> x) instance ToHttpApiData VPNTunnelStatus where toQueryParam = \case VTSAllocatingResources -> "ALLOCATING_RESOURCES" VTSAuthorizationError -> "AUTHORIZATION_ERROR" VTSDeprovisioning -> "DEPROVISIONING" VTSEstablished -> "ESTABLISHED" VTSFailed -> "FAILED" VTSFirstHandshake -> "FIRST_HANDSHAKE" VTSNegotiationFailure -> "NEGOTIATION_FAILURE" VTSNetworkError -> "NETWORK_ERROR" VTSNoIncomingPackets -> "NO_INCOMING_PACKETS" VTSProvisioning -> "PROVISIONING" VTSRejected -> "REJECTED" VTSWaitingForFullConfig -> "WAITING_FOR_FULL_CONFIG" instance FromJSON VPNTunnelStatus where parseJSON = parseJSONText "VPNTunnelStatus" instance ToJSON VPNTunnelStatus where toJSON = toJSONText -- | Specifies the balancing mode for this backend. For global HTTP(S) or -- TCP\/SSL load balancing, the default is UTILIZATION. Valid values are -- UTILIZATION, RATE (for HTTP(S)) and CONNECTION (for TCP\/SSL). This -- cannot be used for internal load balancing. data BackendBalancingMode = Connection -- ^ @CONNECTION@ | Rate -- ^ @RATE@ | Utilization -- ^ @UTILIZATION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable BackendBalancingMode instance FromHttpApiData BackendBalancingMode where parseQueryParam = \case "CONNECTION" -> Right Connection "RATE" -> Right Rate "UTILIZATION" -> Right Utilization x -> Left ("Unable to parse BackendBalancingMode from: " <> x) instance ToHttpApiData BackendBalancingMode where toQueryParam = \case Connection -> "CONNECTION" Rate -> "RATE" Utilization -> "UTILIZATION" instance FromJSON BackendBalancingMode where parseJSON = parseJSONText "BackendBalancingMode" instance ToJSON BackendBalancingMode where toJSON = toJSONText -- | The IP protocol to which this rule applies. Valid options are TCP, UDP, -- ESP, AH, SCTP or ICMP. When the load balancing scheme is INTERNAL data ForwardingRuleIPProtocol = FRIPAH -- ^ @AH@ | FRIPEsp -- ^ @ESP@ | FRIPSctp -- ^ @SCTP@ | FRIPTCP -- ^ @TCP@ | FRIPUdp -- ^ @UDP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ForwardingRuleIPProtocol instance FromHttpApiData ForwardingRuleIPProtocol where parseQueryParam = \case "AH" -> Right FRIPAH "ESP" -> Right FRIPEsp "SCTP" -> Right FRIPSctp "TCP" -> Right FRIPTCP "UDP" -> Right FRIPUdp x -> Left ("Unable to parse ForwardingRuleIPProtocol from: " <> x) instance ToHttpApiData ForwardingRuleIPProtocol where toQueryParam = \case FRIPAH -> "AH" FRIPEsp -> "ESP" FRIPSctp -> "SCTP" FRIPTCP -> "TCP" FRIPUdp -> "UDP" instance FromJSON ForwardingRuleIPProtocol where parseJSON = parseJSONText "ForwardingRuleIPProtocol" instance ToJSON ForwardingRuleIPProtocol where toJSON = toJSONText -- | [Output Only] The status of the address, which can be either IN_USE or -- RESERVED. An address that is RESERVED is currently reserved and -- available to use. An IN_USE address is currently being used by another -- resource and is not available. data AddressStatus = InUse -- ^ @IN_USE@ | Reserved -- ^ @RESERVED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AddressStatus instance FromHttpApiData AddressStatus where parseQueryParam = \case "IN_USE" -> Right InUse "RESERVED" -> Right Reserved x -> Left ("Unable to parse AddressStatus from: " <> x) instance ToHttpApiData AddressStatus where toQueryParam = \case InUse -> "IN_USE" Reserved -> "RESERVED" instance FromJSON AddressStatus where parseJSON = parseJSONText "AddressStatus" instance ToJSON AddressStatus where toJSON = toJSONText -- | A filter for the state of the instances in the instance group. Valid -- options are ALL or RUNNING. If you do not specify this parameter the -- list includes all instances regardless of their state. data InstanceGroupsListInstancesRequestInstanceState = IGLIRISAll -- ^ @ALL@ | IGLIRISRunning -- ^ @RUNNING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstanceGroupsListInstancesRequestInstanceState instance FromHttpApiData InstanceGroupsListInstancesRequestInstanceState where parseQueryParam = \case "ALL" -> Right IGLIRISAll "RUNNING" -> Right IGLIRISRunning x -> Left ("Unable to parse InstanceGroupsListInstancesRequestInstanceState from: " <> x) instance ToHttpApiData InstanceGroupsListInstancesRequestInstanceState where toQueryParam = \case IGLIRISAll -> "ALL" IGLIRISRunning -> "RUNNING" instance FromJSON InstanceGroupsListInstancesRequestInstanceState where parseJSON = parseJSONText "InstanceGroupsListInstancesRequestInstanceState" instance ToJSON InstanceGroupsListInstancesRequestInstanceState where toJSON = toJSONText -- | Specifies the type of proxy header to append before sending data to the -- backend, either NONE or PROXY_V1. The default is NONE. data HTTPSHealthCheckProxyHeader = HHCPHNone -- ^ @NONE@ | HHCPHProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable HTTPSHealthCheckProxyHeader instance FromHttpApiData HTTPSHealthCheckProxyHeader where parseQueryParam = \case "NONE" -> Right HHCPHNone "PROXY_V1" -> Right HHCPHProxyV1 x -> Left ("Unable to parse HTTPSHealthCheckProxyHeader from: " <> x) instance ToHttpApiData HTTPSHealthCheckProxyHeader where toQueryParam = \case HHCPHNone -> "NONE" HHCPHProxyV1 -> "PROXY_V1" instance FromJSON HTTPSHealthCheckProxyHeader where parseJSON = parseJSONText "HTTPSHealthCheckProxyHeader" instance ToJSON HTTPSHealthCheckProxyHeader where toJSON = toJSONText -- | Specifies the disk interface to use for attaching this disk, which is -- either SCSI or NVME. The default is SCSI. Persistent disks must always -- use SCSI and the request will fail if you attempt to attach a persistent -- disk in any other format than SCSI. Local SSDs can use either NVME or -- SCSI. For performance characteristics of SCSI over NVMe, see Local SSD -- performance. data AttachedDiskInterface = Nvme -- ^ @NVME@ | Scsi -- ^ @SCSI@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AttachedDiskInterface instance FromHttpApiData AttachedDiskInterface where parseQueryParam = \case "NVME" -> Right Nvme "SCSI" -> Right Scsi x -> Left ("Unable to parse AttachedDiskInterface from: " <> x) instance ToHttpApiData AttachedDiskInterface where toQueryParam = \case Nvme -> "NVME" Scsi -> "SCSI" instance FromJSON AttachedDiskInterface where parseJSON = parseJSONText "AttachedDiskInterface" instance ToJSON AttachedDiskInterface where toJSON = toJSONText -- | Specifies the type of the healthCheck, either TCP, SSL, HTTP or HTTPS. -- If not specified, the default is TCP. Exactly one of the -- protocol-specific health check field must be specified, which must match -- type field. data HealthCheckType = HCTHTTP -- ^ @HTTP@ | HCTHTTPS -- ^ @HTTPS@ | HCTInvalid -- ^ @INVALID@ | HCTSSL -- ^ @SSL@ | HCTTCP -- ^ @TCP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable HealthCheckType instance FromHttpApiData HealthCheckType where parseQueryParam = \case "HTTP" -> Right HCTHTTP "HTTPS" -> Right HCTHTTPS "INVALID" -> Right HCTInvalid "SSL" -> Right HCTSSL "TCP" -> Right HCTTCP x -> Left ("Unable to parse HealthCheckType from: " <> x) instance ToHttpApiData HealthCheckType where toQueryParam = \case HCTHTTP -> "HTTP" HCTHTTPS -> "HTTPS" HCTInvalid -> "INVALID" HCTSSL -> "SSL" HCTTCP -> "TCP" instance FromJSON HealthCheckType where parseJSON = parseJSONText "HealthCheckType" instance ToJSON HealthCheckType where toJSON = toJSONText -- | [Output Only] Status of the zone, either UP or DOWN. data ZoneStatus = ZSDown -- ^ @DOWN@ | ZSUP -- ^ @UP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ZoneStatus instance FromHttpApiData ZoneStatus where parseQueryParam = \case "DOWN" -> Right ZSDown "UP" -> Right ZSUP x -> Left ("Unable to parse ZoneStatus from: " <> x) instance ToHttpApiData ZoneStatus where toQueryParam = \case ZSDown -> "DOWN" ZSUP -> "UP" instance FromJSON ZoneStatus where parseJSON = parseJSONText "ZoneStatus" instance ToJSON ZoneStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data SubnetworksScopedListWarningCode = SSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | SSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | SSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | SSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | SSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | SSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | SSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | SSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | SSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | SSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | SSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | SSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | SSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | SSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | SSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | SSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SubnetworksScopedListWarningCode instance FromHttpApiData SubnetworksScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right SSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right SSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right SSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right SSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right SSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right SSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right SSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right SSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right SSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right SSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right SSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right SSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right SSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right SSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right SSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right SSLWCUnreachable x -> Left ("Unable to parse SubnetworksScopedListWarningCode from: " <> x) instance ToHttpApiData SubnetworksScopedListWarningCode where toQueryParam = \case SSLWCCleanupFailed -> "CLEANUP_FAILED" SSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" SSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" SSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" SSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" SSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" SSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" SSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" SSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" SSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" SSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" SSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" SSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" SSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" SSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" SSLWCUnreachable -> "UNREACHABLE" instance FromJSON SubnetworksScopedListWarningCode where parseJSON = parseJSONText "SubnetworksScopedListWarningCode" instance ToJSON SubnetworksScopedListWarningCode where toJSON = toJSONText -- | [Output Only] Name of the quota metric. data QuotaMetric = Autoscalers -- ^ @AUTOSCALERS@ | BackendServices -- ^ @BACKEND_SERVICES@ | CPUs -- ^ @CPUS@ | DisksTotalGb -- ^ @DISKS_TOTAL_GB@ | Firewalls -- ^ @FIREWALLS@ | ForwardingRules -- ^ @FORWARDING_RULES@ | HealthChecks -- ^ @HEALTH_CHECKS@ | Images -- ^ @IMAGES@ | Instances -- ^ @INSTANCES@ | InstanceGroups -- ^ @INSTANCE_GROUPS@ | InstanceGroupManagers -- ^ @INSTANCE_GROUP_MANAGERS@ | InstanceTemplates -- ^ @INSTANCE_TEMPLATES@ | InUseAddresses -- ^ @IN_USE_ADDRESSES@ | LocalSsdTotalGb -- ^ @LOCAL_SSD_TOTAL_GB@ | Networks -- ^ @NETWORKS@ | PreemptibleCPUs -- ^ @PREEMPTIBLE_CPUS@ | RegionalAutoscalers -- ^ @REGIONAL_AUTOSCALERS@ | RegionalInstanceGroupManagers -- ^ @REGIONAL_INSTANCE_GROUP_MANAGERS@ | Routers -- ^ @ROUTERS@ | Routes -- ^ @ROUTES@ | Snapshots -- ^ @SNAPSHOTS@ | SsdTotalGb -- ^ @SSD_TOTAL_GB@ | SSLCertificates -- ^ @SSL_CERTIFICATES@ | StaticAddresses -- ^ @STATIC_ADDRESSES@ | Subnetworks -- ^ @SUBNETWORKS@ | TargetHTTPSProxies -- ^ @TARGET_HTTPS_PROXIES@ | TargetHTTPProxies -- ^ @TARGET_HTTP_PROXIES@ | TargetInstances -- ^ @TARGET_INSTANCES@ | TargetPools -- ^ @TARGET_POOLS@ | TargetSSLProxies -- ^ @TARGET_SSL_PROXIES@ | TargetVPNGateways -- ^ @TARGET_VPN_GATEWAYS@ | TotalCPUs -- ^ @TOTAL_CPUS@ | URLMaps -- ^ @URL_MAPS@ | VPNTunnels -- ^ @VPN_TUNNELS@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable QuotaMetric instance FromHttpApiData QuotaMetric where parseQueryParam = \case "AUTOSCALERS" -> Right Autoscalers "BACKEND_SERVICES" -> Right BackendServices "CPUS" -> Right CPUs "DISKS_TOTAL_GB" -> Right DisksTotalGb "FIREWALLS" -> Right Firewalls "FORWARDING_RULES" -> Right ForwardingRules "HEALTH_CHECKS" -> Right HealthChecks "IMAGES" -> Right Images "INSTANCES" -> Right Instances "INSTANCE_GROUPS" -> Right InstanceGroups "INSTANCE_GROUP_MANAGERS" -> Right InstanceGroupManagers "INSTANCE_TEMPLATES" -> Right InstanceTemplates "IN_USE_ADDRESSES" -> Right InUseAddresses "LOCAL_SSD_TOTAL_GB" -> Right LocalSsdTotalGb "NETWORKS" -> Right Networks "PREEMPTIBLE_CPUS" -> Right PreemptibleCPUs "REGIONAL_AUTOSCALERS" -> Right RegionalAutoscalers "REGIONAL_INSTANCE_GROUP_MANAGERS" -> Right RegionalInstanceGroupManagers "ROUTERS" -> Right Routers "ROUTES" -> Right Routes "SNAPSHOTS" -> Right Snapshots "SSD_TOTAL_GB" -> Right SsdTotalGb "SSL_CERTIFICATES" -> Right SSLCertificates "STATIC_ADDRESSES" -> Right StaticAddresses "SUBNETWORKS" -> Right Subnetworks "TARGET_HTTPS_PROXIES" -> Right TargetHTTPSProxies "TARGET_HTTP_PROXIES" -> Right TargetHTTPProxies "TARGET_INSTANCES" -> Right TargetInstances "TARGET_POOLS" -> Right TargetPools "TARGET_SSL_PROXIES" -> Right TargetSSLProxies "TARGET_VPN_GATEWAYS" -> Right TargetVPNGateways "TOTAL_CPUS" -> Right TotalCPUs "URL_MAPS" -> Right URLMaps "VPN_TUNNELS" -> Right VPNTunnels x -> Left ("Unable to parse QuotaMetric from: " <> x) instance ToHttpApiData QuotaMetric where toQueryParam = \case Autoscalers -> "AUTOSCALERS" BackendServices -> "BACKEND_SERVICES" CPUs -> "CPUS" DisksTotalGb -> "DISKS_TOTAL_GB" Firewalls -> "FIREWALLS" ForwardingRules -> "FORWARDING_RULES" HealthChecks -> "HEALTH_CHECKS" Images -> "IMAGES" Instances -> "INSTANCES" InstanceGroups -> "INSTANCE_GROUPS" InstanceGroupManagers -> "INSTANCE_GROUP_MANAGERS" InstanceTemplates -> "INSTANCE_TEMPLATES" InUseAddresses -> "IN_USE_ADDRESSES" LocalSsdTotalGb -> "LOCAL_SSD_TOTAL_GB" Networks -> "NETWORKS" PreemptibleCPUs -> "PREEMPTIBLE_CPUS" RegionalAutoscalers -> "REGIONAL_AUTOSCALERS" RegionalInstanceGroupManagers -> "REGIONAL_INSTANCE_GROUP_MANAGERS" Routers -> "ROUTERS" Routes -> "ROUTES" Snapshots -> "SNAPSHOTS" SsdTotalGb -> "SSD_TOTAL_GB" SSLCertificates -> "SSL_CERTIFICATES" StaticAddresses -> "STATIC_ADDRESSES" Subnetworks -> "SUBNETWORKS" TargetHTTPSProxies -> "TARGET_HTTPS_PROXIES" TargetHTTPProxies -> "TARGET_HTTP_PROXIES" TargetInstances -> "TARGET_INSTANCES" TargetPools -> "TARGET_POOLS" TargetSSLProxies -> "TARGET_SSL_PROXIES" TargetVPNGateways -> "TARGET_VPN_GATEWAYS" TotalCPUs -> "TOTAL_CPUS" URLMaps -> "URL_MAPS" VPNTunnels -> "VPN_TUNNELS" instance FromJSON QuotaMetric where parseJSON = parseJSONText "QuotaMetric" instance ToJSON QuotaMetric where toJSON = toJSONText -- | [Output Only] The status of the instance. One of the following values: -- PROVISIONING, STAGING, RUNNING, STOPPING, SUSPENDING, SUSPENDED, and -- TERMINATED. data InstanceStatus = ISProvisioning -- ^ @PROVISIONING@ | ISRunning -- ^ @RUNNING@ | ISStaging -- ^ @STAGING@ | ISStopped -- ^ @STOPPED@ | ISStopping -- ^ @STOPPING@ | ISSuspended -- ^ @SUSPENDED@ | ISSuspending -- ^ @SUSPENDING@ | ISTerminated -- ^ @TERMINATED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstanceStatus instance FromHttpApiData InstanceStatus where parseQueryParam = \case "PROVISIONING" -> Right ISProvisioning "RUNNING" -> Right ISRunning "STAGING" -> Right ISStaging "STOPPED" -> Right ISStopped "STOPPING" -> Right ISStopping "SUSPENDED" -> Right ISSuspended "SUSPENDING" -> Right ISSuspending "TERMINATED" -> Right ISTerminated x -> Left ("Unable to parse InstanceStatus from: " <> x) instance ToHttpApiData InstanceStatus where toQueryParam = \case ISProvisioning -> "PROVISIONING" ISRunning -> "RUNNING" ISStaging -> "STAGING" ISStopped -> "STOPPED" ISStopping -> "STOPPING" ISSuspended -> "SUSPENDED" ISSuspending -> "SUSPENDING" ISTerminated -> "TERMINATED" instance FromJSON InstanceStatus where parseJSON = parseJSONText "InstanceStatus" instance ToJSON InstanceStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data MachineTypesScopedListWarningCode = MTSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | MTSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | MTSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | MTSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | MTSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | MTSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | MTSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | MTSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | MTSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | MTSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | MTSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | MTSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | MTSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | MTSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | MTSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | MTSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MachineTypesScopedListWarningCode instance FromHttpApiData MachineTypesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right MTSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right MTSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right MTSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right MTSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right MTSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right MTSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right MTSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right MTSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right MTSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right MTSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right MTSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right MTSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right MTSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right MTSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right MTSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right MTSLWCUnreachable x -> Left ("Unable to parse MachineTypesScopedListWarningCode from: " <> x) instance ToHttpApiData MachineTypesScopedListWarningCode where toQueryParam = \case MTSLWCCleanupFailed -> "CLEANUP_FAILED" MTSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" MTSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" MTSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" MTSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" MTSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" MTSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" MTSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" MTSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" MTSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" MTSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" MTSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" MTSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" MTSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" MTSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" MTSLWCUnreachable -> "UNREACHABLE" instance FromJSON MachineTypesScopedListWarningCode where parseJSON = parseJSONText "MachineTypesScopedListWarningCode" instance ToJSON MachineTypesScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data DiskTypesScopedListWarningCode = DTSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | DTSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | DTSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | DTSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | DTSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | DTSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | DTSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | DTSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | DTSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | DTSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | DTSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | DTSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | DTSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | DTSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | DTSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | DTSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DiskTypesScopedListWarningCode instance FromHttpApiData DiskTypesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right DTSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right DTSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right DTSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right DTSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right DTSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right DTSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right DTSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right DTSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right DTSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right DTSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right DTSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right DTSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right DTSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right DTSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right DTSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right DTSLWCUnreachable x -> Left ("Unable to parse DiskTypesScopedListWarningCode from: " <> x) instance ToHttpApiData DiskTypesScopedListWarningCode where toQueryParam = \case DTSLWCCleanupFailed -> "CLEANUP_FAILED" DTSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" DTSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" DTSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" DTSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" DTSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" DTSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" DTSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" DTSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" DTSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" DTSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" DTSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" DTSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" DTSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" DTSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" DTSLWCUnreachable -> "UNREACHABLE" instance FromJSON DiskTypesScopedListWarningCode where parseJSON = parseJSONText "DiskTypesScopedListWarningCode" instance ToJSON DiskTypesScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data AutoscalersScopedListWarningCode = ACleanupFailed -- ^ @CLEANUP_FAILED@ | ADeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | ADiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | AFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | AInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | ANextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | ANextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | ANextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | ANextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | ANextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | ANotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | ANoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | ARequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | AResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | ASingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | AUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AutoscalersScopedListWarningCode instance FromHttpApiData AutoscalersScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right ACleanupFailed "DEPRECATED_RESOURCE_USED" -> Right ADeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right ADiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right AFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right AInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right ANextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right ANextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right ANextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right ANextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right ANextHopNotRunning "NOT_CRITICAL_ERROR" -> Right ANotCriticalError "NO_RESULTS_ON_PAGE" -> Right ANoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right ARequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right AResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right ASingleInstancePropertyTemplate "UNREACHABLE" -> Right AUnreachable x -> Left ("Unable to parse AutoscalersScopedListWarningCode from: " <> x) instance ToHttpApiData AutoscalersScopedListWarningCode where toQueryParam = \case ACleanupFailed -> "CLEANUP_FAILED" ADeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" ADiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" AFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" AInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" ANextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" ANextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" ANextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" ANextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" ANextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" ANotCriticalError -> "NOT_CRITICAL_ERROR" ANoResultsOnPage -> "NO_RESULTS_ON_PAGE" ARequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" AResourceNotDeleted -> "RESOURCE_NOT_DELETED" ASingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" AUnreachable -> "UNREACHABLE" instance FromJSON AutoscalersScopedListWarningCode where parseJSON = parseJSONText "AutoscalersScopedListWarningCode" instance ToJSON AutoscalersScopedListWarningCode where toJSON = toJSONText -- | This signifies what the ForwardingRule will be used for and can only -- take the following values: INTERNAL EXTERNAL The value of INTERNAL means -- that this will be used for Internal Network Load Balancing (TCP, UDP). -- The value of EXTERNAL means that this will be used for External Load -- Balancing (HTTP(S) LB, External TCP\/UDP LB, SSL Proxy) data ForwardingRuleLoadBalancingScheme = FRLBSExternal -- ^ @EXTERNAL@ | FRLBSInternal -- ^ @INTERNAL@ | FRLBSInvalid -- ^ @INVALID@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ForwardingRuleLoadBalancingScheme instance FromHttpApiData ForwardingRuleLoadBalancingScheme where parseQueryParam = \case "EXTERNAL" -> Right FRLBSExternal "INTERNAL" -> Right FRLBSInternal "INVALID" -> Right FRLBSInvalid x -> Left ("Unable to parse ForwardingRuleLoadBalancingScheme from: " <> x) instance ToHttpApiData ForwardingRuleLoadBalancingScheme where toQueryParam = \case FRLBSExternal -> "EXTERNAL" FRLBSInternal -> "INTERNAL" FRLBSInvalid -> "INVALID" instance FromJSON ForwardingRuleLoadBalancingScheme where parseJSON = parseJSONText "ForwardingRuleLoadBalancingScheme" instance ToJSON ForwardingRuleLoadBalancingScheme where toJSON = toJSONText -- | Status of the BGP peer: {UP, DOWN} data RouterStatusBGPPeerStatusStatus = RSBPSSDown -- ^ @DOWN@ | RSBPSSUnknown -- ^ @UNKNOWN@ | RSBPSSUP -- ^ @UP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RouterStatusBGPPeerStatusStatus instance FromHttpApiData RouterStatusBGPPeerStatusStatus where parseQueryParam = \case "DOWN" -> Right RSBPSSDown "UNKNOWN" -> Right RSBPSSUnknown "UP" -> Right RSBPSSUP x -> Left ("Unable to parse RouterStatusBGPPeerStatusStatus from: " <> x) instance ToHttpApiData RouterStatusBGPPeerStatusStatus where toQueryParam = \case RSBPSSDown -> "DOWN" RSBPSSUnknown -> "UNKNOWN" RSBPSSUP -> "UP" instance FromJSON RouterStatusBGPPeerStatusStatus where parseJSON = parseJSONText "RouterStatusBGPPeerStatusStatus" instance ToJSON RouterStatusBGPPeerStatusStatus where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data VPNTunnelsScopedListWarningCode = VTSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | VTSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | VTSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | VTSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | VTSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | VTSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | VTSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | VTSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | VTSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | VTSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | VTSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | VTSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | VTSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | VTSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | VTSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | VTSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable VPNTunnelsScopedListWarningCode instance FromHttpApiData VPNTunnelsScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right VTSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right VTSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right VTSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right VTSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right VTSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right VTSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right VTSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right VTSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right VTSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right VTSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right VTSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right VTSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right VTSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right VTSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right VTSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right VTSLWCUnreachable x -> Left ("Unable to parse VPNTunnelsScopedListWarningCode from: " <> x) instance ToHttpApiData VPNTunnelsScopedListWarningCode where toQueryParam = \case VTSLWCCleanupFailed -> "CLEANUP_FAILED" VTSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" VTSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" VTSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" VTSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" VTSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" VTSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" VTSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" VTSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" VTSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" VTSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" VTSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" VTSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" VTSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" VTSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" VTSLWCUnreachable -> "UNREACHABLE" instance FromJSON VPNTunnelsScopedListWarningCode where parseJSON = parseJSONText "VPNTunnelsScopedListWarningCode" instance ToJSON VPNTunnelsScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data InstanceGroupsScopedListWarningCode = IGSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | IGSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | IGSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | IGSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | IGSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | IGSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | IGSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | IGSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | IGSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | IGSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | IGSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | IGSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | IGSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | IGSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | IGSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | IGSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstanceGroupsScopedListWarningCode instance FromHttpApiData InstanceGroupsScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right IGSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right IGSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right IGSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right IGSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right IGSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right IGSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right IGSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right IGSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right IGSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right IGSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right IGSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right IGSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right IGSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right IGSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right IGSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right IGSLWCUnreachable x -> Left ("Unable to parse InstanceGroupsScopedListWarningCode from: " <> x) instance ToHttpApiData InstanceGroupsScopedListWarningCode where toQueryParam = \case IGSLWCCleanupFailed -> "CLEANUP_FAILED" IGSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" IGSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" IGSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" IGSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" IGSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" IGSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" IGSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" IGSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" IGSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" IGSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" IGSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" IGSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" IGSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" IGSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" IGSLWCUnreachable -> "UNREACHABLE" instance FromJSON InstanceGroupsScopedListWarningCode where parseJSON = parseJSONText "InstanceGroupsScopedListWarningCode" instance ToJSON InstanceGroupsScopedListWarningCode where toJSON = toJSONText -- | [Output Only] The status of the instance. data InstanceWithNamedPortsStatus = IWNPSProvisioning -- ^ @PROVISIONING@ | IWNPSRunning -- ^ @RUNNING@ | IWNPSStaging -- ^ @STAGING@ | IWNPSStopped -- ^ @STOPPED@ | IWNPSStopping -- ^ @STOPPING@ | IWNPSSuspended -- ^ @SUSPENDED@ | IWNPSSuspending -- ^ @SUSPENDING@ | IWNPSTerminated -- ^ @TERMINATED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstanceWithNamedPortsStatus instance FromHttpApiData InstanceWithNamedPortsStatus where parseQueryParam = \case "PROVISIONING" -> Right IWNPSProvisioning "RUNNING" -> Right IWNPSRunning "STAGING" -> Right IWNPSStaging "STOPPED" -> Right IWNPSStopped "STOPPING" -> Right IWNPSStopping "SUSPENDED" -> Right IWNPSSuspended "SUSPENDING" -> Right IWNPSSuspending "TERMINATED" -> Right IWNPSTerminated x -> Left ("Unable to parse InstanceWithNamedPortsStatus from: " <> x) instance ToHttpApiData InstanceWithNamedPortsStatus where toQueryParam = \case IWNPSProvisioning -> "PROVISIONING" IWNPSRunning -> "RUNNING" IWNPSStaging -> "STAGING" IWNPSStopped -> "STOPPED" IWNPSStopping -> "STOPPING" IWNPSSuspended -> "SUSPENDED" IWNPSSuspending -> "SUSPENDING" IWNPSTerminated -> "TERMINATED" instance FromJSON InstanceWithNamedPortsStatus where parseJSON = parseJSONText "InstanceWithNamedPortsStatus" instance ToJSON InstanceWithNamedPortsStatus where toJSON = toJSONText -- | Specifies the type of proxy header to append before sending data to the -- backend, either NONE or PROXY_V1. The default is NONE. data TCPHealthCheckProxyHeader = THCPHNone -- ^ @NONE@ | THCPHProxyV1 -- ^ @PROXY_V1@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TCPHealthCheckProxyHeader instance FromHttpApiData TCPHealthCheckProxyHeader where parseQueryParam = \case "NONE" -> Right THCPHNone "PROXY_V1" -> Right THCPHProxyV1 x -> Left ("Unable to parse TCPHealthCheckProxyHeader from: " <> x) instance ToHttpApiData TCPHealthCheckProxyHeader where toQueryParam = \case THCPHNone -> "NONE" THCPHProxyV1 -> "PROXY_V1" instance FromJSON TCPHealthCheckProxyHeader where parseJSON = parseJSONText "TCPHealthCheckProxyHeader" instance ToJSON TCPHealthCheckProxyHeader where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data InstancesScopedListWarningCode = ISLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | ISLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | ISLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | ISLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | ISLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | ISLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | ISLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | ISLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | ISLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | ISLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | ISLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | ISLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | ISLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | ISLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | ISLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | ISLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InstancesScopedListWarningCode instance FromHttpApiData InstancesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right ISLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right ISLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right ISLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right ISLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right ISLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right ISLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right ISLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right ISLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right ISLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right ISLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right ISLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right ISLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right ISLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right ISLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right ISLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right ISLWCUnreachable x -> Left ("Unable to parse InstancesScopedListWarningCode from: " <> x) instance ToHttpApiData InstancesScopedListWarningCode where toQueryParam = \case ISLWCCleanupFailed -> "CLEANUP_FAILED" ISLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" ISLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" ISLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" ISLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" ISLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" ISLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" ISLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" ISLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" ISLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" ISLWCNotCriticalError -> "NOT_CRITICAL_ERROR" ISLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" ISLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" ISLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" ISLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" ISLWCUnreachable -> "UNREACHABLE" instance FromJSON InstancesScopedListWarningCode where parseJSON = parseJSONText "InstancesScopedListWarningCode" instance ToJSON InstancesScopedListWarningCode where toJSON = toJSONText -- | [Output Only] A warning code, if applicable. For example, Compute Engine -- returns NO_RESULTS_ON_PAGE if there are no results in the response. data BackendServicesScopedListWarningCode = BSSLWCCleanupFailed -- ^ @CLEANUP_FAILED@ | BSSLWCDeprecatedResourceUsed -- ^ @DEPRECATED_RESOURCE_USED@ | BSSLWCDiskSizeLargerThanImageSize -- ^ @DISK_SIZE_LARGER_THAN_IMAGE_SIZE@ | BSSLWCFieldValueOverriden -- ^ @FIELD_VALUE_OVERRIDEN@ | BSSLWCInjectedKernelsDeprecated -- ^ @INJECTED_KERNELS_DEPRECATED@ | BSSLWCNextHopAddressNotAssigned -- ^ @NEXT_HOP_ADDRESS_NOT_ASSIGNED@ | BSSLWCNextHopCannotIPForward -- ^ @NEXT_HOP_CANNOT_IP_FORWARD@ | BSSLWCNextHopInstanceNotFound -- ^ @NEXT_HOP_INSTANCE_NOT_FOUND@ | BSSLWCNextHopInstanceNotOnNetwork -- ^ @NEXT_HOP_INSTANCE_NOT_ON_NETWORK@ | BSSLWCNextHopNotRunning -- ^ @NEXT_HOP_NOT_RUNNING@ | BSSLWCNotCriticalError -- ^ @NOT_CRITICAL_ERROR@ | BSSLWCNoResultsOnPage -- ^ @NO_RESULTS_ON_PAGE@ | BSSLWCRequiredTosAgreement -- ^ @REQUIRED_TOS_AGREEMENT@ | BSSLWCResourceNotDeleted -- ^ @RESOURCE_NOT_DELETED@ | BSSLWCSingleInstancePropertyTemplate -- ^ @SINGLE_INSTANCE_PROPERTY_TEMPLATE@ | BSSLWCUnreachable -- ^ @UNREACHABLE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable BackendServicesScopedListWarningCode instance FromHttpApiData BackendServicesScopedListWarningCode where parseQueryParam = \case "CLEANUP_FAILED" -> Right BSSLWCCleanupFailed "DEPRECATED_RESOURCE_USED" -> Right BSSLWCDeprecatedResourceUsed "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" -> Right BSSLWCDiskSizeLargerThanImageSize "FIELD_VALUE_OVERRIDEN" -> Right BSSLWCFieldValueOverriden "INJECTED_KERNELS_DEPRECATED" -> Right BSSLWCInjectedKernelsDeprecated "NEXT_HOP_ADDRESS_NOT_ASSIGNED" -> Right BSSLWCNextHopAddressNotAssigned "NEXT_HOP_CANNOT_IP_FORWARD" -> Right BSSLWCNextHopCannotIPForward "NEXT_HOP_INSTANCE_NOT_FOUND" -> Right BSSLWCNextHopInstanceNotFound "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" -> Right BSSLWCNextHopInstanceNotOnNetwork "NEXT_HOP_NOT_RUNNING" -> Right BSSLWCNextHopNotRunning "NOT_CRITICAL_ERROR" -> Right BSSLWCNotCriticalError "NO_RESULTS_ON_PAGE" -> Right BSSLWCNoResultsOnPage "REQUIRED_TOS_AGREEMENT" -> Right BSSLWCRequiredTosAgreement "RESOURCE_NOT_DELETED" -> Right BSSLWCResourceNotDeleted "SINGLE_INSTANCE_PROPERTY_TEMPLATE" -> Right BSSLWCSingleInstancePropertyTemplate "UNREACHABLE" -> Right BSSLWCUnreachable x -> Left ("Unable to parse BackendServicesScopedListWarningCode from: " <> x) instance ToHttpApiData BackendServicesScopedListWarningCode where toQueryParam = \case BSSLWCCleanupFailed -> "CLEANUP_FAILED" BSSLWCDeprecatedResourceUsed -> "DEPRECATED_RESOURCE_USED" BSSLWCDiskSizeLargerThanImageSize -> "DISK_SIZE_LARGER_THAN_IMAGE_SIZE" BSSLWCFieldValueOverriden -> "FIELD_VALUE_OVERRIDEN" BSSLWCInjectedKernelsDeprecated -> "INJECTED_KERNELS_DEPRECATED" BSSLWCNextHopAddressNotAssigned -> "NEXT_HOP_ADDRESS_NOT_ASSIGNED" BSSLWCNextHopCannotIPForward -> "NEXT_HOP_CANNOT_IP_FORWARD" BSSLWCNextHopInstanceNotFound -> "NEXT_HOP_INSTANCE_NOT_FOUND" BSSLWCNextHopInstanceNotOnNetwork -> "NEXT_HOP_INSTANCE_NOT_ON_NETWORK" BSSLWCNextHopNotRunning -> "NEXT_HOP_NOT_RUNNING" BSSLWCNotCriticalError -> "NOT_CRITICAL_ERROR" BSSLWCNoResultsOnPage -> "NO_RESULTS_ON_PAGE" BSSLWCRequiredTosAgreement -> "REQUIRED_TOS_AGREEMENT" BSSLWCResourceNotDeleted -> "RESOURCE_NOT_DELETED" BSSLWCSingleInstancePropertyTemplate -> "SINGLE_INSTANCE_PROPERTY_TEMPLATE" BSSLWCUnreachable -> "UNREACHABLE" instance FromJSON BackendServicesScopedListWarningCode where parseJSON = parseJSONText "BackendServicesScopedListWarningCode" instance ToJSON BackendServicesScopedListWarningCode where toJSON = toJSONText -- | Sesssion affinity option, must be one of the following values: NONE: -- Connections from the same client IP may go to any instance in the pool. -- CLIENT_IP: Connections from the same client IP will go to the same -- instance in the pool while that instance remains healthy. -- CLIENT_IP_PROTO: Connections from the same client IP with the same IP -- protocol will go to the same instance in the pool while that instance -- remains healthy. data TargetPoolSessionAffinity = TPSAClientIP -- ^ @CLIENT_IP@ | TPSAClientIPPortProto -- ^ @CLIENT_IP_PORT_PROTO@ | TPSAClientIPProto -- ^ @CLIENT_IP_PROTO@ | TPSAGeneratedCookie -- ^ @GENERATED_COOKIE@ | TPSANone -- ^ @NONE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetPoolSessionAffinity instance FromHttpApiData TargetPoolSessionAffinity where parseQueryParam = \case "CLIENT_IP" -> Right TPSAClientIP "CLIENT_IP_PORT_PROTO" -> Right TPSAClientIPPortProto "CLIENT_IP_PROTO" -> Right TPSAClientIPProto "GENERATED_COOKIE" -> Right TPSAGeneratedCookie "NONE" -> Right TPSANone x -> Left ("Unable to parse TargetPoolSessionAffinity from: " <> x) instance ToHttpApiData TargetPoolSessionAffinity where toQueryParam = \case TPSAClientIP -> "CLIENT_IP" TPSAClientIPPortProto -> "CLIENT_IP_PORT_PROTO" TPSAClientIPProto -> "CLIENT_IP_PROTO" TPSAGeneratedCookie -> "GENERATED_COOKIE" TPSANone -> "NONE" instance FromJSON TargetPoolSessionAffinity where parseJSON = parseJSONText "TargetPoolSessionAffinity" instance ToJSON TargetPoolSessionAffinity where toJSON = toJSONText -- | The format used to encode and transmit the block device, which should be -- TAR. This is just a container and transmission format and not a runtime -- format. Provided by the client when the disk image is created. data ImageRawDiskContainerType = TAR -- ^ @TAR@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ImageRawDiskContainerType instance FromHttpApiData ImageRawDiskContainerType where parseQueryParam = \case "TAR" -> Right TAR x -> Left ("Unable to parse ImageRawDiskContainerType from: " <> x) instance ToHttpApiData ImageRawDiskContainerType where toQueryParam = \case TAR -> "TAR" instance FromJSON ImageRawDiskContainerType where parseJSON = parseJSONText "ImageRawDiskContainerType" instance ToJSON ImageRawDiskContainerType where toJSON = toJSONText
rueshyna/gogol
gogol-compute/gen/Network/Google/Compute/Types/Sum.hs
mpl-2.0
131,997
0
11
26,138
17,038
8,952
8,086
2,219
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.ServiceControl.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.ServiceControl.Types.Sum where import Network.Google.Prelude -- | The error code. data CheckErrorCode = ErrorCodeUnspecified -- ^ @ERROR_CODE_UNSPECIFIED@ -- This is never used in \`CheckResponse\`. | NotFound -- ^ @NOT_FOUND@ -- The consumer\'s project id was not found. Same as -- google.rpc.Code.NOT_FOUND. | PermissionDenied -- ^ @PERMISSION_DENIED@ -- The consumer doesn\'t have access to the specified resource. Same as -- google.rpc.Code.PERMISSION_DENIED. | ResourceExhausted -- ^ @RESOURCE_EXHAUSTED@ -- Quota check failed. Same as google.rpc.Code.RESOURCE_EXHAUSTED. | ServiceNotActivated -- ^ @SERVICE_NOT_ACTIVATED@ -- The consumer hasn\'t activated the service. | BillingDisabled -- ^ @BILLING_DISABLED@ -- The consumer cannot access the service because billing is disabled. | ProjectDeleted -- ^ @PROJECT_DELETED@ -- The consumer\'s project has been marked as deleted (soft deletion). | ProjectInvalid -- ^ @PROJECT_INVALID@ -- The consumer\'s project number or id does not represent a valid project. | IPAddressBlocked -- ^ @IP_ADDRESS_BLOCKED@ -- The IP address of the consumer is invalid for the specific consumer -- project. | RefererBlocked -- ^ @REFERER_BLOCKED@ -- The referer address of the consumer request is invalid for the specific -- consumer project. | ClientAppBlocked -- ^ @CLIENT_APP_BLOCKED@ -- The client application of the consumer request is invalid for the -- specific consumer project. | APITargetBlocked -- ^ @API_TARGET_BLOCKED@ -- The API targeted by this request is invalid for the specified consumer -- project. | APIKeyInvalid -- ^ @API_KEY_INVALID@ -- The consumer\'s API key is invalid. | APIKeyExpired -- ^ @API_KEY_EXPIRED@ -- The consumer\'s API Key has expired. | APIKeyNotFound -- ^ @API_KEY_NOT_FOUND@ -- The consumer\'s API Key was not found in config record. | NamespaceLookupUnavailable -- ^ @NAMESPACE_LOOKUP_UNAVAILABLE@ -- The backend server for looking up project id\/number is unavailable. | ServiceStatusUnavailable -- ^ @SERVICE_STATUS_UNAVAILABLE@ -- The backend server for checking service status is unavailable. | BillingStatusUnavailable -- ^ @BILLING_STATUS_UNAVAILABLE@ -- The backend server for checking billing status is unavailable. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CheckErrorCode instance FromHttpApiData CheckErrorCode where parseQueryParam = \case "ERROR_CODE_UNSPECIFIED" -> Right ErrorCodeUnspecified "NOT_FOUND" -> Right NotFound "PERMISSION_DENIED" -> Right PermissionDenied "RESOURCE_EXHAUSTED" -> Right ResourceExhausted "SERVICE_NOT_ACTIVATED" -> Right ServiceNotActivated "BILLING_DISABLED" -> Right BillingDisabled "PROJECT_DELETED" -> Right ProjectDeleted "PROJECT_INVALID" -> Right ProjectInvalid "IP_ADDRESS_BLOCKED" -> Right IPAddressBlocked "REFERER_BLOCKED" -> Right RefererBlocked "CLIENT_APP_BLOCKED" -> Right ClientAppBlocked "API_TARGET_BLOCKED" -> Right APITargetBlocked "API_KEY_INVALID" -> Right APIKeyInvalid "API_KEY_EXPIRED" -> Right APIKeyExpired "API_KEY_NOT_FOUND" -> Right APIKeyNotFound "NAMESPACE_LOOKUP_UNAVAILABLE" -> Right NamespaceLookupUnavailable "SERVICE_STATUS_UNAVAILABLE" -> Right ServiceStatusUnavailable "BILLING_STATUS_UNAVAILABLE" -> Right BillingStatusUnavailable x -> Left ("Unable to parse CheckErrorCode from: " <> x) instance ToHttpApiData CheckErrorCode where toQueryParam = \case ErrorCodeUnspecified -> "ERROR_CODE_UNSPECIFIED" NotFound -> "NOT_FOUND" PermissionDenied -> "PERMISSION_DENIED" ResourceExhausted -> "RESOURCE_EXHAUSTED" ServiceNotActivated -> "SERVICE_NOT_ACTIVATED" BillingDisabled -> "BILLING_DISABLED" ProjectDeleted -> "PROJECT_DELETED" ProjectInvalid -> "PROJECT_INVALID" IPAddressBlocked -> "IP_ADDRESS_BLOCKED" RefererBlocked -> "REFERER_BLOCKED" ClientAppBlocked -> "CLIENT_APP_BLOCKED" APITargetBlocked -> "API_TARGET_BLOCKED" APIKeyInvalid -> "API_KEY_INVALID" APIKeyExpired -> "API_KEY_EXPIRED" APIKeyNotFound -> "API_KEY_NOT_FOUND" NamespaceLookupUnavailable -> "NAMESPACE_LOOKUP_UNAVAILABLE" ServiceStatusUnavailable -> "SERVICE_STATUS_UNAVAILABLE" BillingStatusUnavailable -> "BILLING_STATUS_UNAVAILABLE" instance FromJSON CheckErrorCode where parseJSON = parseJSONText "CheckErrorCode" instance ToJSON CheckErrorCode where toJSON = toJSONText -- | DO NOT USE. This is an experimental field. data OperationImportance = Low -- ^ @LOW@ -- The API implementation may cache and aggregate the data. The data may be -- lost when rare and unexpected system failures occur. | High -- ^ @HIGH@ -- The API implementation doesn\'t cache and aggregate the data. If the -- method returns successfully, it\'s guaranteed that the data has been -- persisted in durable storage. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OperationImportance instance FromHttpApiData OperationImportance where parseQueryParam = \case "LOW" -> Right Low "HIGH" -> Right High x -> Left ("Unable to parse OperationImportance from: " <> x) instance ToHttpApiData OperationImportance where toQueryParam = \case Low -> "LOW" High -> "HIGH" instance FromJSON OperationImportance where parseJSON = parseJSONText "OperationImportance" instance ToJSON OperationImportance where toJSON = toJSONText -- | V1 error format. data Xgafv = X1 -- ^ @1@ -- v1 error format | X2 -- ^ @2@ -- v2 error format deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable Xgafv instance FromHttpApiData Xgafv where parseQueryParam = \case "1" -> Right X1 "2" -> Right X2 x -> Left ("Unable to parse Xgafv from: " <> x) instance ToHttpApiData Xgafv where toQueryParam = \case X1 -> "1" X2 -> "2" instance FromJSON Xgafv where parseJSON = parseJSONText "Xgafv" instance ToJSON Xgafv where toJSON = toJSONText -- | The severity of the log entry. The default value is -- \`LogSeverity.DEFAULT\`. data LogEntrySeverity = Default -- ^ @DEFAULT@ -- (0) The log entry has no assigned severity level. | Debug -- ^ @DEBUG@ -- (100) Debug or trace information. | Info -- ^ @INFO@ -- (200) Routine information, such as ongoing status or performance. | Notice -- ^ @NOTICE@ -- (300) Normal but significant events, such as start up, shut down, or a -- configuration change. | Warning -- ^ @WARNING@ -- (400) Warning events might cause problems. | Error' -- ^ @ERROR@ -- (500) Error events are likely to cause problems. | Critical -- ^ @CRITICAL@ -- (600) Critical events cause more severe problems or outages. | Alert -- ^ @ALERT@ -- (700) A person must take an action immediately. | Emergency -- ^ @EMERGENCY@ -- (800) One or more systems are unusable. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable LogEntrySeverity instance FromHttpApiData LogEntrySeverity where parseQueryParam = \case "DEFAULT" -> Right Default "DEBUG" -> Right Debug "INFO" -> Right Info "NOTICE" -> Right Notice "WARNING" -> Right Warning "ERROR" -> Right Error' "CRITICAL" -> Right Critical "ALERT" -> Right Alert "EMERGENCY" -> Right Emergency x -> Left ("Unable to parse LogEntrySeverity from: " <> x) instance ToHttpApiData LogEntrySeverity where toQueryParam = \case Default -> "DEFAULT" Debug -> "DEBUG" Info -> "INFO" Notice -> "NOTICE" Warning -> "WARNING" Error' -> "ERROR" Critical -> "CRITICAL" Alert -> "ALERT" Emergency -> "EMERGENCY" instance FromJSON LogEntrySeverity where parseJSON = parseJSONText "LogEntrySeverity" instance ToJSON LogEntrySeverity where toJSON = toJSONText
rueshyna/gogol
gogol-servicecontrol/gen/Network/Google/ServiceControl/Types/Sum.hs
mpl-2.0
9,132
0
11
2,272
1,148
629
519
149
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Analytics.Management.Goals.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a goal to which the user has access. -- -- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.goals.get@. module Network.Google.Resource.Analytics.Management.Goals.Get ( -- * REST Resource ManagementGoalsGetResource -- * Creating a Request , managementGoalsGet , ManagementGoalsGet -- * Request Lenses , mggWebPropertyId , mggGoalId , mggProFileId , mggAccountId ) where import Network.Google.Analytics.Types import Network.Google.Prelude -- | A resource alias for @analytics.management.goals.get@ method which the -- 'ManagementGoalsGet' request conforms to. type ManagementGoalsGetResource = "analytics" :> "v3" :> "management" :> "accounts" :> Capture "accountId" Text :> "webproperties" :> Capture "webPropertyId" Text :> "profiles" :> Capture "profileId" Text :> "goals" :> Capture "goalId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Goal -- | Gets a goal to which the user has access. -- -- /See:/ 'managementGoalsGet' smart constructor. data ManagementGoalsGet = ManagementGoalsGet' { _mggWebPropertyId :: !Text , _mggGoalId :: !Text , _mggProFileId :: !Text , _mggAccountId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ManagementGoalsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mggWebPropertyId' -- -- * 'mggGoalId' -- -- * 'mggProFileId' -- -- * 'mggAccountId' managementGoalsGet :: Text -- ^ 'mggWebPropertyId' -> Text -- ^ 'mggGoalId' -> Text -- ^ 'mggProFileId' -> Text -- ^ 'mggAccountId' -> ManagementGoalsGet managementGoalsGet pMggWebPropertyId_ pMggGoalId_ pMggProFileId_ pMggAccountId_ = ManagementGoalsGet' { _mggWebPropertyId = pMggWebPropertyId_ , _mggGoalId = pMggGoalId_ , _mggProFileId = pMggProFileId_ , _mggAccountId = pMggAccountId_ } -- | Web property ID to retrieve the goal for. mggWebPropertyId :: Lens' ManagementGoalsGet Text mggWebPropertyId = lens _mggWebPropertyId (\ s a -> s{_mggWebPropertyId = a}) -- | Goal ID to retrieve the goal for. mggGoalId :: Lens' ManagementGoalsGet Text mggGoalId = lens _mggGoalId (\ s a -> s{_mggGoalId = a}) -- | View (Profile) ID to retrieve the goal for. mggProFileId :: Lens' ManagementGoalsGet Text mggProFileId = lens _mggProFileId (\ s a -> s{_mggProFileId = a}) -- | Account ID to retrieve the goal for. mggAccountId :: Lens' ManagementGoalsGet Text mggAccountId = lens _mggAccountId (\ s a -> s{_mggAccountId = a}) instance GoogleRequest ManagementGoalsGet where type Rs ManagementGoalsGet = Goal type Scopes ManagementGoalsGet = '["https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.readonly"] requestClient ManagementGoalsGet'{..} = go _mggAccountId _mggWebPropertyId _mggProFileId _mggGoalId (Just AltJSON) analyticsService where go = buildClient (Proxy :: Proxy ManagementGoalsGetResource) mempty
rueshyna/gogol
gogol-analytics/gen/Network/Google/Resource/Analytics/Management/Goals/Get.hs
mpl-2.0
4,232
0
19
1,063
547
324
223
89
1