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
-- File Parser.hs module Make.Parser ( makefile ) where import Text.ParserCombinators.Parsec import Make.Primitives -- Returns the complete list of Rules makefile :: GenParser Char st [Rule] makefile = do result <- many parseRule eof return result -- Parses a Rule, separately parses the target, source and the commands and then builds the object parseRule :: GenParser Char st Rule parseRule = do t <- parseTarget char ':' s <- parseSources eol cmds <- parseCommands spaces return Rule {target = t, sources = s, commands = cmds} --Parses a newLine eol :: GenParser Char st Char eol = char '\n' parseTarget :: GenParser Char st Target parseTarget = many (noneOf ":") parseSources :: GenParser Char st [Source] parseSources = do many (char ' ' >> parseSource) <|> (return []) parseSource :: GenParser Char st Source parseSource = do -- Skip Whitespace characters at the beginning many (oneOf " \t") s <- many (noneOf " \n\t") return s parseCommands :: GenParser Char st [String] parseCommands = many (command) <|> (return []) command :: GenParser Char st String command = do char '\t' cmd <- many(noneOf "\n") char '\n' return cmd
sahnib/haskell-make
src/Make/Parser.hs
mit
1,239
0
11
297
376
186
190
46
1
module Language.Pepa.Compile.MarkovChain ( MarkovChain , Row , Probability , ProbVector , indexProbVector , solveForSteadyState ) where {- Standard Library Modules Imported -} {- External Library Modules Imported -} import qualified Data.Matrix as Matrix import qualified Data.Matrix.Solve as Solve {- Local Modules Imported -} {- End of Module Imports -} {-| The type of the representation of a Markov chain. Note that we do not specify whether this is a continuous-time Markov Chain or a discrete-time Markov Chain. -} type MarkovChain = Matrix.Matrix Probability {-| A row within a Markov chain is just a vector of probabilities -} type Row = Matrix.Vector Probability {-| The type of a probability within a Markov Chain -} type Probability = Double {-| The type of a probability vector which is the solution to a Markov Chain -} type ProbVector = Matrix.Vector Probability {-| indexing a probability vector. -} indexProbVector :: ProbVector -> Int -> Probability indexProbVector = Matrix.safeVectorIndex {-| Solving the Markov chain for steady state. This function takes care of transposing the Markov chain, replacing the final row with a row full of ones (to ensure that the solution is a probability vector). The first argument determines whether or not the input Markov chain's generator matrix has already been transposed. Since the transpose TODO: Very good question here, why can't we just add the row of ones to the top, this would simplify the creation of both the qtn and the solVector. In other words why do we replace the LAST row and not the FIRST? UPDATE: Okay I've tried this and it seems to work, the old code I've left commented below because I'm obviously still not one hundred percent convinced by this. One thing I really need is a good test suite. I've now removed the commented code because I'm more convinced that it does indeed work. Obviously it can be retrieved via the darcs repository. TODO: There should be an argument to determine which kind of matrix solver to use. -} solveForSteadyState :: Bool -- ^ Whether the input Markov chain -- generator matrix has already -- been transposed. -> MarkovChain -- ^ Markov chain to be solved -> ProbVector -- ^ Resulting probability vector solveForSteadyState transposed markov = solution where -- First we transpose the matrix Q to obtain Q^{T} qt | transposed = markov | otherwise = Matrix.transposeMatrix markov -- Then we make it into a probability matrix -- by replacing the final row with a row of -- ones, this ensures that the solution is a probability -- vector (ie the values sum to one). -- In fact we may replace the FIRST row, when using lists to build -- up this matrix this was definitely faster since replacing the -- first element of a list is faster than replacing the second element. -- However when using maps or arrays it may be worthwhile NOT replacing -- the first row, since the top row likely contains a few zeros which -- when added to other rows during echelon reduction won't change zeros -- in those rows, allowing the matrix to still be represented sparsely. -- However it needs some benchmarking to see which would be better, -- the key point is that the row we replace must be the same as the index -- of the one in the solution vector. indexOfOneVec = 1 qtn = Matrix.replaceRow indexOfOneVec oneVector qt -- oneVector : (Matrix.dropRows 1 qt) -- The one vector is just a vector full of ones of the correct length -- this seems a trifle risky. Okay if we do it with 'fromListWithSize' -- it's not so risky but also not as efficient. The problem with the -- other way was attempting to add two vectors with different zero elements -- together, that should be possible, but at the moment unimplemented in -- Data.Matrix oneVector = Matrix.fromListWithSize 0.0 matrixSize $ replicate matrixSize 1.0 -- Matrix.empty 1.0 matrixSize -- -- The solution vector is all zeros apart from the first column which -- is one. The zeros represent that the flow into each state must equal -- the flow out of that state. The one represents that the probability -- of being in each state must sum to one. We must be in exactly one of -- of the states in question. The one is in the first column because we -- replaced with first row with the oneVector. solVector = Matrix.vectorInsert indexOfOneVec 1.0 zeroVector zeroVector = Matrix.empty 0.0 matrixSize -- Building up the solVector with a list, inefficient! -- Matrix.fromListWithSize solutionList matrixSize --- solutionList = 1.0 : (replicate (matrixSize - 1) 0.0) -- The size of the matrix is just the number of row -- (which should equal the number of columns). We might check for this? matrixSize = Matrix.numberOfRows markov -- So then the solution is simply the result of solving the system of -- linear equations which we have made for ourselves. solution = Solve.guassianElimination qtn solVector
allanderek/ipclib
Language/Pepa/Compile/MarkovChain.hs
gpl-2.0
5,259
0
9
1,237
294
185
109
31
1
module Grammatik.Hierarchie -- -- $Id$ ( typ0 , typ1 , typ2 , typ3 , immergut , monoton , kontextsensitiv , kontextfrei , linear , rechtslinear, linkslinear , at_most_one_terminal_in_rhs , epsfrei , kettenfrei , chomsky , greibach ) where import Grammatik.Type import qualified Autolib.Reporter.Checker as C import Autolib.Wort import Autolib.Reporter import Autolib.ToDoc import Autolib.Util.Splits import Control.Monad (guard) import Data.List (partition) import Autolib.Set import Data.Maybe --------------------------------------------------------------------------- typ0 :: C.Type Grammatik typ0 = C.make "Typ0" ( text "Die Grammatik soll vom Typ 0 sein." ) $ \ g -> do let us = sfilter ( \ (l, r) -> any ( not . ( `elementOf` ( terminale g `union` nichtterminale g ) ) ) (l ++ r) ) $ regeln g when ( not $ isEmptySet us ) $ reject $ fsep [ text "Diese Regeln enthalten ein Zeichen," , text "das weder Terminal noch Nichtterminal ist:" , toDoc us ] let cs = intersect (terminale g) ( nichtterminale g ) when ( not $ isEmptySet cs ) $ reject $ fsep [ text "Terminal- und Nichtterminalmenge sind nicht disjunkt." , text "Der Durchschnitt ist:" , toDoc cs ] let rs = sfilter ( \ (l, r) -> all ( `elementOf` (terminale g)) l ) $ regeln g verboten ( not $ isEmptySet rs ) "enthalten links kein Nichtterminal" rs --------------------------------------------------------------------------- monoton :: C.Type Grammatik monoton = C.make "Monoton" ( text "Die Grammatik soll monoton sein." ) $ \ g -> do let (eps, noeps) = partition ( null . snd ) $ rules g weps = mkSet $ filter ((/= [startsymbol g]) . fst) eps when ( not $ isEmptySet weps ) $ reject $ fsep [ text "Das leere Wort darf nur aus dem Startsymbol erzeugt werden." , text "Diese Regeln sind deswegen verboten:" , toDoc weps ] let feps = mkSet $ do -- falls leeres wort erzeugt wird guard $ not $ null $ eps (l,r) <- rules g guard $ startsymbol g `elem` r return (l, r) when ( not $ isEmptySet feps ) $ reject $ fsep [ text "Wenn aus dem Startsymbol ein leeres Wort abgeleitet wird," , text "dann darf das Startsymbol in keiner rechten Regelseite vorkommen." , text "Diese Regeln sind deswegen verboten:" , toDoc feps ] let kurz = filter ( \ (l, r) -> length l > length r ) $ noeps when ( not $ null kurz ) $ reject $ fsep [ text "Die rechte Regelseite darf nicht kürzer als die linke sein." , text "Diese Regeln sind deswegen verboten:" , toDoc kurz ] inform $ text "Ja." --------------------------------------------------------------------------- kontexte :: Grammatik -> (String, String) -> [ ((String, String), (Char, String)) ] kontexte g (lhs, rhs) = do (pre, x : post) <- splits lhs guard $ x `elementOf` nichtterminale g let (vorn, rest) = splitAt (length pre) rhs guard $ pre == vorn let (mitte, hinten) = splitAt (length rest - length post) rest guard $ post == hinten return $ ((pre, post), (x, mitte)) kontextsensitiv :: C.Type Grammatik kontextsensitiv = C.make "CS" ( text "Die Grammatik soll kontextsensitiv sein." ) $ \ g -> do let zs = sfilter (null . kontexte g ) $ regeln g verboten ( not $ isEmptySet zs ) "haben nicht die Form c V d -> c w d:" zs --------------------------------------------------------------------------- kontextfrei :: C.Type Grammatik kontextfrei = C.make "CF" ( text "Die Grammatik soll kontextfrei sein." ) $ \ g -> do let lang = sfilter ( (> 1) . length . fst ) $ regeln g verboten ( not $ isEmptySet lang ) "haben nicht die Form V -> w:" lang ----------------------------------------------------------------------------- linear :: C.Type Grammatik linear = C.make "Lin" ( text "Die Grammatik soll linear sein." ) $ \ g -> do let schlecht = sfilter ( (>1) . length . filter (`elementOf` nichtterminale g) . snd ) $ regeln g verboten ( not $ isEmptySet schlecht ) "enthalten rechts mehr als ein Nichtterminal:" schlecht ------------------------------------------------------------------------------ rechtslinear :: C.Type Grammatik rechtslinear = C.make "RightLin" ( text "Die Grammatik soll rechtslinear sein." ) $ \ g -> do let schlecht = do lr @ ( l, r ) <- setToList $ regeln g case reverse r of x : xs | any (`elementOf` variablen g ) xs -> return lr _ -> case l of [ v ] | v `elementOf` variablen g -> [] _ -> return lr verboten ( not $ null schlecht ) "sind nicht von der Form Variable -> Terminal^* [ Variable ]" schlecht at_most_one_terminal_in_rhs :: C.Type Grammatik at_most_one_terminal_in_rhs = C.make "at_most_one_terminal" ( text "In rechter Regelseite höchstens ein Terminal" ) $ \ g -> do let schlecht = do lr @ ( l, r ) <- setToList $ regeln g guard $ 2 <= length ( filter ( `elementOf` terminale g ) r ) return lr verboten ( not $ null schlecht ) "Regeln enthalten rechts mehr als ein Terminal" schlecht ------------------------------------------------------------------------------ linkslinear :: C.Type Grammatik linkslinear = C.make "LeftLin" ( text "Die Grammatik soll linkslinear sein." ) $ \ g -> do let schlecht = do lr @ ( l, r ) <- setToList $ regeln g case r of x : xs | any (`elementOf` nichtterminale g ) xs -> return lr _ -> [] verboten ( not $ null schlecht ) "sind nicht von der Form V -> V T^*" schlecht --------------------------------------------------------------------------- epsfrei :: C.Type Grammatik epsfrei = C.make "EpsFree" ( text "Die Grammatik soll Epsilon-frei sein." ) $ \ g -> do let schlecht = sfilter ( \ (lhs, rhs) -> null rhs ) $ regeln g verboten ( not $ isEmptySet schlecht ) "sind verboten:" schlecht kettenfrei :: C.Type Grammatik kettenfrei = C.make "ChFree" ( text "Die Grammatik soll kettenfrei sein." ) $ \ g -> do let schlecht = sfilter ( \ (lhs, rhs) -> length rhs == 1 && head rhs `elementOf` nichtterminale g ) $ regeln g verboten ( not $ isEmptySet schlecht ) "sind verboten:" schlecht chomsky :: C.Type Grammatik chomsky = C.make "CNF" ( text "Die Grammatik soll in Chomsky-Normalform sein." ) $ \ g -> do let ok rhs = ( length rhs == 1 && head rhs `elementOf` terminale g ) || ( length rhs == 2 && and [ x `elementOf` nichtterminale g | x <- rhs ] ) schlecht = sfilter ( \ ( lhs, rhs) -> not (ok rhs) ) $ regeln g verboten ( not $ isEmptySet schlecht ) "sind nicht von der Form N -> T oder N -> N N" schlecht greibach :: C.Type Grammatik greibach = C.make "Greibach" ( text "Die Grammatik soll in Greibach-Normalform sein." ) $ \ g -> do let ok rhs = ( length rhs > 0 && head rhs `elementOf` terminale g && and [ x `elementOf` nichtterminale g | x <- tail rhs ] ) schlecht = sfilter ( \ ( lhs, rhs) -> not (ok rhs) ) $ regeln g verboten ( not $ isEmptySet schlecht ) "sind nicht von der Form N -> T N^*" schlecht --------------------------------------------------------------------------- verboten :: ToDoc a => Bool -> String -> a -> Reporter () verboten f msg d = if f then reject $ fsep [ text "Diese Regeln", text msg, text ":" , toDoc d ] else inform $ text "Ja." combine :: String -> [ C.Type Grammatik ] -> C.Type Grammatik combine msg cs = C.make msg ( text "Die Grammatik soll vom" <+> text msg <+> text "sein." ) $ \ g -> do f <- wrap $ nested 4 $ sequence_ $ do c <- cs ; return $ C.run c g let answer f = fsep [ text "Das ist", text (if f then "" else "k" ) <> text "eine" , text msg <> text "-Grammatik." ] if ( isNothing f ) then reject $ answer False else inform $ answer True ---------------------------------------------------------------------------- typ1 = combine "Typ1" $ [ typ0, monoton ] typ2 = combine "Typ2" $ [ typ0, kontextfrei ] typ3 = combine "Typ3" $ [ typ0, kontextfrei, linear, rechtslinear ] immergut :: C.Type Grammatik immergut = C.make "G" empty $ \ g -> return ()
marcellussiegburg/autotool
collection/src/Grammatik/Hierarchie.hs
gpl-2.0
8,407
133
24
2,183
2,612
1,354
1,258
191
3
module Chap02.Data.BinaryTree where import Prelude hiding (foldr) import Test.QuickCheck (Arbitrary(..), sized) import Control.Applicative (pure, liftA3) import Data.Foldable data BinaryTree a = E | T (BinaryTree a) a (BinaryTree a) deriving (Show, Eq) instance Functor (BinaryTree) where fmap _ E = E fmap f (T l x r) = T (fmap f l) (f x) (fmap f r) instance Foldable BinaryTree where foldr _ z E = z foldr f z (T l x r) = foldr f (f x $ foldr f z r) l instance Arbitrary a => Arbitrary (BinaryTree a) where arbitrary = sized arbTree where arbTree 0 = pure E arbTree n = let p = (n-1) `div` 2 q = n - 1 - p in liftA3 T (arbTree p) arbitrary (arbTree q) inOrderTraversal :: BinaryTree a -> [a] inOrderTraversal = foldr (:) [] isCompleteTo :: Eq a => Int -> BinaryTree a -> Bool isCompleteTo d E | d == (-1) = True | otherwise = False isCompleteTo d (T E _ E) | d == 0 = True | otherwise = False isCompleteTo d (T l _ r) = isCompleteTo d' l && isCompleteTo d' r where d' = d - 1 size :: Foldable f => f a -> Int size = foldr (const (+1)) 0 getBalance :: BinaryTree a -> Int getBalance E = -1 getBalance (T l _ r) = size l - size r isBalanced :: Int -> Bool isBalanced n = abs n < 2
stappit/okasaki-pfds
src/Chap02/Data/BinaryTree.hs
gpl-3.0
1,365
0
14
430
618
315
303
39
1
module DynamicGraphs.GraphOptions where import Data.Aeson (FromJSON (parseJSON), withObject, (.!=), (.:?)) import qualified Data.Text.Lazy as T data GraphOptions = GraphOptions { taken :: [T.Text], -- courses to exclude from graph departments :: [T.Text], -- department prefixes to include excludedDepth :: Int, -- depth to recurse on courses from excluded departments maxDepth :: Int, -- total recursive depth to recurse on (depth of the overall graph) courseNumPrefix :: [Int], -- filter based on course number (most useful for filtering based on year) distribution :: [T.Text], -- distribution to include: like "artsci", or "engineering" location :: [T.Text], -- location of courses to include: like "utsg", or "utsc" includeRaws :: Bool, -- True to include nodes which are raw values includeGrades :: Bool -- True to include grade nodes } deriving (Show) data CourseGraphOptions = CourseGraphOptions { courses :: [T.Text], graphOptions :: GraphOptions } deriving (Show) defaultGraphOptions :: GraphOptions defaultGraphOptions = GraphOptions [] -- taken [] -- departments 0 -- excludedDepth (-1) -- maxDepth [] -- courseNumPrefix [] -- distribution [] -- location True -- includeRaws True -- includeGrades instance FromJSON CourseGraphOptions where parseJSON = withObject "Expected Object for GraphOptions" $ \o -> do rootCourses <- o .:? "courses" .!= [] takenCourses <- o .:? "taken" .!= [] dept <- o .:? "departments" .!= [] excludedCourseDepth <- o .:? "excludedDepth" .!= 0 maxGraphDepth <- o .:? "maxDepth" .!= (-1) courseNumPref <- o .:? "courseNumPrefix" .!= [] distrib <- o .:? "distribution" .!= [] includedLocation <- o .:? "location" .!= [] incRaws <- o .:? "includeRaws" .!= True incGrades <- o .:? "includeGrades" .!= True let options = GraphOptions takenCourses dept excludedCourseDepth maxGraphDepth courseNumPref distrib includedLocation incRaws incGrades return $ CourseGraphOptions rootCourses options
Courseography/courseography
app/DynamicGraphs/GraphOptions.hs
gpl-3.0
2,741
0
13
1,095
462
260
202
49
1
import Control.Monad import Data.ByteString.Char8 (pack, unpack, singleton) import Data.Maybe import System.Environment import System.Exit import System.Hardware.Serialport helpMsg = unlines [ "Usage: powerstrip [OPTION] DEVICE COMMAND [PORT]..." , "An interface for the USB controlled powerstrip written in Haskell" , "Commands: up, down, status" , "Ports : 0, 1" , "" , "Options:" , " -h, --help show this help message" ] data Command = Unpower | Power | Status deriving (Show, Eq, Enum) data Port = Port0 | Port1 deriving (Show, Eq, Enum) data Status = Powered | Unpowered deriving (Show, Eq) parsePort :: String -> Maybe Port parsePort "0" = Just Port0 parsePort "1" = Just Port1 parsePort _ = Nothing parseCommand :: String -> Maybe Command parseCommand "up" = Just Power parseCommand "down" = Just Unpower parseCommand "status" = Just Status parseCommand _ = Nothing parseStatus :: Char -> Status parseStatus c = if c == '0' then Unpowered else Powered data Arguments = Arguments { device :: String , command :: Command , ports :: [Port] } deriving (Show, Eq) parseArgs :: [String] -> Either String Arguments parseArgs (d:c:p) = if and [isJust mCmd, length p == length mPorts] then Right args else Left helpMsg where mCmd = parseCommand c mPorts = mapMaybe parsePort p args = Arguments d (fromJust mCmd) (if null mPorts then [Port0 ..] else mPorts) parseArgs _ = Left helpMsg main = do argv <- getArgs either putStrLn execute $ parseArgs argv execute :: Arguments -> IO () execute (Arguments d c p) = communicate d c p >>= (\x -> mapM_ (uncurry printStatus) $ zip p x) printStatus :: (Enum a, Show a1) => a -> a1 -> IO () printStatus p s = putStrLn $ "Socket " ++ (show . fromEnum) p ++ " is " ++ show s communicate :: Enum a => String -> Command -> [a] -> IO [Status] communicate device cmd ports = withSerial device defaultSerialSettings (communicate' cmd ports) communicate' cmd ports serial = do when (cmd /= Status) $ mapM_ (\x -> send serial $ pack $ decideByteString cmd x) ports out <- mapM (queryStatus . decideByteString Status) ports return $ map (parseStatus . head . unpack) out where decideByteString cmd port = show $ fromEnum cmd + (fromEnum port) * 3 queryStatus c = send serial (pack c) >> recv serial 1
chrisrosset/powerstrip
powerstrip.hs
gpl-3.0
2,488
9
13
645
846
434
412
53
3
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module Language.ArrayForth.HLL.Compile where import Control.Applicative ((<$), (<$>), (<*), (<*>)) import Control.Arrow (second) import Control.Monad.Free (Free (..)) import Control.Monad.State (State, get, gets, modify, put, runState) import Data.List (genericLength) import Data.Maybe (isNothing) import qualified Language.ArrayForth.Opcode as OP import qualified Language.ArrayForth.Program as AF import Language.ArrayForth.HLL.AST -- | Wraps a number into a constant instruction. num :: OP.F18Word -> AF.Instruction num = AF.Number -- | A chunk of memory used to store a variable or array. data Mem = Mem { location, size :: OP.F18Word } deriving (Show, Eq) data St = St { counter :: Int , vars :: [(String, Mem)] , startData :: [OP.F18Word] } deriving Show nextName :: St -> St nextName s@St { counter } = s { counter = succ counter } addArray :: String -> [OP.F18Word] -> State St () addArray name values = do state@St { vars, startData } <- get let mem = Mem (genericLength startData) (genericLength values) case lookup name vars of Nothing -> put state { vars = (name, mem) : vars , startData = startData ++ values } Just{} -> return () compile :: AST -> (AF.Program, [OP.F18Word]) compile ast = second startData . runState (compileAST ast) $ St 0 [] [] compileAST :: AST -> State St AF.Program compileAST (Pure _) = return [] compileAST (Free (Forth expr next)) = (++) <$> go expr <*> compileAST next where jump opcode label = AF.Jump opcode $ AF.Abstract label labelName = (show <$> gets counter) <* modify nextName go (Num n) = return [num n] go Nil = return [] go (Op Set name value) = do St { vars } <- get case name of Free (Forth (ArrayRef n) (Pure ())) | isNothing $ lookup n vars -> case value of Free (Forth (Num val) (Pure ())) -> [] <$ addArray n [val] _ -> addArray n [0] >> go expr _ -> set <$> compileName name <*> compileAST value where set addr val = addr ++ "b!" ++ val ++ "!b" go (Op Index name offset) = ( ++ "b! @b") <$> compileIndex name offset go (Op opr e1 e2) = do e1' <- compileAST e1 e2' <- compileAST e2 return $ e1' ++ e2' ++ operator opr go (UOp Neg e) = (++ "-") <$> compileAST e go (If cond e1 e2) = do cond' <- compileAST cond end <- labelName yes <- labelName let ifInstr = [if minusIf cond then jump OP.MinusIf yes else jump OP.If yes] ifExpr a b = cond' ++ ifInstr ++ a ++ [jump OP.Jmp end, AF.Label yes] ++ b ++ [AF.Label end] if flipped cond then ifExpr <$> compileAST e2 <*> compileAST e1 else ifExpr <$> compileAST e1 <*> compileAST e2 go (Array name values) = [] <$ addArray name values go (ArrayRef name) = (++ "b! @b") <$> getName name go _ = error "Not implemented yet. Sorry!" compileName (Free (Forth (ArrayRef n) (Pure ()))) = getName n compileName (Free (Forth (Op Index n offset) (Pure ()))) = compileIndex n offset compileName _ = error "Need a variable name here." compileIndex name offset = add <$> compileName name <*> compileAST offset where add loc idx = loc ++ idx ++ "+" getName name = do St { vars } <- get case lookup name vars of Just Mem { location } -> return $ [AF.Number location] Nothing -> error $ "Unknown variable " ++ name operator Add = "+" operator Sub = "- 1 + +" operator Mul = concat $ replicate 18 "+*" -- TODO: implement less stupidly operator Lt = "- 1 + +" operator LtE = "- +" operator Gt = "- 1 + +" operator GtE = "- +" operator Eq = "or" operator NEq = "or" operator _ = error "This operator not implemented yet." minusIf (Free (Forth (Op opr _ _) _)) = opr `elem` [Lt, Gt, LtE, GtE] minusIf _ = False flipped (Free (Forth (Op opr _ _) _)) = opr `elem` [Gt, GtE, NEq] flipped _ = False
TikhonJelvis/array-forth-hll
src/Language/ArrayForth/HLL/Compile.hs
gpl-3.0
4,849
0
21
1,877
1,599
825
774
85
28
module Sorters ( msort, msortwith , oemerge, oemerges , unimerge, unimerges , diff, dsplit , uniq, us , Plug(..), unplug ) where import Trace infixl 5 `oemerge` infixl 5 `unimerge` msort :: Ord a => [a] -> [a] msort = oemerges . runs -- todo: which is better? -- mrgsort -- utilities for sorting and merging ----------------------------------- -- find runs runs :: Ord a => [a] -> [[a]] runs [] = [] runs [x] = [[x]] runs (x : xs) = let rrs @ (r @ (y:_) : rs) = runs xs in if x <= y then (x : r) : rs else [x] : rrs mrgsort :: Ord a => [a] -> [a] mrgsort [] = []; mrgsort [x] = [x] mrgsort [x,y] = if x < y then [x,y] else [y,x] mrgsort xs = let (as, bs) = conquer xs in oemerge (mrgsort as) (mrgsort bs) conquer [] = ([],[]) conquer [x] = ([x], []) conquer (x : y : zs) = let (as, bs) = conquer zs in (x : as, y : bs) oemerge :: Ord a => [a] -> [a] -> [a] -- keeps duplicates oemerge [] ys = ys; oemerge xs [] = xs oemerge xxs @ (x : xs) yys @ (y : ys) = if x < y then x : oemerge xs yys else y : oemerge xxs ys oemerges :: Ord a => [[a]] -> [a] oemerges [] = [] oemerges [xs] = xs oemerges [xs,ys] = oemerge xs ys oemerges xss = let (ass, bss) = conquer xss in oemerge (oemerges ass) (oemerges bss) unimerge :: Ord a => [a] -> [a] -> [a] -- removes duplicates unimerge xs [] = xs; unimerge [] ys = ys unimerge xxs @ (x : xs) yys @ (y : ys) = case compare x y of LT -> x : unimerge xs yys GT -> y : unimerge xxs ys EQ -> x : unimerge xs ys unimerges :: Ord a => [[a]] -> [a] -- removes duplicates unimerges [] = [] unimerges [xs] = xs unimerges [xs,ys] = unimerge xs ys unimerges xss = let (ass, bss) = conquer xss in unimerge (unimerges ass) (unimerges bss) uniq :: Ord a => [a] -> [a] -- arg must be sorted already uniq [] = []; uniq [x] = [x] uniq (x : yys @ (y : ys)) = (if x == y then id else (x :)) (uniq yys) us :: Ord a => [a] -> [a] us = uniq . msort diff :: Ord a => [a] -> [a] -> [a] -- diff xs ys = all x <- xs that are not in ys -- args must be sorted, without duplicates diff [] ys = []; diff xs [] = xs diff xxs @ (x : xs) yys @ (y : ys) | x == y = diff xs ys | x < y = x : diff xs yys | otherwise = diff xxs ys dsplit :: Ord a => [a] -> [a] -> ([a],[a]) -- dsplit xs ys = (as, bs) where as = xs intersect ys, bs = xs setminus ys dsplit [] ys = ([], []) dsplit xs [] = ([], xs) dsplit xxs @ (x : xs) yys @ (y : ys) | x == y = let (as, bs) = dsplit xs ys in (x : as, bs) | x < y = let (as, bs) = dsplit xs yys in ( as, x : bs) | otherwise = let (as, bs) = dsplit xxs ys in ( as, bs) --------------------------------------------------------------------- best :: Ord a => [a] -> [a] best = take 1 . reverse . msort --------------------------------------------------------------------- asc :: Ord b => [(a, b)] -> [(a, b)] -- show successive maxima, lazily asc [] = [] asc ((x, c) : xs) = (x, c) : asc [ (x', c') | (x', c') <- xs, c' > c ] ascWith :: Ord b => (a -> b) -> [a] -> [a] ascWith f xs = [ x | (x, c) <- asc [ (x, f x) | x <- xs ] ] ----------------------------------------------------------------------- data Plug a b = Plug a b deriving Show instance Eq a => Eq (Plug a b) where Plug x _ == Plug y _ = x == y instance Ord a => Ord (Plug a b) where compare (Plug x _) (Plug y _) = compare x y unplug :: Plug a b -> b; unplug (Plug x y) = y msortwith :: Ord b => (a -> b) -> [a] -> [a] msortwith f xs = map unplug . msort $ [ Plug (f x) x | x <- xs ]
jwaldmann/rx
src/Sorters.hs
gpl-3.0
3,509
19
15
921
1,873
1,012
861
86
3
module Language.Objection.SyntaxTree where import Data.Int import qualified Data.Map as M type Identifier = String data Module = Module (M.Map Identifier Class) deriving (Show, Read, Eq) data PrivacyLevel = Private | Protected | Public deriving (Show, Read, Eq) data Primitive = PrimitiveInt | PrimitiveDouble | PrimitiveFloat | PrimitiveLong | PrimitiveChar | PrimitiveBool deriving (Show, Read, Eq) -- | A type is either a primitive or the name of some other -- class data Type = PrimitiveType Primitive | ClassType Identifier deriving (Show, Read, Eq) -- | A class consists of fields, constructors, and methods data Class = Class Identifier PrivacyLevel [Constructor] (M.Map Identifier Field) (M.Map Identifier Method) deriving (Show, Read, Eq) data Field = Field Identifier PrivacyLevel Type deriving (Show, Read, Eq) data Method = Method Identifier PrivacyLevel (Maybe Type) [(Type, Identifier)] [Statement] deriving (Show, Read, Eq) data Constructor = Constructor [Type] [Statement] deriving (Show, Read, Eq) data Statement = DeclareVariable Type Identifier | DeclareSetVariable Identifier Expression | IfStatement Expression Statement (Maybe Statement) | MethodCallStatement Identifier Identifier [Expression] | Return Expression | SetVariable Identifier Expression | StatementGroup [Statement] deriving (Show, Read, Eq) -- | TODO: Change MethodCallExpression to take an Expression for the client -- object rather than an identifier.... Would be much better that way -- (and most people would rely on this behavior) data Expression = ComparisonExpression ComparisonOperation Expression Expression | MathOperationExpression MathOperation Expression Expression | MethodCallExpression Identifier Identifier [Expression] | GetVariableExpression Identifier | LiteralExpression Literal | ParenExpression Expression deriving (Show, Read, Eq) data Literal = LiteralInt Int32 | LiteralLong Int64 | LiteralFloat Float | LiteralDouble Double | LiteralBool Bool deriving (Show, Read, Eq) data MathOperation = Add | Subtract | Multiply | Divide deriving (Show, Read, Eq) data ComparisonOperation = CEquals | CGreater | CGreaterEquals | CLess | CLessEquals deriving (Show, Read, Eq)
jhance/objection
Language/Objection/SyntaxTree.hs
gpl-3.0
2,859
0
9
978
578
330
248
54
0
module P31KarvonenHRSpec (main,spec) where import Test.Hspec import P31KarvonenHR hiding (main) main :: IO () main = hspec spec spec :: Spec spec = do describe "targetHR" $ do it "calculates the book example at 55% correctly" $ do targetHR 22 65 55 `shouldBe` 138 it "calculates the book example at 60% correctly" $ do targetHR 22 65 60 `shouldBe` 145 it "calculates the book example at 65% correctly" $ do targetHR 22 65 65 `shouldBe` 151 it "calculates the book example at 85% correctly" $ do targetHR 22 65 85 `shouldBe` 178 it "calculates the book example at 90% correctly" $ do targetHR 22 65 90 `shouldBe` 185 it "calculates the book example at 95% correctly" $ do targetHR 22 65 95 `shouldBe` 191
ciderpunx/57-exercises-for-programmers
test/P31KarvonenHRSpec.hs
gpl-3.0
772
0
14
192
220
108
112
20
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} module Bluesnap.Client.API ( Object(..) , retrieve , create , update ) where import Prelude hiding (last, log) import Data.Char (toLower) import Data.List (find) import Data.List.Split (splitOn) import qualified Bluesnap.API.Request as Request import qualified Bluesnap.API.Response as Response import Bluesnap.API.XML import Bluesnap.Client hiding (get, post, put) import qualified Bluesnap.Client as Client (get, post, put) import Network.URI class Object o where data ObjectID o data ObjectRequest o data ObjectResponse o servicePath :: o -> Path idToPath :: ObjectID o -> Path responseParser :: o -> XMLParser (ObjectResponse o) fromResponse :: ObjectResponse o -> Either String o toRequest :: o -> ObjectRequest o requestToContents :: ObjectRequest o -> [Content ()] oidConstructor :: String -> ObjectID o -- | Type inference trick to get out the object type from a given object id type fakeObj :: (Object o) => ObjectID o -> o fakeObj = error "fakeObj :: (Object o) => ObjectID o -> o" fullPath :: (Object o) => ObjectID o -> Path fullPath oid = concat [servicePath (fakeObj oid), idToPath oid] -- | Gets the object from Bluesnap based on the given id. retrieve :: Object o => (ObjectID o) -> Bluesnap o retrieve oid = do let parser = responseParser (fakeObj oid) payload <- Client.get (fullPath oid) responseXML <- checkParse $ parse parser payload checkParse $ fromResponse responseXML -- | Saves the object in Bluesnap and returns its id based on -- the location header. create :: Object o => o -> Bluesnap (ObjectID o) create obj = do payload <- fmap render . safeHead . requestToContents $ toRequest obj log $ "PAYLOAD: " ++ payload (headers, payload) <- Client.post (servicePath obj) payload oid <- getIDFromLocation headers return $ oidConstructor oid -- | Updates the object in Bluesnap for the given object id and -- returns unit if the update was successful otherwise throws a -- bluesnap error update :: Object o => (ObjectID o) -> o -> Bluesnap () update oid obj = do payload <- fmap render . safeHead . requestToContents $ toRequest obj _ <- Client.put (fullPath oid) payload return () -- * Helpers -- | Get the head of the list or throws a bluesnap error if the list is empty safeHead :: [a] -> Bluesnap a safeHead [] = throwError $ BluesnapError "safeHead failed" safeHead (a:_) = return a -- | Get the value of location header or throws a Bluesnap error getIDFromLocation :: [Header] -> Bluesnap String getIDFromLocation headers = maybe (throwError $ BluesnapError "Location header is not found!") return (maybeIDFromLocation headers) -- EG: maybeIDFromLocation [("Location", "https://sandbox.bluesnap.com/services/2/shoppers/19575974")] -- Just "19575974" maybeIDFromLocation :: [Header] -> Maybe String maybeIDFromLocation headers = ((find (("location"==) . map toLower . fst) headers) >>= (return . snd) >>= parseURI >>= getOID) where getOID :: URI -> Maybe String getOID = last . splitOn "/" . uriPath last :: [a] -> Maybe a last [] = Nothing last [a] = Just a last (_:as) = last as -- * Examples data Subscription = Subscription String deriving (Eq, Show) instance Object Subscription where data ObjectID Subscription = SubscriptionID String data ObjectRequest Subscription = SubsReq { unSubsReq :: Request.Subscription } data ObjectResponse Subscription = SubsResp { unSubsResp :: Response.Subscription } servicePath _ = "/services/2/subscriptions/" idToPath (SubscriptionID value) = value responseParser _ = fmap SubsResp $ Response.elementSubscription fromResponse (SubsResp r) = Right $ Subscription (show r) toRequest s = error "toRequest s" requestToContents = Request.elementToXMLSubscription . unSubsReq oidConstructor = SubscriptionID
andorp/hs-bluesnap
src/Bluesnap/Client/API.hs
gpl-3.0
4,028
0
14
864
1,082
565
517
80
1
module PdfGenerator (createPDF) where import System.Process import GHC.IO.Handle.Types import ImageConversion (removeImage) import Data.List.Utils (replace) -- | Opens a new process to create a PDF from a TEX (texName) and deletes -- the tex file and extra files created by pdflatex createPDF :: String -> IO () createPDF texName = do (_, _, _, pid) <- convertTexToPDF texName print "Waiting for a process..." waitForProcess pid let aux = replace ".tex" ".aux" texName log = replace ".tex" ".log" texName removeImage (aux ++ " " ++ log ++ " " ++ texName) print "Process Complete" -- | Create a process to use the pdflatex program to create a PDF from a TEX -- file (texName). The process is run in nonstop mode and so it will not block -- if an error occurs. The resulting PDF will have the same filename as texName. convertTexToPDF :: String -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) convertTexToPDF texName = createProcess $ CreateProcess (ShellCommand $ "pdflatex -interaction=nonstopmode " ++ texName) Nothing Nothing CreatePipe CreatePipe CreatePipe False False False
miameng/courseography
app/PdfGenerator.hs
gpl-3.0
1,438
0
12
516
235
123
112
30
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.YouTube.SuperChatEvents.List -- 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) -- -- Retrieves a list of resources, possibly filtered. -- -- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.superChatEvents.list@. module Network.Google.Resource.YouTube.SuperChatEvents.List ( -- * REST Resource SuperChatEventsListResource -- * Creating a Request , superChatEventsList , SuperChatEventsList -- * Request Lenses , scelXgafv , scelPart , scelUploadProtocol , scelAccessToken , scelUploadType , scelHl , scelPageToken , scelMaxResults , scelCallback ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.superChatEvents.list@ method which the -- 'SuperChatEventsList' request conforms to. type SuperChatEventsListResource = "youtube" :> "v3" :> "superChatEvents" :> QueryParams "part" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "hl" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] SuperChatEventListResponse -- | Retrieves a list of resources, possibly filtered. -- -- /See:/ 'superChatEventsList' smart constructor. data SuperChatEventsList = SuperChatEventsList' { _scelXgafv :: !(Maybe Xgafv) , _scelPart :: ![Text] , _scelUploadProtocol :: !(Maybe Text) , _scelAccessToken :: !(Maybe Text) , _scelUploadType :: !(Maybe Text) , _scelHl :: !(Maybe Text) , _scelPageToken :: !(Maybe Text) , _scelMaxResults :: !(Textual Word32) , _scelCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SuperChatEventsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scelXgafv' -- -- * 'scelPart' -- -- * 'scelUploadProtocol' -- -- * 'scelAccessToken' -- -- * 'scelUploadType' -- -- * 'scelHl' -- -- * 'scelPageToken' -- -- * 'scelMaxResults' -- -- * 'scelCallback' superChatEventsList :: [Text] -- ^ 'scelPart' -> SuperChatEventsList superChatEventsList pScelPart_ = SuperChatEventsList' { _scelXgafv = Nothing , _scelPart = _Coerce # pScelPart_ , _scelUploadProtocol = Nothing , _scelAccessToken = Nothing , _scelUploadType = Nothing , _scelHl = Nothing , _scelPageToken = Nothing , _scelMaxResults = 5 , _scelCallback = Nothing } -- | V1 error format. scelXgafv :: Lens' SuperChatEventsList (Maybe Xgafv) scelXgafv = lens _scelXgafv (\ s a -> s{_scelXgafv = a}) -- | The *part* parameter specifies the superChatEvent resource parts that -- the API response will include. This parameter is currently not -- supported. scelPart :: Lens' SuperChatEventsList [Text] scelPart = lens _scelPart (\ s a -> s{_scelPart = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). scelUploadProtocol :: Lens' SuperChatEventsList (Maybe Text) scelUploadProtocol = lens _scelUploadProtocol (\ s a -> s{_scelUploadProtocol = a}) -- | OAuth access token. scelAccessToken :: Lens' SuperChatEventsList (Maybe Text) scelAccessToken = lens _scelAccessToken (\ s a -> s{_scelAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). scelUploadType :: Lens' SuperChatEventsList (Maybe Text) scelUploadType = lens _scelUploadType (\ s a -> s{_scelUploadType = a}) -- | Return rendered funding amounts in specified language. scelHl :: Lens' SuperChatEventsList (Maybe Text) scelHl = lens _scelHl (\ s a -> s{_scelHl = a}) -- | The *pageToken* parameter identifies a specific page in the result set -- that should be returned. In an API response, the nextPageToken and -- prevPageToken properties identify other pages that could be retrieved. scelPageToken :: Lens' SuperChatEventsList (Maybe Text) scelPageToken = lens _scelPageToken (\ s a -> s{_scelPageToken = a}) -- | The *maxResults* parameter specifies the maximum number of items that -- should be returned in the result set. scelMaxResults :: Lens' SuperChatEventsList Word32 scelMaxResults = lens _scelMaxResults (\ s a -> s{_scelMaxResults = a}) . _Coerce -- | JSONP scelCallback :: Lens' SuperChatEventsList (Maybe Text) scelCallback = lens _scelCallback (\ s a -> s{_scelCallback = a}) instance GoogleRequest SuperChatEventsList where type Rs SuperChatEventsList = SuperChatEventListResponse type Scopes SuperChatEventsList = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtube.readonly"] requestClient SuperChatEventsList'{..} = go _scelPart _scelXgafv _scelUploadProtocol _scelAccessToken _scelUploadType _scelHl _scelPageToken (Just _scelMaxResults) _scelCallback (Just AltJSON) youTubeService where go = buildClient (Proxy :: Proxy SuperChatEventsListResource) mempty
brendanhay/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/SuperChatEvents/List.hs
mpl-2.0
6,337
0
20
1,543
980
568
412
141
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( getApplicationDev , appMain , develMain , makeFoundation , makeLogWare -- * for DevelMain , getApplicationRepl , shutdownApp -- * for GHCI , handler , db ) where import Control.Monad.Logger (liftLoc, runLoggingT) --import Database.Persist.Sql (runMigrationUnsafe) import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool) import Import import Language.Haskell.TH.Syntax (qLocation) import Network.Wai (Middleware) import Network.Wai.Handler.Warp (Settings, defaultSettings, defaultShouldDisplayException, runSettings, setHost, setOnException, setPort, getPort) import Network.Wai.Middleware.RequestLogger (Destination (Logger), IPAddrSource (..), OutputFormat (..), destination, mkRequestLogger, outputFormat) import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet, toLogStr) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Common import Handler.Tutorial import Handler.Home -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- | This function allocates resources (such as a database connection pool), -- performs initialization and returns a foundation datatype value. This is also -- the place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeFoundation :: AppSettings -> IO App makeFoundation appSettings = do -- Some basic initializations: HTTP connection manager, logger, and static -- subsite. appHttpManager <- newManager appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger appStatic <- (if appMutableStatic appSettings then staticDevel else static) (appStaticDir appSettings) -- We need a log function to create a connection pool. We need a connection -- pool to create our foundation. And we need our foundation to get a -- logging function. To get out of this loop, we initially create a -- temporary foundation without a real connection pool, get a log function -- from there, and then create the real foundation. let mkFoundation appConnPool = App {..} -- The App {..} syntax is an example of record wild cards. For more -- information, see: -- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html tempFoundation = mkFoundation $ error "connPool forced in tempFoundation" logFunc = messageLoggerSource tempFoundation appLogger -- Create the database connection pool pool <- flip runLoggingT logFunc $ createPostgresqlPool (pgConnStr $ appDatabaseConf appSettings) (pgPoolSize $ appDatabaseConf appSettings) -- Perform database migration using our application's logging settings. runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc -- Return the foundation return $ mkFoundation pool -- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and -- applying some additional middlewares. makeApplication :: App -> IO Application makeApplication foundation = do logWare <- makeLogWare foundation -- Create the WAI application and apply middlewares appPlain <- toWaiAppPlain foundation return $ logWare $ defaultMiddlewaresNoLogging appPlain makeLogWare :: App -> IO Middleware makeLogWare foundation = mkRequestLogger def { outputFormat = if appDetailedRequestLogging $ appSettings foundation then Detailed True else Apache (if appIpFromHeader $ appSettings foundation then FromFallback else FromSocket) , destination = Logger $ loggerSet $ appLogger foundation } -- | Warp settings for the given foundation value. warpSettings :: App -> Settings warpSettings foundation = setPort (appPort $ appSettings foundation) $ setHost (appHost $ appSettings foundation) $ setOnException (\_req e -> when (defaultShouldDisplayException e) $ messageLoggerSource foundation (appLogger foundation) $(qLocation >>= liftLoc) "yesod" LevelError (toLogStr $ "Exception from Warp: " ++ show e)) defaultSettings -- | For yesod devel, return the Warp settings and WAI Application. getApplicationDev :: IO (Settings, Application) getApplicationDev = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app <- makeApplication foundation return (wsettings, app) getAppSettings :: IO AppSettings getAppSettings = loadAppSettings [configSettingsYml] [] useEnv -- | main function for use by yesod devel develMain :: IO () develMain = develMainHelper getApplicationDev -- | The @main@ function for an executable running this site. appMain :: IO () appMain = do -- Get the settings from all relevant sources settings <- loadAppSettingsArgs -- fall back to compile-time values, set to [] to require values at runtime [configSettingsYmlValue] -- allow environment variables to override useEnv -- Generate the foundation from the settings foundation <- makeFoundation settings -- Generate a WAI Application from the foundation app <- makeApplication foundation -- Run the application with Warp runSettings (warpSettings foundation) app -------------------------------------------------------------- -- Functions for DevelMain.hs (a way to run the app from GHCi) -------------------------------------------------------------- getApplicationRepl :: IO (Int, App, Application) getApplicationRepl = do settings <- getAppSettings foundation <- makeFoundation settings wsettings <- getDevSettings $ warpSettings foundation app1 <- makeApplication foundation return (getPort wsettings, foundation, app1) shutdownApp :: App -> IO () shutdownApp _ = return () --------------------------------------------- -- Functions for use in development with GHCi --------------------------------------------- -- | Run a handler handler :: Handler a -> IO a handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h -- | Run DB queries db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a db = handler . runDB
montanonic/well-typed
Application.hs
agpl-3.0
7,029
0
13
1,804
1,054
565
489
-1
-1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} module BoardGame.Common.Message.HandShakeResponse ( HandShakeResponse(..) , tupleToHandShakeResponse ) where import GHC.Generics (Generic) import Data.Aeson (FromJSON, ToJSON) import Control.DeepSeq (NFData) data HandShakeResponse = HandShakeResponse { serverType :: String , apiVersion :: String -- Not yet used. For the future. } deriving (Eq, Show, Generic, NFData) instance FromJSON HandShakeResponse instance ToJSON HandShakeResponse tupleToHandShakeResponse :: (String, String) -> HandShakeResponse tupleToHandShakeResponse (serverType, apiVersion) = HandShakeResponse serverType apiVersion
azadbolour/boardgame
haskell-server/src/BoardGame/Common/Message/HandShakeResponse.hs
agpl-3.0
855
0
8
117
149
90
59
17
1
module QuantLib.Stochastic ( module Q ) where import QuantLib.Stochastic.Process as Q import QuantLib.Stochastic.Discretize as Q import QuantLib.Stochastic.Random as Q import QuantLib.Stochastic.PureMT as Q
paulrzcz/hquantlib
src/QuantLib/Stochastic.hs
lgpl-3.0
208
0
4
24
44
32
12
5
0
module Utils (tuplein, tuplecomp) where tuplecomp :: (Eq a, Show a) => (a, a) -> a -> a tuplecomp t n | n == fst t = snd t | n == snd t = fst t | otherwise = -- error "tuple does not contain thing" error ("<" ++ show t ++ "> does not contain <" ++ show n ++ ">") -- <tuplein t n> is true if <n> is in <t> tuplein :: Eq a => (a, a) -> a -> Bool tuplein t n | n == fst t = True | n == snd t = True | otherwise = False
ekalosak/haskell-practice
Utils.hs
lgpl-3.0
470
0
12
160
204
100
104
12
1
{-# LANGUAGE LambdaCase #-} module Main where import Control.Exception import Control.Concurrent import Control.Monad import Data.Char import Data.Maybe import System.Console.GetOpt import System.Environment import qualified Data.ByteString.Lazy as L import qualified Network.WebSockets as WS lGetLine = fmap (L.pack . map (fromIntegral . ord)) getLine safeRead = fmap fst . listToMaybe . reads -- Gracefully close the connection and mask the default printout exnHandler :: WS.Connection -> SomeException -> IO () exnHandler conn _ = WS.sendClose conn L.empty server = WS.acceptRequest >=> client client conn = (handle $ exnHandler conn) $ do forkIO . forever $ lGetLine >>= WS.sendBinaryData conn forever $ WS.receiveData conn >>= L.putStr data WSCatConfig = WSCatConfig { cfgHostname :: Maybe String, cfgPort :: Maybe Int, cfgPath :: Maybe String, cfgMainFunc :: WSCatConfig -> IO () } defaultConfig = WSCatConfig { cfgHostname = Nothing, cfgPort = Nothing, cfgPath = Nothing, cfgMainFunc = clientMain } getOptOptions = [ Option "l" [] (NoArg $ \cfg -> return cfg {cfgMainFunc = serverMain}) "Listen for inbound websocket connections.", Option "p" [] (ReqArg (\arg cfg -> return cfg {cfgPort = safeRead arg}) "PORT") "Which port number to use." ] applyLeftovers cfg [] = cfg applyLeftovers cfg [port] = cfg { cfgPort = safeRead port } applyLeftovers cfg [hostname, port] = applyLeftovers (cfg { cfgHostname = Just hostname }) [port] applyLeftovers cfg [hostname, port, path] = applyLeftovers (cfg { cfgPath = Just path }) [hostname, port] errorHelp :: a errorHelp = error $ usageInfo (unlines ["","\twscat -l [-p] PORT","\twscat HOST PORT [PATH]"]) getOptOptions main = do (cfg, leftovers, errors) <- fmap (getOpt RequireOrder getOptOptions) getArgs unless (null errors) . error $ unlines errors cfg' <- foldl (>>=) (return defaultConfig :: IO WSCatConfig) cfg let cfg'' = applyLeftovers cfg' leftovers cfgMainFunc cfg'' $ cfg'' clientMain (WSCatConfig {cfgHostname = hostname, cfgPort = port, cfgPath = path}) = WS.runClient hostname' port' path' client where hostname' = fromMaybe errorHelp hostname port' = fromMaybe errorHelp port path' = fromMaybe "/" path serverMain (WSCatConfig {cfgPort = port}) = WS.runServer "0.0.0.0" port' server where port' = fromMaybe errorHelp port
aweinstock314/wscat
src/wscat.hs
apache-2.0
2,395
0
14
447
761
408
353
48
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Service.SMF ( handleDiscover, handleCommand ) where import Shelly import Prelude hiding (FilePath) import qualified Data.Text as T default (T.Text) handleDiscover :: IO String handleDiscover = return "smf" handleCommand :: String -> IO () handleCommand "stop tomcat" = do stopService "tomcat" handleCommand "start tomcat" = do startService "tomcat" handleCommand unsupported = do putStrLn $ "unsupported command " ++ unsupported stopService :: T.Text -> IO () stopService service = shelly $ verbosely $ do run_ "svcadm" ["disable", service] startService :: T.Text -> IO () startService service = shelly $ verbosely $do run_ "svcadm" ["enable", service]
AlainODea/haskell-amqp-examples
Service/SMF.hs
apache-2.0
816
0
9
145
212
112
100
25
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} module Network.IRC.MessageBus ( MessageBus , newMessageBus , MessageChannel , newMessageChannel , sendMessage , receiveMessage , receiveMessageEither , closeMessageChannel , awaitMessageChannel , isClosedMessageChannel ) where import ClassyPrelude newtype Latch = Latch (MVar ()) newLatch :: IO Latch newLatch = liftM Latch newEmptyMVar doLatch :: Latch -> IO () doLatch (Latch mv) = putMVar mv () awaitLatch :: Latch -> IO () awaitLatch (Latch mv) = void $ takeMVar mv latched :: Latch -> IO Bool latched (Latch mv) = map isJust . tryReadMVar $ mv newtype MessageBus a = MessageBus (TChan a) newMessageBus :: IO (MessageBus a) newMessageBus = MessageBus <$> newBroadcastTChanIO -- | A channel through which messages are sent and received. data MessageChannel a = MessageChannel Latch (TChan a) (TChan a) newMessageChannel ::MessageBus a -> IO (MessageChannel a) newMessageChannel (MessageBus wChan) = do latch <- newLatch rChan <- atomically $ dupTChan wChan return $ MessageChannel latch rChan wChan sendMessageSTM :: MessageChannel a -> a -> STM () sendMessageSTM (MessageChannel _ _ wChan) = writeTChan wChan receiveMessageSTM :: MessageChannel a -> STM a receiveMessageSTM (MessageChannel _ rChan _) = readTChan rChan -- | Sends a message through a message channel. sendMessage :: MessageChannel a -- ^ The channel -> a -- ^ The message to send -> IO () sendMessage chan = atomically . sendMessageSTM chan receiveMessage :: MessageChannel a -> IO a receiveMessage = atomically . receiveMessageSTM closeMessageChannel :: MessageChannel a -> IO () closeMessageChannel (MessageChannel latch _ _) = doLatch latch awaitMessageChannel :: MessageChannel a -> IO () awaitMessageChannel (MessageChannel latch _ _) = awaitLatch latch isClosedMessageChannel :: MessageChannel a -> IO Bool isClosedMessageChannel (MessageChannel latch _ _) = latched latch receiveMessageEither :: MessageChannel a -> MessageChannel b -> IO (Either a b) receiveMessageEither chan1 chan2 = atomically $ map Left (receiveMessageSTM chan1) `orElseSTM` map Right (receiveMessageSTM chan2)
abhin4v/hask-irc
hask-irc-core/Network/IRC/MessageBus.hs
apache-2.0
2,290
0
9
402
647
327
320
53
1
import Data.List cons a as = Just (a:as) ans' _ [] = Nothing ans' m (a:as) = if m < a then Nothing else if m == a then Just [a] else if a' /= Nothing then a' >>= (cons a) else b' where a' = ans' (m-a) as b' = ans' m as ans m a = let o = ans' m a in case o of Nothing -> "no" Just _ -> "yes" main = do _ <- getLine a <- getLine _ <- getLine m <- getLine let a' = sort $ map read $ words a :: [Int] m' = map read $ words m :: [Int] o = map (\ m -> ans m a') m' -- print o mapM_ putStrLn o
a143753/AOJ
ALDS1_5_A.hs
apache-2.0
644
0
13
284
296
149
147
27
4
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE AutoDeriveTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Maybe -- Copyright : (c) 2007 Yitzak Gale, Eric Kidd -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The 'MaybeT' monad transformer extends a monad with the ability to exit -- the computation without returning a value. -- -- A sequence of actions produces a value only if all the actions in -- the sequence do. If one exits, the rest of the sequence is skipped -- and the composite action exits. -- -- For a variant allowing a range of exception values, see -- "Control.Monad.Trans.Except". ----------------------------------------------------------------------------- module Control.Monad.Trans.Maybe ( -- * The MaybeT monad transformer MaybeT(..), mapMaybeT, -- * Conversion maybeToExceptT, exceptToMaybeT, -- * Lifting other operations liftCallCC, liftCatch, liftListen, liftPass, ) where import Control.Monad.IO.Class import Control.Monad.Signatures import Control.Monad.Trans.Class import Control.Monad.Trans.Except (ExceptT(..)) import Data.Functor.Classes import Control.Applicative import Control.Monad (MonadPlus(mzero, mplus), liftM, ap) import Control.Monad.Fix (MonadFix(mfix)) import Data.Foldable (Foldable(foldMap)) import Data.Maybe (fromMaybe) import Data.Traversable (Traversable(traverse)) -- | The parameterizable maybe monad, obtained by composing an arbitrary -- monad with the 'Maybe' monad. -- -- Computations are actions that may produce a value or exit. -- -- The 'return' function yields a computation that produces that -- value, while @>>=@ sequences two subcomputations, exiting if either -- computation does. newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) } instance (Eq1 m, Eq a) => Eq (MaybeT m a) where MaybeT x == MaybeT y = eq1 x y instance (Ord1 m, Ord a) => Ord (MaybeT m a) where compare (MaybeT x) (MaybeT y) = compare1 x y instance (Read1 m, Read a) => Read (MaybeT m a) where readsPrec = readsData $ readsUnary1 "MaybeT" MaybeT instance (Show1 m, Show a) => Show (MaybeT m a) where showsPrec d (MaybeT m) = showsUnary1 "MaybeT" d m instance (Eq1 m) => Eq1 (MaybeT m) where eq1 = (==) instance (Ord1 m) => Ord1 (MaybeT m) where compare1 = compare instance (Read1 m) => Read1 (MaybeT m) where readsPrec1 = readsPrec instance (Show1 m) => Show1 (MaybeT m) where showsPrec1 = showsPrec -- | Transform the computation inside a @MaybeT@. -- -- * @'runMaybeT' ('mapMaybeT' f m) = f ('runMaybeT' m)@ mapMaybeT :: (m (Maybe a) -> n (Maybe b)) -> MaybeT m a -> MaybeT n b mapMaybeT f = MaybeT . f . runMaybeT -- | Convert a 'MaybeT' computation to 'ExceptT', with a default -- exception value. maybeToExceptT :: (Functor m) => e -> MaybeT m a -> ExceptT e m a maybeToExceptT e (MaybeT m) = ExceptT $ fmap (maybe (Left e) Right) m -- | Convert a 'ExceptT' computation to 'MaybeT', discarding the -- value of any exception. exceptToMaybeT :: (Functor m) => ExceptT e m a -> MaybeT m a exceptToMaybeT (ExceptT m) = MaybeT $ fmap (either (const Nothing) Just) m instance (Functor m) => Functor (MaybeT m) where fmap f = mapMaybeT (fmap (fmap f)) instance (Foldable f) => Foldable (MaybeT f) where foldMap f (MaybeT a) = foldMap (foldMap f) a instance (Traversable f) => Traversable (MaybeT f) where traverse f (MaybeT a) = MaybeT <$> traverse (traverse f) a instance (Functor m, Monad m) => Applicative (MaybeT m) where pure = return (<*>) = ap instance (Functor m, Monad m) => Alternative (MaybeT m) where empty = mzero (<|>) = mplus instance (Monad m) => Monad (MaybeT m) where fail _ = MaybeT (return Nothing) return = lift . return x >>= f = MaybeT $ do v <- runMaybeT x case v of Nothing -> return Nothing Just y -> runMaybeT (f y) instance (Monad m) => MonadPlus (MaybeT m) where mzero = MaybeT (return Nothing) mplus x y = MaybeT $ do v <- runMaybeT x case v of Nothing -> runMaybeT y Just _ -> return v instance (MonadFix m) => MonadFix (MaybeT m) where mfix f = MaybeT (mfix (runMaybeT . f . fromMaybe bomb)) where bomb = error "mfix (MaybeT): inner computation returned Nothing" instance MonadTrans MaybeT where lift = MaybeT . liftM Just instance (MonadIO m) => MonadIO (MaybeT m) where liftIO = lift . liftIO -- | Lift a @callCC@ operation to the new monad. liftCallCC :: CallCC m (Maybe a) (Maybe b) -> CallCC (MaybeT m) a b liftCallCC callCC f = MaybeT $ callCC $ \ c -> runMaybeT (f (MaybeT . c . Just)) -- | Lift a @catchE@ operation to the new monad. liftCatch :: Catch e m (Maybe a) -> Catch e (MaybeT m) a liftCatch f m h = MaybeT $ f (runMaybeT m) (runMaybeT . h) -- | Lift a @listen@ operation to the new monad. liftListen :: (Monad m) => Listen w m (Maybe a) -> Listen w (MaybeT m) a liftListen listen = mapMaybeT $ \ m -> do (a, w) <- listen m return $! fmap (\ r -> (r, w)) a -- | Lift a @pass@ operation to the new monad. liftPass :: (Monad m) => Pass w m (Maybe a) -> Pass w (MaybeT m) a liftPass pass = mapMaybeT $ \ m -> pass $ do a <- m return $! case a of Nothing -> (Nothing, id) Just (v, f) -> (Just v, f)
holoed/Junior
lib/transformers-0.4.3.0/Control/Monad/Trans/Maybe.hs
apache-2.0
5,481
0
15
1,188
1,679
898
781
89
2
{-# LANGUAGE ViewPatterns #-} {-| Implementation of the Ganeti configuration database. -} {- Copyright (C) 2011, 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 Ganeti.Config ( LinkIpMap , NdParamObject(..) , loadConfig , saveConfig , getNodeInstances , getNodeRole , getNodeNdParams , getDefaultNicLink , getDefaultHypervisor , getInstancesIpByLink , getMasterNodes , getMasterCandidates , getMasterOrCandidates , getMasterNetworkParameters , getOnlineNodes , getNode , getInstance , getDisk , getFilterRule , getGroup , getGroupNdParams , getGroupIpolicy , getGroupDiskParams , getGroupNodes , getGroupInstances , getGroupOfNode , getInstPrimaryNode , getInstMinorsForNode , getInstAllNodes , getInstDisks , getInstDisksFromObj , getDrbdMinorsForDisk , getDrbdMinorsForInstance , getFilledInstHvParams , getFilledInstBeParams , getFilledInstOsParams , getNetwork , MAC , getAllMACs , getAllDrbdSecrets , NodeLVsMap , getInstanceLVsByNode , getAllLVs , buildLinkIpInstnameMap , instNodes ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Monad import Control.Monad.State import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Foldable as F import Data.List (foldl', nub) import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid import qualified Data.Map as M import qualified Data.Set as S import qualified Text.JSON as J import System.IO import Ganeti.BasicTypes import qualified Ganeti.Constants as C import Ganeti.Errors import Ganeti.JSON (fromJResult, fromContainer, GenericContainer(..)) import Ganeti.Objects import Ganeti.Types import qualified Ganeti.Utils.MultiMap as MM -- | Type alias for the link and ip map. type LinkIpMap = M.Map String (M.Map String String) -- * Operations on the whole configuration -- | Reads the config file. readConfig :: FilePath -> IO (Result String) readConfig = runResultT . liftIO . readFile -- | Parses the configuration file. parseConfig :: String -> Result ConfigData parseConfig = fromJResult "parsing configuration" . J.decodeStrict -- | Encodes the configuration file. encodeConfig :: ConfigData -> String encodeConfig = J.encodeStrict -- | Wrapper over 'readConfig' and 'parseConfig'. loadConfig :: FilePath -> IO (Result ConfigData) loadConfig = fmap (>>= parseConfig) . readConfig -- | Wrapper over 'hPutStr' and 'encodeConfig'. saveConfig :: Handle -> ConfigData -> IO () saveConfig fh = hPutStr fh . encodeConfig -- * Query functions -- | Annotate Nothing as missing parameter and apply the given -- transformation otherwise withMissingParam :: String -> (a -> ErrorResult b) -> Maybe a -> ErrorResult b withMissingParam = maybe . Bad . ParameterError -- | Computes the nodes covered by a disk. computeDiskNodes :: Disk -> S.Set String computeDiskNodes dsk = case diskLogicalId dsk of Just (LIDDrbd8 nodeA nodeB _ _ _ _) -> S.fromList [nodeA, nodeB] _ -> S.empty -- | Computes all disk-related nodes of an instance. For non-DRBD, -- this will be empty, for DRBD it will contain both the primary and -- the secondaries. instDiskNodes :: ConfigData -> Instance -> S.Set String instDiskNodes cfg inst = case getInstDisksFromObj cfg inst of Ok disks -> S.unions $ map computeDiskNodes disks Bad _ -> S.empty -- | Computes all nodes of an instance. instNodes :: ConfigData -> Instance -> S.Set String instNodes cfg inst = maybe id S.insert (instPrimaryNode inst) $ instDiskNodes cfg inst -- | Computes the secondary node UUID for a DRBD disk computeDiskSecondaryNode :: Disk -> String -> Maybe String computeDiskSecondaryNode dsk primary = case diskLogicalId dsk of Just (LIDDrbd8 a b _ _ _ _) -> Just $ if primary == a then b else a _ -> Nothing -- | Get instances of a given node. -- The node is specified through its UUID. -- The secondary calculation is expensive and frequently called, so optimise -- this to allocate fewer temporary values getNodeInstances :: ConfigData -> String -> ([Instance], [Instance]) getNodeInstances cfg nname = let all_insts = M.elems . fromContainer . configInstances $ cfg all_disks = fromContainer . configDisks $ cfg pri_inst = filter ((== Just nname) . instPrimaryNode) all_insts find_disk :: String -> Maybe Disk find_disk d_uuid = M.lookup (UTF8.fromString d_uuid) all_disks inst_disks :: [(Instance, [Disk])] inst_disks = [(i, mapMaybe find_disk $ instDisks i) | i <- all_insts] sec_insts :: [Instance] sec_insts = [inst | (inst, disks) <- inst_disks, s_uuid <- mapMaybe (\d -> (instPrimaryNode inst) >>= (computeDiskSecondaryNode d)) disks, s_uuid == nname] in (pri_inst, sec_insts) -- | Computes the role of a node. getNodeRole :: ConfigData -> Node -> NodeRole getNodeRole cfg node | uuidOf node == clusterMasterNode (configCluster cfg) = NRMaster | nodeMasterCandidate node = NRCandidate | nodeDrained node = NRDrained | nodeOffline node = NROffline | otherwise = NRRegular -- | Get the list of the master nodes (usually one). getMasterNodes :: ConfigData -> [Node] getMasterNodes cfg = filter ((==) NRMaster . getNodeRole cfg) . F.toList . configNodes $ cfg -- | Get the list of master candidates, /not including/ the master itself. getMasterCandidates :: ConfigData -> [Node] getMasterCandidates cfg = filter ((==) NRCandidate . getNodeRole cfg) . F.toList . configNodes $ cfg -- | Get the list of master candidates, /including/ the master. getMasterOrCandidates :: ConfigData -> [Node] getMasterOrCandidates cfg = let isMC r = (r == NRCandidate) || (r == NRMaster) in filter (isMC . getNodeRole cfg) . F.toList . configNodes $ cfg -- | Get the network parameters for the master IP address. getMasterNetworkParameters :: ConfigData -> MasterNetworkParameters getMasterNetworkParameters cfg = let cluster = configCluster cfg in MasterNetworkParameters { masterNetworkParametersUuid = clusterMasterNode cluster , masterNetworkParametersIp = clusterMasterIp cluster , masterNetworkParametersNetmask = clusterMasterNetmask cluster , masterNetworkParametersNetdev = clusterMasterNetdev cluster , masterNetworkParametersIpFamily = clusterPrimaryIpFamily cluster } -- | Get the list of online nodes. getOnlineNodes :: ConfigData -> [Node] getOnlineNodes = filter (not . nodeOffline) . F.toList . configNodes -- | Returns the default cluster link. getDefaultNicLink :: ConfigData -> String getDefaultNicLink = let ppDefault = UTF8.fromString C.ppDefault in nicpLink . (M.! ppDefault) . fromContainer . clusterNicparams . configCluster -- | Returns the default cluster hypervisor. getDefaultHypervisor :: ConfigData -> Hypervisor getDefaultHypervisor cfg = case clusterEnabledHypervisors $ configCluster cfg of -- FIXME: this case shouldn't happen (configuration broken), but -- for now we handle it here because we're not authoritative for -- the config [] -> XenPvm x:_ -> x -- | Returns instances of a given link. getInstancesIpByLink :: LinkIpMap -> String -> [String] getInstancesIpByLink linkipmap link = M.keys $ M.findWithDefault M.empty link linkipmap -- | Generic lookup function that converts from a possible abbreviated -- name to a full name. getItem :: String -> String -> M.Map String a -> ErrorResult a getItem kind name allitems = do let lresult = lookupName (M.keys allitems) name err msg = Bad $ OpPrereqError (kind ++ " name " ++ name ++ " " ++ msg) ECodeNoEnt fullname <- case lrMatchPriority lresult of PartialMatch -> Ok $ lrContent lresult ExactMatch -> Ok $ lrContent lresult MultipleMatch -> err "has multiple matches" FailMatch -> err "not found" maybe (err "not found after successfull match?!") Ok $ M.lookup fullname allitems -- | Simple lookup function, insisting on exact matches and using -- byte strings. getItem' :: String -> String -> M.Map BS.ByteString a -> ErrorResult a getItem' kind name allitems = let name' = UTF8.fromString name err = Bad $ OpPrereqError (kind ++ " uuid " ++ name ++ " not found") ECodeNoEnt in maybe err Ok $ M.lookup name' allitems -- | Looks up a node by name or uuid. getNode :: ConfigData -> String -> ErrorResult Node getNode cfg name = let nodes = fromContainer (configNodes cfg) in case getItem' "Node" name nodes of -- if not found by uuid, we need to look it up by name Ok node -> Ok node Bad _ -> let by_name = M.mapKeys (nodeName . (M.!) nodes) nodes in getItem "Node" name by_name -- | Looks up an instance by name or uuid. getInstance :: ConfigData -> String -> ErrorResult Instance getInstance cfg name = let instances = fromContainer (configInstances cfg) in case getItem' "Instance" name instances of -- if not found by uuid, we need to look it up by name Ok inst -> Ok inst Bad _ -> let by_name = M.delete "" . M.mapKeys (fromMaybe "" . instName . (M.!) instances) $ instances in getItem "Instance" name by_name -- | Looks up an instance by exact name match getInstanceByName :: ConfigData -> String -> ErrorResult Instance getInstanceByName cfg name = let instances = M.elems . fromContainer . configInstances $ cfg matching = F.find (maybe False (== name) . instName) instances in case matching of Just inst -> Ok inst Nothing -> Bad $ OpPrereqError ("Instance name " ++ name ++ " not found") ECodeNoEnt -- | Looks up a disk by uuid. getDisk :: ConfigData -> String -> ErrorResult Disk getDisk cfg name = let disks = fromContainer (configDisks cfg) in getItem' "Disk" name disks -- | Looks up a filter by uuid. getFilterRule :: ConfigData -> String -> ErrorResult FilterRule getFilterRule cfg name = let filters = fromContainer (configFilters cfg) in getItem' "Filter" name filters -- | Looks up a node group by name or uuid. getGroup :: ConfigData -> String -> ErrorResult NodeGroup getGroup cfg name = let groups = fromContainer (configNodegroups cfg) in case getItem' "NodeGroup" name groups of -- if not found by uuid, we need to look it up by name, slow Ok grp -> Ok grp Bad _ -> let by_name = M.mapKeys (groupName . (M.!) groups) groups in getItem "NodeGroup" name by_name -- | Computes a node group's node params. getGroupNdParams :: ConfigData -> NodeGroup -> FilledNDParams getGroupNdParams cfg ng = fillParams (clusterNdparams $ configCluster cfg) (groupNdparams ng) -- | Computes a node group's ipolicy. getGroupIpolicy :: ConfigData -> NodeGroup -> FilledIPolicy getGroupIpolicy cfg ng = fillParams (clusterIpolicy $ configCluster cfg) (groupIpolicy ng) -- | Computes a group\'s (merged) disk params. getGroupDiskParams :: ConfigData -> NodeGroup -> GroupDiskParams getGroupDiskParams cfg ng = GenericContainer $ fillDict (fromContainer . clusterDiskparams $ configCluster cfg) (fromContainer $ groupDiskparams ng) [] -- | Get nodes of a given node group. getGroupNodes :: ConfigData -> String -> [Node] getGroupNodes cfg gname = let all_nodes = M.elems . fromContainer . configNodes $ cfg in filter ((==gname) . nodeGroup) all_nodes -- | Get (primary, secondary) instances of a given node group. getGroupInstances :: ConfigData -> String -> ([Instance], [Instance]) getGroupInstances cfg gname = let gnodes = map uuidOf (getGroupNodes cfg gname) ginsts = map (getNodeInstances cfg) gnodes in (concatMap fst ginsts, concatMap snd ginsts) -- | Retrieves the instance hypervisor params, missing values filled with -- cluster defaults. getFilledInstHvParams :: [String] -> ConfigData -> Instance -> HvParams getFilledInstHvParams globals cfg inst = -- First get the defaults of the parent let maybeHvName = instHypervisor inst hvParamMap = fromContainer . clusterHvparams $ configCluster cfg parentHvParams = maybe M.empty fromContainer (maybeHvName >>= flip M.lookup hvParamMap) -- Then the os defaults for the given hypervisor maybeOsName = UTF8.fromString <$> instOs inst osParamMap = fromContainer . clusterOsHvp $ configCluster cfg osHvParamMap = maybe M.empty (maybe M.empty fromContainer . flip M.lookup osParamMap) maybeOsName osHvParams = maybe M.empty (maybe M.empty fromContainer . flip M.lookup osHvParamMap) maybeHvName -- Then the child childHvParams = fromContainer . instHvparams $ inst -- Helper function fillFn con val = fillDict con val $ fmap UTF8.fromString globals in GenericContainer $ fillFn (fillFn parentHvParams osHvParams) childHvParams -- | Retrieves the instance backend params, missing values filled with cluster -- defaults. getFilledInstBeParams :: ConfigData -> Instance -> ErrorResult FilledBeParams getFilledInstBeParams cfg inst = do let beParamMap = fromContainer . clusterBeparams . configCluster $ cfg parentParams <- getItem' "FilledBeParams" C.ppDefault beParamMap return $ fillParams parentParams (instBeparams inst) -- | Retrieves the instance os params, missing values filled with cluster -- defaults. This does NOT include private and secret parameters. getFilledInstOsParams :: ConfigData -> Instance -> OsParams getFilledInstOsParams cfg inst = let maybeOsLookupName = liftM (takeWhile (/= '+')) (instOs inst) osParamMap = fromContainer . clusterOsparams $ configCluster cfg childOsParams = instOsparams inst in case withMissingParam "Instance without OS" (flip (getItem' "OsParams") osParamMap) maybeOsLookupName of Ok parentOsParams -> GenericContainer $ fillDict (fromContainer parentOsParams) (fromContainer childOsParams) [] Bad _ -> childOsParams -- | Looks up an instance's primary node. getInstPrimaryNode :: ConfigData -> String -> ErrorResult Node getInstPrimaryNode cfg name = getInstanceByName cfg name >>= withMissingParam "Instance without primary node" return . instPrimaryNode >>= getNode cfg -- | Retrieves all nodes hosting a DRBD disk getDrbdDiskNodes :: ConfigData -> Disk -> [Node] getDrbdDiskNodes cfg disk = let retrieved = case diskLogicalId disk of Just (LIDDrbd8 nodeA nodeB _ _ _ _) -> justOk [getNode cfg nodeA, getNode cfg nodeB] _ -> [] in retrieved ++ concatMap (getDrbdDiskNodes cfg) (diskChildren disk) -- | Retrieves all the nodes of the instance. -- -- As instances not using DRBD can be sent as a parameter as well, -- the primary node has to be appended to the results. getInstAllNodes :: ConfigData -> String -> ErrorResult [Node] getInstAllNodes cfg name = do inst <- getInstanceByName cfg name inst_disks <- getInstDisksFromObj cfg inst let disk_nodes = concatMap (getDrbdDiskNodes cfg) inst_disks pNode <- getInstPrimaryNode cfg name return . nub $ pNode:disk_nodes -- | Get disks for a given instance. -- The instance is specified by name or uuid. getInstDisks :: ConfigData -> String -> ErrorResult [Disk] getInstDisks cfg iname = getInstance cfg iname >>= mapM (getDisk cfg) . instDisks -- | Get disks for a given instance object. getInstDisksFromObj :: ConfigData -> Instance -> ErrorResult [Disk] getInstDisksFromObj cfg = getInstDisks cfg . uuidOf -- | Collects a value for all DRBD disks collectFromDrbdDisks :: (Monoid a) => (String -> String -> Int -> Int -> Int -> Private DRBDSecret -> a) -- ^ NodeA, NodeB, Port, MinorA, MinorB, Secret -> Disk -> a collectFromDrbdDisks f = col where col (diskLogicalId &&& diskChildren -> (Just (LIDDrbd8 nA nB port mA mB secret), ch)) = f nA nB port mA mB secret <> F.foldMap col ch col d = F.foldMap col (diskChildren d) -- | Returns the DRBD secrets of a given 'Disk' getDrbdSecretsForDisk :: Disk -> [DRBDSecret] getDrbdSecretsForDisk = collectFromDrbdDisks (\_ _ _ _ _ (Private secret) -> [secret]) -- | Returns the DRBD minors of a given 'Disk' getDrbdMinorsForDisk :: Disk -> [(Int, String)] getDrbdMinorsForDisk = collectFromDrbdDisks (\nA nB _ mnA mnB _ -> [(mnA, nA), (mnB, nB)]) -- | Filters DRBD minors for a given node. getDrbdMinorsForNode :: String -> Disk -> [(Int, String)] getDrbdMinorsForNode node disk = let child_minors = concatMap (getDrbdMinorsForNode node) (diskChildren disk) this_minors = case diskLogicalId disk of Just (LIDDrbd8 nodeA nodeB _ minorA minorB _) | nodeA == node -> [(minorA, nodeB)] | nodeB == node -> [(minorB, nodeA)] _ -> [] in this_minors ++ child_minors -- | Returns the DRBD minors of a given instance getDrbdMinorsForInstance :: ConfigData -> Instance -> ErrorResult [(Int, String)] getDrbdMinorsForInstance cfg = liftM (concatMap getDrbdMinorsForDisk) . getInstDisksFromObj cfg -- | String for primary role. rolePrimary :: String rolePrimary = "primary" -- | String for secondary role. roleSecondary :: String roleSecondary = "secondary" -- | Gets the list of DRBD minors for an instance that are related to -- a given node. getInstMinorsForNode :: ConfigData -> String -- ^ The UUID of a node. -> Instance -> [(String, Int, String, String, String, String)] getInstMinorsForNode cfg node inst = let nrole = if Just node == instPrimaryNode inst then rolePrimary else roleSecondary iname = fromMaybe "" $ instName inst inst_disks = case getInstDisksFromObj cfg inst of Ok disks -> disks Bad _ -> [] -- FIXME: the disk/ build there is hack-ish; unify this in a -- separate place, or reuse the iv_name (but that is deprecated on -- the Python side) in concatMap (\(idx, dsk) -> [(node, minor, iname, "disk/" ++ show idx, nrole, peer) | (minor, peer) <- getDrbdMinorsForNode node dsk]) . zip [(0::Int)..] $ inst_disks -- | Builds link -> ip -> instname map. -- For instances without a name, we insert the uuid instead. -- -- TODO: improve this by splitting it into multiple independent functions: -- -- * abstract the \"fetch instance with filled params\" functionality -- -- * abstsract the [instance] -> [(nic, instance_name)] part -- -- * etc. buildLinkIpInstnameMap :: ConfigData -> LinkIpMap buildLinkIpInstnameMap cfg = let cluster = configCluster cfg instances = M.elems . fromContainer . configInstances $ cfg defparams = (M.!) (fromContainer $ clusterNicparams cluster) $ UTF8.fromString C.ppDefault nics = concatMap (\i -> [(fromMaybe (uuidOf i) $ instName i, nic) | nic <- instNics i]) instances in foldl' (\accum (iname, nic) -> let pparams = nicNicparams nic fparams = fillParams defparams pparams link = nicpLink fparams in case nicIp nic of Nothing -> accum Just ip -> let oldipmap = M.findWithDefault M.empty link accum newipmap = M.insert ip iname oldipmap in M.insert link newipmap accum ) M.empty nics -- | Returns a node's group, with optional failure if we can't find it -- (configuration corrupt). getGroupOfNode :: ConfigData -> Node -> Maybe NodeGroup getGroupOfNode cfg node = M.lookup (UTF8.fromString $ nodeGroup node) (fromContainer . configNodegroups $ cfg) -- | Returns a node's ndparams, filled. getNodeNdParams :: ConfigData -> Node -> Maybe FilledNDParams getNodeNdParams cfg node = do group <- getGroupOfNode cfg node let gparams = getGroupNdParams cfg group return $ fillParams gparams (nodeNdparams node) -- * Network -- | Looks up a network. If looking up by uuid fails, we look up -- by name. getNetwork :: ConfigData -> String -> ErrorResult Network getNetwork cfg name = let networks = fromContainer (configNetworks cfg) in case getItem' "Network" name networks of Ok net -> Ok net Bad _ -> let by_name = M.mapKeys (fromNonEmpty . networkName . (M.!) networks) networks in getItem "Network" name by_name -- ** MACs type MAC = String -- | Returns all MAC addresses used in the cluster. getAllMACs :: ConfigData -> [MAC] getAllMACs = F.foldMap (map nicMac . instNics) . configInstances -- ** DRBD secrets getAllDrbdSecrets :: ConfigData -> [DRBDSecret] getAllDrbdSecrets = F.foldMap getDrbdSecretsForDisk . configDisks -- ** LVs -- | A map from node UUIDs to -- -- FIXME: After adding designated types for UUIDs, -- use them to replace 'String' here. type NodeLVsMap = MM.MultiMap String LogicalVolume getInstanceLVsByNode :: ConfigData -> Instance -> ErrorResult NodeLVsMap getInstanceLVsByNode cd inst = withMissingParam "Instance without Primary Node" (\i -> return $ MM.fromList . lvsByNode i) (instPrimaryNode inst) <*> getInstDisksFromObj cd inst where lvsByNode :: String -> [Disk] -> [(String, LogicalVolume)] lvsByNode node = concatMap (lvsByNode1 node) lvsByNode1 :: String -> Disk -> [(String, LogicalVolume)] lvsByNode1 _ (diskLogicalId &&& diskChildren -> (Just (LIDDrbd8 nA nB _ _ _ _), ch)) = lvsByNode nA ch ++ lvsByNode nB ch lvsByNode1 node (diskLogicalId -> (Just (LIDPlain lv))) = [(node, lv)] lvsByNode1 node (diskChildren -> ch) = lvsByNode node ch getAllLVs :: ConfigData -> ErrorResult (S.Set LogicalVolume) getAllLVs cd = mconcat <$> mapM (liftM MM.values . getInstanceLVsByNode cd) (F.toList $ configInstances cd) -- * ND params -- | Type class denoting objects which have node parameters. class NdParamObject a where getNdParamsOf :: ConfigData -> a -> Maybe FilledNDParams instance NdParamObject Node where getNdParamsOf = getNodeNdParams instance NdParamObject NodeGroup where getNdParamsOf cfg = Just . getGroupNdParams cfg instance NdParamObject Cluster where getNdParamsOf _ = Just . clusterNdparams
yiannist/ganeti
src/Ganeti/Config.hs
bsd-2-clause
24,039
0
20
5,579
5,395
2,809
2,586
414
4
{-# LANGUAGE TemplateHaskell, DeriveFunctor #-} {-| Some common Ganeti types. This holds types common to both core work, and to htools. Types that are very core specific (e.g. configuration objects) should go in 'Ganeti.Objects', while types that are specific to htools in-memory representation should go into 'Ganeti.HTools.Types'. -} {- Copyright (C) 2012, 2013, 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 Ganeti.Types ( AllocPolicy(..) , allocPolicyFromRaw , allocPolicyToRaw , InstanceStatus(..) , instanceStatusFromRaw , instanceStatusToRaw , DiskTemplate(..) , diskTemplateToRaw , diskTemplateFromRaw , TagKind(..) , tagKindToRaw , tagKindFromRaw , NonNegative , fromNonNegative , mkNonNegative , Positive , fromPositive , mkPositive , Negative , fromNegative , mkNegative , NonEmpty , fromNonEmpty , mkNonEmpty , NonEmptyString , QueryResultCode , IPv4Address , mkIPv4Address , IPv4Network , mkIPv4Network , IPv6Address , mkIPv6Address , IPv6Network , mkIPv6Network , MigrationMode(..) , migrationModeToRaw , VerifyOptionalChecks(..) , verifyOptionalChecksToRaw , DdmSimple(..) , DdmFull(..) , ddmFullToRaw , CVErrorCode(..) , cVErrorCodeToRaw , Hypervisor(..) , hypervisorFromRaw , hypervisorToRaw , OobCommand(..) , oobCommandToRaw , OobStatus(..) , oobStatusToRaw , StorageType(..) , storageTypeToRaw , EvacMode(..) , evacModeToRaw , FileDriver(..) , fileDriverToRaw , InstCreateMode(..) , instCreateModeToRaw , RebootType(..) , rebootTypeToRaw , ExportMode(..) , exportModeToRaw , IAllocatorTestDir(..) , iAllocatorTestDirToRaw , IAllocatorMode(..) , iAllocatorModeToRaw , NICMode(..) , nICModeToRaw , JobStatus(..) , jobStatusToRaw , jobStatusFromRaw , FinalizedJobStatus(..) , finalizedJobStatusToRaw , JobId , fromJobId , makeJobId , makeJobIdS , RelativeJobId , JobIdDep(..) , JobDependency(..) , absoluteJobDependency , getJobIdFromDependency , OpSubmitPriority(..) , opSubmitPriorityToRaw , parseSubmitPriority , fmtSubmitPriority , OpStatus(..) , opStatusToRaw , opStatusFromRaw , ELogType(..) , eLogTypeToRaw , ReasonElem , ReasonTrail , StorageUnit(..) , StorageUnitRaw(..) , StorageKey , addParamsToStorageUnit , diskTemplateToStorageType , VType(..) , vTypeFromRaw , vTypeToRaw , NodeRole(..) , nodeRoleToRaw , roleDescription , DiskMode(..) , diskModeToRaw , BlockDriver(..) , blockDriverToRaw , AdminState(..) , adminStateFromRaw , adminStateToRaw , AdminStateSource(..) , adminStateSourceFromRaw , adminStateSourceToRaw , StorageField(..) , storageFieldToRaw , DiskAccessMode(..) , diskAccessModeToRaw , LocalDiskStatus(..) , localDiskStatusFromRaw , localDiskStatusToRaw , localDiskStatusName , ReplaceDisksMode(..) , replaceDisksModeToRaw , RpcTimeout(..) , rpcTimeoutFromRaw -- FIXME: no used anywhere , rpcTimeoutToRaw , HotplugTarget(..) , hotplugTargetToRaw , HotplugAction(..) , hotplugActionToRaw , Private(..) , showPrivateJSObject , HvParams , OsParams , OsParamsPrivate , TimeStampObject(..) , UuidObject(..) , ForthcomingObject(..) , SerialNoObject(..) , TagsObject(..) ) where import Control.Applicative import Control.Monad (liftM) import qualified Text.JSON as JSON import Text.JSON (JSON, readJSON, showJSON) import Data.Ratio (numerator, denominator) import qualified Data.Set as Set import System.Time (ClockTime) import qualified Ganeti.ConstantUtils as ConstantUtils import Ganeti.JSON import qualified Ganeti.THH as THH import Ganeti.Utils -- * Generic types -- | Type that holds a non-negative value. newtype NonNegative a = NonNegative { fromNonNegative :: a } deriving (Show, Eq, Ord) -- | Smart constructor for 'NonNegative'. mkNonNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (NonNegative a) mkNonNegative i | i >= 0 = return (NonNegative i) | otherwise = fail $ "Invalid value for non-negative type '" ++ show i ++ "'" instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (NonNegative a) where showJSON = JSON.showJSON . fromNonNegative readJSON v = JSON.readJSON v >>= mkNonNegative -- | Type that holds a positive value. newtype Positive a = Positive { fromPositive :: a } deriving (Show, Eq, Ord) -- | Smart constructor for 'Positive'. mkPositive :: (Monad m, Num a, Ord a, Show a) => a -> m (Positive a) mkPositive i | i > 0 = return (Positive i) | otherwise = fail $ "Invalid value for positive type '" ++ show i ++ "'" instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Positive a) where showJSON = JSON.showJSON . fromPositive readJSON v = JSON.readJSON v >>= mkPositive -- | Type that holds a negative value. newtype Negative a = Negative { fromNegative :: a } deriving (Show, Eq, Ord) -- | Smart constructor for 'Negative'. mkNegative :: (Monad m, Num a, Ord a, Show a) => a -> m (Negative a) mkNegative i | i < 0 = return (Negative i) | otherwise = fail $ "Invalid value for negative type '" ++ show i ++ "'" instance (JSON.JSON a, Num a, Ord a, Show a) => JSON.JSON (Negative a) where showJSON = JSON.showJSON . fromNegative readJSON v = JSON.readJSON v >>= mkNegative -- | Type that holds a non-null list. newtype NonEmpty a = NonEmpty { fromNonEmpty :: [a] } deriving (Show, Eq, Ord) -- | Smart constructor for 'NonEmpty'. mkNonEmpty :: (Monad m) => [a] -> m (NonEmpty a) mkNonEmpty [] = fail "Received empty value for non-empty list" mkNonEmpty xs = return (NonEmpty xs) instance (JSON.JSON a) => JSON.JSON (NonEmpty a) where showJSON = JSON.showJSON . fromNonEmpty readJSON v = JSON.readJSON v >>= mkNonEmpty -- | A simple type alias for non-empty strings. type NonEmptyString = NonEmpty Char type QueryResultCode = Int newtype IPv4Address = IPv4Address { fromIPv4Address :: String } deriving (Show, Eq, Ord) -- FIXME: this should check that 'address' is a valid ip mkIPv4Address :: Monad m => String -> m IPv4Address mkIPv4Address address = return IPv4Address { fromIPv4Address = address } instance JSON.JSON IPv4Address where showJSON = JSON.showJSON . fromIPv4Address readJSON v = JSON.readJSON v >>= mkIPv4Address newtype IPv4Network = IPv4Network { fromIPv4Network :: String } deriving (Show, Eq, Ord) -- FIXME: this should check that 'address' is a valid ip mkIPv4Network :: Monad m => String -> m IPv4Network mkIPv4Network address = return IPv4Network { fromIPv4Network = address } instance JSON.JSON IPv4Network where showJSON = JSON.showJSON . fromIPv4Network readJSON v = JSON.readJSON v >>= mkIPv4Network newtype IPv6Address = IPv6Address { fromIPv6Address :: String } deriving (Show, Eq, Ord) -- FIXME: this should check that 'address' is a valid ip mkIPv6Address :: Monad m => String -> m IPv6Address mkIPv6Address address = return IPv6Address { fromIPv6Address = address } instance JSON.JSON IPv6Address where showJSON = JSON.showJSON . fromIPv6Address readJSON v = JSON.readJSON v >>= mkIPv6Address newtype IPv6Network = IPv6Network { fromIPv6Network :: String } deriving (Show, Eq, Ord) -- FIXME: this should check that 'address' is a valid ip mkIPv6Network :: Monad m => String -> m IPv6Network mkIPv6Network address = return IPv6Network { fromIPv6Network = address } instance JSON.JSON IPv6Network where showJSON = JSON.showJSON . fromIPv6Network readJSON v = JSON.readJSON v >>= mkIPv6Network -- * Ganeti types -- | Instance disk template type. The disk template is a name for the -- constructor of the disk configuration 'DiskLogicalId' used for -- serialization, configuration values, etc. $(THH.declareLADT ''String "DiskTemplate" [ ("DTDiskless", "diskless") , ("DTFile", "file") , ("DTSharedFile", "sharedfile") , ("DTPlain", "plain") , ("DTBlock", "blockdev") , ("DTDrbd8", "drbd") , ("DTRbd", "rbd") , ("DTExt", "ext") , ("DTGluster", "gluster") ]) $(THH.makeJSONInstance ''DiskTemplate) instance THH.PyValue DiskTemplate where showValue = show . diskTemplateToRaw instance HasStringRepr DiskTemplate where fromStringRepr = diskTemplateFromRaw toStringRepr = diskTemplateToRaw -- | Data type representing what items the tag operations apply to. $(THH.declareLADT ''String "TagKind" [ ("TagKindInstance", "instance") , ("TagKindNode", "node") , ("TagKindGroup", "nodegroup") , ("TagKindCluster", "cluster") , ("TagKindNetwork", "network") ]) $(THH.makeJSONInstance ''TagKind) -- | The Group allocation policy type. -- -- Note that the order of constructors is important as the automatic -- Ord instance will order them in the order they are defined, so when -- changing this data type be careful about the interaction with the -- desired sorting order. $(THH.declareLADT ''String "AllocPolicy" [ ("AllocPreferred", "preferred") , ("AllocLastResort", "last_resort") , ("AllocUnallocable", "unallocable") ]) $(THH.makeJSONInstance ''AllocPolicy) -- | The Instance real state type. $(THH.declareLADT ''String "InstanceStatus" [ ("StatusDown", "ADMIN_down") , ("StatusOffline", "ADMIN_offline") , ("ErrorDown", "ERROR_down") , ("ErrorUp", "ERROR_up") , ("NodeDown", "ERROR_nodedown") , ("NodeOffline", "ERROR_nodeoffline") , ("Running", "running") , ("UserDown", "USER_down") , ("WrongNode", "ERROR_wrongnode") ]) $(THH.makeJSONInstance ''InstanceStatus) -- | Migration mode. $(THH.declareLADT ''String "MigrationMode" [ ("MigrationLive", "live") , ("MigrationNonLive", "non-live") ]) $(THH.makeJSONInstance ''MigrationMode) -- | Verify optional checks. $(THH.declareLADT ''String "VerifyOptionalChecks" [ ("VerifyNPlusOneMem", "nplusone_mem") ]) $(THH.makeJSONInstance ''VerifyOptionalChecks) -- | Cluster verify error codes. $(THH.declareLADT ''String "CVErrorCode" [ ("CvECLUSTERCFG", "ECLUSTERCFG") , ("CvECLUSTERCERT", "ECLUSTERCERT") , ("CvECLUSTERCLIENTCERT", "ECLUSTERCLIENTCERT") , ("CvECLUSTERFILECHECK", "ECLUSTERFILECHECK") , ("CvECLUSTERDANGLINGNODES", "ECLUSTERDANGLINGNODES") , ("CvECLUSTERDANGLINGINST", "ECLUSTERDANGLINGINST") , ("CvEINSTANCEBADNODE", "EINSTANCEBADNODE") , ("CvEINSTANCEDOWN", "EINSTANCEDOWN") , ("CvEINSTANCELAYOUT", "EINSTANCELAYOUT") , ("CvEINSTANCEMISSINGDISK", "EINSTANCEMISSINGDISK") , ("CvEINSTANCEFAULTYDISK", "EINSTANCEFAULTYDISK") , ("CvEINSTANCEWRONGNODE", "EINSTANCEWRONGNODE") , ("CvEINSTANCESPLITGROUPS", "EINSTANCESPLITGROUPS") , ("CvEINSTANCEPOLICY", "EINSTANCEPOLICY") , ("CvEINSTANCEUNSUITABLENODE", "EINSTANCEUNSUITABLENODE") , ("CvEINSTANCEMISSINGCFGPARAMETER", "EINSTANCEMISSINGCFGPARAMETER") , ("CvENODEDRBD", "ENODEDRBD") , ("CvENODEDRBDVERSION", "ENODEDRBDVERSION") , ("CvENODEDRBDHELPER", "ENODEDRBDHELPER") , ("CvENODEFILECHECK", "ENODEFILECHECK") , ("CvENODEHOOKS", "ENODEHOOKS") , ("CvENODEHV", "ENODEHV") , ("CvENODELVM", "ENODELVM") , ("CvENODEN1", "ENODEN1") , ("CvENODENET", "ENODENET") , ("CvENODEOS", "ENODEOS") , ("CvENODEORPHANINSTANCE", "ENODEORPHANINSTANCE") , ("CvENODEORPHANLV", "ENODEORPHANLV") , ("CvENODERPC", "ENODERPC") , ("CvENODESSH", "ENODESSH") , ("CvENODEVERSION", "ENODEVERSION") , ("CvENODESETUP", "ENODESETUP") , ("CvENODETIME", "ENODETIME") , ("CvENODEOOBPATH", "ENODEOOBPATH") , ("CvENODEUSERSCRIPTS", "ENODEUSERSCRIPTS") , ("CvENODEFILESTORAGEPATHS", "ENODEFILESTORAGEPATHS") , ("CvENODEFILESTORAGEPATHUNUSABLE", "ENODEFILESTORAGEPATHUNUSABLE") , ("CvENODESHAREDFILESTORAGEPATHUNUSABLE", "ENODESHAREDFILESTORAGEPATHUNUSABLE") , ("CvENODEGLUSTERSTORAGEPATHUNUSABLE", "ENODEGLUSTERSTORAGEPATHUNUSABLE") , ("CvEGROUPDIFFERENTPVSIZE", "EGROUPDIFFERENTPVSIZE") ]) $(THH.makeJSONInstance ''CVErrorCode) -- | Dynamic device modification, just add/remove version. $(THH.declareLADT ''String "DdmSimple" [ ("DdmSimpleAdd", "add") , ("DdmSimpleAttach", "attach") , ("DdmSimpleRemove", "remove") , ("DdmSimpleDetach", "detach") ]) $(THH.makeJSONInstance ''DdmSimple) -- | Dynamic device modification, all operations version. -- -- TODO: DDM_SWAP, DDM_MOVE? $(THH.declareLADT ''String "DdmFull" [ ("DdmFullAdd", "add") , ("DdmFullAttach", "attach") , ("DdmFullRemove", "remove") , ("DdmFullDetach", "detach") , ("DdmFullModify", "modify") ]) $(THH.makeJSONInstance ''DdmFull) -- | Hypervisor type definitions. $(THH.declareLADT ''String "Hypervisor" [ ("Kvm", "kvm") , ("XenPvm", "xen-pvm") , ("Chroot", "chroot") , ("XenHvm", "xen-hvm") , ("Lxc", "lxc") , ("Fake", "fake") ]) $(THH.makeJSONInstance ''Hypervisor) instance THH.PyValue Hypervisor where showValue = show . hypervisorToRaw instance HasStringRepr Hypervisor where fromStringRepr = hypervisorFromRaw toStringRepr = hypervisorToRaw -- | Oob command type. $(THH.declareLADT ''String "OobCommand" [ ("OobHealth", "health") , ("OobPowerCycle", "power-cycle") , ("OobPowerOff", "power-off") , ("OobPowerOn", "power-on") , ("OobPowerStatus", "power-status") ]) $(THH.makeJSONInstance ''OobCommand) -- | Oob command status $(THH.declareLADT ''String "OobStatus" [ ("OobStatusCritical", "CRITICAL") , ("OobStatusOk", "OK") , ("OobStatusUnknown", "UNKNOWN") , ("OobStatusWarning", "WARNING") ]) $(THH.makeJSONInstance ''OobStatus) -- | Storage type. $(THH.declareLADT ''String "StorageType" [ ("StorageFile", "file") , ("StorageSharedFile", "sharedfile") , ("StorageGluster", "gluster") , ("StorageLvmPv", "lvm-pv") , ("StorageLvmVg", "lvm-vg") , ("StorageDiskless", "diskless") , ("StorageBlock", "blockdev") , ("StorageRados", "rados") , ("StorageExt", "ext") ]) $(THH.makeJSONInstance ''StorageType) -- | Storage keys are identifiers for storage units. Their content varies -- depending on the storage type, for example a storage key for LVM storage -- is the volume group name. type StorageKey = String -- | Storage parameters type SPExclusiveStorage = Bool -- | Storage units without storage-type-specific parameters data StorageUnitRaw = SURaw StorageType StorageKey -- | Full storage unit with storage-type-specific parameters data StorageUnit = SUFile StorageKey | SUSharedFile StorageKey | SUGluster StorageKey | SULvmPv StorageKey SPExclusiveStorage | SULvmVg StorageKey SPExclusiveStorage | SUDiskless StorageKey | SUBlock StorageKey | SURados StorageKey | SUExt StorageKey deriving (Eq) instance Show StorageUnit where show (SUFile key) = showSUSimple StorageFile key show (SUSharedFile key) = showSUSimple StorageSharedFile key show (SUGluster key) = showSUSimple StorageGluster key show (SULvmPv key es) = showSULvm StorageLvmPv key es show (SULvmVg key es) = showSULvm StorageLvmVg key es show (SUDiskless key) = showSUSimple StorageDiskless key show (SUBlock key) = showSUSimple StorageBlock key show (SURados key) = showSUSimple StorageRados key show (SUExt key) = showSUSimple StorageExt key instance JSON StorageUnit where showJSON (SUFile key) = showJSON (StorageFile, key, []::[String]) showJSON (SUSharedFile key) = showJSON (StorageSharedFile, key, []::[String]) showJSON (SUGluster key) = showJSON (StorageGluster, key, []::[String]) showJSON (SULvmPv key es) = showJSON (StorageLvmPv, key, [es]) showJSON (SULvmVg key es) = showJSON (StorageLvmVg, key, [es]) showJSON (SUDiskless key) = showJSON (StorageDiskless, key, []::[String]) showJSON (SUBlock key) = showJSON (StorageBlock, key, []::[String]) showJSON (SURados key) = showJSON (StorageRados, key, []::[String]) showJSON (SUExt key) = showJSON (StorageExt, key, []::[String]) -- FIXME: add readJSON implementation readJSON = fail "Not implemented" -- | Composes a string representation of storage types without -- storage parameters showSUSimple :: StorageType -> StorageKey -> String showSUSimple st sk = show (storageTypeToRaw st, sk, []::[String]) -- | Composes a string representation of the LVM storage types showSULvm :: StorageType -> StorageKey -> SPExclusiveStorage -> String showSULvm st sk es = show (storageTypeToRaw st, sk, [es]) -- | Mapping from disk templates to storage types. diskTemplateToStorageType :: DiskTemplate -> StorageType diskTemplateToStorageType DTExt = StorageExt diskTemplateToStorageType DTFile = StorageFile diskTemplateToStorageType DTSharedFile = StorageSharedFile diskTemplateToStorageType DTDrbd8 = StorageLvmVg diskTemplateToStorageType DTPlain = StorageLvmVg diskTemplateToStorageType DTRbd = StorageRados diskTemplateToStorageType DTDiskless = StorageDiskless diskTemplateToStorageType DTBlock = StorageBlock diskTemplateToStorageType DTGluster = StorageGluster -- | Equips a raw storage unit with its parameters addParamsToStorageUnit :: SPExclusiveStorage -> StorageUnitRaw -> StorageUnit addParamsToStorageUnit _ (SURaw StorageBlock key) = SUBlock key addParamsToStorageUnit _ (SURaw StorageDiskless key) = SUDiskless key addParamsToStorageUnit _ (SURaw StorageExt key) = SUExt key addParamsToStorageUnit _ (SURaw StorageFile key) = SUFile key addParamsToStorageUnit _ (SURaw StorageSharedFile key) = SUSharedFile key addParamsToStorageUnit _ (SURaw StorageGluster key) = SUGluster key addParamsToStorageUnit es (SURaw StorageLvmPv key) = SULvmPv key es addParamsToStorageUnit es (SURaw StorageLvmVg key) = SULvmVg key es addParamsToStorageUnit _ (SURaw StorageRados key) = SURados key -- | Node evac modes. -- -- This is part of the 'IAllocator' interface and it is used, for -- example, in 'Ganeti.HTools.Loader.RqType'. However, it must reside -- in this module, and not in 'Ganeti.HTools.Types', because it is -- also used by 'Ganeti.Constants'. $(THH.declareLADT ''String "EvacMode" [ ("ChangePrimary", "primary-only") , ("ChangeSecondary", "secondary-only") , ("ChangeAll", "all") ]) $(THH.makeJSONInstance ''EvacMode) -- | The file driver type. $(THH.declareLADT ''String "FileDriver" [ ("FileLoop", "loop") , ("FileBlktap", "blktap") , ("FileBlktap2", "blktap2") ]) $(THH.makeJSONInstance ''FileDriver) -- | The instance create mode. $(THH.declareLADT ''String "InstCreateMode" [ ("InstCreate", "create") , ("InstImport", "import") , ("InstRemoteImport", "remote-import") ]) $(THH.makeJSONInstance ''InstCreateMode) -- | Reboot type. $(THH.declareLADT ''String "RebootType" [ ("RebootSoft", "soft") , ("RebootHard", "hard") , ("RebootFull", "full") ]) $(THH.makeJSONInstance ''RebootType) -- | Export modes. $(THH.declareLADT ''String "ExportMode" [ ("ExportModeLocal", "local") , ("ExportModeRemote", "remote") ]) $(THH.makeJSONInstance ''ExportMode) -- | IAllocator run types (OpTestIAllocator). $(THH.declareLADT ''String "IAllocatorTestDir" [ ("IAllocatorDirIn", "in") , ("IAllocatorDirOut", "out") ]) $(THH.makeJSONInstance ''IAllocatorTestDir) -- | IAllocator mode. FIXME: use this in "HTools.Backend.IAlloc". $(THH.declareLADT ''String "IAllocatorMode" [ ("IAllocatorAlloc", "allocate") , ("IAllocatorMultiAlloc", "multi-allocate") , ("IAllocatorReloc", "relocate") , ("IAllocatorNodeEvac", "node-evacuate") , ("IAllocatorChangeGroup", "change-group") ]) $(THH.makeJSONInstance ''IAllocatorMode) -- | Network mode. $(THH.declareLADT ''String "NICMode" [ ("NMBridged", "bridged") , ("NMRouted", "routed") , ("NMOvs", "openvswitch") , ("NMPool", "pool") ]) $(THH.makeJSONInstance ''NICMode) -- | The JobStatus data type. Note that this is ordered especially -- such that greater\/lesser comparison on values of this type makes -- sense. $(THH.declareLADT ''String "JobStatus" [ ("JOB_STATUS_QUEUED", "queued") , ("JOB_STATUS_WAITING", "waiting") , ("JOB_STATUS_CANCELING", "canceling") , ("JOB_STATUS_RUNNING", "running") , ("JOB_STATUS_CANCELED", "canceled") , ("JOB_STATUS_SUCCESS", "success") , ("JOB_STATUS_ERROR", "error") ]) $(THH.makeJSONInstance ''JobStatus) -- | Finalized job status. $(THH.declareLADT ''String "FinalizedJobStatus" [ ("JobStatusCanceled", "canceled") , ("JobStatusSuccessful", "success") , ("JobStatusFailed", "error") ]) $(THH.makeJSONInstance ''FinalizedJobStatus) -- | The Ganeti job type. newtype JobId = JobId { fromJobId :: Int } deriving (Show, Eq, Ord) -- | Builds a job ID. makeJobId :: (Monad m) => Int -> m JobId makeJobId i | i >= 0 = return $ JobId i | otherwise = fail $ "Invalid value for job ID ' " ++ show i ++ "'" -- | Builds a job ID from a string. makeJobIdS :: (Monad m) => String -> m JobId makeJobIdS s = tryRead "parsing job id" s >>= makeJobId -- | Parses a job ID. parseJobId :: (Monad m) => JSON.JSValue -> m JobId parseJobId (JSON.JSString x) = makeJobIdS $ JSON.fromJSString x parseJobId (JSON.JSRational _ x) = if denominator x /= 1 then fail $ "Got fractional job ID from master daemon?! Value:" ++ show x -- FIXME: potential integer overflow here on 32-bit platforms else makeJobId . fromIntegral . numerator $ x parseJobId x = fail $ "Wrong type/value for job id: " ++ show x instance JSON.JSON JobId where showJSON = JSON.showJSON . fromJobId readJSON = parseJobId -- | Relative job ID type alias. type RelativeJobId = Negative Int -- | Job ID dependency. data JobIdDep = JobDepRelative RelativeJobId | JobDepAbsolute JobId deriving (Show, Eq, Ord) instance JSON.JSON JobIdDep where showJSON (JobDepRelative i) = showJSON i showJSON (JobDepAbsolute i) = showJSON i readJSON v = case JSON.readJSON v::JSON.Result (Negative Int) of -- first try relative dependency, usually most common JSON.Ok r -> return $ JobDepRelative r JSON.Error _ -> liftM JobDepAbsolute (parseJobId v) -- | From job ID dependency and job ID, compute the absolute dependency. absoluteJobIdDep :: (Monad m) => JobIdDep -> JobId -> m JobIdDep absoluteJobIdDep (JobDepAbsolute jid) _ = return $ JobDepAbsolute jid absoluteJobIdDep (JobDepRelative rjid) jid = liftM JobDepAbsolute . makeJobId $ fromJobId jid + fromNegative rjid -- | Job Dependency type. data JobDependency = JobDependency JobIdDep [FinalizedJobStatus] deriving (Show, Eq, Ord) instance JSON JobDependency where showJSON (JobDependency dep status) = showJSON (dep, status) readJSON = liftM (uncurry JobDependency) . readJSON -- | From job dependency and job id compute an absolute job dependency. absoluteJobDependency :: (Monad m) => JobDependency -> JobId -> m JobDependency absoluteJobDependency (JobDependency jdep fstats) jid = liftM (flip JobDependency fstats) $ absoluteJobIdDep jdep jid -- | From a job dependency get the absolute job id it depends on, -- if given absolutely. getJobIdFromDependency :: JobDependency -> [JobId] getJobIdFromDependency (JobDependency (JobDepAbsolute jid) _) = [jid] getJobIdFromDependency _ = [] -- | Valid opcode priorities for submit. $(THH.declareIADT "OpSubmitPriority" [ ("OpPrioLow", 'ConstantUtils.priorityLow) , ("OpPrioNormal", 'ConstantUtils.priorityNormal) , ("OpPrioHigh", 'ConstantUtils.priorityHigh) ]) $(THH.makeJSONInstance ''OpSubmitPriority) -- | Parse submit priorities from a string. parseSubmitPriority :: (Monad m) => String -> m OpSubmitPriority parseSubmitPriority "low" = return OpPrioLow parseSubmitPriority "normal" = return OpPrioNormal parseSubmitPriority "high" = return OpPrioHigh parseSubmitPriority str = fail $ "Unknown priority '" ++ str ++ "'" -- | Format a submit priority as string. fmtSubmitPriority :: OpSubmitPriority -> String fmtSubmitPriority OpPrioLow = "low" fmtSubmitPriority OpPrioNormal = "normal" fmtSubmitPriority OpPrioHigh = "high" -- | Our ADT for the OpCode status at runtime (while in a job). $(THH.declareLADT ''String "OpStatus" [ ("OP_STATUS_QUEUED", "queued") , ("OP_STATUS_WAITING", "waiting") , ("OP_STATUS_CANCELING", "canceling") , ("OP_STATUS_RUNNING", "running") , ("OP_STATUS_CANCELED", "canceled") , ("OP_STATUS_SUCCESS", "success") , ("OP_STATUS_ERROR", "error") ]) $(THH.makeJSONInstance ''OpStatus) -- | Type for the job message type. $(THH.declareLADT ''String "ELogType" [ ("ELogMessage", "message") , ("ELogRemoteImport", "remote-import") , ("ELogJqueueTest", "jqueue-test") , ("ELogDelayTest", "delay-test") ]) $(THH.makeJSONInstance ''ELogType) -- | Type of one element of a reason trail, of form -- @(source, reason, timestamp)@. type ReasonElem = (String, String, Integer) -- | Type representing a reason trail. type ReasonTrail = [ReasonElem] -- | The VTYPES, a mini-type system in Python. $(THH.declareLADT ''String "VType" [ ("VTypeString", "string") , ("VTypeMaybeString", "maybe-string") , ("VTypeBool", "bool") , ("VTypeSize", "size") , ("VTypeInt", "int") , ("VTypeFloat", "float") ]) $(THH.makeJSONInstance ''VType) instance THH.PyValue VType where showValue = THH.showValue . vTypeToRaw -- * Node role type $(THH.declareLADT ''String "NodeRole" [ ("NROffline", "O") , ("NRDrained", "D") , ("NRRegular", "R") , ("NRCandidate", "C") , ("NRMaster", "M") ]) $(THH.makeJSONInstance ''NodeRole) -- | The description of the node role. roleDescription :: NodeRole -> String roleDescription NROffline = "offline" roleDescription NRDrained = "drained" roleDescription NRRegular = "regular" roleDescription NRCandidate = "master candidate" roleDescription NRMaster = "master" -- * Disk types $(THH.declareLADT ''String "DiskMode" [ ("DiskRdOnly", "ro") , ("DiskRdWr", "rw") ]) $(THH.makeJSONInstance ''DiskMode) -- | The persistent block driver type. Currently only one type is allowed. $(THH.declareLADT ''String "BlockDriver" [ ("BlockDrvManual", "manual") ]) $(THH.makeJSONInstance ''BlockDriver) -- * Instance types $(THH.declareLADT ''String "AdminState" [ ("AdminOffline", "offline") , ("AdminDown", "down") , ("AdminUp", "up") ]) $(THH.makeJSONInstance ''AdminState) $(THH.declareLADT ''String "AdminStateSource" [ ("AdminSource", "admin") , ("UserSource", "user") ]) $(THH.makeJSONInstance ''AdminStateSource) instance THH.PyValue AdminStateSource where showValue = THH.showValue . adminStateSourceToRaw -- * Storage field type $(THH.declareLADT ''String "StorageField" [ ( "SFUsed", "used") , ( "SFName", "name") , ( "SFAllocatable", "allocatable") , ( "SFFree", "free") , ( "SFSize", "size") ]) $(THH.makeJSONInstance ''StorageField) -- * Disk access protocol $(THH.declareLADT ''String "DiskAccessMode" [ ( "DiskUserspace", "userspace") , ( "DiskKernelspace", "kernelspace") ]) $(THH.makeJSONInstance ''DiskAccessMode) -- | Local disk status -- -- Python code depends on: -- DiskStatusOk < DiskStatusUnknown < DiskStatusFaulty $(THH.declareILADT "LocalDiskStatus" [ ("DiskStatusOk", 1) , ("DiskStatusSync", 2) , ("DiskStatusUnknown", 3) , ("DiskStatusFaulty", 4) ]) localDiskStatusName :: LocalDiskStatus -> String localDiskStatusName DiskStatusFaulty = "faulty" localDiskStatusName DiskStatusOk = "ok" localDiskStatusName DiskStatusSync = "syncing" localDiskStatusName DiskStatusUnknown = "unknown" -- | Replace disks type. $(THH.declareLADT ''String "ReplaceDisksMode" [ -- Replace disks on primary ("ReplaceOnPrimary", "replace_on_primary") -- Replace disks on secondary , ("ReplaceOnSecondary", "replace_on_secondary") -- Change secondary node , ("ReplaceNewSecondary", "replace_new_secondary") , ("ReplaceAuto", "replace_auto") ]) $(THH.makeJSONInstance ''ReplaceDisksMode) -- | Basic timeouts for RPC calls. $(THH.declareILADT "RpcTimeout" [ ("Urgent", 60) -- 1 minute , ("Fast", 5 * 60) -- 5 minutes , ("Normal", 15 * 60) -- 15 minutes , ("Slow", 3600) -- 1 hour , ("FourHours", 4 * 3600) -- 4 hours , ("OneDay", 86400) -- 1 day ]) -- | Hotplug action. $(THH.declareLADT ''String "HotplugAction" [ ("HAAdd", "hotadd") , ("HARemove", "hotremove") , ("HAMod", "hotmod") ]) $(THH.makeJSONInstance ''HotplugAction) -- | Hotplug Device Target. $(THH.declareLADT ''String "HotplugTarget" [ ("HTDisk", "hotdisk") , ("HTNic", "hotnic") ]) $(THH.makeJSONInstance ''HotplugTarget) -- * Private type and instances -- | A container for values that should be happy to be manipulated yet -- refuses to be shown unless explicitly requested. newtype Private a = Private { getPrivate :: a } deriving (Eq, Ord, Functor) instance (Show a, JSON.JSON a) => JSON.JSON (Private a) where readJSON = liftM Private . JSON.readJSON showJSON (Private x) = JSON.showJSON x -- | "Show" the value of the field. -- -- It would be better not to implement this at all. -- Alas, Show OpCode requires Show Private. instance Show a => Show (Private a) where show _ = "<redacted>" instance THH.PyValue a => THH.PyValue (Private a) where showValue (Private x) = "Private(" ++ THH.showValue x ++ ")" instance Applicative Private where pure = Private Private f <*> Private x = Private (f x) instance Monad Private where (Private x) >>= f = f x return = Private showPrivateJSObject :: (JSON.JSON a) => [(String, a)] -> JSON.JSObject (Private JSON.JSValue) showPrivateJSObject value = JSON.toJSObject $ map f value where f (k, v) = (k, Private $ JSON.showJSON v) -- | The hypervisor parameter type. This is currently a simple map, -- without type checking on key/value pairs. type HvParams = Container JSON.JSValue -- | The OS parameters type. This is, and will remain, a string -- container, since the keys are dynamically declared by the OSes, and -- the values are always strings. type OsParams = Container String type OsParamsPrivate = Container (Private String) -- | Class of objects that have timestamps. class TimeStampObject a where cTimeOf :: a -> ClockTime mTimeOf :: a -> ClockTime -- | Class of objects that have an UUID. class UuidObject a where uuidOf :: a -> String -- | Class of objects that can be forthcoming. class ForthcomingObject a where isForthcoming :: a -> Bool -- | Class of object that have a serial number. class SerialNoObject a where serialOf :: a -> Int -- | Class of objects that have tags. class TagsObject a where tagsOf :: a -> Set.Set String
apyrgio/ganeti
src/Ganeti/Types.hs
bsd-2-clause
32,624
0
11
6,399
7,516
4,238
3,278
668
2
{-# LANGUAGE FlexibleContexts, RankNTypes #-} module Cloud.AWS.EC2.Instance ( describeInstances , runInstances , defaultRunInstancesRequest , terminateInstances , startInstances , stopInstances , rebootInstances , getConsoleOutput , getPasswordData , describeInstanceStatus , describeInstanceAttribute , resetInstanceAttribute , modifyInstanceAttribute , monitorInstances , unmonitorInstances , describeSpotInstanceRequests , requestSpotInstances , defaultRequestSpotInstancesParam , cancelSpotInstanceRequests ) where import Data.Text (Text) import Data.Conduit import Control.Applicative import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl) import Data.Maybe (fromMaybe, fromJust) import qualified Data.Map as Map import Control.Monad import Cloud.AWS.Lib.Parser.Unordered (XmlElement, (.<), elementM, element, ElementPath) import Cloud.AWS.EC2.Internal import Cloud.AWS.EC2.Types import Cloud.AWS.EC2.Params import Cloud.AWS.EC2.Query import Cloud.AWS.Lib.FromText (fromText) import Cloud.AWS.Lib.ToText (toText) ------------------------------------------------------------ -- DescribeInstances ------------------------------------------------------------ describeInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> [Filter] -- ^ Filters -> EC2 m (ResumableSource m Reservation) describeInstances instances filters = do ec2QuerySource "DescribeInstances" params path $ itemConduit reservationConv where path = itemsPath "reservationSet" params = [ "InstanceId" |.#= instances , filtersParam filters ] reservationConv :: (MonadThrow m, Applicative m) => XmlElement -> m Reservation reservationConv xml = Reservation <$> xml .< "reservationId" <*> xml .< "ownerId" <*> groupSetConv xml <*> instanceSetConv xml <*> xml .< "requesterId" instanceSetConv :: (MonadThrow m, Applicative m) => XmlElement -> m [Instance] instanceSetConv = itemsSet "instancesSet" conv where placementConv e = Placement <$> e .< "availabilityZone" <*> e .< "groupName" <*> e .< "tenancy" profileConv e = IamInstanceProfile <$> e .< "arn" <*> e .< "id" conv e = Instance <$> e .< "instanceId" <*> e .< "imageId" <*> instanceStateConv "instanceState" e <*> e .< "privateDnsName" <*> e .< "dnsName" <*> e .< "reason" <*> e .< "keyName" <*> e .< "amiLaunchIndex" <*> productCodeConv e <*> e .< "instanceType" <*> e .< "launchTime" <*> element "placement" placementConv e <*> e .< "kernelId" <*> e .< "ramdiskId" <*> e .< "platform" <*> element "monitoring" (.< "state") e <*> e .< "subnetId" <*> e .< "vpcId" <*> e .< "privateIpAddress" <*> e .< "ipAddress" <*> e .< "sourceDestCheck" <*> groupSetConv e <*> stateReasonConv e <*> e .< "architecture" <*> e .< "rootDeviceType" <*> e .< "rootDeviceName" <*> instanceBlockDeviceMappingsConv e <*> e .< "instanceLifecycle" <*> e .< "spotInstanceRequestId" <*> e .< "virtualizationType" <*> e .< "clientToken" <*> resourceTagConv e <*> e .< "hypervisor" <*> networkInterfaceConv e <*> elementM "iamInstanceProfile" profileConv e <*> e .< "ebsOptimized" instanceBlockDeviceMappingsConv :: (MonadThrow m, Applicative m) => XmlElement -> m [InstanceBlockDeviceMapping] instanceBlockDeviceMappingsConv = itemsSet "blockDeviceMapping" conv where ebsConv e = EbsInstanceBlockDevice <$> e .< "volumeId" <*> e .< "status" <*> e .< "attachTime" <*> e .< "deleteOnTermination" conv e = InstanceBlockDeviceMapping <$> e .< "deviceName" <*> element "ebs" ebsConv e instanceStateCodes :: [(Int, InstanceState)] instanceStateCodes = [ ( 0, InstanceStatePending) , (16, InstanceStateRunning) , (32, InstanceStateShuttingDown) , (48, InstanceStateTerminated) , (64, InstanceStateStopping) , (80, InstanceStateStopped) ] codeToState :: Int -> Text -> InstanceState codeToState code _name = fromMaybe (InstanceStateUnknown code) (lookup code instanceStateCodes) instanceStateConv :: (MonadThrow m, Applicative m) => Text -> XmlElement -> m InstanceState instanceStateConv label = element label conv where conv e = codeToState <$> e .< "code" <*> e .< "name" networkInterfaceConv :: (MonadThrow m, Applicative m) => XmlElement -> m [InstanceNetworkInterface] networkInterfaceConv = itemsSet "networkInterfaceSet" conv where attachmentConv e = InstanceNetworkInterfaceAttachment <$> e .< "attachmentId" <*> e .< "deviceIndex" <*> e .< "status" <*> e .< "attachTime" <*> e .< "deleteOnTermination" ipConv e = InstancePrivateIpAddress <$> e .< "privateIpAddress" <*> e .< "privateDnsName" <*> e .< "primary" <*> instanceNetworkInterfaceAssociationConv e conv e = InstanceNetworkInterface <$> e .< "networkInterfaceId" <*> e .< "subnetId" <*> e .< "vpcId" <*> e .< "description" <*> e .< "ownerId" <*> e .< "status" <*> e .< "macAddress" <*> e .< "privateIpAddress" <*> e .< "privateDnsName" <*> e .< "sourceDestCheck" <*> groupSetConv e <*> elementM "attachment" attachmentConv e <*> instanceNetworkInterfaceAssociationConv e <*> itemsSet "privateIpAddressesSet" ipConv e instanceNetworkInterfaceAssociationConv :: (MonadThrow m, Applicative m) => XmlElement -> m (Maybe InstanceNetworkInterfaceAssociation) instanceNetworkInterfaceAssociationConv = elementM "association" conv where conv e = InstanceNetworkInterfaceAssociation <$> e .< "publicIp" <*> e .< "publicDnsName" <*> e .< "ipOwnerId" ------------------------------------------------------------ -- DescribeInstanceStatus ------------------------------------------------------------ -- | raise 'ResponseParserException'('NextToken' token) describeInstanceStatus :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> Bool -- ^ is all instance? 'False': running instance only. -> [Filter] -- ^ Filters -> Maybe Text -- ^ next token -> EC2 m (ResumableSource m InstanceStatus) describeInstanceStatus instanceIds isAll filters token = ec2QuerySource' "DescribeInstanceStatus" params token path $ itemConduit instanceStatusConv where path = itemsPath "instanceStatusSet" params = [ "InstanceId" |.#= instanceIds , "IncludeAllInstances" |= isAll , filtersParam filters ] instanceStatusConv :: (MonadThrow m, Applicative m) => XmlElement -> m InstanceStatus instanceStatusConv = conv where conv e = InstanceStatus <$> e .< "instanceId" <*> e .< "availabilityZone" <*> itemsSet "eventsSet" eventConv e <*> instanceStateConv "instanceState" e <*> instanceStatusTypeConv "systemStatus" e <*> instanceStatusTypeConv "instanceStatus" e eventConv e = InstanceStatusEvent <$> e .< "code" <*> e .< "description" <*> e .< "notBefore" <*> e .< "notAfter" instanceStatusTypeConv :: (MonadThrow m, Applicative m) => Text -> XmlElement -> m InstanceStatusType instanceStatusTypeConv name = element name conv where detailConv e = InstanceStatusDetail <$> e .< "name" <*> e .< "status" <*> e .< "impairedSince" conv e = InstanceStatusType <$> e .< "status" <*> itemsSet "details" detailConv e ------------------------------------------------------------ -- StartInstances ------------------------------------------------------------ startInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m (ResumableSource m InstanceStateChange) startInstances instanceIds = ec2QuerySource "StartInstances" params instanceStateChangePath instanceStateChangeSet where params = ["InstanceId" |.#= instanceIds] instanceStateChangePath :: ElementPath instanceStateChangePath = itemsPath "instancesSet" instanceStateChangeSet :: (MonadResource m, MonadBaseControl IO m) => Conduit XmlElement m InstanceStateChange instanceStateChangeSet = itemConduit conv where conv e = InstanceStateChange <$> e .< "instanceId" <*> instanceStateConv "currentState" e <*> instanceStateConv "previousState" e ------------------------------------------------------------ -- StopInstances ------------------------------------------------------------ stopInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> Bool -- ^ Force -> EC2 m (ResumableSource m InstanceStateChange) stopInstances instanceIds force = ec2QuerySource "StopInstances" params instanceStateChangePath instanceStateChangeSet where params = [ "InstanceId" |.#= instanceIds , "Force" |= force] ------------------------------------------------------------ -- RebootInstances ------------------------------------------------------------ rebootInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m Bool rebootInstances instanceIds = ec2Query "RebootInstances" params (.< "return") where params = ["InstanceId" |.#= instanceIds] ------------------------------------------------------------ -- TerminateInstances ------------------------------------------------------------ terminateInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m (ResumableSource m InstanceStateChange) terminateInstances instanceIds = ec2QuerySource "TerminateInstances" params instanceStateChangePath instanceStateChangeSet where params = ["InstanceId" |.#= instanceIds] ------------------------------------------------------------ -- RunInstances ------------------------------------------------------------ -- | 'RunInstancesParam' is genereted with 'defaultRunInstancesParam' runInstances :: (MonadResource m, MonadBaseControl IO m) => RunInstancesRequest -> EC2 m Reservation runInstances param = ec2Query "RunInstances" params $ reservationConv where params = [ "ImageId" |= runInstancesRequestImageId param , "MinCount" |= runInstancesRequestMinCount param , "MaxCount" |= runInstancesRequestMaxCount param , "KeyName" |=? runInstancesRequestKeyName param , "SecurityGroupId" |.#= runInstancesRequestSecurityGroupIds param , "SecurityGroup" |.#= runInstancesRequestSecurityGroups param , "UserData" |=? runInstancesRequestUserData param , "InstanceType" |=? runInstancesRequestInstanceType param , "Placement" |. [ "AvailabilityZone" |=? runInstancesRequestAvailabilityZone param , "GroupName" |=? runInstancesRequestPlacementGroup param , "Tenancy" |=? runInstancesRequestTenancy param ] , "KernelId" |=? runInstancesRequestKernelId param , "RamdiskId" |=? runInstancesRequestRamdiskId param , blockDeviceMappingsParam $ runInstancesRequestBlockDeviceMappings param , "Monitoring" |.+ "Enabled" |=? runInstancesRequestMonitoringEnabled param , "SubnetId" |=? runInstancesRequestSubnetId param , "DisableApiTermination" |=? runInstancesRequestDisableApiTermination param , "InstanceInitiatedShutdownBehavior" |=? runInstancesRequestShutdownBehavior param , "PrivateIpAddress" |=? runInstancesRequestPrivateIpAddress param , "ClientToken" |=? runInstancesRequestClientToken param , "NetworkInterface" |.#. map networkInterfaceParams (runInstancesRequestNetworkInterfaces param) , "IamInstanceProfile" |.? iamInstanceProfileParams <$> runInstancesRequestIamInstanceProfile param , "EbsOptimized" |=? runInstancesRequestEbsOptimized param ] iamInstanceProfileParams iam = [ "Arn" |= iamInstanceProfileArn iam , "Name" |= iamInstanceProfileId iam ] -- | RunInstances parameter utility defaultRunInstancesRequest :: Text -- ^ ImageId -> Int -- ^ MinCount -> Int -- ^ MaxCount -> RunInstancesRequest defaultRunInstancesRequest iid minCount maxCount = RunInstancesRequest iid minCount maxCount Nothing [] [] Nothing Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing Nothing Nothing Nothing Nothing Nothing [] Nothing Nothing networkInterfaceParams :: NetworkInterfaceParam -> [QueryParam] networkInterfaceParams (NetworkInterfaceParamCreate di si d pia pias sgi dot) = [ "DeviceIndex" |= di , "SubnetId" |= si , "Description" |= d , "PrivateIpAddress" |=? pia , "SecurityGroupId" |.#= sgi , "DeleteOnTermination" |= dot ] ++ s pias where s SecondaryPrivateIpAddressParamNothing = [] s (SecondaryPrivateIpAddressParamCount c) = ["SecondaryPrivateIpAddressCount" |= c] s (SecondaryPrivateIpAddressParamSpecified addrs pr) = [ privateIpAddressesParam "PrivateIpAddresses" addrs , maybeParam $ ipAddressPrimaryParam <$> pr ] ipAddressPrimaryParam i = "PrivateIpAddresses" |.+ toText i |.+ "Primary" |= True networkInterfaceParams (NetworkInterfaceParamAttach nid idx dot) = [ "NetworkInterfaceId" |= nid , "DeviceIndex" |= idx , "DeleteOnTermination" |= dot ] ------------------------------------------------------------ -- GetConsoleOutput ------------------------------------------------------------ getConsoleOutput :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ InstanceId -> EC2 m ConsoleOutput getConsoleOutput iid = ec2Query "GetConsoleOutput" ["InstanceId" |= iid] $ \e -> ConsoleOutput <$> e .< "instanceId" <*> e .< "timestamp" <*> e .< "output" ------------------------------------------------------------ -- GetPasswordData ------------------------------------------------------------ getPasswordData :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ InstanceId -> EC2 m PasswordData getPasswordData iid = ec2Query "GetPasswordData" ["InstanceId" |= iid] $ \e -> PasswordData <$> e .< "instanceId" <*> e .< "timestamp" <*> e .< "passwordData" describeInstanceAttribute :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ InstanceId -> InstanceAttributeRequest -- ^ Attribute -> EC2 m InstanceAttribute describeInstanceAttribute iid attr = ec2Query "DescribeInstanceAttribute" params $ f attr where str = iar attr params = [ "InstanceId" |= iid , "Attribute" |= str ] f InstanceAttributeRequestBlockDeviceMapping = instanceBlockDeviceMappingsConv >=> return . InstanceAttributeBlockDeviceMapping f InstanceAttributeRequestProductCodes = productCodeConv >=> return . InstanceAttributeProductCodes f InstanceAttributeRequestGroupSet = itemsSet str (.< "groupId") >=> return . InstanceAttributeGroupSet f req = valueConv str (fromJust $ Map.lookup req h) h = Map.fromList [ (InstanceAttributeRequestInstanceType, InstanceAttributeInstanceType . fromJust) , (InstanceAttributeRequestKernelId, InstanceAttributeKernelId) , (InstanceAttributeRequestRamdiskId, InstanceAttributeRamdiskId) , (InstanceAttributeRequestUserData, InstanceAttributeUserData) , (InstanceAttributeRequestDisableApiTermination, InstanceAttributeDisableApiTermination . just) , (InstanceAttributeRequestShutdownBehavior, InstanceAttributeShutdownBehavior . fromJust . fromText . fromJust) , (InstanceAttributeRequestRootDeviceName, InstanceAttributeRootDeviceName) , (InstanceAttributeRequestSourceDestCheck, InstanceAttributeSourceDestCheck . fromText . fromJust) , (InstanceAttributeRequestEbsOptimized, InstanceAttributeEbsOptimized . just) ] just = fromJust . join . (fromText <$>) valueConv name val = element name (.< "value") >=> return . val iar :: InstanceAttributeRequest -> Text iar InstanceAttributeRequestInstanceType = "instanceType" iar InstanceAttributeRequestKernelId = "kernel" iar InstanceAttributeRequestRamdiskId = "ramdisk" iar InstanceAttributeRequestUserData = "userData" iar InstanceAttributeRequestDisableApiTermination = "disableApiTermination" iar InstanceAttributeRequestShutdownBehavior = "instanceInitiatedShutdownBehavior" iar InstanceAttributeRequestRootDeviceName = "rootDeviceName" iar InstanceAttributeRequestBlockDeviceMapping = "blockDeviceMapping" iar InstanceAttributeRequestSourceDestCheck = "sourceDestCheck" iar InstanceAttributeRequestGroupSet = "groupSet" iar InstanceAttributeRequestProductCodes = "productCodes" iar InstanceAttributeRequestEbsOptimized = "ebsOptimized" riap :: ResetInstanceAttributeRequest -> Text riap ResetInstanceAttributeRequestKernel = "kernel" riap ResetInstanceAttributeRequestRamdisk = "ramdisk" riap ResetInstanceAttributeRequestSourceDestCheck = "sourceDestCheck" resetInstanceAttribute :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ InstanceId -> ResetInstanceAttributeRequest -> EC2 m Bool resetInstanceAttribute iid attr = ec2Query "ResetInstanceAttribute" params (.< "return") where params = [ "InstanceId" |= iid , "Attribute" |= riap attr ] -- | not tested modifyInstanceAttribute :: (MonadResource m, MonadBaseControl IO m) => Text -- ^ InstanceId -> ModifyInstanceAttributeRequest -> EC2 m Bool modifyInstanceAttribute iid attr = ec2Query "ModifyInstanceAttribute" params (.< "return") where params = ["InstanceId" |= iid, miap attr] miap :: ModifyInstanceAttributeRequest -> QueryParam miap (ModifyInstanceAttributeRequestInstanceType a) = "InstanceType" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestKernelId a) = "Kernel" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestRamdiskId a) = "Ramdisk" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestUserData a) = "UserData" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestDisableApiTermination a) = "DisableApiTermination" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestShutdownBehavior a) = "InstanceInitiatedShutdownBehavior" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestRootDeviceName a) = "RootDeviceName" |= a miap (ModifyInstanceAttributeRequestBlockDeviceMapping a) = blockDeviceMappingsParam a miap (ModifyInstanceAttributeRequestSourceDestCheck a) = "SourceDestCheck" |.+ "Value" |= a miap (ModifyInstanceAttributeRequestGroupSet a) = "GroupId" |.#= a miap (ModifyInstanceAttributeRequestEbsOptimized a) = "EbsOptimized" |= a ------------------------------------------------------------ -- MonitorInstances ------------------------------------------------------------ monitorInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m (ResumableSource m MonitorInstancesResponse) monitorInstances iids = ec2QuerySource "MonitorInstances" ["InstanceId" |.#= iids] (itemsPath "instancesSet") monitorInstancesResponseConv monitorInstancesResponseConv :: (MonadResource m, MonadBaseControl IO m) => Conduit XmlElement m MonitorInstancesResponse monitorInstancesResponseConv = itemConduit $ \e -> MonitorInstancesResponse <$> e .< "instanceId" <*> element "monitoring" (.< "state") e ------------------------------------------------------------ -- UnmonitorInstances ------------------------------------------------------------ unmonitorInstances :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m (ResumableSource m MonitorInstancesResponse) unmonitorInstances iids = ec2QuerySource "UnmonitorInstances" ["InstanceId" |.#= iids] (itemsPath "instancesSet") monitorInstancesResponseConv ------------------------------------------------------------ -- DescribeSpotInstanceRequests ------------------------------------------------------------ describeSpotInstanceRequests :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ SpotInstanceRequestIds -> [Filter] -- ^ Filters -> EC2 m (ResumableSource m SpotInstanceRequest) describeSpotInstanceRequests requests filters = do -- ec2QueryDebug "DescribeInstances" params ec2QuerySource "DescribeSpotInstanceRequests" params path $ itemConduit spotInstanceRequestConv where path = itemsPath "spotInstanceRequestSet" params = [ "SpotInstanceRequestId" |.#= requests , filtersParam filters ] spotInstanceRequestConv :: (MonadThrow m, Applicative m) => XmlElement -> m SpotInstanceRequest spotInstanceRequestConv = conv where conv e = SpotInstanceRequest <$> e .< "spotInstanceRequestId" <*> e .< "spotPrice" <*> e .< "type" <*> e .< "state" <*> elementM "fault" faultConv e <*> element "status" statusConv e <*> e .< "validFrom" <*> e .< "validUntil" <*> e .< "launchGroup" <*> e .< "availabilityZoneGroup" <*> spotInstanceLaunchSpecificationConv "launchSpecification" e <*> e .< "instanceId" <*> e .< "createTime" <*> e .< "productDescription" <*> resourceTagConv e <*> e .< "launchedAvailabilityZone" faultConv e = SpotInstanceFault <$> e .< "code" <*> e .< "message" statusConv e = SpotInstanceStatus <$> e .< "code" <*> e .< "updateTime" <*> e .< "message" spotInstanceLaunchSpecificationConv :: (MonadThrow m, Applicative m) => Text -> XmlElement -> m SpotInstanceLaunchSpecification spotInstanceLaunchSpecificationConv label = element label conv where conv e = SpotInstanceLaunchSpecification <$> e .< "imageId" <*> e .< "keyName" <*> groupSetConv e <*> e .< "instanceType" <*> element "placement" plConv e <*> e .< "kernelId" <*> e .< "ramdiskId" <*> spotInstanceBlockDeviceMappingsConv e <*> element "monitoring" monConv e <*> e .< "subnetId" <*> spotInstanceNetworkInterfaceConv e <*> elementM "iamInstanceProfile" profConv e <*> e .< "ebsOptimized" plConv e = Placement <$> e .< "availabilityZone" <*> e .< "groupName" <*> e .< "tenancy" profConv e = IamInstanceProfile <$> e .< "arn" <*> e .< "id" monConv e = SpotInstanceMonitoringState <$> e .< "enabled" spotInstanceBlockDeviceMappingsConv :: (MonadThrow m, Applicative m) => XmlElement -> m [SpotInstanceBlockDeviceMapping] spotInstanceBlockDeviceMappingsConv = itemsSet "blockDeviceMapping" conv where conv e = SpotInstanceBlockDeviceMapping <$> e .< "deviceName" <*> element "ebs" ebsConv e ebsConv e = EbsSpotInstanceBlockDevice <$> e .< "volumeSize" <*> e .< "deleteOnTermination" <*> e .< "volumeType" spotInstanceNetworkInterfaceConv :: (MonadThrow m, Applicative m) => XmlElement -> m [SpotInstanceNetworkInterface] spotInstanceNetworkInterfaceConv = itemsSet "networkInterfaceSet" conv where conv e = SpotInstanceNetworkInterface <$> e .< "deviceIndex" <*> e .< "subnetId" <*> securityGroupSetConv e securityGroupSetConv :: (MonadThrow m, Applicative m) => XmlElement -> m [SpotInstanceSecurityGroup] securityGroupSetConv = itemsSet "groupSet" conv where conv e = SpotInstanceSecurityGroup <$> e .< "groupId" ------------------------------------------------------------ -- RequestSpotInstances ------------------------------------------------------------ -- | 'RequestSpotInstancesParam' is genereted with 'defaultRequestSpotInstancesParam' requestSpotInstances :: (MonadResource m, MonadBaseControl IO m) => RequestSpotInstancesParam -> EC2 m [SpotInstanceRequest] requestSpotInstances param = ec2Query "RequestSpotInstances" params $ itemsSet "spotInstanceRequestSet" spotInstanceRequestConv where params = [ "SpotPrice" |= requestSpotInstancesSpotPrice param , "InstanceCount" |=? requestSpotInstancesCount param , "Type" |=? requestSpotInstancesType param , "ValidFrom" |=? requestSpotInstancesValidFrom param , "ValidUntil" |=? requestSpotInstancesValidUntil param , "LaunchGroup" |=? requestSpotInstancesLaunchGroup param , "AvailabilityZoneGroup" |=? requestSpotInstancesLaunchGroup param , "LaunchSpecification" |. [ "ImageId" |= requestSpotInstancesImageId param , "KeyName" |=? requestSpotInstancesKeyName param , "SecurityGroupId" |.#= requestSpotInstancesSecurityGroupIds param , "SecurityGroup" |.#= requestSpotInstancesSecurityGroups param , "UserData" |=? requestSpotInstancesUserData param , "InstanceType" |= requestSpotInstancesInstanceType param , "Placement" |. [ "AvailabilityZone" |=? requestSpotInstancesAvailabilityZone param , "GroupName" |=? requestSpotInstancesPlacementGroup param ] , "KernelId" |=? requestSpotInstancesKernelId param , "RamdiskId" |=? requestSpotInstancesRamdiskId param , blockDeviceMappingsParam $ requestSpotInstancesBlockDeviceMappings param , "Monitoring" |.+ "Enabled" |=? requestSpotInstancesMonitoringEnabled param , "SubnetId" |=? requestSpotInstancesSubnetId param , "NetworkInterface" |.#. map networkInterfaceParams (requestSpotInstancesNetworkInterfaces param) , "IamInstanceProfile" |.? iamInstanceProfileParams <$> requestSpotInstancesIamInstancesProfile param , "EbsOptimized" |=? requestSpotInstancesEbsOptimized param ] ] iamInstanceProfileParams iam = [ "Arn" |= iamInstanceProfileArn iam , "Name" |= iamInstanceProfileId iam ] -- | RequestSpotInstances parameter utility defaultRequestSpotInstancesParam :: Text -- ^ Price -> Text -- ^ ImageId -> Text -- ^ Instance type -> RequestSpotInstancesParam defaultRequestSpotInstancesParam price iid iType = RequestSpotInstancesParam price Nothing Nothing Nothing Nothing Nothing Nothing iid Nothing [] [] Nothing iType Nothing Nothing Nothing Nothing [] Nothing Nothing [] Nothing Nothing ------------------------------------------------------------ -- CancelSpotInstanceRequests ------------------------------------------------------------ cancelSpotInstanceRequests :: (MonadResource m, MonadBaseControl IO m) => [Text] -- ^ InstanceIds -> EC2 m (ResumableSource m CancelSpotInstanceRequestsResponse) cancelSpotInstanceRequests requestIds = ec2QuerySource "CancelSpotInstanceRequests" params path $ itemConduit cancelSpotInstanceResponseConv where path = itemsPath "spotInstanceRequestSet" params = ["SpotInstanceRequestId" |.#= requestIds] cancelSpotInstanceResponseConv :: (MonadThrow m, Applicative m) => XmlElement -> m CancelSpotInstanceRequestsResponse cancelSpotInstanceResponseConv e = CancelSpotInstanceRequestsResponse <$> e .< "spotInstanceRequestId" <*> e .< "state"
worksap-ate/aws-sdk
Cloud/AWS/EC2/Instance.hs
bsd-3-clause
28,553
0
68
6,577
5,498
2,876
2,622
-1
-1
module GreedyIndSet where import Graph(ArrayGraph(..), Subgraph(..)) import Data.IntMap(IntMap,(!)) import Data.IntSet(IntSet, member, delete) import Data.List(foldl') import Util(mapFst) remainingNeighbors :: IntMap [Int] -> IntSet -> Int -> [Int] remainingNeighbors graph vs = filter (flip member vs) . (graph !) updateSubgraph :: IntMap [Int] -> Subgraph -> Int -> Subgraph updateSubgraph graph (Subgraph vs ds) v = let rn = remainingNeighbors graph vs v newVs = foldl' (flip delete) vs (v:rn) newDs = filter (flip member newVs . fst) ds reduced = map (map (\x -> (x,-1)) . remainingNeighbors graph newVs) rn newestDs = foldr addListIntMaps [] (newDs : reduced) in Subgraph newVs newestDs minDegs :: [(Int,Int)] -> [Int] minDegs [] = [] minDegs ((x,deg):xs) = fst $ foldr mins ([x],deg) xs where mins :: (Int,Int) -> ([Int],Int) -> ([Int],Int) mins (v, m) (vs, n) = case compare m n of GT -> (vs, n) EQ -> (v : vs, n) LT -> ([v], m) addListIntMaps :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)] addListIntMaps xs [] = xs addListIntMaps [] ys = ys addListIntMaps xx@((x,m):xs) yy@((y,n):ys) = case compare x y of EQ -> (x,m+n) : addListIntMaps xs ys LT -> (x,m) : addListIntMaps xs yy GT -> (y,n) : addListIntMaps xx ys greedyIndSet :: ArrayGraph -> [Int] greedyIndSet (ArrayGraph graph sg) = gis sg where gis sg@(Subgraph _ ds) = case minDegs ds of [] -> [] (x:_) -> x : gis (updateSubgraph graph sg x) greedyIndSets :: ArrayGraph -> [[Int]] greedyIndSets (ArrayGraph graph sg) = gis sg where f sg x = map (x :) (gis (updateSubgraph graph sg x)) gis (Subgraph _ ds) = case minDegs ds of [] -> [[]] xs -> concatMap (f sg) xs greedyIndSetN :: Int -> ArrayGraph -> ([Int],Int) greedyIndSetN n (ArrayGraph graph sg) = gis n sg where gis n sg@(Subgraph _ ds) = case minDegs ds of [] -> ([],n) xs -> let (x, newN) = rListElem xs n in mapFst (x :) (gis newN (updateSubgraph graph sg x)) greedyIndSetFirstN :: Int -> ArrayGraph -> [[Int]] greedyIndSetFirstN n g = map fst . filter ((0 ==) . snd) $ map (flip greedyIndSetN g) [0..n-1] rListElem :: [a] -> Int -> (a,Int) rListElem xs n = let (q,r) = quotRem n (length xs) in (xs !! r, q)
cullina/Extractor
src/GreedyIndSet.hs
bsd-3-clause
2,371
0
16
615
1,188
641
547
59
3
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} module Stack.Setup ( setupEnv , ensureGHC , SetupOpts (..) ) where import Control.Applicative import Control.Exception.Enclosed (catchIO) import Control.Monad (liftM, when, join, void, unless) import Control.Monad.Catch import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger import Control.Monad.Reader (MonadReader, ReaderT (..), asks) import Control.Monad.State (get, put, modify) import Control.Monad.Trans.Control import Crypto.Hash (SHA1(SHA1)) import Data.Aeson.Extended import Data.ByteString (ByteString) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Conduit (Conduit, ($$), (=$), await, yield, awaitForever) import Data.Conduit.Lift (evalStateC) import qualified Data.Conduit.List as CL import Data.Either import Data.Foldable import Data.IORef import Data.List hiding (concat, elem, maximumBy) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Ord (comparing) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime) import Data.Typeable (Typeable) import qualified Data.Yaml as Yaml import Distribution.System (OS (..), Arch (..), Platform (..)) import Distribution.Text (simpleParse) import Network.HTTP.Client.Conduit import Network.HTTP.Download.Verified import Path import Path.IO import Prelude hiding (concat, elem) -- Fix AMP warning import Safe (headMay, readMay) import Stack.Types.Build import Stack.Config (resolvePackageEntry) import Stack.Constants (distRelativeDir) import Stack.Fetch import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB) import Stack.Solver (getGhcVersion) import Stack.Types import Stack.Types.StackT import System.Environment (getExecutablePath) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (searchPathSeparator) import qualified System.FilePath as FP import System.IO.Temp (withSystemTempDirectory) import System.Process (rawSystem) import System.Process.Read import System.Process.Run (runIn) import Text.Printf (printf) data SetupOpts = SetupOpts { soptsInstallIfMissing :: !Bool , soptsUseSystem :: !Bool , soptsWantedCompiler :: !CompilerVersion , soptsCompilerCheck :: !VersionCheck , soptsStackYaml :: !(Maybe (Path Abs File)) -- ^ If we got the desired GHC version from that file , soptsForceReinstall :: !Bool , soptsSanityCheck :: !Bool -- ^ Run a sanity check on the selected GHC , soptsSkipGhcCheck :: !Bool -- ^ Don't check for a compatible GHC version/architecture , soptsSkipMsys :: !Bool -- ^ Do not use a custom msys installation on Windows , soptsUpgradeCabal :: !Bool -- ^ Upgrade the global Cabal library in the database to the newest -- version. Only works reliably with a stack-managed installation. , soptsResolveMissingGHC :: !(Maybe Text) -- ^ Message shown to user for how to resolve the missing GHC } deriving Show data SetupException = UnsupportedSetupCombo OS Arch | MissingDependencies [String] | UnknownGHCVersion Text CompilerVersion (Set Version) | UnknownOSKey Text | GHCSanityCheckCompileFailed ReadProcessException (Path Abs File) deriving Typeable instance Exception SetupException instance Show SetupException where show (UnsupportedSetupCombo os arch) = concat [ "I don't know how to install GHC for " , show (os, arch) , ", please install manually" ] show (MissingDependencies tools) = "The following executables are missing and must be installed: " ++ intercalate ", " tools show (UnknownGHCVersion oskey wanted known) = concat [ "No information found for GHC version " , T.unpack (compilerVersionName wanted) , ".\nSupported GHC major versions for OS key '" ++ T.unpack oskey ++ "': " , intercalate ", " (map show $ Set.toList known) ] show (UnknownOSKey oskey) = "Unable to find installation URLs for OS key: " ++ T.unpack oskey show (GHCSanityCheckCompileFailed e ghc) = concat [ "The GHC located at " , toFilePath ghc , " failed to compile a sanity check. Please see:\n\n" , " https://github.com/commercialhaskell/stack/wiki/Downloads\n\n" , "for more information. Exception was:\n" , show e ] -- | Modify the environment variables (like PATH) appropriately, possibly doing installation too setupEnv :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasBuildConfig env, HasHttpManager env, MonadBaseControl IO m) => Maybe Text -- ^ Message to give user when necessary GHC is not available -> m EnvConfig setupEnv mResolveMissingGHC = do bconfig <- asks getBuildConfig let platform = getPlatform bconfig sopts = SetupOpts { soptsInstallIfMissing = configInstallGHC $ bcConfig bconfig , soptsUseSystem = configSystemGHC $ bcConfig bconfig , soptsWantedCompiler = bcWantedCompiler bconfig , soptsCompilerCheck = configCompilerCheck $ bcConfig bconfig , soptsStackYaml = Just $ bcStackYaml bconfig , soptsForceReinstall = False , soptsSanityCheck = False , soptsSkipGhcCheck = configSkipGHCCheck $ bcConfig bconfig , soptsSkipMsys = configSkipMsys $ bcConfig bconfig , soptsUpgradeCabal = False , soptsResolveMissingGHC = mResolveMissingGHC } mghcBin <- ensureGHC sopts -- Modify the initial environment to include the GHC path, if a local GHC -- is being used menv0 <- getMinimalEnvOverride let env = removeHaskellEnvVars $ augmentPathMap (fromMaybe [] mghcBin) $ unEnvOverride menv0 menv <- mkEnvOverride platform env ghcVer <- getGhcVersion menv cabalVer <- getCabalPkgVer menv packages <- mapM (resolvePackageEntry menv (bcRoot bconfig)) (bcPackageEntries bconfig) let envConfig0 = EnvConfig { envConfigBuildConfig = bconfig , envConfigCabalVersion = cabalVer , envConfigGhcVersion = ghcVer , envConfigPackages = Map.fromList $ concat packages } -- extra installation bin directories mkDirs <- runReaderT extraBinDirs envConfig0 let mpath = Map.lookup "PATH" env mkDirs' = map toFilePath . mkDirs depsPath = augmentPath (mkDirs' False) mpath localsPath = augmentPath (mkDirs' True) mpath deps <- runReaderT packageDatabaseDeps envConfig0 createDatabase menv deps localdb <- runReaderT packageDatabaseLocal envConfig0 createDatabase menv localdb globalDB <- getGlobalDB menv let mkGPP locals = T.pack $ intercalate [searchPathSeparator] $ concat [ [toFilePathNoTrailingSlash localdb | locals] , [toFilePathNoTrailingSlash deps] , [toFilePathNoTrailingSlash globalDB] ] distDir <- runReaderT distRelativeDir envConfig0 executablePath <- liftIO getExecutablePath envRef <- liftIO $ newIORef Map.empty let getEnvOverride' es = do m <- readIORef envRef case Map.lookup es m of Just eo -> return eo Nothing -> do eo <- mkEnvOverride platform $ Map.insert "PATH" (if esIncludeLocals es then localsPath else depsPath) $ (if esIncludeGhcPackagePath es then Map.insert "GHC_PACKAGE_PATH" (mkGPP (esIncludeLocals es)) else id) $ (if esStackExe es then Map.insert "STACK_EXE" (T.pack executablePath) else id) -- For reasoning and duplication, see: https://github.com/fpco/stack/issues/70 $ Map.insert "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSlash deps) $ Map.insert "HASKELL_PACKAGE_SANDBOXES" (T.pack $ if esIncludeLocals es then intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash localdb , toFilePathNoTrailingSlash deps , "" ] else intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash deps , "" ]) $ Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePathNoTrailingSlash distDir) $ env !() <- atomicModifyIORef envRef $ \m' -> (Map.insert es eo m', ()) return eo return EnvConfig { envConfigBuildConfig = bconfig { bcConfig = (bcConfig bconfig) { configEnvOverride = getEnvOverride' } } , envConfigCabalVersion = cabalVer , envConfigGhcVersion = ghcVer , envConfigPackages = envConfigPackages envConfig0 } -- | Ensure GHC is installed and provide the PATHs to add if necessary ensureGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupOpts -> m (Maybe [FilePath]) ensureGHC sopts = do case soptsWantedCompiler sopts of GhcVersion v | v < $(mkVersion "7.8") -> do $logWarn "stack will almost certainly fail with GHC below version 7.8" $logWarn "Valiantly attempting to run anyway, but I know this is doomed" $logWarn "For more information, see: https://github.com/commercialhaskell/stack/issues/648" $logWarn "" _ -> return () -- Check the available GHCs menv0 <- getMinimalEnvOverride msystem <- if soptsUseSystem sopts then getSystemGHC menv0 else return Nothing Platform expectedArch _ <- asks getPlatform let needLocal = case msystem of Nothing -> True Just _ | soptsSkipGhcCheck sopts -> False Just (system, arch) -> not (isWanted system) || arch /= expectedArch isWanted = isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts) . GhcVersion -- If we need to install a GHC, try to do so mpaths <- if needLocal then do -- Avoid having to load it twice siRef <- liftIO $ newIORef Nothing manager <- asks getHttpManager let getSetupInfo' = liftIO $ do msi <- readIORef siRef case msi of Just si -> return si Nothing -> do si <- getSetupInfo manager writeIORef siRef $ Just si return si config <- asks getConfig installed <- runReaderT listInstalled config -- Install GHC ghcIdent <- case getInstalledTool installed $(mkPackageName "ghc") isWanted of Just ident -> return ident Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' downloadAndInstallGHC menv0 si (soptsWantedCompiler sopts) (soptsCompilerCheck sopts) | otherwise -> do Platform arch _ <- asks getPlatform throwM $ GHCVersionMismatch msystem (soptsWantedCompiler sopts, arch) (soptsCompilerCheck sopts) (soptsStackYaml sopts) (fromMaybe "Try running stack setup to locally install the correct GHC" $ soptsResolveMissingGHC sopts) -- Install git on windows, if necessary mgitIdent <- case configPlatform config of Platform _ os | isWindows os && not (soptsSkipMsys sopts) -> case getInstalledTool installed $(mkPackageName "git") (const True) of Just ident -> return (Just ident) Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' let VersionedDownloadInfo version info = siPortableGit si Just <$> downloadAndInstallTool si info $(mkPackageName "git") version installGitWindows | otherwise -> do $logWarn "Continuing despite missing tool: git" return Nothing _ -> return Nothing let idents = catMaybes [Just ghcIdent, mgitIdent] paths <- runReaderT (mapM binDirs idents) config return $ Just $ map toFilePathNoTrailingSlash $ concat paths else return Nothing menv <- case mpaths of Nothing -> return menv0 Just paths -> do config <- asks getConfig let m0 = unEnvOverride menv0 path0 = Map.lookup "PATH" m0 path = augmentPath paths path0 m = Map.insert "PATH" path m0 mkEnvOverride (configPlatform config) (removeHaskellEnvVars m) when (soptsUpgradeCabal sopts) $ do unless needLocal $ do $logWarn "Trying to upgrade Cabal library on a GHC not installed by stack." $logWarn "This may fail, caveat emptor!" upgradeCabal menv when (soptsSanityCheck sopts) $ sanityCheck menv return mpaths -- | Install the newest version of Cabal globally upgradeCabal :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadMask m) => EnvOverride -> m () upgradeCabal menv = do let name = $(mkPackageName "Cabal") rmap <- resolvePackages menv Set.empty (Set.singleton name) newest <- case Map.keys rmap of [] -> error "No Cabal library found in index, cannot upgrade" [PackageIdentifier name' version] | name == name' -> return version x -> error $ "Unexpected results for resolvePackages: " ++ show x installed <- getCabalPkgVer menv if installed >= newest then $logInfo $ T.concat [ "Currently installed Cabal is " , T.pack $ versionString installed , ", newest is " , T.pack $ versionString newest , ". I'm not upgrading Cabal." ] else withSystemTempDirectory "stack-cabal-upgrade" $ \tmpdir -> do $logInfo $ T.concat [ "Installing Cabal-" , T.pack $ versionString newest , " to replace " , T.pack $ versionString installed ] tmpdir' <- parseAbsDir tmpdir let ident = PackageIdentifier name newest m <- unpackPackageIdents menv tmpdir' Nothing (Set.singleton ident) ghcPath <- join $ findExecutable menv "ghc" newestDir <- parseRelDir $ versionString newest let installRoot = toFilePath $ parent (parent ghcPath) </> $(mkRelDir "new-cabal") </> newestDir dir <- case Map.lookup ident m of Nothing -> error $ "upgradeCabal: Invariant violated, dir missing" Just dir -> return dir runIn dir "ghc" menv ["Setup.hs"] Nothing let setupExe = toFilePath $ dir </> $(mkRelFile "Setup") dirArgument name' = concat [ "--" , name' , "dir=" , installRoot FP.</> name' ] runIn dir setupExe menv ( "configure" : map dirArgument (words "lib bin data doc") ) Nothing runIn dir setupExe menv ["build"] Nothing runIn dir setupExe menv ["install"] Nothing $logInfo "New Cabal library installed" -- | Get the major version of the system GHC, if available getSystemGHC :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> m (Maybe (Version, Arch)) getSystemGHC menv = do exists <- doesExecutableExist menv "ghc" if exists then do eres <- tryProcessStdout Nothing menv "ghc" ["--info"] return $ do Right bs <- Just eres pairs <- readMay $ S8.unpack bs :: Maybe [(String, String)] version <- lookup "Project version" pairs >>= parseVersionFromString arch <- lookup "Target platform" pairs >>= simpleParse . takeWhile (/= '-') Just (version, arch) else return Nothing data DownloadInfo = DownloadInfo { downloadInfoUrl :: Text , downloadInfoContentLength :: Int , downloadInfoSha1 :: Maybe ByteString } deriving Show data VersionedDownloadInfo = VersionedDownloadInfo { vdiVersion :: Version , vdiDownloadInfo :: DownloadInfo } deriving Show parseDownloadInfoFromObject :: Yaml.Object -> Yaml.Parser DownloadInfo parseDownloadInfoFromObject o = do url <- o .: "url" contentLength <- o .: "content-length" sha1TextMay <- o .:? "sha1" return DownloadInfo { downloadInfoUrl = url , downloadInfoContentLength = contentLength , downloadInfoSha1 = fmap T.encodeUtf8 sha1TextMay } instance FromJSON DownloadInfo where parseJSON = withObject "DownloadInfo" parseDownloadInfoFromObject instance FromJSON VersionedDownloadInfo where parseJSON = withObject "VersionedDownloadInfo" $ \o -> do version <- o .: "version" downloadInfo <- parseDownloadInfoFromObject o return VersionedDownloadInfo { vdiVersion = version , vdiDownloadInfo = downloadInfo } data SetupInfo = SetupInfo { siSevenzExe :: DownloadInfo , siSevenzDll :: DownloadInfo , siPortableGit :: VersionedDownloadInfo , siGHCs :: Map Text (Map Version DownloadInfo) } deriving Show instance FromJSON SetupInfo where parseJSON = withObject "SetupInfo" $ \o -> SetupInfo <$> o .: "sevenzexe-info" <*> o .: "sevenzdll-info" <*> o .: "portable-git" <*> o .: "ghc" -- | Download the most recent SetupInfo getSetupInfo :: (MonadIO m, MonadThrow m) => Manager -> m SetupInfo getSetupInfo manager = do bss <- liftIO $ flip runReaderT manager $ withResponse req $ \res -> responseBody res $$ CL.consume let bs = S8.concat bss either throwM return $ Yaml.decodeEither' bs where req = "https://raw.githubusercontent.com/fpco/stackage-content/master/stack/stack-setup-2.yaml" markInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => PackageIdentifier -- ^ e.g., ghc-7.8.4, git-2.4.0.1 -> m () markInstalled ident = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed" liftIO $ writeFile (toFilePath $ dir </> fpRel) "installed" unmarkInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => PackageIdentifier -> m () unmarkInstalled ident = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed" removeFileIfExists $ dir </> fpRel listInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => m [PackageIdentifier] listInstalled = do dir <- asks $ configLocalPrograms . getConfig createTree dir (_, files) <- listDirectory dir return $ mapMaybe toIdent files where toIdent fp = do x <- T.stripSuffix ".installed" $ T.pack $ toFilePath $ filename fp parsePackageIdentifierFromString $ T.unpack x installDir :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => PackageIdentifier -> m (Path Abs Dir) installDir ident = do config <- asks getConfig reldir <- parseRelDir $ packageIdentifierString ident return $ configLocalPrograms config </> reldir -- | Binary directories for the given installed package binDirs :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => PackageIdentifier -> m [Path Abs Dir] binDirs ident = do config <- asks getConfig dir <- installDir ident case (configPlatform config, packageNameString $ packageIdentifierName ident) of (Platform _ (isWindows -> True), "ghc") -> return [ dir </> $(mkRelDir "bin") , dir </> $(mkRelDir "mingw") </> $(mkRelDir "bin") ] (Platform _ (isWindows -> True), "git") -> return [ dir </> $(mkRelDir "cmd") , dir </> $(mkRelDir "usr") </> $(mkRelDir "bin") ] (_, "ghc") -> return [ dir </> $(mkRelDir "bin") ] (Platform _ x, tool) -> do $logWarn $ "binDirs: unexpected OS/tool combo: " <> T.pack (show (x, tool)) return [] getInstalledTool :: [PackageIdentifier] -- ^ already installed -> PackageName -- ^ package to find -> (Version -> Bool) -- ^ which versions are acceptable -> Maybe PackageIdentifier getInstalledTool installed name goodVersion = if null available then Nothing else Just $ maximumBy (comparing packageIdentifierVersion) available where available = filter goodPackage installed goodPackage pi' = packageIdentifierName pi' == name && goodVersion (packageIdentifierVersion pi') downloadAndInstallTool :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> DownloadInfo -> PackageName -> Version -> (SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m ()) -> m PackageIdentifier downloadAndInstallTool si downloadInfo name version installer = do let ident = PackageIdentifier name version (file, at) <- downloadFromInfo downloadInfo ident dir <- installDir ident unmarkInstalled ident installer si file at dir ident markInstalled ident return ident downloadAndInstallGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => EnvOverride -> SetupInfo -> CompilerVersion -> VersionCheck -> m PackageIdentifier downloadAndInstallGHC menv si wanted versionCheck = do osKey <- getOSKey menv pairs <- case Map.lookup osKey $ siGHCs si of Nothing -> throwM $ UnknownOSKey osKey Just pairs -> return pairs let mpair = listToMaybe $ sortBy (flip (comparing fst)) $ filter (\(v, _) -> isWantedCompiler versionCheck wanted (GhcVersion v)) (Map.toList pairs) (selectedVersion, downloadInfo) <- case mpair of Just pair -> return pair Nothing -> throwM $ UnknownGHCVersion osKey wanted (Map.keysSet pairs) platform <- asks $ configPlatform . getConfig let installer = case platform of Platform _ os | isWindows os -> installGHCWindows _ -> installGHCPosix downloadAndInstallTool si downloadInfo $(mkPackageName "ghc") selectedVersion installer getOSKey :: (MonadReader env m, MonadThrow m, HasConfig env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m) => EnvOverride -> m Text getOSKey menv = do platform <- asks $ configPlatform . getConfig case platform of Platform I386 Linux -> ("linux32" <>) <$> getLinuxSuffix Platform X86_64 Linux -> ("linux64" <>) <$> getLinuxSuffix Platform I386 OSX -> return "macosx" Platform X86_64 OSX -> return "macosx" Platform I386 FreeBSD -> return "freebsd32" Platform X86_64 FreeBSD -> return "freebsd64" Platform I386 OpenBSD -> return "openbsd32" Platform X86_64 OpenBSD -> return "openbsd64" Platform I386 Windows -> return "windows32" Platform X86_64 Windows -> return "windows64" Platform I386 (OtherOS "windowsintegersimple") -> return "windowsintegersimple32" Platform X86_64 (OtherOS "windowsintegersimple") -> return "windowsintegersimple64" Platform arch os -> throwM $ UnsupportedSetupCombo os arch where getLinuxSuffix = do executablePath <- liftIO getExecutablePath elddOut <- tryProcessStdout Nothing menv "ldd" [executablePath] return $ case elddOut of Left _ -> "" Right lddOut -> if hasLineWithFirstWord "libgmp.so.3" lddOut then "-gmp4" else "" hasLineWithFirstWord w = elem (Just w) . map (headMay . T.words) . T.lines . T.decodeUtf8With T.lenientDecode downloadFromInfo :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => DownloadInfo -> PackageIdentifier -> m (Path Abs File, ArchiveType) downloadFromInfo downloadInfo ident = do config <- asks getConfig at <- case extension of ".tar.xz" -> return TarXz ".tar.bz2" -> return TarBz2 ".7z.exe" -> return SevenZ _ -> error $ "Unknown extension: " ++ extension relfile <- parseRelFile $ packageIdentifierString ident ++ extension let path = configLocalPrograms config </> relfile chattyDownload (packageIdentifierText ident) downloadInfo path return (path, at) where url = downloadInfoUrl downloadInfo extension = loop $ T.unpack url where loop fp | ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z"] = loop fp' ++ ext | otherwise = "" where (fp', ext) = FP.splitExtension fp data ArchiveType = TarBz2 | TarXz | SevenZ installGHCPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installGHCPosix _ archiveFile archiveType destDir ident = do platform <- asks getPlatform menv0 <- getMinimalEnvOverride menv <- mkEnvOverride platform (removeHaskellEnvVars (unEnvOverride menv0)) $logDebug $ "menv = " <> T.pack (show (unEnvOverride menv)) zipTool' <- case archiveType of TarXz -> return "xz" TarBz2 -> return "bzip2" SevenZ -> error "Don't know how to deal with .7z files on non-Windows" (zipTool, makeTool, tarTool) <- checkDependencies $ (,,) <$> checkDependency zipTool' <*> (checkDependency "gmake" <|> checkDependency "make") <*> checkDependency "tar" $logDebug $ "ziptool: " <> T.pack zipTool $logDebug $ "make: " <> T.pack makeTool $logDebug $ "tar: " <> T.pack tarTool withSystemTempDirectory "stack-setup" $ \root' -> do root <- parseAbsDir root' dir <- liftM (root Path.</>) $ parseRelDir $ packageIdentifierString ident $logSticky $ "Unpacking GHC ..." $logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile) readInNull root tarTool menv ["xf", toFilePath archiveFile] Nothing $logSticky "Configuring GHC ..." readInNull dir (toFilePath $ dir Path.</> $(mkRelFile "configure")) menv ["--prefix=" ++ toFilePath destDir] Nothing $logSticky "Installing GHC ..." readInNull dir makeTool menv ["install"] Nothing $logStickyDone $ "Installed GHC." $logDebug $ "GHC installed to " <> T.pack (toFilePath destDir) where -- | Check if given processes appear to be present, throwing an exception if -- missing. checkDependencies :: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env) => CheckDependency a -> m a checkDependencies (CheckDependency f) = do menv <- getMinimalEnvOverride liftIO (f menv) >>= either (throwM . MissingDependencies) return checkDependency :: String -> CheckDependency String checkDependency tool = CheckDependency $ \menv -> do exists <- doesExecutableExist menv tool return $ if exists then Right tool else Left [tool] newtype CheckDependency a = CheckDependency (EnvOverride -> IO (Either [String] a)) deriving Functor instance Applicative CheckDependency where pure x = CheckDependency $ \_ -> return (Right x) CheckDependency f <*> CheckDependency x = CheckDependency $ \menv -> do f' <- f menv x' <- x menv return $ case (f', x') of (Left e1, Left e2) -> Left $ e1 ++ e2 (Left e, Right _) -> Left e (Right _, Left e) -> Left e (Right f'', Right x'') -> Right $ f'' x'' instance Alternative CheckDependency where empty = CheckDependency $ \_ -> return $ Left [] CheckDependency x <|> CheckDependency y = CheckDependency $ \menv -> do res1 <- x menv case res1 of Left _ -> y menv Right x' -> return $ Right x' installGHCWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installGHCWindows si archiveFile archiveType destDir _ = do suffix <- case archiveType of TarXz -> return ".xz" TarBz2 -> return ".bz2" _ -> error $ "GHC on Windows must be a tarball file" tarFile <- case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of Nothing -> error $ "Invalid GHC filename: " ++ show archiveFile Just x -> parseAbsFile $ T.unpack x config <- asks getConfig run7z <- setup7z si config run7z (parent archiveFile) archiveFile run7z (parent archiveFile) tarFile removeFile tarFile `catchIO` \e -> $logWarn (T.concat [ "Exception when removing " , T.pack $ toFilePath tarFile , ": " , T.pack $ show e ]) $logInfo $ "GHC installed to " <> T.pack (toFilePath destDir) installGitWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> PackageIdentifier -> m () installGitWindows si archiveFile archiveType destDir _ = do case archiveType of SevenZ -> return () _ -> error $ "Git on Windows must be a 7z archive" config <- asks getConfig run7z <- setup7z si config run7z destDir archiveFile -- | Download 7z as necessary, and get a function for unpacking things. -- -- Returned function takes an unpack directory and archive. setup7z :: (MonadReader env m, HasHttpManager env, MonadThrow m, MonadIO m, MonadIO n, MonadLogger m, MonadBaseControl IO m) => SetupInfo -> Config -> m (Path Abs Dir -> Path Abs File -> n ()) setup7z si config = do chattyDownload "7z.dll" (siSevenzDll si) dll chattyDownload "7z.exe" (siSevenzExe si) exe return $ \outdir archive -> liftIO $ do ec <- rawSystem (toFilePath exe) [ "x" , "-o" ++ toFilePath outdir , "-y" , toFilePath archive ] when (ec /= ExitSuccess) $ error $ "Problem while decompressing " ++ toFilePath archive where dir = configLocalPrograms config </> $(mkRelDir "7z") exe = dir </> $(mkRelFile "7z.exe") dll = dir </> $(mkRelFile "7z.dll") chattyDownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m, MonadThrow m, MonadBaseControl IO m) => Text -- ^ label -> DownloadInfo -- ^ URL, content-length, and sha1 -> Path Abs File -- ^ destination -> m () chattyDownload label downloadInfo path = do let url = downloadInfoUrl downloadInfo req <- parseUrl $ T.unpack url $logSticky $ T.concat [ "Preparing to download " , label , " ..." ] $logDebug $ T.concat [ "Downloading from " , url , " to " , T.pack $ toFilePath path , " ..." ] hashChecks <- case downloadInfoSha1 downloadInfo of Just sha1ByteString -> do let sha1 = CheckHexDigestByteString sha1ByteString $logDebug $ T.concat [ "Will check against sha1 hash: " , T.decodeUtf8With T.lenientDecode sha1ByteString ] return [HashCheck SHA1 sha1] Nothing -> do $logWarn $ T.concat [ "No sha1 found in metadata," , " download hash won't be checked." ] return [] let dReq = DownloadRequest { drRequest = req , drHashChecks = hashChecks , drLengthCheck = Just totalSize , drRetryPolicy = drRetryPolicyDefault } runInBase <- liftBaseWith $ \run -> return (void . run) x <- verifiedDownload dReq path (chattyDownloadProgress runInBase) if x then $logStickyDone ("Downloaded " <> label <> ".") else $logStickyDone "Already downloaded." where totalSize = downloadInfoContentLength downloadInfo chattyDownloadProgress runInBase _ = do _ <- liftIO $ runInBase $ $logSticky $ label <> ": download has begun" CL.map (Sum . S.length) =$ chunksOverTime 1 =$ go where go = evalStateC 0 $ awaitForever $ \(Sum size) -> do modify (+ size) totalSoFar <- get liftIO $ runInBase $ $logSticky $ T.pack $ chattyProgressWithTotal totalSoFar totalSize -- Note(DanBurton): Total size is now always known in this file. -- However, printing in the case where it isn't known may still be -- useful in other parts of the codebase. -- So I'm just commenting out the code rather than deleting it. -- case mcontentLength of -- Nothing -> chattyProgressNoTotal totalSoFar -- Just 0 -> chattyProgressNoTotal totalSoFar -- Just total -> chattyProgressWithTotal totalSoFar total ---- Example: ghc: 42.13 KiB downloaded... --chattyProgressNoTotal totalSoFar = -- printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " downloaded...") -- (T.unpack label) -- Example: ghc: 50.00 MiB / 100.00 MiB (50.00%) downloaded... chattyProgressWithTotal totalSoFar total = printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " / " <> bytesfmt "%.2f" total <> " (%6.2f%%) downloaded...") (T.unpack label) percentage where percentage :: Double percentage = (fromIntegral totalSoFar / fromIntegral total * 100) -- | Given a printf format string for the decimal part and a number of -- bytes, formats the bytes using an appropiate unit and returns the -- formatted string. -- -- >>> bytesfmt "%.2" 512368 -- "500.359375 KiB" bytesfmt :: Integral a => String -> a -> String bytesfmt formatter bs = printf (formatter <> " %s") (fromIntegral (signum bs) * dec :: Double) (bytesSuffixes !! i) where (dec,i) = getSuffix (abs bs) getSuffix n = until p (\(x,y) -> (x / 1024, y+1)) (fromIntegral n,0) where p (n',numDivs) = n' < 1024 || numDivs == (length bytesSuffixes - 1) bytesSuffixes :: [String] bytesSuffixes = ["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"] -- Await eagerly (collect with monoidal append), -- but space out yields by at least the given amount of time. -- The final yield may come sooner, and may be a superfluous mempty. -- Note that Integer and Float literals can be turned into NominalDiffTime -- (these literals are interpreted as "seconds") chunksOverTime :: (Monoid a, MonadIO m) => NominalDiffTime -> Conduit a m a chunksOverTime diff = do currentTime <- liftIO getCurrentTime evalStateC (currentTime, mempty) go where -- State is a tuple of: -- * the last time a yield happened (or the beginning of the sink) -- * the accumulated awaits since the last yield go = await >>= \case Nothing -> do (_, acc) <- get yield acc Just a -> do (lastTime, acc) <- get let acc' = acc <> a currentTime <- liftIO getCurrentTime if diff < diffUTCTime currentTime lastTime then put (currentTime, mempty) >> yield acc' else put (lastTime, acc') go -- | Perform a basic sanity check of GHC sanityCheck :: (MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m) => EnvOverride -> m () sanityCheck menv = withSystemTempDirectory "stack-sanity-check" $ \dir -> do dir' <- parseAbsDir dir let fp = toFilePath $ dir' </> $(mkRelFile "Main.hs") liftIO $ writeFile fp $ unlines [ "import Distribution.Simple" -- ensure Cabal library is present , "main = putStrLn \"Hello World\"" ] ghc <- join $ findExecutable menv "ghc" $logDebug $ "Performing a sanity check on: " <> T.pack (toFilePath ghc) eres <- tryProcessStdout (Just dir') menv "ghc" [ fp , "-no-user-package-db" ] case eres of Left e -> throwM $ GHCSanityCheckCompileFailed e ghc Right _ -> return () -- TODO check that the output of running the command is correct toFilePathNoTrailingSlash :: Path loc Dir -> FilePath toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath -- Remove potentially confusing environment variables removeHaskellEnvVars :: Map Text Text -> Map Text Text removeHaskellEnvVars = Map.delete "GHC_PACKAGE_PATH" . Map.delete "HASKELL_PACKAGE_SANDBOX" . Map.delete "HASKELL_PACKAGE_SANDBOXES" . Map.delete "HASKELL_DIST_DIR"
joozek78/stack
src/Stack/Setup.hs
bsd-3-clause
40,416
0
30
12,974
9,649
4,789
4,860
816
15
{- mkindex :: Making index.html for the current directory. -} import Control.Applicative import Data.Bits import Data.Time import Data.Time.Clock.POSIX import System.Directory import System.Locale import System.Posix.Files import Text.Printf indexFile :: String indexFile = "index.html" main :: IO () main = do contents <- mkContents writeFile indexFile $ header ++ contents ++ tailer setFileMode indexFile mode where mode = ownerReadMode .|. ownerWriteMode .|. groupReadMode .|. otherReadMode mkContents :: IO String mkContents = do fileNames <- filter dotAndIndex <$> getDirectoryContents "." stats <- mapM getFileStatus fileNames let fmsls = zipWith pp fileNames stats maxLen = maximum $ map (\(_,_,_,x) -> x) fmsls contents = concatMap (content maxLen) fmsls return contents where dotAndIndex x = head x /= '.' && x /= indexFile pp :: String -> FileStatus -> (String,String,String,Int) pp f st = (file,mtime,size,flen) where file = ppFile f st flen = length file mtime = ppMtime st size = ppSize st ppFile :: String -> FileStatus -> String ppFile f st | isDirectory st = f ++ "/" | otherwise = f ppMtime :: FileStatus -> String ppMtime st = dateFormat . epochTimeToUTCTime $ st where epochTimeToUTCTime = posixSecondsToUTCTime . realToFrac . modificationTime dateFormat = formatTime defaultTimeLocale "%d-%b-%Y %H:%M" ppSize :: FileStatus -> String ppSize st | isDirectory st = " - " | otherwise = sizeFormat . fromIntegral . fileSize $ st where sizeFormat siz = unit siz " KMGT" unit _ [] = error "unit" unit s [u] = format s u unit s (u:us) | s >= 1024 = unit (s `div` 1024) us | otherwise = format s u format :: Integer -> Char -> String format = printf "%3d%c" header :: String header = "\ \<html>\n\ \<head>\n\ \<style type=\"text/css\">\n\ \<!--\n\ \body { padding-left: 10%; }\n\ \h1 { font-size: x-large; }\n\ \pre { font-size: large; }\n\ \hr { text-align: left; margin-left: 0px; width: 80% }\n\ \-->\n\ \</style>\n\ \</head>\n\ \<title>Directory contents</title>\n\ \<body>\n\ \<h1>Directory contents</h1>\n\ \<hr>\n\ \<pre>\n" content :: Int -> (String,String,String,Int) -> String content lim (f,m,s,len) = "<a href=\"" ++ f ++ "\">" ++ f ++ "</a> " ++ replicate (lim - len) ' ' ++ m ++ " " ++ s ++ "\n" tailer :: String tailer = "\ \</pre>\n\ \<hr>\n\ \</body>\n\ \</html>\n"
mietek/mighttpd2
utils/mkindex.hs
bsd-3-clause
2,450
39
14
520
727
374
353
57
3
{- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 \section[StgLint]{A ``lint'' pass to check for Stg correctness} -} {-# LANGUAGE CPP #-} module StgLint ( lintStgBindings ) where import StgSyn import Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList ) import Id ( Id, idType, isLocalId ) import VarSet import DataCon import CoreSyn ( AltCon(..) ) import PrimOp ( primOpType ) import Literal ( literalType ) import Maybes import Name ( getSrcLoc ) import ErrUtils ( MsgDoc, Severity(..), mkLocMessage ) import Type import TyCon import Util import SrcLoc import Outputable #if __GLASGOW_HASKELL__ < 709 import Control.Applicative ( Applicative(..) ) #endif import Control.Monad import Data.Function #include "HsVersions.h" {- Checks for (a) *some* type errors (b) locally-defined variables used but not defined Note: unless -dverbose-stg is on, display of lint errors will result in "panic: bOGUS_LVs". WARNING: ~~~~~~~~ This module has suffered bit-rot; it is likely to yield lint errors for Stg code that is currently perfectly acceptable for code generation. Solution: don't use it! (KSW 2000-05). ************************************************************************ * * \subsection{``lint'' for various constructs} * * ************************************************************************ @lintStgBindings@ is the top-level interface function. -} lintStgBindings :: String -> [StgBinding] -> [StgBinding] lintStgBindings whodunnit binds = {-# SCC "StgLint" #-} case (initL (lint_binds binds)) of Nothing -> binds Just msg -> pprPanic "" (vcat [ text "*** Stg Lint ErrMsgs: in" <+> text whodunnit <+> text "***", msg, text "*** Offending Program ***", pprStgBindings binds, text "*** End of Offense ***"]) where lint_binds :: [StgBinding] -> LintM () lint_binds [] = return () lint_binds (bind:binds) = do binders <- lintStgBinds bind addInScopeVars binders $ lint_binds binds lintStgArg :: StgArg -> LintM (Maybe Type) lintStgArg (StgLitArg lit) = return (Just (literalType lit)) lintStgArg (StgVarArg v) = lintStgVar v lintStgVar :: Id -> LintM (Maybe Kind) lintStgVar v = do checkInScope v return (Just (idType v)) lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders lintStgBinds (StgNonRec binder rhs) = do lint_binds_help (binder,rhs) return [binder] lintStgBinds (StgRec pairs) = addInScopeVars binders $ do mapM_ lint_binds_help pairs return binders where binders = [b | (b,_) <- pairs] lint_binds_help :: (Id, StgRhs) -> LintM () lint_binds_help (binder, rhs) = addLoc (RhsOf binder) $ do -- Check the rhs _maybe_rhs_ty <- lintStgRhs rhs -- Check binder doesn't have unlifted type checkL (not (isUnliftedType binder_ty)) (mkUnliftedTyMsg binder rhs) -- Check match to RHS type -- Actually we *can't* check the RHS type, because -- unsafeCoerce means it really might not match at all -- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce... -- case maybe_rhs_ty of -- Nothing -> return () -- Just rhs_ty -> checkTys binder_ty -- rhs_ty --- (mkRhsMsg binder rhs_ty) return () where binder_ty = idType binder lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact lintStgRhs (StgRhsClosure _ _ _ _ _ [] expr) = lintStgExpr expr lintStgRhs (StgRhsClosure _ _ _ _ _ binders expr) = addLoc (LambdaBodyOf binders) $ addInScopeVars binders $ runMaybeT $ do body_ty <- MaybeT $ lintStgExpr expr return (mkFunTys (map idType binders) body_ty) lintStgRhs (StgRhsCon _ con args) = runMaybeT $ do arg_tys <- mapM (MaybeT . lintStgArg) args MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys) where con_ty = dataConRepType con lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact lintStgExpr (StgLit l) = return (Just (literalType l)) lintStgExpr e@(StgApp fun args) = runMaybeT $ do fun_ty <- MaybeT $ lintStgVar fun arg_tys <- mapM (MaybeT . lintStgArg) args MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e) lintStgExpr e@(StgConApp con args) = runMaybeT $ do arg_tys <- mapM (MaybeT . lintStgArg) args MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e) where con_ty = dataConRepType con lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do arg_tys <- mapM (MaybeT . lintStgArg) args MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e) where op_ty = primOpType op lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do -- We don't have enough type information to check -- the application for StgFCallOp and StgPrimCallOp; ToDo _maybe_arg_tys <- mapM (MaybeT . lintStgArg) args return res_ty lintStgExpr (StgLam bndrs _) = do addErrL (text "Unexpected StgLam" <+> ppr bndrs) return Nothing lintStgExpr (StgLet binds body) = do binders <- lintStgBinds binds addLoc (BodyOfLetRec binders) $ addInScopeVars binders $ lintStgExpr body lintStgExpr (StgLetNoEscape _ _ binds body) = do binders <- lintStgBinds binds addLoc (BodyOfLetRec binders) $ addInScopeVars binders $ lintStgExpr body lintStgExpr (StgTick _ expr) = lintStgExpr expr lintStgExpr (StgCase scrut _ _ bndr _ alts_type alts) = runMaybeT $ do _ <- MaybeT $ lintStgExpr scrut in_scope <- MaybeT $ liftM Just $ case alts_type of AlgAlt tc -> check_bndr tc >> return True PrimAlt tc -> check_bndr tc >> return True UbxTupAlt _ -> return False -- Binder is always dead in this case PolyAlt -> return True MaybeT $ addInScopeVars [bndr | in_scope] $ lintStgAlts alts scrut_ty where scrut_ty = idType bndr UnaryRep scrut_rep = repType scrut_ty -- Not used if scrutinee is unboxed tuple check_bndr tc = case tyConAppTyCon_maybe scrut_rep of Just bndr_tc -> checkL (tc == bndr_tc) bad_bndr Nothing -> addErrL bad_bndr where bad_bndr = mkDefltMsg bndr tc lintStgAlts :: [StgAlt] -> Type -- Type of scrutinee -> LintM (Maybe Type) -- Just ty => type is accurage lintStgAlts alts scrut_ty = do maybe_result_tys <- mapM (lintAlt scrut_ty) alts -- Check the result types case catMaybes (maybe_result_tys) of [] -> return Nothing (first_ty:_tys) -> do -- mapM_ check tys return (Just first_ty) where -- check ty = checkTys first_ty ty (mkCaseAltMsg alts) -- We can't check that the alternatives have the -- same type, because they don't, with unsafeCoerce# lintAlt :: Type -> (AltCon, [Id], [Bool], StgExpr) -> LintM (Maybe Type) lintAlt _ (DEFAULT, _, _, rhs) = lintStgExpr rhs lintAlt scrut_ty (LitAlt lit, _, _, rhs) = do checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty) lintStgExpr rhs lintAlt scrut_ty (DataAlt con, args, _, rhs) = do case splitTyConApp_maybe scrut_ty of Just (tycon, tys_applied) | isAlgTyCon tycon && not (isNewTyCon tycon) -> do let cons = tyConDataCons tycon arg_tys = dataConInstArgTys con tys_applied -- This does not work for existential constructors checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con) checkL (length args == dataConRepArity con) (mkAlgAltMsg3 con args) when (isVanillaDataCon con) $ mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args) return () _ -> addErrL (mkAltMsg1 scrut_ty) addInScopeVars args $ lintStgExpr rhs where check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg) -- elem: yes, the elem-list here can sometimes be long-ish, -- but as it's use-once, probably not worth doing anything different -- We give it its own copy, so it isn't overloaded. elem _ [] = False elem x (y:ys) = x==y || elem x ys {- ************************************************************************ * * \subsection[lint-monad]{The Lint monad} * * ************************************************************************ -} newtype LintM a = LintM { unLintM :: [LintLocInfo] -- Locations -> IdSet -- Local vars in scope -> Bag MsgDoc -- Error messages so far -> (a, Bag MsgDoc) -- Result and error messages (if any) } data LintLocInfo = RhsOf Id -- The variable bound | LambdaBodyOf [Id] -- The lambda-binder | BodyOfLetRec [Id] -- One of the binders dumpLoc :: LintLocInfo -> (SrcSpan, SDoc) dumpLoc (RhsOf v) = (srcLocSpan (getSrcLoc v), text " [RHS of " <> pp_binders [v] <> char ']' ) dumpLoc (LambdaBodyOf bs) = (srcLocSpan (getSrcLoc (head bs)), text " [in body of lambda with binders " <> pp_binders bs <> char ']' ) dumpLoc (BodyOfLetRec bs) = (srcLocSpan (getSrcLoc (head bs)), text " [in body of letrec with binders " <> pp_binders bs <> char ']' ) pp_binders :: [Id] -> SDoc pp_binders bs = sep (punctuate comma (map pp_binder bs)) where pp_binder b = hsep [ppr b, dcolon, ppr (idType b)] initL :: LintM a -> Maybe MsgDoc initL (LintM m) = case (m [] emptyVarSet emptyBag) of { (_, errs) -> if isEmptyBag errs then Nothing else Just (vcat (punctuate blankLine (bagToList errs))) } instance Functor LintM where fmap = liftM instance Applicative LintM where pure a = LintM $ \_loc _scope errs -> (a, errs) (<*>) = ap (*>) = thenL_ instance Monad LintM where return = pure (>>=) = thenL (>>) = (*>) thenL :: LintM a -> (a -> LintM b) -> LintM b thenL m k = LintM $ \loc scope errs -> case unLintM m loc scope errs of (r, errs') -> unLintM (k r) loc scope errs' thenL_ :: LintM a -> LintM b -> LintM b thenL_ m k = LintM $ \loc scope errs -> case unLintM m loc scope errs of (_, errs') -> unLintM k loc scope errs' checkL :: Bool -> MsgDoc -> LintM () checkL True _ = return () checkL False msg = addErrL msg addErrL :: MsgDoc -> LintM () addErrL msg = LintM $ \loc _scope errs -> ((), addErr errs msg loc) addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc addErr errs_so_far msg locs = errs_so_far `snocBag` mk_msg locs where mk_msg (loc:_) = let (l,hdr) = dumpLoc loc in mkLocMessage SevWarning l (hdr $$ msg) mk_msg [] = msg addLoc :: LintLocInfo -> LintM a -> LintM a addLoc extra_loc m = LintM $ \loc scope errs -> unLintM m (extra_loc:loc) scope errs addInScopeVars :: [Id] -> LintM a -> LintM a addInScopeVars ids m = LintM $ \loc scope errs -> -- We check if these "new" ids are already -- in scope, i.e., we have *shadowing* going on. -- For now, it's just a "trace"; we may make -- a real error out of it... let new_set = mkVarSet ids in -- After adding -fliberate-case, Simon decided he likes shadowed -- names after all. WDP 94/07 -- (if isEmptyVarSet shadowed -- then id -- else pprTrace "Shadowed vars:" (ppr (varSetElems shadowed))) $ unLintM m loc (scope `unionVarSet` new_set) errs {- Checking function applications: we only check that the type has the right *number* of arrows, we don't actually compare the types. This is because we can't expect the types to be equal - the type applications and type lambdas that we use to calculate accurate types have long since disappeared. -} checkFunApp :: Type -- The function type -> [Type] -- The arg type(s) -> MsgDoc -- Error message -> LintM (Maybe Type) -- Just ty => result type is accurate checkFunApp fun_ty arg_tys msg = do { case mb_msg of Just msg -> addErrL msg Nothing -> return () ; return mb_ty } where (mb_ty, mb_msg) = cfa True fun_ty arg_tys cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result? , Maybe MsgDoc) -- Errors? cfa accurate fun_ty [] -- Args have run out; that's fine = (if accurate then Just fun_ty else Nothing, Nothing) cfa accurate fun_ty arg_tys@(arg_ty':arg_tys') | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty = if accurate && not (arg_ty `stgEqType` arg_ty') then (Nothing, Just msg) -- Arg type mismatch else cfa accurate res_ty arg_tys' | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty = cfa False fun_ty' arg_tys | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty , isNewTyCon tc = if length tc_args < tyConArity tc then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg ) (Nothing, Nothing) -- This is odd, but I've seen it else cfa False (newTyConInstRhs tc tc_args) arg_tys | Just tc <- tyConAppTyCon_maybe fun_ty , not (isTypeFamilyTyCon tc) -- Definite error = (Nothing, Just msg) -- Too many args | otherwise = (Nothing, Nothing) stgEqType :: Type -> Type -> Bool -- Compare types, but crudely because we have discarded -- both casts and type applications, so types might look -- different but be the same. So reply "True" if in doubt. -- "False" means that the types are definitely different. -- -- Fundamentally this is a losing battle because of unsafeCoerce stgEqType orig_ty1 orig_ty2 = gos (repType orig_ty1) (repType orig_ty2) where gos :: RepType -> RepType -> Bool gos (UbxTupleRep tys1) (UbxTupleRep tys2) = equalLength tys1 tys2 && and (zipWith go tys1 tys2) gos (UnaryRep ty1) (UnaryRep ty2) = go ty1 ty2 gos _ _ = False go :: UnaryType -> UnaryType -> Bool go ty1 ty2 | Just (tc1, tc_args1) <- splitTyConApp_maybe ty1 , Just (tc2, tc_args2) <- splitTyConApp_maybe ty2 , let res = if tc1 == tc2 then equalLength tc_args1 tc_args2 && and (zipWith (gos `on` repType) tc_args1 tc_args2) else -- TyCons don't match; but don't bleat if either is a -- family TyCon because a coercion might have made it -- equal to something else (isFamilyTyCon tc1 || isFamilyTyCon tc2) = if res then True else pprTrace "stgEqType: unequal" (vcat [ppr ty1, ppr ty2]) False | otherwise = True -- Conservatively say "fine". -- Type variables in particular checkInScope :: Id -> LintM () checkInScope id = LintM $ \loc scope errs -> if isLocalId id && not (id `elemVarSet` scope) then ((), addErr errs (hsep [ppr id, text "is out of scope"]) loc) else ((), errs) checkTys :: Type -> Type -> MsgDoc -> LintM () checkTys ty1 ty2 msg = LintM $ \loc _scope errs -> if (ty1 `stgEqType` ty2) then ((), errs) else ((), addErr errs msg loc) _mkCaseAltMsg :: [StgAlt] -> MsgDoc _mkCaseAltMsg _alts = ($$) (text "In some case alternatives, type of alternatives not all same:") (Outputable.empty) -- LATER: ppr alts mkDefltMsg :: Id -> TyCon -> MsgDoc mkDefltMsg bndr tc = ($$) (text "Binder of a case expression doesn't match type of scrutinee:") (ppr bndr $$ ppr (idType bndr) $$ ppr tc) mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc mkFunAppMsg fun_ty arg_tys expr = vcat [text "In a function application, function type doesn't match arg types:", hang (text "Function type:") 4 (ppr fun_ty), hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)), hang (text "Expression:") 4 (ppr expr)] mkRhsConMsg :: Type -> [Type] -> MsgDoc mkRhsConMsg fun_ty arg_tys = vcat [text "In a RHS constructor application, con type doesn't match arg types:", hang (text "Constructor type:") 4 (ppr fun_ty), hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))] mkAltMsg1 :: Type -> MsgDoc mkAltMsg1 ty = ($$) (text "In a case expression, type of scrutinee does not match patterns") (ppr ty) mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc mkAlgAltMsg2 ty con = vcat [ text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:", ppr ty, ppr con ] mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc mkAlgAltMsg3 con alts = vcat [ text "In some algebraic case alternative, number of arguments doesn't match constructor:", ppr con, ppr alts ] mkAlgAltMsg4 :: Type -> Id -> MsgDoc mkAlgAltMsg4 ty arg = vcat [ text "In some algebraic case alternative, type of argument doesn't match data constructor:", ppr ty, ppr arg ] _mkRhsMsg :: Id -> Type -> MsgDoc _mkRhsMsg binder ty = vcat [hsep [text "The type of this binder doesn't match the type of its RHS:", ppr binder], hsep [text "Binder's type:", ppr (idType binder)], hsep [text "Rhs type:", ppr ty] ] mkUnliftedTyMsg :: Id -> StgRhs -> SDoc mkUnliftedTyMsg binder rhs = (text "Let(rec) binder" <+> quotes (ppr binder) <+> text "has unlifted type" <+> quotes (ppr (idType binder))) $$ (text "RHS:" <+> ppr rhs)
GaloisInc/halvm-ghc
compiler/stgSyn/StgLint.hs
bsd-3-clause
18,096
0
19
5,271
4,775
2,436
2,339
-1
-1
module HasOffers.API.Brand.Advertiser where import Data.Text import GHC.Generics import Data.Aeson import Control.Applicative import Network.HTTP.Client import qualified Data.ByteString.Char8 as BS import HasOffers.API.Common -------------------------------------------------------------------------------- updateSignupQuestion :: [Text] -> Call updateSignupQuestion params = Call "Advertiser" "updateSignupQuestion" "POST" [ Param "question_id" True $ getParam params 0 , Param "data" True $ getParam params 1 ] updateSignupQuestionAnswer :: [Text] -> Call updateSignupQuestionAnswer params = Call "Advertiser" "updateSignupQuestionAnswer" "POST" [ Param "answer_id" True $ getParam params 0 , Param "data" True $ getParam params 1 ]
kelecorix/api-hasoffers
src/HasOffers/API/Brand/Advertiser.hs
bsd-3-clause
842
0
8
186
176
96
80
22
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- | Import this module qualified as follows: -- -- @ -- import qualified Money -- @ -- -- Note: This module exports support for many well-known currencies -- out-of-the-box, but you are not limited to the currencies mentioned here. You -- can simply create a new 'I.UnitScale' instance, and /voilà/. If you want to add a -- new currency to the out-of-the-box offer, please request so in -- https://github.com/k0001/safe-money/issues and the authors will see to it. -- -- This module offers plenty of documentation, but for a deep explanation of -- how all of the pieces fit together, please read -- <https://ren.zone/articles/safe-money>. Notice, however, that this library -- has changed a bit since that article was written. You can always see the -- [change log](https://github.com/k0001/safe-money/blob/master/changelog.md) to -- understand what has changed. -- -- Also, keep in mind that useful instances for the many types defined by -- @safe-money@ can be found in these other libraries: -- -- * [safe-money-aeson](https://hackage.haskell.org/package/safe-money-aeson): -- `FromJSON` and `ToJSON` instances (from the -- [aeson](https://hackage.haskell.org/package/aeson) library). -- -- * [safe-money-cereal](https://hackage.haskell.org/package/safe-money-cereal): -- `Serialize` instances (from the -- [cereal](https://hackage.haskell.org/package/cereal) library). -- -- * [safe-money-serialise](https://hackage.haskell.org/package/safe-money-serialise): -- `Serialise` instances (from the -- [serialise](https://hackage.haskell.org/package/serialise) library). -- -- * [safe-money-store](https://hackage.haskell.org/package/safe-money-store): -- `Store` instances (from the -- [store](https://hackage.haskell.org/package/store) library). -- -- * [safe-money-xmlbf](https://hackage.haskell.org/package/safe-money-xmlbf): -- `FromXml` and `ToXml` instances (from the -- [xmlbf](https://hackage.haskell.org/package/xmlbf) library). module Money ( -- * Dense monetary values I.Dense , I.denseCurrency , I.dense , I.dense' , I.denseFromDiscrete , I.denseFromDecimal , I.denseToDecimal -- * Discrete monetary values , I.Discrete , I.Discrete' , I.discrete , I.discreteCurrency , I.discreteFromDense , I.discreteFromDecimal , I.discreteToDecimal -- * Currency scales , I.Scale , I.scaleFromRational , I.scaleToRational , I.scale , I.UnitScale , I.CurrencyScale , I.GoodScale , I.ErrScaleNonCanonical -- * Currency exchange , I.ExchangeRate , I.exchangeRate , I.exchange , I.exchangeRateRecip , I.exchangeRateFromDecimal , I.exchangeRateToDecimal , I.exchangeRateToRational -- * Serializable representations , I.SomeDense , I.toSomeDense , I.mkSomeDense , I.fromSomeDense , I.withSomeDense , I.someDenseToDecimal , I.someDenseCurrency , I.someDenseAmount , I.SomeDiscrete , I.toSomeDiscrete , I.mkSomeDiscrete , I.fromSomeDiscrete , I.withSomeDiscrete , I.someDiscreteToDecimal , I.someDiscreteCurrency , I.someDiscreteScale , I.someDiscreteAmount , I.SomeExchangeRate , I.toSomeExchangeRate , I.mkSomeExchangeRate , I.fromSomeExchangeRate , I.withSomeExchangeRate , I.someExchangeRateToDecimal , I.someExchangeRateSrcCurrency , I.someExchangeRateDstCurrency , I.someExchangeRateRate -- * Miscellaneous , I.Approximation(..) -- ** Decimal config , I.DecimalConf(..) , I.defaultDecimalConf -- *** Separators , I.Separators , I.mkSeparators , I.separatorsComma , I.separatorsCommaDot , I.separatorsCommaNarrownbsp , I.separatorsCommaNbsp , I.separatorsCommaThinsp , I.separatorsCommaSpace , I.separatorsDot , I.separatorsDotComma , I.separatorsDotNarrownbsp , I.separatorsDotThinsp , I.separatorsDotNbsp , I.separatorsDotSpace ) where import qualified Money.Internal as I -------------------------------------------------------------------------------- -- Currency scales -- | United Arab Emirates dirham type instance I.CurrencyScale "AED" = I.UnitScale "AED" "fils" type instance I.UnitScale "AED" "dirham" = '(1, 1) type instance I.UnitScale "AED" "fils" = '(100, 1) -- | Afghan afghani type instance I.CurrencyScale "AFN" = I.UnitScale "AFN" "pul" type instance I.UnitScale "AFN" "afghani" = '(1, 1) type instance I.UnitScale "AFN" "pul" = '(100, 1) -- | Albanian lek type instance I.CurrencyScale "ALL" = I.UnitScale "ALL" "lek" type instance I.UnitScale "ALL" "lek" = '(1, 1) type instance I.UnitScale "ALL" "qindarke" = '(100, 1) -- | Armenian dram type instance I.CurrencyScale "AMD" = I.UnitScale "AMD" "luma" type instance I.UnitScale "AMD" "dram" = '(1, 1) type instance I.UnitScale "AMD" "luma" = '(100, 1) -- | Netherlands Antillean guilder type instance I.CurrencyScale "ANG" = I.UnitScale "AMD" "cent" type instance I.UnitScale "ANG" "guilder" = '(1, 1) type instance I.UnitScale "ANG" "cent" = '(100, 1) -- | Angolan kwanza type instance I.CurrencyScale "AOA" = I.UnitScale "AOA" "centimo" type instance I.UnitScale "AOA" "kwanza" = '(1, 1) type instance I.UnitScale "AOA" "centimo" = '(100, 1) -- | Argentine peso type instance I.CurrencyScale "ARS" = I.UnitScale "ARS" "centavo" type instance I.UnitScale "ARS" "peso" = '(1, 1) type instance I.UnitScale "ARS" "centavo" = '(100, 1) -- | Australian dollar type instance I.CurrencyScale "AUD" = I.UnitScale "AUD" "cent" type instance I.UnitScale "AUD" "dollar" = '(1, 1) type instance I.UnitScale "AUD" "cent" = '(100, 1) -- | Aruban florin type instance I.CurrencyScale "AWG" = I.UnitScale "AWG" "cent" type instance I.UnitScale "AWG" "florin" = '(1, 1) type instance I.UnitScale "AWG" "cent" = '(100, 1) -- | Azerbaijani manat type instance I.CurrencyScale "AZN" = I.UnitScale "AZN" "qapik" type instance I.UnitScale "AZN" "manat" = '(1, 1) type instance I.UnitScale "AZN" "qapik" = '(100, 1) -- | Bosnia and Herzegovina convertible mark type instance I.CurrencyScale "BAM" = I.UnitScale "BAM" "fenig" type instance I.UnitScale "BAM" "mark" = '(1, 1) type instance I.UnitScale "BAM" "fening" = '(100, 1) -- | Barbadian dollar type instance I.CurrencyScale "BBD" = I.UnitScale "BBD" "cent" type instance I.UnitScale "BBD" "dollar" = '(1, 1) type instance I.UnitScale "BBD" "cent" = '(100, 1) -- | Bangladeshi taka type instance I.CurrencyScale "BDT" = I.UnitScale "BDT" "paisa" type instance I.UnitScale "BDT" "taka" = '(1, 1) type instance I.UnitScale "BDT" "paisa" = '(100, 1) -- | Bulgarian lev type instance I.CurrencyScale "BGN" = I.UnitScale "BGN" "stotinka" type instance I.UnitScale "BGN" "lev" = '(1, 1) type instance I.UnitScale "BGN" "stotinka" = '(100, 1) -- | Bahraini dinar type instance I.CurrencyScale "BHD" = I.UnitScale "BHD" "fils" type instance I.UnitScale "BHD" "dinar" = '(1, 1) type instance I.UnitScale "BHD" "fils" = '(1000, 1) -- | Burundi franc type instance I.CurrencyScale "BIF" = I.UnitScale "BIF" "centime" type instance I.UnitScale "BIF" "franc" = '(1, 1) type instance I.UnitScale "BIF" "centime" = '(100, 1) -- | Bermudian dollar type instance I.CurrencyScale "BMD" = I.UnitScale "BMD" "cent" type instance I.UnitScale "BMD" "dollar" = '(1, 1) type instance I.UnitScale "BMD" "cent" = '(100, 1) -- | Brunei dollar type instance I.CurrencyScale "BND" = I.UnitScale "BND" "sen" type instance I.UnitScale "BND" "dollar" = '(1, 1) type instance I.UnitScale "BND" "sen" = '(100, 1) -- | Bolivian boliviano type instance I.CurrencyScale "BOB" = I.UnitScale "BOB" "centavo" type instance I.UnitScale "BOB" "boliviano" = '(1, 1) type instance I.UnitScale "BOB" "centavo" = '(100, 1) -- | Bolivian Mvdol type instance I.CurrencyScale "BOV" = '(100, 1) -- | Brazilian real type instance I.CurrencyScale "BRL" = I.UnitScale "BRL" "centavo" type instance I.UnitScale "BRL" "real" = '(1, 1) type instance I.UnitScale "BRL" "centavo" = '(100, 1) -- | Bahamian dollar type instance I.CurrencyScale "BSD" = I.UnitScale "BSD" "cent" type instance I.UnitScale "BSD" "dollar" = '(1, 1) type instance I.UnitScale "BSD" "cent" = '(100, 1) -- | Bhutanese ngultrum type instance I.CurrencyScale "BTN" = I.UnitScale "BTN" "chetrum" type instance I.UnitScale "BTN" "ngultrum" = '(1, 1) type instance I.UnitScale "BTN" "chetrum" = '(100, 1) -- | Botswana pula type instance I.CurrencyScale "BWP" = I.UnitScale "BWP" "thebe" type instance I.UnitScale "BWP" "pula" = '(1, 1) type instance I.UnitScale "BWP" "thebe" = '(100, 1) -- | Belarusian ruble type instance I.CurrencyScale "BYN" = I.UnitScale "BYN" "kapiejka" type instance I.UnitScale "BYN" "ruble" = '(1, 1) type instance I.UnitScale "BYN" "kapiejka" = '(100, 1) -- | Belarusian ruble type instance I.CurrencyScale "BYR" = I.UnitScale "BYR" "kapiejka" type instance I.UnitScale "BYR" "ruble" = '(1, 1) type instance I.UnitScale "BYR" "kapiejka" = '(100, 1) -- | Belize dollar type instance I.CurrencyScale "BZD" = I.UnitScale "BZD" "cent" type instance I.UnitScale "BZD" "dollar" = '(1, 1) type instance I.UnitScale "BZD" "cent" = '(100, 1) -- | Canadian dollar type instance I.CurrencyScale "CAD" = I.UnitScale "CAD" "cent" type instance I.UnitScale "CAD" "dollar" = '(1, 1) type instance I.UnitScale "CAD" "cent" = '(100, 1) -- | Congolese franc type instance I.CurrencyScale "CDF" = I.UnitScale "CDF" "centime" type instance I.UnitScale "CDF" "franc" = '(1, 1) type instance I.UnitScale "CDF" "centime" = '(100, 1) -- | WIR euro type instance I.CurrencyScale "CHE" = '(100, 1) -- | Swiss franc type instance I.CurrencyScale "CHF" = I.UnitScale "CHF" "rappen" type instance I.UnitScale "CHF" "franc" = '(1, 1) type instance I.UnitScale "CHF" "rappen" = '(100, 1) -- | WIR franc type instance I.CurrencyScale "CHW" = '(100, 1) -- | Chilean unidad de fomento type instance I.CurrencyScale "CLF" = '(10000, 1) -- | Chilean peso type instance I.CurrencyScale "CLP" = I.UnitScale "CLP" "centavo" type instance I.UnitScale "CLP" "peso" = '(1, 1) type instance I.UnitScale "CLP" "centavo" = '(100, 1) -- | Chinese Renminbi type instance I.CurrencyScale "CNY" = I.UnitScale "CNY" "fen" type instance I.UnitScale "CNY" "yuan" = '(1, 1) type instance I.UnitScale "CNY" "fen" = '(100, 1) -- | Colombian peso type instance I.CurrencyScale "COP" = I.UnitScale "COP" "centavo" type instance I.UnitScale "COP" "peso" = '(1, 1) type instance I.UnitScale "COP" "centavo" = '(100, 1) -- | Colombian unidad de valor real type instance I.CurrencyScale "COU" = '(100, 1) -- | Costa Rican colon type instance I.CurrencyScale "CRC" = I.UnitScale "CRC" "centimo" type instance I.UnitScale "CRC" "colon" = '(1, 1) type instance I.UnitScale "CRC" "centimo" = '(100, 1) -- | Cuban peso convertible type instance I.CurrencyScale "CUC" = I.UnitScale "CUC" "centavo" type instance I.UnitScale "CUC" "peso" = '(1, 1) type instance I.UnitScale "CUC" "centavo" = '(100, 1) -- | Cuban peso type instance I.CurrencyScale "CUP" = I.UnitScale "CUP" "centavo" type instance I.UnitScale "CUP" "peso" = '(1, 1) type instance I.UnitScale "CUP" "centavo" = '(100, 1) -- | Cape Verdean escudo type instance I.CurrencyScale "CVE" = I.UnitScale "CVE" "centavo" type instance I.UnitScale "CVE" "escudo" = '(1, 1) type instance I.UnitScale "CVE" "centavo" = '(100, 1) -- | Czech koruna type instance I.CurrencyScale "CZK" = I.UnitScale "CZK" "haler" type instance I.UnitScale "CZK" "koruna" = '(1, 1) type instance I.UnitScale "CZK" "haler" = '(100, 1) -- | Djiboutian franc type instance I.CurrencyScale "DJF" = I.UnitScale "DJF" "centime" type instance I.UnitScale "DJF" "franc" = '(1, 1) type instance I.UnitScale "DJF" "centime" = '(100, 1) -- | Danish krone type instance I.CurrencyScale "DKK" = I.UnitScale "DKK" "ore" type instance I.UnitScale "DKK" "krone" = '(1, 1) type instance I.UnitScale "DKK" "ore" = '(100, 1) -- | Dominican peso type instance I.CurrencyScale "DOP" = I.UnitScale "DOP" "centavo" type instance I.UnitScale "DOP" "peso" = '(1, 1) type instance I.UnitScale "DOP" "centavo" = '(100, 1) -- | Algerian dinar type instance I.CurrencyScale "DZD" = I.UnitScale "DZD" "santeem" type instance I.UnitScale "DZD" "dinar" = '(1, 1) type instance I.UnitScale "DZD" "santeem" = '(100, 1) -- | Egyptian pound type instance I.CurrencyScale "EGP" = I.UnitScale "EGP" "piastre" type instance I.UnitScale "EGP" "pound" = '(1, 1) type instance I.UnitScale "EGP" "piastre" = '(100, 1) -- | Eritrean nakfa type instance I.CurrencyScale "ERN" = I.UnitScale "ERN" "cent" type instance I.UnitScale "ERN" "nafka" = '(1, 1) type instance I.UnitScale "ERN" "cent" = '(100, 1) -- | Ethiopian birr type instance I.CurrencyScale "ETB" = I.UnitScale "ETB" "santim" type instance I.UnitScale "ETB" "birr" = '(1, 1) type instance I.UnitScale "ETB" "santim" = '(100, 1) -- | European euro type instance I.CurrencyScale "EUR" = I.UnitScale "EUR" "cent" type instance I.UnitScale "EUR" "euro" = '(1, 1) type instance I.UnitScale "EUR" "cent" = '(100, 1) -- | Fijian dollar type instance I.CurrencyScale "FJD" = I.UnitScale "FJD" "cent" type instance I.UnitScale "FJD" "dollar" = '(1, 1) type instance I.UnitScale "FJD" "cent" = '(100, 1) -- | Falkland Islands pound type instance I.CurrencyScale "FKP" = I.UnitScale "FKP" "penny" type instance I.UnitScale "FKP" "pound" = '(1, 1) type instance I.UnitScale "FKP" "penny" = '(100, 1) -- | Pound sterling type instance I.CurrencyScale "GBP" = I.UnitScale "GBP" "penny" type instance I.UnitScale "GBP" "pound" = '(1, 1) type instance I.UnitScale "GBP" "penny" = '(100, 1) -- | Georgian lari type instance I.CurrencyScale "GEL" = I.UnitScale "GEL" "tetri" type instance I.UnitScale "GEL" "lari" = '(1, 1) type instance I.UnitScale "GEL" "tetri" = '(100, 1) -- | Ghanaian cedi type instance I.CurrencyScale "GHS" = I.UnitScale "GHS" "pesewa" type instance I.UnitScale "GHS" "cedi" = '(1, 1) type instance I.UnitScale "GHS" "pesewa" = '(100, 1) -- | Gibraltar pound type instance I.CurrencyScale "GIP" = I.UnitScale "GIP" "penny" type instance I.UnitScale "GIP" "pound" = '(1, 1) type instance I.UnitScale "GIP" "penny" = '(100, 1) -- | Gambian dalasi type instance I.CurrencyScale "GMD" = I.UnitScale "GMD" "butut" type instance I.UnitScale "GMD" "dalasi" = '(1, 1) type instance I.UnitScale "GMD" "butut" = '(100, 1) -- | Guinean franc type instance I.CurrencyScale "GNF" = I.UnitScale "GNF" "centime" type instance I.UnitScale "GNF" "franc" = '(1, 1) type instance I.UnitScale "GNF" "centime" = '(100, 1) -- | Guatemalan quetzal type instance I.CurrencyScale "GTQ" = I.UnitScale "GTQ" "centavo" type instance I.UnitScale "GTQ" "quetzal" = '(1, 1) type instance I.UnitScale "GTQ" "centavo" = '(100, 1) -- | Guyanese dollar type instance I.CurrencyScale "GYD" = I.UnitScale "GYD" "cent" type instance I.UnitScale "GYD" "dollar" = '(1, 1) type instance I.UnitScale "GYD" "cent" = '(100, 1) -- | Hong Kong dollar type instance I.CurrencyScale "HKD" = I.UnitScale "HKD" "cent" type instance I.UnitScale "HKD" "dollar" = '(1, 1) type instance I.UnitScale "HKD" "cent" = '(100, 1) -- | Honduran lempira type instance I.CurrencyScale "HNL" = I.UnitScale "HNL" "centavo" type instance I.UnitScale "HNL" "lempira" = '(1, 1) type instance I.UnitScale "HNL" "centavo" = '(100, 1) -- | Croatian kuna type instance I.CurrencyScale "HRK" = I.UnitScale "HRK" "lipa" type instance I.UnitScale "HRK" "kuna" = '(1, 1) type instance I.UnitScale "HRK" "lipa" = '(100, 1) -- | Haitian gourde type instance I.CurrencyScale "HTG" = I.UnitScale "HTG" "centime" type instance I.UnitScale "HTG" "gourde" = '(1, 1) type instance I.UnitScale "HTG" "centime" = '(100, 1) -- | Hungarian forint type instance I.CurrencyScale "HUF" = I.UnitScale "HUF" "filler" type instance I.UnitScale "HUF" "forint" = '(1, 1) type instance I.UnitScale "HUF" "filler" = '(100, 1) -- | Indonesian rupiah type instance I.CurrencyScale "IDR" = I.UnitScale "IDR" "sen" type instance I.UnitScale "IDR" "rupiah" = '(1, 1) type instance I.UnitScale "IDR" "sen" = '(100, 1) -- | Israeli new shekel type instance I.CurrencyScale "ILS" = I.UnitScale "ILS" "agora" type instance I.UnitScale "ILS" "shekel" = '(1, 1) type instance I.UnitScale "ILS" "agora" = '(100, 1) -- | Indian rupee type instance I.CurrencyScale "INR" = I.UnitScale "INR" "paisa" type instance I.UnitScale "INR" "rupee" = '(1, 1) type instance I.UnitScale "INR" "paisa" = '(100, 1) -- | Iraqi dinar type instance I.CurrencyScale "IQD" = I.UnitScale "IQD" "fils" type instance I.UnitScale "IQD" "dinar" = '(1, 1) type instance I.UnitScale "IQD" "fils" = '(1000, 1) -- | Iranian rial type instance I.CurrencyScale "IRR" = I.UnitScale "IRR" "dinar" type instance I.UnitScale "IRR" "rial" = '(1, 1) type instance I.UnitScale "IRR" "dinar" = '(100, 1) -- | Icelandic króna type instance I.CurrencyScale "ISK" = I.UnitScale "ISK" "eyrir" type instance I.UnitScale "ISK" "krona" = '(1, 1) type instance I.UnitScale "ISK" "eyrir" = '(100, 1) -- | Jamaican dollar type instance I.CurrencyScale "JMD" = I.UnitScale "JMD" "cent" type instance I.UnitScale "JMD" "dollar" = '(1, 1) type instance I.UnitScale "JMD" "cent" = '(100, 1) -- | Jordanian dinar type instance I.CurrencyScale "JOD" = I.UnitScale "JOD" "piastre" type instance I.UnitScale "JOD" "dinar" = '(1, 1) type instance I.UnitScale "JOD" "piastre" = '(100, 1) -- | Japanese yen type instance I.CurrencyScale "JPY" = I.UnitScale "JPY" "sen" type instance I.UnitScale "JPY" "yen" = '(1, 1) type instance I.UnitScale "JPY" "sen" = '(100, 1) -- | Kenyan shilling type instance I.CurrencyScale "KES" = I.UnitScale "KES" "cent" type instance I.UnitScale "KES" "shilling" = '(1, 1) type instance I.UnitScale "KES" "cent" = '(100, 1) -- | Kyrgyzstani som type instance I.CurrencyScale "KGS" = I.UnitScale "KGS" "tyiyn" type instance I.UnitScale "KGS" "som" = '(1, 1) type instance I.UnitScale "KGS" "tyiyn" = '(100, 1) -- | Cambodian riel type instance I.CurrencyScale "KHR" = I.UnitScale "KHR" "sen" type instance I.UnitScale "KHR" "riel" = '(1, 1) type instance I.UnitScale "KHR" "sen" = '(100, 1) -- | Comorian franc type instance I.CurrencyScale "KMF" = I.UnitScale "KMF" "centime" type instance I.UnitScale "KMF" "franc" = '(1, 1) type instance I.UnitScale "KMF" "centime" = '(100, 1) -- | North Korean won type instance I.CurrencyScale "KPW" = I.UnitScale "KPW" "chon" type instance I.UnitScale "KPW" "won" = '(1, 1) type instance I.UnitScale "KPW" "chon" = '(100, 1) -- | South Korean won type instance I.CurrencyScale "KRW" = I.UnitScale "KRW" "jeon" type instance I.UnitScale "KRW" "won" = '(1, 1) type instance I.UnitScale "KRW" "jeon" = '(100, 1) -- | Kuwaiti dinar type instance I.CurrencyScale "KWD" = I.UnitScale "KWD" "fils" type instance I.UnitScale "KWD" "dinar" = '(1, 1) type instance I.UnitScale "KWD" "fils" = '(1000, 1) -- | Cayman Islands dollar type instance I.CurrencyScale "KYD" = I.UnitScale "KYD" "cent" type instance I.UnitScale "KYD" "dollar" = '(1, 1) type instance I.UnitScale "KYD" "cent" = '(100, 1) -- | Kazakhstani tenge type instance I.CurrencyScale "KZT" = I.UnitScale "KZT" "tiyin" type instance I.UnitScale "KZT" "tenge" = '(1, 1) type instance I.UnitScale "KZT" "tiyin" = '(100, 1) -- | Lao kip type instance I.CurrencyScale "LAK" = I.UnitScale "LAK" "att" type instance I.UnitScale "LAK" "kip" = '(1, 1) type instance I.UnitScale "LAK" "att" = '(100, 1) -- | Lebanese pound type instance I.CurrencyScale "LBP" = I.UnitScale "LBP" "piastre" type instance I.UnitScale "LBP" "pound" = '(1, 1) type instance I.UnitScale "LBP" "piastre" = '(100, 1) -- | Sri Lankan rupee type instance I.CurrencyScale "LKR" = I.UnitScale "LKR" "cent" type instance I.UnitScale "LKR" "rupee" = '(1, 1) type instance I.UnitScale "LKR" "cent" = '(100, 1) -- | Liberian dollar type instance I.CurrencyScale "LRD" = I.UnitScale "LRD" "cent" type instance I.UnitScale "LRD" "dollar" = '(1, 1) type instance I.UnitScale "LRD" "cent" = '(100, 1) -- | Lesotho loti type instance I.CurrencyScale "LSL" = I.UnitScale "LSL" "sente" type instance I.UnitScale "LSL" "loti" = '(1, 1) type instance I.UnitScale "LSL" "sente" = '(100, 1) -- | Libyan dinar type instance I.CurrencyScale "LYD" = I.UnitScale "LYD" "dirham" type instance I.UnitScale "LYD" "dinar" = '(1, 1) type instance I.UnitScale "LYD" "dirham" = '(1000, 1) -- | Moroccan dirham type instance I.CurrencyScale "MAD" = I.UnitScale "MAD" "centime" type instance I.UnitScale "MAD" "dirham" = '(1, 1) type instance I.UnitScale "MAD" "centime" = '(100, 1) -- | Moldovan leu type instance I.CurrencyScale "MDL" = I.UnitScale "MDL" "ban" type instance I.UnitScale "MDL" "leu" = '(1, 1) type instance I.UnitScale "MDL" "ban" = '(100, 1) -- | Malagasy ariary type instance I.CurrencyScale "MGA" = I.UnitScale "MGA" "iraimbilanja" type instance I.UnitScale "MGA" "ariary" = '(1, 1) type instance I.UnitScale "MGA" "iraimbilanja" = '(5, 1) -- | Macedonian denar type instance I.CurrencyScale "MKD" = I.UnitScale "MKD" "deni" type instance I.UnitScale "MKD" "denar" = '(1, 1) type instance I.UnitScale "MKD" "deni" = '(100, 1) -- | Myanmar kyat type instance I.CurrencyScale "MMK" = I.UnitScale "MMK" "pya" type instance I.UnitScale "MMK" "kyat" = '(1, 1) type instance I.UnitScale "MMK" "pya" = '(100, 1) -- | Mongolian tugrik type instance I.CurrencyScale "MNT" = I.UnitScale "MNT" "mongo" type instance I.UnitScale "MNT" "tugrik" = '(1, 1) type instance I.UnitScale "MNT" "mongo" = '(100, 1) -- | Macanese pataca type instance I.CurrencyScale "MOP" = I.UnitScale "MOP" "avo" type instance I.UnitScale "MOP" "pataca" = '(1, 1) type instance I.UnitScale "MOP" "avo" = '(100, 1) -- | Mauritanian ouguiya type instance I.CurrencyScale "MRO" = I.UnitScale "MRO" "khoums" type instance I.UnitScale "MRO" "ouguiya" = '(1, 1) type instance I.UnitScale "MRO" "khoums" = '(5, 1) -- | Mauritian rupee type instance I.CurrencyScale "MUR" = I.UnitScale "MUR" "cent" type instance I.UnitScale "MUR" "rupee" = '(1, 1) type instance I.UnitScale "MUR" "cent" = '(100, 1) -- | Maldivian rufiyaa type instance I.CurrencyScale "MVR" = I.UnitScale "MVR" "laari" type instance I.UnitScale "MVR" "rufiyaa" = '(1, 1) type instance I.UnitScale "MVR" "laari" = '(100, 1) -- | Malawian kwacha type instance I.CurrencyScale "MWK" = I.UnitScale "MWK" "tambala" type instance I.UnitScale "MWK" "kwacha" = '(1, 1) type instance I.UnitScale "MWK" "tambala" = '(100, 1) -- | Mexican peso type instance I.CurrencyScale "MXN" = I.UnitScale "MXN" "centavo" type instance I.UnitScale "MXN" "peso" = '(1, 1) type instance I.UnitScale "MXN" "centavo" = '(100, 1) -- | Mexican unidad de inversion type instance I.CurrencyScale "MXV" = '(100, 1) -- | Malaysian ringgit type instance I.CurrencyScale "MYR" = I.UnitScale "MYR" "sen" type instance I.UnitScale "MYR" "ringgit" = '(1, 1) type instance I.UnitScale "MYR" "sen" = '(100, 1) -- | Mozambican metical type instance I.CurrencyScale "MZN" = I.UnitScale "MZN" "centavo" type instance I.UnitScale "MZN" "metical" = '(1, 1) type instance I.UnitScale "MZN" "centavo" = '(100, 1) -- | Namibian dollar type instance I.CurrencyScale "NAD" = I.UnitScale "NAD" "cent" type instance I.UnitScale "NAD" "dollar" = '(1, 1) type instance I.UnitScale "NAD" "cent" = '(100, 1) -- | Nigerian naira type instance I.CurrencyScale "NGN" = I.UnitScale "NGN" "kobo" type instance I.UnitScale "NGN" "naira" = '(1, 1) type instance I.UnitScale "NGN" "kobo" = '(100, 1) -- | Nicaraguan cordoba type instance I.CurrencyScale "NIO" = I.UnitScale "NIO" "centavo" type instance I.UnitScale "NIO" "cordoba" = '(1, 1) type instance I.UnitScale "NIO" "centavo" = '(100, 1) -- | Norwegian krone type instance I.CurrencyScale "NOK" = I.UnitScale "NOK" "ore" type instance I.UnitScale "NOK" "krone" = '(1, 1) type instance I.UnitScale "NOK" "ore" = '(100, 1) -- | Nepalese rupee type instance I.CurrencyScale "NPR" = I.UnitScale "NPR" "paisa" type instance I.UnitScale "NPR" "rupee" = '(1, 1) type instance I.UnitScale "NPR" "paisa" = '(100, 1) -- | New Zealand dollar type instance I.CurrencyScale "NZD" = I.UnitScale "NZD" "cent" type instance I.UnitScale "NZD" "dollar" = '(1, 1) type instance I.UnitScale "NZD" "cent" = '(100, 1) -- | Omani rial type instance I.CurrencyScale "OMR" = I.UnitScale "OMR" "baisa" type instance I.UnitScale "OMR" "rial" = '(1, 1) type instance I.UnitScale "OMR" "baisa" = '(1000, 1) -- | Panamenian balboa type instance I.CurrencyScale "PAB" = I.UnitScale "PAB" "centesimo" type instance I.UnitScale "PAB" "balboa" = '(1, 1) type instance I.UnitScale "PAB" "centesimo" = '(100, 1) -- | Peruvian sol type instance I.CurrencyScale "PEN" = I.UnitScale "PEN" "centimo" type instance I.UnitScale "PEN" "sol" = '(1, 1) type instance I.UnitScale "PEN" "centimo" = '(100, 1) -- | Papua New Guinean kina type instance I.CurrencyScale "PGK" = I.UnitScale "PGK" "toea" type instance I.UnitScale "PGK" "kina" = '(1, 1) type instance I.UnitScale "PGK" "toea" = '(100, 1) -- | Philippine peso type instance I.CurrencyScale "PHP" = I.UnitScale "PHP" "centavo" type instance I.UnitScale "PHP" "peso" = '(1, 1) type instance I.UnitScale "PHP" "centavo" = '(100, 1) -- | Pakistani rupee type instance I.CurrencyScale "PKR" = I.UnitScale "PKR" "paisa" type instance I.UnitScale "PKR" "rupee" = '(1, 1) type instance I.UnitScale "PKR" "paisa" = '(100, 1) -- | Polish zloty type instance I.CurrencyScale "PLN" = I.UnitScale "PLN" "grosz" type instance I.UnitScale "PLN" "zloty" = '(1, 1) type instance I.UnitScale "PLN" "grosz" = '(100, 1) -- | Paraguayan guarani type instance I.CurrencyScale "PYG" = I.UnitScale "PYG" "centimo" type instance I.UnitScale "PYG" "guarani" = '(1, 1) type instance I.UnitScale "PYG" "centimo" = '(100, 1) -- | Qatari riyal type instance I.CurrencyScale "QAR" = I.UnitScale "QAR" "dirham" type instance I.UnitScale "QAR" "riyal" = '(1, 1) type instance I.UnitScale "QAR" "dirham" = '(100, 1) -- | Romanian leu type instance I.CurrencyScale "RON" = I.UnitScale "RON" "ban" type instance I.UnitScale "RON" "leu" = '(1, 1) type instance I.UnitScale "RON" "ban" = '(100, 1) -- | Serbian dinar type instance I.CurrencyScale "RSD" = I.UnitScale "RSD" "para" type instance I.UnitScale "RSD" "dinar" = '(1, 1) type instance I.UnitScale "RSD" "para" = '(100, 1) -- | Russian ruble type instance I.CurrencyScale "RUB" = I.UnitScale "RUB" "kopek" type instance I.UnitScale "RUB" "ruble" = '(1, 1) type instance I.UnitScale "RUB" "kopek" = '(100, 1) -- | Rwandan franc type instance I.CurrencyScale "RWF" = I.UnitScale "RWF" "centime" type instance I.UnitScale "RWF" "franc" = '(1, 1) type instance I.UnitScale "RWF" "centime" = '(100, 1) -- | Saudi Arabian riyal type instance I.CurrencyScale "SAR" = I.UnitScale "SAR" "halala" type instance I.UnitScale "SAR" "riyal" = '(1, 1) type instance I.UnitScale "SAR" "halala" = '(100, 1) -- | Solomon Islands dollar type instance I.CurrencyScale "SBD" = I.UnitScale "SBD" "cent" type instance I.UnitScale "SBD" "dollar" = '(1, 1) type instance I.UnitScale "SBD" "cent" = '(100, 1) -- | Seychellois rupee type instance I.CurrencyScale "SCR" = I.UnitScale "SCR" "cent" type instance I.UnitScale "SCR" "rupee" = '(1, 1) type instance I.UnitScale "SCR" "cent" = '(100, 1) -- | Sudanese pound type instance I.CurrencyScale "SDG" = I.UnitScale "SDG" "piastre" type instance I.UnitScale "SDG" "pound" = '(1, 1) type instance I.UnitScale "SDG" "piastre" = '(100, 1) -- | Swedish krona type instance I.CurrencyScale "SEK" = I.UnitScale "SEK" "ore" type instance I.UnitScale "SEK" "krona" = '(1, 1) type instance I.UnitScale "SEK" "ore" = '(100, 1) -- | Singapore dollar type instance I.CurrencyScale "SGD" = I.UnitScale "SGD" "cent" type instance I.UnitScale "SGD" "dollar" = '(1, 1) type instance I.UnitScale "SGD" "cent" = '(100, 1) -- | Saint Helena pound type instance I.CurrencyScale "SHP" = I.UnitScale "SHP" "penny" type instance I.UnitScale "SHP" "pound" = '(1, 1) type instance I.UnitScale "SHP" "penny" = '(100, 1) -- | Sierra Leonean leone type instance I.CurrencyScale "SLL" = I.UnitScale "SLL" "cent" type instance I.UnitScale "SLL" "leone" = '(1, 1) type instance I.UnitScale "SLL" "cent" = '(100, 1) -- | Somali shilling type instance I.CurrencyScale "SOS" = I.UnitScale "SOS" "cent" type instance I.UnitScale "SOS" "shilling" = '(1, 1) type instance I.UnitScale "SOS" "cent" = '(100, 1) -- | Surinamese dollar type instance I.CurrencyScale "SRD" = I.UnitScale "SRD" "cent" type instance I.UnitScale "SRD" "dollar" = '(1, 1) type instance I.UnitScale "SRD" "cent" = '(100, 1) -- | South Sudanese pound type instance I.CurrencyScale "SSP" = I.UnitScale "SSP" "piastre" type instance I.UnitScale "SSP" "pound" = '(1, 1) type instance I.UnitScale "SSP" "piastre" = '(100, 1) -- | Sao Tome and Principe dobra type instance I.CurrencyScale "STD" = I.UnitScale "STD" "centimo" type instance I.UnitScale "STD" "dobra" = '(1, 1) type instance I.UnitScale "STD" "centimo" = '(100, 1) -- | Salvadoran colon type instance I.CurrencyScale "SVC" = I.UnitScale "SVC" "centavo" type instance I.UnitScale "SVC" "colon" = '(1, 1) type instance I.UnitScale "SVC" "centavo" = '(100, 1) -- | Syrian pound type instance I.CurrencyScale "SYP" = I.UnitScale "SYP" "piastre" type instance I.UnitScale "SYP" "pound" = '(1, 1) type instance I.UnitScale "SYP" "piastre" = '(100, 1) -- | Swazi lilangeni type instance I.CurrencyScale "SZL" = I.UnitScale "SZL" "cent" type instance I.UnitScale "SZL" "lilangeni" = '(1, 1) type instance I.UnitScale "SZL" "cent" = '(100, 1) -- | Thai baht type instance I.CurrencyScale "THB" = I.UnitScale "THB" "satang" type instance I.UnitScale "THB" "baht" = '(1, 1) type instance I.UnitScale "THB" "satang" = '(100, 1) -- | Tajikistani somoni type instance I.CurrencyScale "TJS" = I.UnitScale "TJS" "diram" type instance I.UnitScale "TJS" "somoni" = '(1, 1) type instance I.UnitScale "TJS" "diram" = '(100, 1) -- | Turkmen manat type instance I.CurrencyScale "TMT" = I.UnitScale "TMT" "tennesi" type instance I.UnitScale "TMT" "manat" = '(1, 1) type instance I.UnitScale "TMT" "tennesi" = '(100, 1) -- | Tunisian dinar type instance I.CurrencyScale "TND" = I.UnitScale "TND" "millime" type instance I.UnitScale "TND" "dinar" = '(1, 1) type instance I.UnitScale "TND" "millime" = '(1000, 1) -- | Tongan pa’anga type instance I.CurrencyScale "TOP" = I.UnitScale "TOP" "seniti" type instance I.UnitScale "TOP" "pa'anga" = '(1, 1) type instance I.UnitScale "TOP" "seniti" = '(100, 1) -- | Turkish lira type instance I.CurrencyScale "TRY" = I.UnitScale "TRY" "kurus" type instance I.UnitScale "TRY" "lira" = '(1, 1) type instance I.UnitScale "TRY" "kurus" = '(100, 1) -- | Tobago Trinidad and Tobago dollar type instance I.CurrencyScale "TTD" = I.UnitScale "TTD" "cent" type instance I.UnitScale "TTD" "dollar" = '(1, 1) type instance I.UnitScale "TTD" "cent" = '(100, 1) -- | New Taiwan dollar type instance I.CurrencyScale "TWD" = I.UnitScale "TWD" "cent" type instance I.UnitScale "TWD" "dollar" = '(1, 1) type instance I.UnitScale "TWD" "cent" = '(100, 1) -- | Tanzanian shilling type instance I.CurrencyScale "TZS" = I.UnitScale "TZS" "cent" type instance I.UnitScale "TZS" "shilling" = '(1, 1) type instance I.UnitScale "TZS" "cent" = '(100, 1) -- | Ukrainian hryvnia type instance I.CurrencyScale "UAH" = I.UnitScale "UAH" "kopiyka" type instance I.UnitScale "UAH" "hryvnia" = '(1, 1) type instance I.UnitScale "UAH" "kopiyka" = '(100, 1) -- | Ugandan shilling type instance I.CurrencyScale "UGX" = I.UnitScale "UGX" "cent" type instance I.UnitScale "UGX" "shilling" = '(1, 1) type instance I.UnitScale "UGX" "cent" = '(100, 1) -- | United States dollar type instance I.CurrencyScale "USD" = I.UnitScale "USD" "cent" type instance I.UnitScale "USD" "dollar" = '(1, 1) type instance I.UnitScale "USD" "cent" = '(100, 1) -- | United States dollar (next day) type instance I.CurrencyScale "USN" = I.UnitScale "USN" "cent" type instance I.UnitScale "USN" "dollar" = '(1, 1) type instance I.UnitScale "USN" "cent" = '(100, 1) -- | Uruguayan peso en unidades indexadas type instance I.CurrencyScale "UYI" = '(1, 1) -- | Uruguayan peso type instance I.CurrencyScale "UYU" = I.UnitScale "UYU" "centesimo" type instance I.UnitScale "UYU" "peso" = '(1, 1) type instance I.UnitScale "UYU" "centesimo" = '(100, 1) -- | Uruguayan unidad previsional type instance I.CurrencyScale "UYW" = '(10000, 1) -- | Uzbekistani som type instance I.CurrencyScale "UZS" = I.UnitScale "UZS" "tiyin" type instance I.UnitScale "UZS" "som" = '(1, 1) type instance I.UnitScale "UZS" "tiyin" = '(100, 1) -- | Venezuelan bolivar fuerte type instance I.CurrencyScale "VEF" = I.UnitScale "VEF" "centimo" type instance I.UnitScale "VEF" "bolivar" = '(1, 1) type instance I.UnitScale "VEF" "centimo" = '(100, 1) -- | Venezuelan bolivar soberano type instance I.CurrencyScale "VES" = I.UnitScale "VES" "centimo" type instance I.UnitScale "VES" "bolivar" = '(1, 1) type instance I.UnitScale "VES" "centimo" = '(100, 1) -- | Vietnamese dong type instance I.CurrencyScale "VND" = I.UnitScale "VND" "hao" type instance I.UnitScale "VND" "dong" = '(1, 1) type instance I.UnitScale "VND" "hao" = '(10, 1) -- | Vanuatu vatu type instance I.CurrencyScale "VUV" = I.UnitScale "VUV" "vatu" type instance I.UnitScale "VUV" "vatu" = '(1, 1) -- | Samoan tālā type instance I.CurrencyScale "WST" = I.UnitScale "WST" "sene" type instance I.UnitScale "WST" "tala" = '(1, 1) type instance I.UnitScale "WST" "sene" = '(100, 1) -- | Central African CFA franc type instance I.CurrencyScale "XAF" = I.UnitScale "XAF" "centime" type instance I.UnitScale "XAF" "franc" = '(1, 1) type instance I.UnitScale "XAF" "centime" = '(100, 1) -- | East Caribbean dollar type instance I.CurrencyScale "XCD" = I.UnitScale "XCD" "cent" type instance I.UnitScale "XCD" "dollar" = '(1, 1) type instance I.UnitScale "XCD" "cent" = '(100, 1) -- | International Monetary Fund Special Drawing Right type instance I.CurrencyScale "XDR" = '(1, 1) -- | West African CFA franc type instance I.CurrencyScale "XOF" = I.UnitScale "XOF" "centime" type instance I.UnitScale "XOF" "franc" = '(1, 1) type instance I.UnitScale "XOF" "centime" = '(100, 1) -- | CFP franc type instance I.CurrencyScale "XPF" = I.UnitScale "XPF" "centime" type instance I.UnitScale "XPF" "franc" = '(1, 1) type instance I.UnitScale "XPF" "centime" = '(100, 1) -- | Sucre type instance I.CurrencyScale "XSU" = '(1, 1) -- | African Development Bank unit of account type instance I.CurrencyScale "XUA" = '(1, 1) -- | Yemeni rial type instance I.CurrencyScale "YER" = I.UnitScale "YER" "fils" type instance I.UnitScale "YER" "rial" = '(1, 1) type instance I.UnitScale "YER" "fils" = '(100, 1) -- | South African rand type instance I.CurrencyScale "ZAR" = I.UnitScale "ZAR" "cent" type instance I.UnitScale "ZAR" "rand" = '(1, 1) type instance I.UnitScale "ZAR" "cent" = '(100, 1) -- | Zambian kwacha type instance I.CurrencyScale "ZMW" = I.UnitScale "ZMW" "ngwee" type instance I.UnitScale "ZMW" "kwacha" = '(1, 1) type instance I.UnitScale "ZMW" "ngwee" = '(100, 1) -- | Zimbawe dollar type instance I.CurrencyScale "ZWL" = I.UnitScale "ZWL" "cent" type instance I.UnitScale "ZWL" "dollar" = '(1, 1) type instance I.UnitScale "ZWL" "cent" = '(100, 1) -- | Gold. No canonical smallest unit. Unusable instance. type instance I.CurrencyScale "XAU" = I.ErrScaleNonCanonical "XAU" type instance I.UnitScale "XAU" "troy-ounce" = '(1, 1) type instance I.UnitScale "XAU" "grain" = '(480, 1) type instance I.UnitScale "XAU" "milligrain" = '(480000, 1) type instance I.UnitScale "XAU" "micrograin" = '(480000000, 1) type instance I.UnitScale "XAU" "kilogram" = '(31103477, 1000000000) type instance I.UnitScale "XAU" "gram" = '(31103477, 1000000) type instance I.UnitScale "XAU" "milligram" = '(31103477, 1000) type instance I.UnitScale "XAU" "microgram" = '(31103477, 1) -- | Silver. No canonical smallest unit. Unusable instance. type instance I.CurrencyScale "XAG" = I.ErrScaleNonCanonical "XAU" type instance I.UnitScale "XAG" "troy-ounce" = '(1, 1) type instance I.UnitScale "XAG" "grain" = '(480, 1) type instance I.UnitScale "XAG" "milligrain" = '(480000, 1) type instance I.UnitScale "XAG" "micrograin" = '(480000000, 1) type instance I.UnitScale "XAG" "kilogram" = '(31103477, 1000000000) type instance I.UnitScale "XAG" "gram" = '(31103477, 1000000) type instance I.UnitScale "XAG" "milligram" = '(31103477, 1000) type instance I.UnitScale "XAG" "microgram" = '(31103477, 1) -- | Palladium. No canonical smallest unit. Unusable instance. type instance I.CurrencyScale "XPD" = I.ErrScaleNonCanonical "XPD" type instance I.UnitScale "XPD" "troy-ounce" = '(1, 1) type instance I.UnitScale "XPD" "grain" = '(480, 1) type instance I.UnitScale "XPD" "milligrain" = '(480000, 1) type instance I.UnitScale "XPD" "micrograin" = '(480000000, 1) type instance I.UnitScale "XPD" "kilogram" = '(31103477, 1000000000) type instance I.UnitScale "XPD" "gram" = '(31103477, 1000000) type instance I.UnitScale "XPD" "milligram" = '(31103477, 1000) type instance I.UnitScale "XPD" "microgram" = '(31103477, 1) -- | Platinum. No canonical smallest unit. Unusable instance. type instance I.CurrencyScale "XPT" = I.ErrScaleNonCanonical "XPT" type instance I.UnitScale "XPT" "troy-ounce" = '(1, 1) type instance I.UnitScale "XPT" "grain" = '(480, 1) type instance I.UnitScale "XPT" "milligrain" = '(480000, 1) type instance I.UnitScale "XPT" "micrograin" = '(480000000, 1) type instance I.UnitScale "XPT" "kilogram" = '(31103477, 1000000000) type instance I.UnitScale "XPT" "gram" = '(31103477, 1000000) type instance I.UnitScale "XPT" "milligram" = '(31103477, 1000) type instance I.UnitScale "XPT" "microgram" = '(31103477, 1) -- | Bitcoin type instance I.CurrencyScale "BTC" = I.UnitScale "BTC" "satoshi" type instance I.UnitScale "BTC" "bitcoin" = '(1, 1) type instance I.UnitScale "BTC" "millibitcoin" = '(1000, 1) type instance I.UnitScale "BTC" "satoshi" = '(100000000, 1) -- | Bitcoin type instance I.CurrencyScale "XBT" = I.CurrencyScale "BTC" type instance I.UnitScale "XBT" "bitcoin" = I.UnitScale "BTC" "bitcoin" type instance I.UnitScale "XBT" "millibitcoin" = I.UnitScale "BTC" "millibitcoin" type instance I.UnitScale "XBT" "satoshi" = I.UnitScale "BTC" "satoshi" -- | Ether type instance I.CurrencyScale "ETH" = I.UnitScale "ETH" "wei" type instance I.UnitScale "ETH" "ether" = '(1, 1) type instance I.UnitScale "ETH" "kwei" = '(1000, 1) type instance I.UnitScale "ETH" "babbage" = '(1000, 1) type instance I.UnitScale "ETH" "mwei" = '(1000000, 1) type instance I.UnitScale "ETH" "lovelace" = '(1000000, 1) type instance I.UnitScale "ETH" "gwei" = '(1000000000, 1) type instance I.UnitScale "ETH" "shannon" = '(1000000000, 1) type instance I.UnitScale "ETH" "microether" = '(1000000000000, 1) type instance I.UnitScale "ETH" "szabo" = '(1000000000000, 1) type instance I.UnitScale "ETH" "finney" = '(1000000000000000, 1) type instance I.UnitScale "ETH" "milliether" = '(1000000000000000, 1) type instance I.UnitScale "ETH" "wei" = '(1000000000000000000, 1) -- | Cardano type instance I.CurrencyScale "ADA" = I.UnitScale "ADA" "lovelace" type instance I.UnitScale "ADA" "ada" = '(1, 1) type instance I.UnitScale "ADA" "lovelace" = '(1000000, 1) -- | Litecoin type instance I.CurrencyScale "LTC" = I.UnitScale "LTC" "photon" type instance I.UnitScale "LTC" "litecoin" = '(1, 1) type instance I.UnitScale "LTC" "lite" = '(1000, 1) type instance I.UnitScale "LTC" "photon" = '(100000000, 1) -- | Ripple type instance I.CurrencyScale "XRP" = I.UnitScale "XRP" "drop" type instance I.UnitScale "XRP" "ripple" = '(1, 1) type instance I.UnitScale "XRP" "drop" = '(1000000, 1) -- | Monero type instance I.CurrencyScale "XMR" = I.UnitScale "XMR" "piconero" type instance I.UnitScale "XMR" "monero" = '(1, 1) type instance I.UnitScale "XMR" "decinero" = '(10, 1) type instance I.UnitScale "XMR" "centinero" = '(100, 1) type instance I.UnitScale "XMR" "millinero" = '(1000, 1) type instance I.UnitScale "XMR" "micronero" = '(1000000, 1) type instance I.UnitScale "XMR" "nanonero" = '(1000000000, 1) type instance I.UnitScale "XMR" "piconero" = '(1000000000000, 1)
k0001/haskell-money
safe-money/src/Money.hs
bsd-3-clause
39,920
0
6
5,897
12,501
7,279
5,222
644
0
{-# LANGUAGE OverloadedStrings #-} -- | Useful utilities that don't really fit in a specific location. module Language.MiniStg.Util ( show', Validate(..), -- * Prettyprinter extensions commaSep, spaceSep, bulletList, pluralS, ) where import Data.Bifunctor import Data.Monoid import Data.String import Data.Text (Text) import qualified Data.Text as T import Text.PrettyPrint.ANSI.Leijen hiding ((<>)) -- | 'show' with 'Text' as codomain. -- -- @ -- show' = 'T.pack' . 'show' -- @ show' :: Show a => a -> Text show' = T.pack . show -- | 'Either' with an accumulating 'Applicative' instance data Validate err a = Failure err | Success a instance Functor (Validate a) where fmap _ (Failure err) = Failure err fmap f (Success x) = Success (f x) instance Bifunctor Validate where first _ (Success x) = Success x first f (Failure err) = Failure (f err) second = fmap bimap f _ (Failure l) = Failure (f l) bimap _ g (Success r) = Success (g r) -- | Return success or the accumulation of all failures instance Monoid a => Applicative (Validate a) where pure = Success Success f <*> Success x = Success (f x) Success _ <*> Failure x = Failure x Failure x <*> Failure y = Failure (x <> y) Failure x <*> Success _ = Failure x -- | @[a,b,c] ==> a, b, c@ commaSep :: Pretty a => [a] -> Doc commaSep = encloseSep mempty mempty (comma <> space) . map pretty -- | @[a,b,c] ==> a b c@ spaceSep :: Pretty a => [a] -> Doc spaceSep = hsep . map pretty -- | Prefix all contained documents with a bullet symbol. bulletList :: Pretty a => [a] -> Doc bulletList = align . vsep . map ((" - " <>) . align . pretty) -- | Add an \'s' for non-singleton lists. pluralS :: IsString string => [a] -> string pluralS [_] = "" pluralS _ = "s"
Neuromancer42/ministgwasm
src/Language/MiniStg/Util.hs
bsd-3-clause
1,898
0
10
509
589
312
277
41
1
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-} module Network.IRC.Bot.Core ( simpleBot , simpleBot' , BotConf(..) , nullBotConf , User(..) , nullUser ) where import Control.Concurrent (ThreadId, forkIO, threadDelay) import Control.Concurrent.Chan (Chan, dupChan, newChan, readChan, writeChan) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TMVar (TMVar, swapTMVar, newTMVar, readTMVar) import Control.Concurrent.QSem (QSem, newQSem, waitQSem, signalQSem) import Control.Exception (IOException, catch) import Control.Monad (mplus, forever, when) import Control.Monad.Trans (liftIO) import Data.Data (Data, Typeable) import Data.Set (Set, empty) import Data.Time (UTCTime, addUTCTime, getCurrentTime) import GHC.IO.Handle (hFlushAll) import Network (HostName, PortID(PortNumber), connectTo) import Network.IRC (Message, decode, encode, joinChan, nick, user) import Network.IRC as I import Network.IRC.Bot.Types (User(..), nullUser) import Network.IRC.Bot.Limiter (Limiter(..), newLimiter, limit) import Network.IRC.Bot.Log (Logger, LogLevel(Normal, Debug), stdoutLogger) import Network.IRC.Bot.BotMonad (BotMonad(logM, sendMessage), BotPartT, BotEnv(..), runBotPartT) import Network.IRC.Bot.Part.NickUser (changeNickUser) import Prelude hiding (catch) import System.IO (BufferMode(NoBuffering, LineBuffering), Handle, hClose, hGetLine, hPutStrLn, hSetBuffering) -- |Bot configuration data BotConf = BotConf { channelLogger :: (Maybe (Chan Message -> IO ())) -- ^ optional channel logging function , logger :: Logger -- ^ app logging , host :: HostName -- ^ irc server to connect , port :: PortID -- ^ irc port to connect to (usually, 'PortNumber 6667') , nick :: String -- ^ irc nick , commandPrefix :: String -- ^ command prefix , user :: User -- ^ irc user info , channels :: Set String -- ^ channel to join , limits :: Maybe (Int, Int) -- ^ (burst length, delay in microseconds) } nullBotConf :: BotConf nullBotConf = BotConf { channelLogger = Nothing , logger = stdoutLogger Normal , host = "" , port = PortNumber 6667 , nick = "" , commandPrefix = "#" , user = nullUser , channels = empty , limits = Nothing } -- | connect to irc server and send NICK and USER commands ircConnect :: HostName -> PortID -> String -> User -> IO Handle ircConnect host port n u = do h <- connectTo host port hSetBuffering h LineBuffering return h partLoop :: Logger -> String -> String -> Chan Message -> Chan Message -> (BotPartT IO ()) -> IO () partLoop logger botName prefix incomingChan outgoingChan botPart = forever $ do msg <- readChan incomingChan runBotPartT botPart (BotEnv msg outgoingChan logger botName prefix) ircLoop :: Logger -> String -> String -> Chan Message -> Chan Message -> [BotPartT IO ()] -> IO [ThreadId] ircLoop logger botName prefix incomingChan outgoingChan parts = mapM forkPart parts where forkPart botPart = do inChan <- dupChan incomingChan forkIO $ partLoop logger botName prefix inChan outgoingChan (botPart `mplus` return ()) -- reconnect loop is still a bit buggy -- if you try to write multiple lines, and the all fail, reconnect will be called multiple times.. -- something should be done so that this does not happen connectionLoop :: Logger -> Maybe (Int, Int) -> TMVar UTCTime -> HostName -> PortID -> String -> User -> Chan Message -> Chan Message -> Maybe (Chan Message) -> QSem -> IO (ThreadId, ThreadId, Maybe ThreadId, IO ()) connectionLoop logger mLimitConf tmv host port nick user outgoingChan incomingChan logChan connQSem = do hTMVar <- atomically $ newTMVar (undefined :: Handle) (limit, limitTid) <- case mLimitConf of Nothing -> return (return (), Nothing) (Just (burst, delay)) -> do limiter <- newLimiter burst delay return (limit limiter, Just $ limitsThreadId limiter) outgoingTid <- forkIO $ forever $ do msg <- readChan outgoingChan writeMaybeChan logChan msg h <- atomically $ readTMVar hTMVar when (msg_command msg `elem` ["PRIVMSG", "NOTICE"]) limit hPutStrLn h (encode msg) `catch` (reconnect logger host port nick user hTMVar connQSem) now <- getCurrentTime atomically $ swapTMVar tmv now incomingTid <- forkIO $ do doConnect logger host port nick user hTMVar connQSem forever $ do h <- atomically $ readTMVar hTMVar msgStr <- (hGetLine h) `catch` (\e -> reconnect logger host port nick user hTMVar connQSem e >> return "") now <- getCurrentTime atomically $ swapTMVar tmv now case decode (msgStr ++ "\n") of Nothing -> logger Normal ("decode failed: " ++ msgStr) (Just msg) -> do logger Debug (show msg) writeMaybeChan logChan msg writeChan incomingChan msg let forceReconnect = do putStrLn "forceReconnect: getting handle" h <- atomically $ readTMVar hTMVar putStrLn "forceReconnect: sending /quit" writeChan outgoingChan (quit $ Just "restarting...") putStrLn "forceReconnect: closing handle" hClose h putStrLn "done." return (outgoingTid, incomingTid, limitTid, forceReconnect) ircConnectLoop :: (LogLevel -> String -> IO a) -- ^ logging -> HostName -> PortID -> String -> User -> IO Handle ircConnectLoop logger host port nick user = (ircConnect host port nick user) `catch` (\e -> do logger Normal $ "irc connect failed ... retry in 60 seconds: " ++ show (e :: IOException) threadDelay (60 * 10^6) ircConnectLoop logger host port nick user) doConnect :: (LogLevel -> String -> IO a) -> String -> PortID -> String -> User -> TMVar Handle -> QSem -> IO () doConnect logger host port nick user hTMVar connQSem = do logger Normal $ showString "Connecting to " . showString host . showString " as " $ nick h <- ircConnectLoop logger host port nick user atomically $ swapTMVar hTMVar h logger Normal $ "Connected." signalQSem connQSem return () reconnect :: Logger -> String -> PortID -> String -> User -> TMVar Handle -> QSem -> IOException -> IO () reconnect logger host port nick user hTMVar connQSem e = do logger Normal $ "IRC Connection died: " ++ show e {- atomically $ do empty <- isEmptyTMVar hTMVar if empty then return () else takeTMVar hTMVar >> return () -} doConnect logger host port nick user hTMVar connQSem onConnectLoop :: Logger -> String -> String -> Chan Message -> QSem -> BotPartT IO () -> IO ThreadId onConnectLoop logger botName prefix outgoingChan connQSem action = forkIO $ forever $ do waitQSem connQSem runBotPartT action (BotEnv undefined outgoingChan logger botName prefix) -- |simpleBot connects to the server and handles messages using the supplied BotPartTs -- -- the 'Chan Message' for the optional logging function will include -- all received and sent messages. This means that the bots output -- will be included in the logs. simpleBot :: BotConf -- ^ Bot configuration -> [BotPartT IO ()] -- ^ bot parts (must include 'pingPart', or equivalent) -> IO ([ThreadId], IO ()) -- ^ 'ThreadId' for all forked handler threads and a function that forces a reconnect simpleBot BotConf{..} parts = simpleBot' channelLogger logger limits host port nick commandPrefix user parts -- |simpleBot' connects to the server and handles messages using the supplied BotPartTs -- -- the 'Chan Message' for the optional logging function will include -- all received and sent messages. This means that the bots output -- will be included in the logs. simpleBot' :: (Maybe (Chan Message -> IO ())) -- ^ optional logging function -> Logger -- ^ application logging -> Maybe (Int, Int) -- ^ rate limiter settings (burst length, delay in microseconds) -> HostName -- ^ irc server to connect -> PortID -- ^ irc port to connect to (usually, 'PortNumber 6667') -> String -- ^ irc nick -> String -- ^ command prefix -> User -- ^ irc user info -> [BotPartT IO ()] -- ^ bot parts (must include 'pingPart', 'channelsPart', and 'nickUserPart)' -> IO ([ThreadId], IO ()) -- ^ 'ThreadId' for all forked handler threads and an IO action that forces a reconnect simpleBot' mChanLogger logger limitConf host port nick prefix user parts = do (mLogTid, mLogChan) <- case mChanLogger of Nothing -> return (Nothing, Nothing) (Just chanLogger) -> do logChan <- newChan :: IO (Chan Message) logTid <- forkIO $ chanLogger logChan return (Just logTid, Just logChan) -- message channels outgoingChan <- newChan :: IO (Chan Message) incomingChan <- newChan :: IO (Chan Message) now <- getCurrentTime tmv <- atomically $ newTMVar now connQSem <- newQSem 0 (outgoingTid, incomingTid, mLimitTid, forceReconnect) <- connectionLoop logger limitConf tmv host port nick user outgoingChan incomingChan mLogChan connQSem watchDogTid <- forkIO $ forever $ do let timeout = 5*60 now <- getCurrentTime lastActivity <- atomically $ readTMVar tmv when (now > addUTCTime (fromIntegral timeout) lastActivity) forceReconnect threadDelay (30*10^6) -- check every 30 seconds ircTids <- ircLoop logger nick prefix incomingChan outgoingChan parts onConnectId <- onConnectLoop logger nick prefix outgoingChan connQSem onConnect return $ (maybe id (:) mLimitTid $ maybe id (:) mLogTid $ (incomingTid : outgoingTid : watchDogTid : ircTids), forceReconnect) where onConnect :: BotPartT IO () onConnect = changeNickUser nick (Just user) -- | call 'writeChan' if 'Just'. Do nothing for Nothing. writeMaybeChan :: Maybe (Chan a) -> a -> IO () writeMaybeChan Nothing _ = return () writeMaybeChan (Just chan) a = writeChan chan a
hrushikesh/ircbot
Network/IRC/Bot/Core.hs
bsd-3-clause
11,300
0
21
3,546
2,756
1,437
1,319
183
3
import System.Environment (getArgs) import Data.List (isInfixOf, isPrefixOf) import Data.List.Split (splitOn) concatstr :: [(String, Bool)] -> String concatstr [] = [] concatstr ((xs, _):yss) = xs ++ concatstr yss prefix :: String -> String -> String prefix xs [] = [] prefix xs (y:ys) | isPrefixOf xs (y:ys) = [] | otherwise = y : prefix xs ys strsu :: [(String, Bool)] -> String -> String -> [String] -> Int -> String strsu xs ys zs ass i | i == length xs = strsub xs ass | snd (xs!!i) || not (isInfixOf ys fs) = strsu xs ys zs ass (succ i) | fs == ys = strsu (take i xs ++ ((zs, True) : drop (i+1) xs)) ys zs ass (succ i) | isPrefixOf ys fs = strsu (take i xs ++ ((zs, True) : (drop (length ys) fs, False) : drop (i+1) xs)) ys zs ass (succ i) | otherwise = strsu (take i xs ++ ((ps, False) : (zs, True) : (drop (length ps + length ys) fs, False) : drop (i+1) xs)) ys zs ass (i+2) where fs = fst (xs!!i) ps = prefix ys fs strsub :: [(String, Bool)] -> [String] -> String strsub xs [] = concatstr xs strsub xs (ys:zs:ass) = strsu xs ys zs ass 0 strsubs :: [String] -> String strsubs [xs, ys] = strsub [(xs, False)] (splitOn "," ys) main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (strsubs . splitOn ";") $ lines input
nikai3d/ce-challenges
hard/str_substitution.hs
bsd-3-clause
1,622
0
16
612
768
395
373
28
1
{-# LANGUAGE OverloadedStrings #-} module Tests.Test.HUnitPlus.Main where import Data.List import Distribution.TestSuite import System.Directory import Test.HUnitPlus.Main import Test.HUnitPlus.Base import qualified Data.Text as Strict makeMainTest :: (String, IO (), IO (), Bool, [TestSuite], Opts) -> Test makeMainTest (name, setup, cleanup, shouldPass, suites, opts) = let runTest = do setup out <- topLevel suites opts cleanup case out of Left msgs -> if not shouldPass then return (Finished Pass) else return (Finished (Fail ("Expected test to pass, " ++ "but failed with\n" ++ intercalate "\n" (map Strict.unpack msgs)))) Right _ -> if shouldPass then return (Finished Pass) else return (Finished (Fail "Expected test to fail")) testInstance = TestInstance { name = name, tags = [], options = [], setOption = (\_ _ -> return testInstance), run = runTest } in Test testInstance makeTestDir :: IO () makeTestDir = createDirectory "TestDir" delTestDir :: IO () delTestDir = removeDirectory "TestDir" delXMLReport :: IO () delXMLReport = removeFile "TestDir/report.xml" >> delTestDir delTxtReport :: IO () delTxtReport = removeFile "TestDir/report.txt" >> delTestDir delTxtXMLReport :: IO () delTxtXMLReport = removeFile "TestDir/report.xml" >> removeFile "TestDir/report.txt" >> delTestDir quietOpts = opts { consmode = [Quiet] } filterOpts = [ (False, False), (True, False), (False, True), (True, True) ] makeSuiteData suitename = map (\filters -> (TestSuite { suiteName = "suitename", suiteConcurrently = False, suiteOptions = [], suiteTests = suiteTestList }, filters))filterOpts suiteCombos = foldl (\accum suite1case -> (foldl (\accum suite2case -> [suite1case, suite2case] : accum) accum (makeSuiteData "Suite2"))) [] (makeSuiteData "Suite1") suitePairCombos = foldl (\accum a -> foldl (\accum b -> (a, b) : accum) accum suiteCombos) [] suiteCombos makeFilter :: String -> (Bool, Bool) -> [String] makeFilter suitename (False, False) = [] makeFilter suitename (True, False) = ["[" ++ suitename ++ "]Pass"] makeFilter suitename (False, True) = ["[" ++ suitename ++ "]Fail"] makeFilter suitename (True, True) = ["[" ++ suitename ++ "]Pass", "[" ++ suitename ++ "]Fail"] makeFilters suitedata = foldl (\accum (TestSuite { suiteName = suitename }, filters) -> makeFilter (Strict.unpack suitename) filters ++ accum) [] suitedata shouldPass suitedata = not (all (\(_, (a, b)) -> not a && not b) suitedata) || not (any (\(_, (_, fail)) -> fail) suitedata) suiteTestList = [ "Pass" ~: assertSuccess, "Fail" ~: assertFailure "Fail" ] makeName suitedata = intercalate "__" (foldl (\accum (TestSuite { suiteName = name }, (pass, fail)) -> (Strict.unpack name ++ "_" ++ show pass ++ "_" ++ show fail) : accum) [] suitedata) makeCmdOptTest suitedata = ("cmdopt___" ++ makeName suitedata, return (), return (), shouldPass suitedata, map fst suitedata, quietOpts { filters = makeFilters suitedata }) makeTestlistTest suitedata = let createFilterFile = do createDirectory "TestDir" writeFile "TestDir/testlist" (intercalate "\n" (makeFilters suitedata)) delFilterFile = removeFile "TestDir/testlist" >> delTestDir in ("testlist___" ++ makeName suitedata, createFilterFile, delFilterFile, shouldPass suitedata, map fst suitedata, quietOpts { testlist = ["TestDir/testlist"] }) makeCmdOptTestlistTest (cmdoptdata, testlistdata) = let createFilterFile = do createDirectory "TestDir" writeFile "TestDir/testlist" (intercalate "\n" (makeFilters testlistdata)) delFilterFile = removeFile "TestDir/testlist" >> delTestDir in ("cmdopt_testlist____" ++ makeName cmdoptdata ++ "___" ++ makeName testlistdata, createFilterFile, delFilterFile, shouldPass cmdoptdata && shouldPass testlistdata, map fst cmdoptdata, quietOpts { testlist = ["TestDir/testlist"], filters = makeFilters cmdoptdata }) makeDualTestlistTest (suitedata1, suitedata2) = let createFilterFile = do createDirectory "TestDir" writeFile "TestDir/testlist1" (intercalate "\n" (makeFilters suitedata1)) writeFile "TestDir/testlist2" (intercalate "\n" (makeFilters suitedata2)) delFilterFile = do removeFile "TestDir/testlist1" removeFile "TestDir/testlist2" delTestDir in ("dual_testlist____" ++ makeName suitedata1 ++ "___" ++ makeName suitedata2, createFilterFile, delFilterFile, shouldPass suitedata1 && shouldPass suitedata2, [], quietOpts { testlist = ["TestDir/testlist1", "TestDir/testlist2"] }) mainTests = [ ("multiple_console_mode", return (), return (), False, [], opts { consmode = [Quiet, Terminal] }), ("multiple_xml_report", return (), return (), False, [], opts { xmlreport = ["report1.xml", "report2.xml"] }), ("multiple_txt_report", return (), return (), False, [], opts { txtreport = ["report1.txt", "report2.txt"] }), ("multiple_xml_txt_report", return (), return (), False, [], opts { xmlreport = ["report1.xml", "report2.xml"], txtreport = ["report1.txt", "report2.txt"] }), ("nonexistent_xml_report", makeTestDir, delTestDir, False, [], opts { xmlreport = ["TestDir/nonexistent/report.xml"] }), ("nonexistent_txt_report", makeTestDir, delTestDir, False, [], opts { txtreport = ["TestDir/nonexistent/report.txt"] }), ("nonexistent_txt_xml_report", makeTestDir, delTestDir, False, [], opts { txtreport = ["TestDir/nonexistent/report.txt"], xmlreport = ["TestDir/nonexistent/report.xml"] }), ("nonexistent_testlist", makeTestDir, delTestDir, False, [], opts { xmlreport = ["TestDir/nonexistent/testlist"] }), ("run_quiet_no_xml_no_txt", return (), return (), True, [], quietOpts), ("run_terminal_no_xml_no_txt", return (), return (), True, [], opts { consmode = [Terminal] }), ("run_text_no_xml_no_txt", return (), return (), True, [], opts { consmode = [Text] }), ("run_verbose_no_xml_no_txt", return (), return (), True, [], opts { consmode = [Verbose] }), ("run_quiet_xml_no_txt", makeTestDir, delXMLReport, True, [], opts { consmode = [Quiet], xmlreport = ["TestDir/report.xml"] }), ("run_terminal_xml_no_txt", makeTestDir, delXMLReport, True, [], opts { consmode = [Terminal], xmlreport = ["TestDir/report.xml"] }), ("run_text_xml_no_txt", makeTestDir, delXMLReport, True, [], opts { consmode = [Text], xmlreport = ["TestDir/report.xml"] }), ("run_verbose_xml_no_txt", makeTestDir, delXMLReport, True, [], opts { consmode = [Verbose], xmlreport = ["TestDir/report.xml"] }), ("run_quiet_no_xml_txt", makeTestDir, delTxtReport, True, [], opts { consmode = [Quiet], txtreport = ["TestDir/report.txt"] }), ("run_terminal_no_xml_txt", makeTestDir, delTxtReport, True, [], opts { consmode = [Terminal], txtreport = ["TestDir/report.txt"] }), ("run_text_no_xml_txt", makeTestDir, delTxtReport, True, [], opts { consmode = [Text], txtreport = ["TestDir/report.txt"] }), ("run_verbose_no_xml_txt", makeTestDir, delTxtReport, True, [], opts { consmode = [Verbose], txtreport = ["TestDir/report.txt"] }), ("run_quiet_xml_no_txt", makeTestDir, delTxtXMLReport, True, [], opts { consmode = [Quiet], xmlreport = ["TestDir/report.xml"], txtreport = ["TestDir/report.txt"] }), ("run_terminal_xml_no_txt", makeTestDir, delTxtXMLReport, True, [], opts { consmode = [Terminal], xmlreport = ["TestDir/report.xml"], txtreport = ["TestDir/report.txt"] }), ("run_text_xml_no_txt", makeTestDir, delTxtXMLReport, True, [], opts { consmode = [Text], xmlreport = ["TestDir/report.xml"], txtreport = ["TestDir/report.txt"] }), ("run_verbose_xml_no_txt", makeTestDir, delTxtXMLReport, True, [], opts { consmode = [Verbose], xmlreport = ["TestDir/report.xml"], txtreport = ["TestDir/report.txt"] }) ] ++ map makeCmdOptTest suiteCombos ++ map makeTestlistTest suiteCombos ++ map makeCmdOptTestlistTest suitePairCombos ++ map makeDualTestlistTest suitePairCombos tests :: Test tests = testGroup "Main" (map makeMainTest mainTests)
emc2/HUnit-Plus
test/Tests/Test/HUnitPlus/Main.hs
bsd-3-clause
8,906
0
25
2,163
2,623
1,502
1,121
180
4
{- FSQL : Expr/Typed.hs -- Typed expression data types and functions - - Copyright (C) 2015 gahag - All rights reserved. - - This software may be modified and distributed under the terms - of the BSD license. See the LICENSE file for details. -} {-# LANGUAGE GADTs, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE DataKinds, KindSignatures #-} module Expr.Typed ( Sel(..), Expr(..), Typed(..), compile ) where import FileInfo (FileInfo, Day, FileSize, name, date, size) import Query (Selection(..)) import Regex (Regex, match) data Sel (s :: Selection) where -- Singleton type to keep track of the used Selection. SName :: Sel 'Name SDate :: Sel 'Date SSize :: Sel 'Size class Typed t t' where coerce :: t -> (FileInfo -> t') instance Typed (Sel 'Name) String where -- ord, regex coerce SName = name instance Typed (Sel 'Date) Day where -- ord coerce SDate = date instance Typed (Sel 'Date) String where -- regex coerce SDate = show . date instance Typed (Sel 'Size) FileSize where -- ord coerce SSize = size instance Typed (Sel 'Size) String where -- regex coerce SSize = show . size data Expr t where -- Expression of type t Sel :: (Typed (Sel s) v) => Sel s -> Expr v Value :: v -> Expr v -- lhs -> rhs -> expr t (:!:) :: Expr Bool -> Expr Bool (:&&:) :: Expr Bool -> Expr Bool -> Expr Bool (:||:) :: Expr Bool -> Expr Bool -> Expr Bool (:>:) :: (Ord t) => Expr t -> Expr t -> Expr Bool (:<:) :: (Ord t) => Expr t -> Expr t -> Expr Bool (:>=:) :: (Ord t) => Expr t -> Expr t -> Expr Bool (:<=:) :: (Ord t) => Expr t -> Expr t -> Expr Bool (:==:) :: (Eq t) => Expr t -> Expr t -> Expr Bool (:/=:) :: (Eq t) => Expr t -> Expr t -> Expr Bool (:=~:) :: Expr String -> Expr Regex -> Expr Bool compile :: Expr t -> (FileInfo -> t) compile (Sel s) = coerce s compile (Value v) = const v compile ((:!:) e) = not . compile e compile (e :&&: e') = (&&) <$> compile e <*> compile e' compile (e :||: e') = (||) <$> compile e <*> compile e' compile (e :>: e') = (>) <$> compile e <*> compile e' compile (e :<: e') = (<) <$> compile e <*> compile e' compile (e :>=: e') = (>=) <$> compile e <*> compile e' compile (e :<=: e') = (<=) <$> compile e <*> compile e' compile (e :==: e') = (==) <$> compile e <*> compile e' compile (e :/=: e') = (/=) <$> compile e <*> compile e' compile (e :=~: e') = flip match <$> compile e <*> compile e'
gahag/FSQL
src/Expr/Typed.hs
bsd-3-clause
2,762
0
9
881
987
523
464
50
1
{-# LANGUAGE FlexibleContexts, CPP #-} module ParseNFA where import qualified Data.Set as S import qualified Data.Map.Strict as M #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ( (<$>), (<*>), (<*) ) #endif import Control.Monad ( when, (>=>) ) import Control.Monad.Trans ( lift ) import Control.Monad.Trans.Either ( hoistEither, runEitherT ) import Data.List ( genericLength ) import Data.List.NonEmpty ( NonEmpty( (:|) ) ) import qualified Data.List.NonEmpty as NEL import qualified Data.Text as T import qualified Data.Traversable as DT import Text.Parsec.Text ( Parser ) import Text.Parsec ( char, try, option, string, noneOf, newline, sepBy1 , between, many1, digit ) import Text.Parsec.Prim ( parse ) import LTS ( LTS(..) ) import qualified MTBDD import NFA ( BoundarySignal(..), BoundarySignals, NFA(..) , NFAWithBoundaries(..), signalsMapToBDD ) textToNFAWith :: (NFADef String -> Either String r) -> [T.Text] -> r textToNFAWith f = dieOr . toNFAWithF . toT where dieOr = either error id toNFAWithF = doParse >=> f doParse = conv . parse parseNetDef "" conv = either (Left . show) Right toT = T.unlines textToNFAWB :: [T.Text] -> NFAWithBoundaries Int textToNFAWB = textToNFAWith (toNFAWBDef >=> defToNFAWithBoundaries) textToNFA :: [T.Text] -> NFA Int Int textToNFA = textToNFAWith ((defToNFA <$>) . toNFADef) defToNFA :: NFADef [ZOS] -> NFA Int Int defToNFA (NFADef is ts fs) = let listsToVarMap = M.fromListWith (M.unionWith S.union) lts = LTS . M.map toBDDs . listsToVarMap $ trans in NFA lts (`inNEL` is) (`elem` fs) where toBDDs = MTBDD.or . map doUnit . M.toList doUnit = uncurry (MTBDD.unitWithVars S.empty) trans = NEL.toList ts >>= toTrans -- ss, ls and ts are all (non-empty) lists, so we use the list Monad to -- construct a single list of pairs from source states to a BDD map. toTrans (NFATransDef srcs ls trgs) = do s <- NEL.toList srcs l <- NEL.toList ls let converted = convertLabel l return (s, M.singleton converted (S.fromList . NEL.toList $ trgs)) convertLabel = toVarList where toVarList = foldr go [] . zip [0..] -- Ignore stars, their variable's value doesn't matter go (pos, x) l = let s = case x of Zero -> Just False One -> Just True Star -> Nothing in maybe l (\s' -> (pos, s') : l) s defToNFAWithBoundaries :: NFADef NFAWBLabel -> Either String (NFAWithBoundaries Int) defToNFAWithBoundaries (NFADef is ts fs) = do let lSizes@(l, r) = getFirstBoundarySizes ts -- Turn the list of transitions into a list of Eithers which are sequenced trans <- DT.sequence . runEitherT $ makeTrans lSizes let listsToSignalMap = M.fromListWith (M.unionWith S.union) lts = LTS . M.map signalsMapToBDD . listsToSignalMap $ trans nfa = NFA lts (`inNEL` is) (`elem` fs) return $ NFAWithBoundaries nfa l r where getFirstBoundarySizes (NFATransDef _ (NFAWBLabel l r :| _) _ :| _) = (genericLength l, genericLength r) makeTrans lSizes = lift (NEL.toList ts) >>= toTrans lSizes -- ss, ls and ts are all (non-empty) lists, so we use the list Monad to -- construct a single list of pairs from source states to a BDD map. toTrans lSizes (NFATransDef srcs ls trgs) = do s <- lift $ NEL.toList srcs l <- lift $ NEL.toList ls converted <- hoistEither $ convertLabel lSizes l return (s, M.singleton converted (S.fromList . NEL.toList $ trgs)) convertLabel :: (Int, Int) -> NFAWBLabel -> Either String (BoundarySignals, BoundarySignals) convertLabel (lSize, rSize) (NFAWBLabel ls rs) = do check lSize ls True check rSize rs False Right (toBS ls, toBS rs) where -- Catch invalid labels check size list isLeft = when (genericLength list /= size) $ Left $ "Invalid length " ++ (if isLeft then "left" else "right") ++ "list: " ++ show list -- toBS constructs a BoundarySignals, a Map from Int to (No)Signal toBS = foldr go M.empty . zip [0..] -- Ignore stars, their variable's value doesn't matter go (pos, x) m = let s = case x of Zero -> Just NoSignal One -> Just Signal Star -> Nothing in maybe m (\s' -> M.insert pos s' m) s inNEL :: (Eq a) => a -> NonEmpty a -> Bool inNEL x nel = x `elem` NEL.toList nel -- Turns an NFADef with String labels into a NFADef with NFAWBLabel labels, if -- its possible to do so. toNFAWBDef :: NFADef String -> Either String (NFADef NFAWBLabel) toNFAWBDef = modifyNFADef transformLabel where transformLabel lbl = case break (== '/') lbl of (l, '/' : r) -> toLabel l r _ -> Left $ "invalid NFAWB label: " ++ show lbl toLabel l r = NFAWBLabel <$> mapM convert l <*> mapM convert r convert '0' = Right Zero convert '1' = Right One convert '*' = Right Star convert c = Left $ "Unknown NFA label part: " ++ show c toNFADef :: NFADef String -> Either String (NFADef [ZOS]) toNFADef = modifyNFADef (mapM convert) where convert '0' = Right Zero convert '1' = Right One convert '*' = Right Star convert c = Left $ "Unknown NFA label part: " ++ show c data NFAWBLabel = NFAWBLabel [ZOS] [ZOS] deriving Show data ZOS = Zero | One | Star deriving (Eq, Ord, Show) -- Transform NFADefs over String labels into arbitrary other labels, using the -- provided function. modifyNFADef :: (String -> Either String a) -> NFADef String -> Either String (NFADef a) modifyNFADef f (NFADef is ts fs) = (\ts' -> NFADef is ts' fs) <$> DT.mapM transform ts where transform (NFATransDef src lbls tgt) = (\lbls' -> NFATransDef src lbls' tgt) <$> DT.mapM f lbls data NFADef trans = NFADef (NonEmpty Int) -- ^ Initial states (NonEmpty (NFATransDef trans)) -- ^ Transitions [Int] -- ^ Final states deriving Show data NFATransDef l = NFATransDef (NonEmpty Int) -- ^ Source states (NonEmpty l) -- ^ Labels (NonEmpty Int) -- ^ Target states deriving Show -- Parse a Net definition: -- NET ::= PLACES, "\n", TRANS, { TRANS }, "\n", MBPLACES "\n"; -- -- PLACE ::= {- Natural Number -}; -- -- MBPLACES ::= [] -- | PLACES; -- -- PLACES ::= PLACE -- | PLACE, ",", PLACES; -- -- TRANS ::= PLACES, "--", LABELS, "->", PLACES; -- -- LABELS ::= LABEL -- | LABEL, ",", LABELS; -- -- LABEL ::= {- Anything but ',' or '-' -} -- -- -- E.g.: -- 0 -- 0--a,b,c->1 -- 0--a->0 -- 1 -- -- is the NFA that has two states and accepts any string a*(a|b|c). parseNetDef :: Parser (NFADef String) parseNetDef = NFADef <$> (parsePlaces <* newline) <*> (NEL.fromList <$> many1 (try (parseNFATrans <* newline))) <*> option [] (NEL.toList <$> parsePlaces <* option '\n' newline) where commaSep1 x = sepBy1 x (char ',') parseInt = read <$> many1 digit parsePlaces = NEL.fromList <$> commaSep1 parseInt parseNFATrans = NFATransDef <$> parsePlaces <*> between (string "--") (string "->") parseLabels <*> parsePlaces parseLabels = NEL.fromList <$> (commaSep1 . many1 $ noneOf "-,")
owst/Penrose
src/ParseNFA.hs
bsd-3-clause
7,797
0
17
2,361
2,182
1,167
1,015
138
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Miso.Mathml.Element -- Copyright : (C) 2016-2018 David M. Johnson -- License : BSD3-style (see the file LICENSE) -- Maintainer : David M. Johnson <[email protected]> -- Stability : experimental -- Portability : non-portable ---------------------------------------------------------------------------- module Miso.Mathml.Element ( -- * Construct an Element nodeMathml ) where import Miso.Html.Types import Miso.String (MisoString) import qualified Prelude as P -- | Used to construct `VNode`'s in `View` nodeMathml :: MisoString -> [Attribute action] -> [View action] -> View action nodeMathml = P.flip (node MATHML) P.Nothing
dmjio/miso
src/Miso/Mathml/Element.hs
bsd-3-clause
857
0
9
157
99
62
37
10
1
{-# LANGUAGE LambdaCase, OverloadedStrings, RecordWildCards #-} module Output where -- Pretty printer functions for the ANSI output. import Prelude as P hiding (putStrLn) import Data.Int import Data.List as L import Data.Maybe import Data.Monoid import Data.Text as T import Data.Text.IO import Database.Persist.Sqlite import Marktime.Common import Marktime.Database -- FIXME: For the love of all that is good please use a pretty printer - taksuyu -- 2016-08-21: Added it to my marktime list. - taksuyu printTasks :: [Entity TaskStore] -> IO () printTasks [] = putStrLn "No tasks were found." printTasks ts = do putStrLn $ taskHeader <> " - Started" mapM_ printTask started putStrLn "" putStrLn $ taskHeader <> " - Paused" mapM_ printTask paused putStrLn "" putStrLn $ taskHeader <> " - Unfinished" mapM_ printTask unfinished where taskHeader = "Tasks (Key: Description)" (started, notStarted) = L.partition (\(Entity _ TaskStore{..}) -> isJust taskStoreStartTime) ts (paused, unfinished) = L.partition (\(Entity _ TaskStore{..}) -> not (L.null taskStoreDurations)) notStarted printTask (Entity TaskStoreKey{..} TaskStore{..}) = putStrLn $ let keylength = T.length keyText keyText = showT (unSqlBackendKey unTaskStoreKey) in leftpad (10 - keylength) keyText <> ": " <> taskStoreTaskDesc -- FIXME: Text builder and fold leftpad :: Int -> Text -> Text leftpad 0 str' = str' leftpad n str' | n > 0 = " " <> leftpad (n - 1) str' | otherwise = leftpad 0 str' taskShow :: Int64 -> Text -> IO () taskShow i t = putStrLn $ "Task " <> showT i <> t printStartTask :: Int64 -> Either StartTaskError () -> IO () printStartTask i = let t = taskShow i in \case Right _ -> t " has been started." Left AlreadyStarted -> t " has already been started." Left StartTaskNotFound -> t " doesn't exist." printStopTask :: Int64 -> Either StopTaskError () -> IO () printStopTask i = let t = taskShow i in \case Right _ -> t " has been stopped." Left AlreadyStopped -> t " has already been stopped." Left NotStarted -> t " hasn't been started yet." Left StopTaskNotFound -> t " doesn't exist." printPauseTask :: Int64 -> Either PauseTaskError () -> IO () printPauseTask i = let t = taskShow i in \case Right _ -> t " has been paused." Left AlreadyFinished -> t " has already been finished." Left PauseNotStarted -> t " hasn't been started yet." Left PauseTaskNotFound -> t " doesn't exist."
taksuyu/marktime
marktime/Output.hs
bsd-3-clause
2,559
0
14
587
761
371
390
54
4
-- | -- Module: Math.NumberTheory.Zeta.Dirichlet -- Copyright: (c) 2018 Alexandre Rodrigues Baldé -- Licence: MIT -- Maintainer: Alexandre Rodrigues Baldé <[email protected]> -- -- Dirichlet beta-function. {-# LANGUAGE ScopedTypeVariables #-} module Math.NumberTheory.Zeta.Dirichlet ( betas , betasEven , betasOdd ) where import Data.ExactPi import Data.List (zipWith4) import Data.Ratio ((%)) import Math.NumberTheory.Recurrences (euler, factorial) import Math.NumberTheory.Zeta.Hurwitz (zetaHurwitz) import Math.NumberTheory.Zeta.Utils (intertwine, skipOdds) -- | Infinite sequence of exact values of Dirichlet beta-function at odd arguments, starting with @β(1)@. -- -- >>> import Data.ExactPi -- >>> approximateValue (betasOdd !! 25) :: Double -- 0.9999999999999987 -- >>> import Data.Number.Fixed -- >>> approximateValue (betasOdd !! 25) :: Fixed Prec50 -- 0.99999999999999999999999960726927497384196726751694 betasOdd :: [ExactPi] betasOdd = zipWith Exact [1, 3 ..] $ zipWith4 (\sgn denom eul twos -> sgn * (eul % (twos * denom))) (cycle [1, -1]) (skipOdds factorial) (skipOdds euler) (iterate (4 *) 4) -- | Infinite sequence of approximate values of the Dirichlet @β@ function at -- positive even integer arguments, starting with @β(0)@. betasEven :: forall a. (Floating a, Ord a) => a -> [a] betasEven eps = (1 / 2) : hurwitz where hurwitz :: [a] hurwitz = zipWith3 (\quarter threeQuarters four -> (quarter - threeQuarters) / four) (tail . skipOdds $ zetaHurwitz eps 0.25) (tail . skipOdds $ zetaHurwitz eps 0.75) (iterate (16 *) 16) -- | Infinite sequence of approximate (up to given precision) -- values of Dirichlet beta-function at integer arguments, starting with @β(0)@. -- -- >>> take 5 (betas 1e-14) :: [Double] -- [0.5,0.7853981633974483,0.9159655941772189,0.9689461462593694,0.9889445517411051] betas :: (Floating a, Ord a) => a -> [a] betas eps = e : o : scanl1 f (intertwine es os) where e : es = betasEven eps o : os = map (getRationalLimit (\a b -> abs (a - b) < eps) . rationalApproximations) betasOdd -- Cap-and-floor to improve numerical stability: -- 1 > beta(n + 1) - 1 > (beta(n) - 1) / 2 -- A similar method is used in @Math.NumberTheory.Zeta.Riemann.zetas@. f x y = 1 `min` (y `max` (1 + (x - 1) / 2))
Bodigrim/arithmoi
Math/NumberTheory/Zeta/Dirichlet.hs
mit
2,582
0
16
673
528
307
221
32
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} module Yesod.Core.Internal.TH where import Prelude hiding (exp) import Yesod.Core.Handler import Language.Haskell.TH hiding (cxt, instanceD) import Language.Haskell.TH.Syntax import qualified Network.Wai as W import Data.ByteString.Lazy.Char8 () import Data.List (foldl') import Control.Monad (replicateM, void) import Text.Parsec (parse, many1, many, eof, try, option, sepBy1) import Text.ParserCombinators.Parsec.Char (alphaNum, spaces, string, char) import Yesod.Routes.TH import Yesod.Routes.Parse import Yesod.Core.Types import Yesod.Core.Class.Dispatch import Yesod.Core.Internal.Run -- | Generates URL datatype and site function for the given 'Resource's. This -- is used for creating sites, /not/ subsites. See 'mkYesodSubData' and 'mkYesodSubDispatch' for the latter. -- Use 'parseRoutes' to create the 'Resource's. -- -- Contexts and type variables in the name of the datatype are parsed. -- For example, a datatype @App a@ with typeclass constraint @MyClass a@ can be written as @\"(MyClass a) => App a\"@. mkYesod :: String -- ^ name of the argument datatype -> [ResourceTree String] -> Q [Dec] mkYesod name = fmap (uncurry (++)) . mkYesodWithParser name False return {-# DEPRECATED mkYesodWith "Contexts and type variables are now parsed from the name in `mkYesod`. <https://github.com/yesodweb/yesod/pull/1366>" #-} -- | Similar to 'mkYesod', except contexts and type variables are not parsed. -- Instead, they are explicitly provided. -- You can write @(MyClass a) => App a@ with @mkYesodWith [[\"MyClass\",\"a\"]] \"App\" [\"a\"] ...@. mkYesodWith :: [[String]] -- ^ list of contexts -> String -- ^ name of the argument datatype -> [String] -- ^ list of type variables -> [ResourceTree String] -> Q [Dec] mkYesodWith cxts name args = fmap (uncurry (++)) . mkYesodGeneral cxts name args False return -- | Sometimes, you will want to declare your routes in one file and define -- your handlers elsewhere. For example, this is the only way to break up a -- monolithic file into smaller parts. Use this function, paired with -- 'mkYesodDispatch', to do just that. mkYesodData :: String -> [ResourceTree String] -> Q [Dec] mkYesodData name resS = fst <$> mkYesodWithParser name False return resS mkYesodSubData :: String -> [ResourceTree String] -> Q [Dec] mkYesodSubData name resS = fst <$> mkYesodWithParser name True return resS -- | Parses contexts and type arguments out of name before generating TH. mkYesodWithParser :: String -- ^ foundation type -> Bool -- ^ is this a subsite -> (Exp -> Q Exp) -- ^ unwrap handler -> [ResourceTree String] -> Q([Dec],[Dec]) mkYesodWithParser name isSub f resS = do let (name', rest, cxt) = case parse parseName "" name of Left err -> error $ show err Right a -> a mkYesodGeneral cxt name' rest isSub f resS where parseName = do cxt <- option [] parseContext name' <- parseWord args <- many parseWord spaces eof return ( name', args, cxt) parseWord = do spaces many1 alphaNum parseContext = try $ do cxts <- parseParen parseContexts spaces _ <- string "=>" return cxts parseParen p = do spaces _ <- char '(' r <- p spaces _ <- char ')' return r parseContexts = sepBy1 (many1 parseWord) (spaces >> char ',' >> return ()) -- | See 'mkYesodData'. mkYesodDispatch :: String -> [ResourceTree String] -> Q [Dec] mkYesodDispatch name = fmap snd . mkYesodWithParser name False return -- | Get the Handler and Widget type synonyms for the given site. masterTypeSyns :: [Name] -> Type -> [Dec] -- FIXME remove from here, put into the scaffolding itself? masterTypeSyns vs site = [ TySynD (mkName "Handler") (fmap plainTV vs) $ ConT ''HandlerFor `AppT` site , TySynD (mkName "Widget") (fmap plainTV vs) $ ConT ''WidgetFor `AppT` site `AppT` ConT ''() ] mkYesodGeneral :: [[String]] -- ^ Appliction context. Used in RenderRoute, RouteAttrs, and ParseRoute instances. -> String -- ^ foundation type -> [String] -- ^ arguments for the type -> Bool -- ^ is this a subsite -> (Exp -> Q Exp) -- ^ unwrap handler -> [ResourceTree String] -> Q([Dec],[Dec]) mkYesodGeneral appCxt' namestr mtys isSub f resS = do let appCxt = fmap (\(c:rest) -> foldl' (\acc v -> acc `AppT` nameToType v) (ConT $ mkName c) rest ) appCxt' mname <- lookupTypeName namestr arity <- case mname of Just name -> do info <- reify name return $ case info of TyConI dec -> case dec of DataD _ _ vs _ _ _ -> length vs NewtypeD _ _ vs _ _ _ -> length vs TySynD _ vs _ -> length vs _ -> 0 _ -> 0 _ -> return 0 let name = mkName namestr -- Generate as many variable names as the arity indicates vns <- replicateM (arity - length mtys) $ newName "t" -- types that you apply to get a concrete site name let argtypes = fmap nameToType mtys ++ fmap VarT vns -- typevars that should appear in synonym head let argvars = (fmap mkName . filter isTvar) mtys ++ vns -- Base type (site type with variables) let site = foldl' AppT (ConT name) argtypes res = map (fmap (parseType . dropBracket)) resS renderRouteDec <- mkRenderRouteInstance appCxt site res routeAttrsDec <- mkRouteAttrsInstance appCxt site res dispatchDec <- mkDispatchInstance site appCxt f res parseRoute <- mkParseRouteInstance appCxt site res let rname = mkName $ "resources" ++ namestr eres <- lift resS let resourcesDec = [ SigD rname $ ListT `AppT` (ConT ''ResourceTree `AppT` ConT ''String) , FunD rname [Clause [] (NormalB eres) []] ] let dataDec = concat [ [parseRoute] , renderRouteDec , [routeAttrsDec] , resourcesDec , if isSub then [] else masterTypeSyns argvars site ] return (dataDec, dispatchDec) mkMDS :: (Exp -> Q Exp) -> Q Exp -> MkDispatchSettings a site b mkMDS f rh = MkDispatchSettings { mdsRunHandler = rh , mdsSubDispatcher = [|\parentRunner getSub toParent env -> yesodSubDispatch YesodSubRunnerEnv { ysreParentRunner = parentRunner , ysreGetSub = getSub , ysreToParentRoute = toParent , ysreParentEnv = env } |] , mdsGetPathInfo = [|W.pathInfo|] , mdsSetPathInfo = [|\p r -> r { W.pathInfo = p }|] , mdsMethod = [|W.requestMethod|] , mds404 = [|void notFound|] , mds405 = [|void badMethod|] , mdsGetHandler = defaultGetHandler , mdsUnwrapper = f } -- | If the generation of @'YesodDispatch'@ instance require finer -- control of the types, contexts etc. using this combinator. You will -- hardly need this generality. However, in certain situations, like -- when writing library/plugin for yesod, this combinator becomes -- handy. mkDispatchInstance :: Type -- ^ The master site type -> Cxt -- ^ Context of the instance -> (Exp -> Q Exp) -- ^ Unwrap handler -> [ResourceTree c] -- ^ The resource -> DecsQ mkDispatchInstance master cxt f res = do clause' <- mkDispatchClause (mkMDS f [|yesodRunner|]) res let thisDispatch = FunD 'yesodDispatch [clause'] return [instanceD cxt yDispatch [thisDispatch]] where yDispatch = ConT ''YesodDispatch `AppT` master mkYesodSubDispatch :: [ResourceTree a] -> Q Exp mkYesodSubDispatch res = do clause' <- mkDispatchClause (mkMDS return [|subHelper|]) res inner <- newName "inner" let innerFun = FunD inner [clause'] helper <- newName "helper" let fun = FunD helper [ Clause [] (NormalB $ VarE inner) [innerFun] ] return $ LetE [fun] (VarE helper) instanceD :: Cxt -> Type -> [Dec] -> Dec instanceD = InstanceD Nothing
geraldus/yesod
yesod-core/src/Yesod/Core/Internal/TH.hs
mit
9,103
0
20
2,941
2,010
1,058
952
167
7
-- -- -- ----------------- -- Exercise 6.24. ----------------- -- -- -- module E'6'24 where -- 6.23 works correctly. -- -- Really, I wouldn't say anything before (coverage-) testing. -- I don't know how to do this in Haskell, yet.
pascal-knodel/haskell-craft
_/links/E'6'24.hs
mit
238
0
2
46
17
16
1
1
0
-- -- -- ----------------- -- Exercise 5.27. ----------------- -- -- -- module E'5'27 where -- Subchapter 5.1 (exercise relevant definitions) ... type Person = String type Book = String type Database = [ (Person , Book) ] exampleDB :: Database exampleDB = [ ( "Alice" , "Tintin" ) , ( "Anna" , "Little Women" ) , ( "Alice" , "Asterix" ) , ( "Rory" , "Tintin" ) ] books :: Database -> Person -> [Book] books database person = [ currentBook | (currentPerson, currentBook) <- database , currentPerson == person ] -- ... -- books exampleDB "Charlie" -- = [ book | (person, book) <- exampleDB , person == "Charlie" ] -- | -- | person = "Alice" "Anna" "Alice" "Rory" -- | book = "Tintin" "Little Women" "Asterix" "Tintin" -- | person == "Charlie" = False False False False -- | -------------------------------------------------------------------------- -- | book = -- | -- = [] -- books exampleDB "Rory" -- = [ book | (person, book) <- exampleDB , person == "Rory" ] -- | -- | person = "Alice" "Anna" "Alice" "Rory" -- | book = "Tintin" "Little Women" "Asterix" "Tintin" -- | person == "Rory" = False False False True -- | ----------------------------------------------------------------------- -- | book = "Tintin" -- | -- = [ "Tintin" ]
pascal-knodel/haskell-craft
_/links/E'5'27.hs
mit
1,594
0
8
575
159
110
49
14
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE CPP #-} module Main where import Foundation import Foundation.Array import Foundation.Foreign import Foundation.List.DList import Foundation.Primitive import Foundation.Check import Foundation.Check.Main (defaultMain) import Foundation.String import Foundation.String.Read import qualified Prelude import Data.Ratio import Test.Foundation.Random import Test.Foundation.Misc import Test.Foundation.Storable import Test.Foundation.Number import Test.Foundation.Conduit import Test.Foundation.String import Test.Foundation.Network.IPv4 import Test.Foundation.Network.IPv6 import Test.Foundation.String.Base64 import Test.Checks.Property.Collection import Test.Foundation.Format import qualified Test.Foundation.Bits as Bits import qualified Test.Basement as Basement #if MIN_VERSION_base(4,9,0) import Test.Foundation.Primitive.BlockN #endif applyFstToSnd :: (String, String -> b) -> b applyFstToSnd (a, fab) = fab a matrixToGroup name l = Group name $ Prelude.concat $ fmap (fmap applyFstToSnd . snd) l functorProxy :: Proxy f -> Proxy ty -> Proxy (f ty) functorProxy _ _ = Proxy primTypesMatrixArbitrary :: (forall ty . (PrimType ty, Typeable ty, Show ty, Ord ty) => Proxy ty -> Gen ty -> a) -> [(String, [(String, a)])] primTypesMatrixArbitrary f = [ ("Words", [ ("W8", f (Proxy :: Proxy Word8) arbitrary) , ("W16", f (Proxy :: Proxy Word16) arbitrary) , ("W32", f (Proxy :: Proxy Word32) arbitrary) , ("W64", f (Proxy :: Proxy Word64) arbitrary) , ("W128", f (Proxy :: Proxy Word128) arbitrary) , ("W256", f (Proxy :: Proxy Word256) arbitrary) , ("Word", f (Proxy :: Proxy Word) arbitrary) ]) , ("Ints", [ ("I8", f (Proxy :: Proxy Int8) arbitrary) , ("I16", f (Proxy :: Proxy Int16) arbitrary) , ("I32", f (Proxy :: Proxy Int32) arbitrary) , ("I64", f (Proxy :: Proxy Int64) arbitrary) , ("Int", f (Proxy :: Proxy Int) arbitrary) ]) , ("Floating", [ ("FP32", f (Proxy :: Proxy Float) arbitrary) , ("FP64", f (Proxy :: Proxy Double) arbitrary) ]) , ("C-Types", [ ("CChar", f (Proxy :: Proxy CChar) (CChar <$> arbitrary)) , ("CUChar", f (Proxy :: Proxy CUChar) (CUChar <$> arbitrary)) ]) , ("Endian", [ ("BE-W16", f (Proxy :: Proxy (BE Word16)) (toBE <$> arbitrary)) , ("BE-W32", f (Proxy :: Proxy (BE Word32)) (toBE <$> arbitrary)) , ("BE-W64", f (Proxy :: Proxy (BE Word64)) (toBE <$> arbitrary)) , ("LE-W16", f (Proxy :: Proxy (LE Word16)) (toLE <$> arbitrary)) , ("LE-W32", f (Proxy :: Proxy (LE Word32)) (toLE <$> arbitrary)) , ("LE-W64", f (Proxy :: Proxy (LE Word64)) (toLE <$> arbitrary)) ]) ] testAdditive :: forall a . (Show a, Eq a, Typeable a, Additive a, Arbitrary a) => Proxy a -> Test testAdditive _ = Group "Additive" [ Property "eq" $ azero === (azero :: a) , Property "a + azero == a" $ \(v :: a) -> v + azero === v , Property "azero + a == a" $ \(v :: a) -> azero + v === v , Property "a + b == b + a" $ \(v1 :: a) v2 -> v1 + v2 === v2 + v1 ] readFloatingExact' :: String -> Maybe (Bool, Natural, Word, Maybe Int) readFloatingExact' str = readFloatingExact str (\s x y z -> Just (s,x,y,z)) doubleEqualApprox :: Double -> Double -> PropertyCheck doubleEqualApprox d1 d2 = propertyCompare name (<) (abs d) lim where d = d2 - d1 name = show d1 <> " - " <> show d2 <> " (differential=" <> show (abs d) <> " )" <> " < " <> show lim lim = min d1 d2 * (10^^(-15 :: Int)) main = defaultMain $ Group "foundation" [ Group "Numerical" [ Group "Int" [ testAdditive (Proxy :: Proxy Int) ] , Group "Word64" [ testAdditive (Proxy :: Proxy Word64) ] , Group "Number" testNumberRefs ] , Basement.tests , Bits.tests , Group "String" [ Group "reading" [ Group "integer" [ Property "empty" $ readInteger "" === Nothing , Property "just-sign" $ readInteger "-" === Nothing , Property "extra-content" $ readInteger "-123a" === Nothing , Property "any" $ \i -> readInteger (show i) === Just i ] , Group "floating-exact" [ Property "empty" $ readFloatingExact' "" === Nothing , Property "just-sign" $ readFloatingExact' "-" === Nothing , Property "extra-content" $ readFloatingExact' "-123a" === Nothing , Property "no-dot-after" $ readFloatingExact' "-123." === Nothing , Property "case0" $ readFloatingExact' "124890" === Just (False, 124890, 0, Nothing) , Property "case1" $ readFloatingExact' "-123.1" === Just (True, 1231, 1, Nothing) , Property "case2" $ readFloatingExact' "10001.001" === Just (False, 10001001, 3, Nothing) {- , Property "any" $ \s i (v :: Word8) n -> let (integral,floating) = i `divMod` (10^v) let vw = integralUpsize v :: Word sfloat = show n digits = integralCast (length sfloat) + vw in readFloatingExact' ((if s then "-" else "") <> show i <> "." <> replicate vw '0' <> sfloat) === Just (s, i, Just (digits, n), Nothing) -} ] , Group "Double" [ Property "case1" $ readDouble "96152.5" === Just 96152.5 , Property "case2" $ maybe (propertyFail "Nothing") (doubleEqualApprox 1.2300000000000002e102) $ readDouble "1.2300000000000002e102" , Property "case3" $ maybe (propertyFail "Nothing") (doubleEqualApprox 0.00001204) $ readDouble "0.00001204" , Property "case4" $ maybe (propertyFail "Nothing") (doubleEqualApprox 2.5e12) $ readDouble "2.5e12" , Property "case5" $ maybe (propertyFail "Nothing") (doubleEqualApprox 6.0e-4) $ readDouble "6.0e-4" , Property "case6" $ maybe (propertyFail "Nothing") ((===) (-31.548)) $ readDouble "-31.548" , Property "case7" $ readDouble "1e100000000" === Just (1/0) , Property "Prelude.read" $ \(d :: Double) -> case readDouble (show d) of Nothing -> propertyFail "Nothing" Just d' -> d' `doubleEqualApprox` (Prelude.read $ toList $ show d) ] , Group "rational" [ Property "case1" $ readRational "124.098" === Just (124098 % 1000) ] ] , Group "conversion" [ Property "lower" $ lower "This is MY test" === "this is my test" , Property "upper" $ upper "This is MY test" === "THIS IS MY TEST" ] ] , collectionProperties "DList a" (Proxy :: Proxy (DList Word8)) arbitrary , collectionProperties "Bitmap" (Proxy :: Proxy Bitmap) arbitrary , Group "Array" [ matrixToGroup "Block" $ primTypesMatrixArbitrary $ \prx arb s -> collectionProperties ("Block " <> s) (functorProxy (Proxy :: Proxy Block) prx) arb , matrixToGroup "Unboxed" $ primTypesMatrixArbitrary $ \prx arb s -> collectionProperties ("Unboxed " <> s) (functorProxy (Proxy :: Proxy UArray) prx) arb , Group "Boxed" [ collectionProperties "Array(W8)" (Proxy :: Proxy (Array Word8)) arbitrary , collectionProperties "Array(W16)" (Proxy :: Proxy (Array Word16)) arbitrary , collectionProperties "Array(W32)" (Proxy :: Proxy (Array Word32)) arbitrary , collectionProperties "Array(W64)" (Proxy :: Proxy (Array Word64)) arbitrary , collectionProperties "Array(I8)" (Proxy :: Proxy (Array Int8)) arbitrary , collectionProperties "Array(I16)" (Proxy :: Proxy (Array Int16)) arbitrary , collectionProperties "Array(I32)" (Proxy :: Proxy (Array Int32)) arbitrary , collectionProperties "Array(I64)" (Proxy :: Proxy (Array Int64)) arbitrary , collectionProperties "Array(F32)" (Proxy :: Proxy (Array Float)) arbitrary , collectionProperties "Array(F64)" (Proxy :: Proxy (Array Double)) arbitrary , collectionProperties "Array(Int)" (Proxy :: Proxy (Array Int)) arbitrary , collectionProperties "Array(Int,Int)" (Proxy :: Proxy (Array (Int,Int))) arbitrary , collectionProperties "Array(Integer)" (Proxy :: Proxy (Array Integer)) arbitrary , collectionProperties "Array(CChar)" (Proxy :: Proxy (Array CChar)) (CChar <$> arbitrary) , collectionProperties "Array(CUChar)" (Proxy :: Proxy (Array CUChar)) (CUChar <$> arbitrary) , collectionProperties "Array(BE W16)" (Proxy :: Proxy (Array (BE Word16))) (toBE <$> arbitrary) , collectionProperties "Array(BE W32)" (Proxy :: Proxy (Array (BE Word32))) (toBE <$> arbitrary) , collectionProperties "Array(BE W64)" (Proxy :: Proxy (Array (BE Word64))) (toBE <$> arbitrary) , collectionProperties "Array(LE W16)" (Proxy :: Proxy (Array (LE Word16))) (toLE <$> arbitrary) , collectionProperties "Array(LE W32)" (Proxy :: Proxy (Array (LE Word32))) (toLE <$> arbitrary) , collectionProperties "Array(LE W64)" (Proxy :: Proxy (Array (LE Word64))) (toLE <$> arbitrary) ] ] , Group "ChunkedUArray" [ matrixToGroup "Unboxed" $ primTypesMatrixArbitrary $ \prx arb s -> collectionProperties ("Unboxed " <> s) (functorProxy (Proxy :: Proxy ChunkedUArray) prx) arb ] , testStringRefs , testForeignStorableRefs , testNetworkIPv4 , testNetworkIPv6 , testBase64Refs , testHexadecimal , testUUID , testRandom , testConduit #if MIN_VERSION_base(4,9,0) , testBlockN #endif , testFormat ]
vincenthz/hs-foundation
foundation/tests/Checks.hs
bsd-3-clause
10,305
0
23
3,008
3,020
1,621
1,399
160
2
{- Codec for de/encoding form data shipped in URL query strings or in POST request bodies. (application/x-www-form-urlencoded) (cf. RFC 3986.) -} module Codec.URLEncoder ( encodeString , decodeString ) where import qualified Codec.Binary.UTF8.String as UTF8 ( encodeString ) import Codec.Percent ( getEncodedChar, getDecodedChar ) encodeString :: String -> String encodeString str = go (UTF8.encodeString str) where go "" = "" go (' ':xs) = '+':go xs go ('\r':'\n':xs) = '%':'0':'D':'%':'0':'A':go xs go ('\r':xs) = go ('\r':'\n':xs) go ('\n':xs) = go ('\r':'\n':xs) go (x:xs) = case getEncodedChar x of Nothing -> x : go xs Just ss -> ss ++ go xs decodeString :: String -> String decodeString "" = "" decodeString ('+':xs) = ' ':decodeString xs decodeString ls@(x:xs) = case getDecodedChar ls of Nothing -> x : decodeString xs Just (ch,xs1) -> ch : decodeString xs1
sof/flickr
Codec/URLEncoder.hs
bsd-3-clause
942
0
12
210
345
180
165
23
7
-- Compile this with 'ghc -o Game Game.hs' and run it with './Game'. import Data.List import Graphics.Gloss.Game -- Window size width = 600 height = 400 -- A sprite representing our character slimeSprite = scale 0.5 0.5 (bmp "Slime.bmp") slimeWidth = fst (snd (boundingBox slimeSprite)) slimeHeight = snd (snd (boundingBox slimeSprite)) -- Additional sprites for a simple animation slimeSprite2 = scale 0.5 0.5 (bmp "Slime2.bmp") slimeSprite3 = scale 0.5 0.5 (bmp "Slime3.bmp") slimeSprite4 = scale 0.5 0.5 (bmp "Slime4.bmp") -- Our game world consists of both the location and the vertical velocity of our character, the state of the character -- animation as well as a list of all currently pressed keys. data World = World Point Float Animation [Char] -- This starts our gamein a window with a give size, running at 30 frames per second. -- -- The argument 'World (0, 0) 0' is the initial state of our game world, where our character is at the centre of the -- window and has no velocity. -- main = playInScene (InWindow "Slime is here!" (round width, round height) (50, 50)) white 30 (World (0, 0) 0 noAnimation []) level handle [applyMovement, applyVelocity, applyGravity] -- Description of a level as a scene. Scenes depend on the state of the world, which means their rendering changes as the -- world changes. Here, we have the character, where both its location and animation depend on the world state. level = translating spritePosition (animating spriteAnimation slimeSprite) -- Extract the character position from the world. spritePosition (World (x, y) v anim keys) = (x, y) -- Extract the character animation from the world. spriteAnimation (World (x, y) v anim keys) = anim -- Pressing the spacebar makes the character jump. All character keys are tracked in the world state. handle now (EventKey (Char ch) Down _ _) (World (x, y) v anim keys) = World (x, y) v anim (ch : keys) handle now (EventKey (Char ch) Up _ _) (World (x, y) v anim keys) = World (x, y) v anim (delete ch keys) handle now (EventKey (SpecialKey KeySpace) Down _ _) (World (x, y) v anim keys) = World (x, y) 8 (animation [slimeSprite2, slimeSprite3, slimeSprite4] 0.1 now) keys handle now event world = world -- don't change the world in case of any other events -- Move horizontally, but box the character in at the window boundaries. moveX (x, y) offset = if x + offset < (-width / 2) + slimeWidth / 2 then ((-width / 2) + slimeWidth / 2, y) else if x + offset > width / 2 - slimeWidth / 2 then (width / 2 - slimeWidth / 2, y) else (x + offset, y) -- Move vertically, but box the character in at the window boundaries. moveY (x, y) offset = if y + offset < (-height / 2) + slimeHeight / 2 then (x, (-height / 2) + slimeHeight / 2) else if y + offset > height / 2 - slimeHeight / 2 then (x, height / 2 - slimeHeight / 2) else (x, y + offset) -- A pressed 'a' and 'd' key moves the character a fixed distance left or right. applyMovement _now _time (World (x, y) v anim keys) = if elem 'a' keys then World (moveX (x, y) (-10)) v anim keys else if elem 'd' keys then World (moveX (x, y) 10) v anim keys else World (x, y) v anim keys -- Each frame, add the veclocity to the verticial position (y-axis). (A negative velocity corresponds to a downward movement.) applyVelocity _now _time (World (x, y) v anim keys) = World (moveY (x, y) v) v anim keys -- We simulate gravity by decrease the velocity slightly on each frame, corresponding to a downward acceleration. -- -- We bounce of the bottom edge by reverting the velocity (with a damping factor). -- applyGravity _now _time (World (x, y) v anim keys) = World (x, y) (if y <= (-200) + slimeHeight / 2 then v * (-0.5) else v - 0.5) anim keys
mchakravarty/lets-program
step5/Game.hs
bsd-3-clause
4,174
0
12
1,175
1,082
593
489
41
3
{-# LANGUAGE NumDecimals #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} module Test.Marshal (tests) where import qualified Data.List.NonEmpty as NE import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import Data.Text.Prettyprint.Doc import Stg.Language.Prettyprint import Stg.Machine import Stg.Marshal import Stg.Parser.QuasiQuoter import Test.Orphans () import Test.Tasty import Test.Tasty.QuickCheck tests :: TestTree tests = testGroup "Marshalling" [ boolRoundtrip , integerRoundtrip , unitRoundtrip , listRoundtrip , nestedListRoundtrip , maybeRoundtrip , nestedMaybeRoundtrip , eitherRoundtrip , testGroup "Tuples" [tuple2Roundtrip , tuple3Roundtrip , tuple4Roundtrip , tuple5Roundtrip ] , crazyRoundtrip ] -- | Specifies a test that is based on the reduction of a closure. data RoundtripSpec a = RoundtripSpec { testName :: Text , testType :: Proxy a -- ^ Pin down the type of @a@ , maxSteps :: Integer } defSpec :: RoundtripSpec a defSpec = RoundtripSpec { testName = "Default test spec" , testType = Proxy , maxSteps = 10e3} roundTripTest :: forall a. (Arbitrary a, ToStg a, FromStg a, Show a, Eq a) => RoundtripSpec a -> TestTree roundTripTest spec = testProperty (T.unpack (testName spec)) test where test :: a -> Property test payload = counterexample (T.unpack ((renderPlain :: Doc StgiAnn -> Text) (prettyStgi finalState))) (expected === Right payload) where source = mconcat [ toStg "payload" payload , [stg| main = \ => case forceUntyped payload of _ -> Done; forceUntyped = \value -> case value of Unit -> Done; Nothing -> Done; Just x -> forceUntyped x; True -> Done; False -> Done; Int# _ -> Done; Left l -> forceUntyped l; Right r -> forceUntyped r; Pair x y -> case forceUntyped x of _ -> forceUntyped y; Triple x y z -> case forceUntyped x of _ -> case forceUntyped y of _ -> forceUntyped z; Nil -> Done; Cons x xs -> case forceUntyped x of _ -> forceUntyped xs; _ -> Error |]] prog = initialState "main" source states = evalsUntil (RunForMaxSteps (maxSteps spec)) (HaltIf (const False)) (PerformGc (const Nothing)) prog finalState = garbageCollect triStateTracing (NE.last states) expected = fromStg finalState "payload" boolRoundtrip :: TestTree boolRoundtrip = roundTripTest defSpec { testName = "Bool" , testType = Proxy :: Proxy Bool } integerRoundtrip :: TestTree integerRoundtrip = roundTripTest defSpec { testName = "Integer" , testType = Proxy :: Proxy Integer } unitRoundtrip :: TestTree unitRoundtrip = roundTripTest defSpec { testName = "Unit" , testType = Proxy :: Proxy () } listRoundtrip :: TestTree listRoundtrip = roundTripTest defSpec { testName = "List" , testType = Proxy :: Proxy [Integer] } nestedListRoundtrip :: TestTree nestedListRoundtrip = roundTripTest defSpec { testName = "Nested list" , testType = Proxy :: Proxy [[Integer]] } maybeRoundtrip :: TestTree maybeRoundtrip = roundTripTest defSpec { testName = "Maybe" , testType = Proxy :: Proxy (Maybe Integer) } nestedMaybeRoundtrip :: TestTree nestedMaybeRoundtrip = roundTripTest defSpec { testName = "Maybe" , testType = Proxy :: Proxy (Maybe (Maybe Integer)) } eitherRoundtrip :: TestTree eitherRoundtrip = roundTripTest defSpec { testName = "Maybe" , testType = Proxy :: Proxy (Either Integer Bool) } tuple2Roundtrip :: TestTree tuple2Roundtrip = roundTripTest defSpec { testName = "2-tuple" , testType = Proxy :: Proxy (Integer, Integer) } tuple3Roundtrip :: TestTree tuple3Roundtrip = roundTripTest defSpec { testName = "3-tuple" , testType = Proxy :: Proxy (Integer, Integer, Integer) } tuple4Roundtrip :: TestTree tuple4Roundtrip = roundTripTest defSpec { testName = "4-tuple" , testType = Proxy :: Proxy (Integer, Integer, Integer, Integer) } tuple5Roundtrip :: TestTree tuple5Roundtrip = roundTripTest defSpec { testName = "5-tuple" , testType = Proxy :: Proxy (Integer, Integer, Integer, Integer, Integer) } crazyRoundtrip :: TestTree crazyRoundtrip = roundTripTest defSpec { testName = "Crazy giant type" , testType = Proxy :: Proxy [Either ([[[Integer]]], [Maybe ()]) (Maybe [([Bool], Integer, [Bool])])] , maxSteps = 10e5 }
quchen/stg
test/Testsuite/Test/Marshal.hs
bsd-3-clause
5,055
0
15
1,550
1,049
607
442
114
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module: Network.FastIRC.IO -- Copyright: (c) 2010 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <[email protected]> -- Stability: alpha -- -- This module helps you with doing input and output on IRC connections -- or even log files. module Network.FastIRC.IO ( hGetIRCLine, hGetMessage, hPutCommand, hPutMessage ) where import qualified Data.ByteString.Char8 as B import Network.FastIRC.Messages import Network.FastIRC.Types import Network.FastIRC.Utils import System.IO -- | Read an IRC message string. hGetIRCLine :: Handle -> IO MsgString hGetIRCLine h = getl B.empty where getl :: MsgString -> IO MsgString getl buf = do c <- hGetChar h if isIRCEOLChar c then return buf else getl (B.snoc buf c) -- | Read the next valid IRC message. hGetMessage :: Handle -> IO Message hGetMessage h = do line <- hGetIRCLine h if B.null line then hGetMessage h else case readMessage line of Just msg -> return msg Nothing -> hGetMessage h -- | Write an IRC command with no origin. hPutCommand :: Handle -> Command -> IO () hPutCommand h cmd = B.hPutStr h $ B.append (showCommand cmd) "\r\n" -- | Write an IRC message. hPutMessage :: Handle -> Message -> IO () hPutMessage h msg = B.hPutStr h $ B.append (showMessage msg) "\r\n"
chrisdone/hulk
fastirc-0.2.0/Network/FastIRC/IO.hs
bsd-3-clause
1,396
0
13
325
331
174
157
33
3
module Servant.Server.Auth.Token.LevelDB( LevelDBBackendT , runLevelDBBackendT , LevelDBEnv , newLevelDBEnv ) where import Control.Monad.Base import Control.Monad.Catch import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Trans.Control import Control.Monad.Trans.Resource import Servant.Server import Servant.Server.Auth.Token.Config import Servant.Server.Auth.Token.LevelDB.Schema (LevelDBEnv, newLevelDBEnv) import Servant.Server.Auth.Token.Model import qualified Servant.Server.Auth.Token.LevelDB.Schema as S -- | Monad transformer that implements storage backend newtype LevelDBBackendT m a = LevelDBBackendT { unLevelDBBackendT :: ReaderT (AuthConfig, LevelDBEnv) (ExceptT ServantErr (ResourceT m)) a } deriving (Functor, Applicative, Monad, MonadIO, MonadError ServantErr, MonadReader (AuthConfig, LevelDBEnv), MonadThrow, MonadCatch) deriving instance MonadBase IO m => MonadBase IO (LevelDBBackendT m) deriving instance (MonadBase IO m, MonadThrow m, MonadIO m) => MonadResource (LevelDBBackendT m) instance Monad m => HasAuthConfig (LevelDBBackendT m) where getAuthConfig = fst <$> LevelDBBackendT ask newtype StMLevelDBBackendT m a = StMLevelDBBackendT { unStMLevelDBBackendT :: StM (ReaderT (AuthConfig, LevelDBEnv) (ExceptT ServantErr m)) a } instance MonadBaseControl IO m => MonadBaseControl IO (LevelDBBackendT m) where type StM (LevelDBBackendT m) a = StMLevelDBBackendT m a liftBaseWith f = LevelDBBackendT $ liftBaseWith $ \q -> f (fmap StMLevelDBBackendT . q . unLevelDBBackendT) restoreM = LevelDBBackendT . restoreM . unStMLevelDBBackendT -- | Execute backend action with given connection pool. runLevelDBBackendT :: MonadBaseControl IO m => AuthConfig -> LevelDBEnv -> LevelDBBackendT m a -> m (Either ServantErr a) runLevelDBBackendT cfg db ma = runResourceT . runExceptT $ runReaderT (unLevelDBBackendT ma) (cfg, db) -- | Helper to extract LevelDB reference getEnv :: Monad m => LevelDBBackendT m LevelDBEnv getEnv = snd <$> LevelDBBackendT ask -- | Helper to lift low-level LevelDB queries to backend monad liftEnv :: Monad m => (LevelDBEnv -> ResourceT m a) -> LevelDBBackendT m a liftEnv f = do e <- getEnv LevelDBBackendT . lift . lift $ f e instance (MonadBase IO m, MonadIO m, MonadThrow m, MonadMask m) => HasStorage (LevelDBBackendT m) where getUserImpl = liftEnv . flip S.load getUserImplByLogin = liftEnv . S.getUserImplByLogin listUsersPaged page size = liftEnv $ S.listUsersPaged page size getUserImplPermissions = liftEnv . S.getUserImplPermissions deleteUserPermissions = liftEnv . S.deleteUserPermissions insertUserPerm = liftEnv . S.insertUserPerm insertUserImpl = liftEnv . S.insertUserImpl replaceUserImpl i v = liftEnv $ S.replaceUserImpl i v deleteUserImpl = liftEnv . S.deleteUserImpl hasPerm i p = liftEnv $ S.hasPerm i p getFirstUserByPerm = liftEnv . S.getFirstUserByPerm selectUserImplGroups = liftEnv . S.selectUserImplGroups clearUserImplGroups = liftEnv . S.clearUserImplGroups insertAuthUserGroup = liftEnv . S.insertAuthUserGroup insertAuthUserGroupUsers = liftEnv . S.insertAuthUserGroupUsers insertAuthUserGroupPerms = liftEnv . S.insertAuthUserGroupPerms getAuthUserGroup = liftEnv . flip S.load listAuthUserGroupPermissions = liftEnv . S.listAuthUserGroupPermissions listAuthUserGroupUsers = liftEnv . S.listAuthUserGroupUsers replaceAuthUserGroup i v = liftEnv $ S.replaceAuthUserGroup i v clearAuthUserGroupUsers = liftEnv . S.clearAuthUserGroupUsers clearAuthUserGroupPerms = liftEnv . S.clearAuthUserGroupPerms deleteAuthUserGroup = liftEnv . S.deleteAuthUserGroup listGroupsPaged page size = liftEnv $ S.listGroupsPaged page size setAuthUserGroupName i n = liftEnv $ S.setAuthUserGroupName i n setAuthUserGroupParent i mp = liftEnv $ S.setAuthUserGroupParent i mp insertSingleUseCode = liftEnv . S.insertSingleUseCode setSingleUseCodeUsed i mt = liftEnv $ S.setSingleUseCodeUsed i mt getUnusedCode c i t = liftEnv $ S.getUnusedCode c i t invalidatePermamentCodes i t = liftEnv $ S.invalidatePermamentCodes i t selectLastRestoreCode i t = liftEnv $ S.selectLastRestoreCode i t insertUserRestore = liftEnv . S.insertUserRestore findRestoreCode i rc t = liftEnv $ S.findRestoreCode i rc t replaceRestoreCode i v = liftEnv $ S.replaceRestoreCode i v findAuthToken i t = liftEnv $ S.findAuthToken i t findAuthTokenByValue t = liftEnv $ S.findAuthTokenByValue t insertAuthToken = liftEnv . S.insertAuthToken replaceAuthToken i v = liftEnv $ S.replaceAuthToken i v {-# INLINE getUserImpl #-} {-# INLINE getUserImplByLogin #-} {-# INLINE listUsersPaged #-} {-# INLINE getUserImplPermissions #-} {-# INLINE deleteUserPermissions #-} {-# INLINE insertUserPerm #-} {-# INLINE insertUserImpl #-} {-# INLINE replaceUserImpl #-} {-# INLINE deleteUserImpl #-} {-# INLINE hasPerm #-} {-# INLINE getFirstUserByPerm #-} {-# INLINE selectUserImplGroups #-} {-# INLINE clearUserImplGroups #-} {-# INLINE insertAuthUserGroup #-} {-# INLINE insertAuthUserGroupUsers #-} {-# INLINE insertAuthUserGroupPerms #-} {-# INLINE getAuthUserGroup #-} {-# INLINE listAuthUserGroupPermissions #-} {-# INLINE listAuthUserGroupUsers #-} {-# INLINE replaceAuthUserGroup #-} {-# INLINE clearAuthUserGroupUsers #-} {-# INLINE clearAuthUserGroupPerms #-} {-# INLINE deleteAuthUserGroup #-} {-# INLINE listGroupsPaged #-} {-# INLINE setAuthUserGroupName #-} {-# INLINE setAuthUserGroupParent #-} {-# INLINE insertSingleUseCode #-} {-# INLINE setSingleUseCodeUsed #-} {-# INLINE getUnusedCode #-} {-# INLINE invalidatePermamentCodes #-} {-# INLINE selectLastRestoreCode #-} {-# INLINE insertUserRestore #-} {-# INLINE findRestoreCode #-} {-# INLINE replaceRestoreCode #-} {-# INLINE findAuthToken #-} {-# INLINE findAuthTokenByValue #-} {-# INLINE insertAuthToken #-} {-# INLINE replaceAuthToken #-}
VyacheslavHashov/servant-auth-token
servant-auth-token-leveldb/src/Servant/Server/Auth/Token/LevelDB.hs
bsd-3-clause
5,942
0
12
896
1,280
693
587
-1
-1
{-# LANGUAGE GADTs, EmptyDataDecls, KindSignatures, ExistentialQuantification, ScopedTypeVariables, DeriveDataTypeable, DeriveFunctor, NoMonomorphismRestriction, ViewPatterns, RankNTypes #-} module Intuitionistic where -- only propositional, sorry import Prelude hiding (catch) import Data.Typeable import Data.Functor.Identity import Data.Data hiding (Prefix,Infix) import Control.Applicative hiding ((<|>),many) import Control.Exception hiding (try) import Text.Parsec import Text.Parsec.Expr import qualified Text.Parsec.Token as P import Text.Parsec.Language (emptyDef) import Common errorModule :: String -> a errorModule s = error ("Intuitionistic." ++ s) -- Sequent data S = S { hyps :: [L], goal :: L } deriving (Show, Eq, Data, Typeable) data L = Prop String | Conj L L | Disj L L | Imp L L | Iff L L | Not L | Top | Bot deriving (Show, Eq, Data, Typeable) -- Parsing userParseError :: Either e a -> IO a userParseError = either (\_ -> throwIO ParseFailure) return parseSequent :: String -> IO S parseSequent g = userParseError $ parse (whiteSpace >> sequent <* eof) "goal" g intuitionisticStyle, intuitionisticStyleUpper, intuitionisticStyleLower :: P.LanguageDef st intuitionisticStyle = emptyDef { P.commentStart = "(*" , P.commentEnd = "*)" , P.nestedComments = True , P.identStart = letter <|> oneOf "_" , P.identLetter = alphaNum <|> oneOf "_'" -- Ops are sloppy, but should work OK for our use case. , P.opStart = P.opLetter intuitionisticStyle , P.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~," , P.reservedOpNames = ["(",")",".",",",";", "->", "→", "<->", "↔", "<=>", "/\\","∧", "\\/","∨", "|-","⊢", "~","¬"] , P.reservedNames = [ "True","False","⊤","⊥", "and", "or", "ex", "iff", "not" ] , P.caseSensitive = True } intuitionisticStyleUpper = intuitionisticStyle {P.identStart = upper} intuitionisticStyleLower = intuitionisticStyle {P.identStart = lower} lexer, lexerUpper, lexerLower :: P.GenTokenParser String u Identity lexer = P.makeTokenParser intuitionisticStyle lexerUpper = P.makeTokenParser intuitionisticStyleUpper lexerLower = P.makeTokenParser intuitionisticStyleLower type Parser a = forall u. ParsecT String u Identity a reserved :: String -> Parser () reserved = P.reserved lexer upperIdentifier :: Parser String upperIdentifier = P.identifier lexerUpper lowerIdentifier :: Parser String lowerIdentifier = P.identifier lexerLower reservedOp :: String -> Parser () reservedOp = P.reservedOp lexer integer :: Parser Integer integer = P.integer lexer whiteSpace :: Parser () whiteSpace = P.whiteSpace lexer parens :: ParsecT String u Identity a -> ParsecT String u Identity a parens = P.parens lexer comma :: Parser String comma = P.comma lexer commaSep :: ParsecT String u Identity a -> ParsecT String u Identity [a] commaSep = P.commaSep lexer commaSep1 :: ParsecT String u Identity a -> ParsecT String u Identity [a] commaSep1 = P.commaSep1 lexer lexeme :: ParsecT String u Identity a -> ParsecT String u Identity a lexeme = P.lexeme lexer -- term ::= term /\ term -- term \/ term -- ~ term -- True -- False -- identifier (universe , ... universe) -- -- also Unicode supported, so that copypasta works sequent :: Parser S sequent = try (S <$> commaSep expr <* choice [reservedOp "|-", reservedOp "⊢" ] <*> expr) <|> try (S [] <$> expr) <?> "sequent" table :: [[Operator String u Identity L]] table = [ [prefix "~" Not, prefix "¬" Not ] , [binary "/\\" Conj AssocLeft, binary "∧" Conj AssocLeft ] , [binary "\\/" Disj AssocLeft, binary "∨" Disj AssocLeft ] , [binary "->" Imp AssocRight, binary "→" Imp AssocRight, binary "<->" Iff AssocRight, binary "↔" Iff AssocRight, binary "<=>" Iff AssocRight ] ] binary :: String -> (a -> a -> a) -> Assoc -> Operator String u Identity a binary name fun assoc = Infix (do{ reservedOp name; return fun }) assoc prefix, postfix :: String -> (a -> a) -> Operator String u Identity a prefix name fun = Prefix (do{ reservedOp name; return fun }) postfix name fun = Postfix (do{ reservedOp name; return fun }) expr :: Parser L expr = buildExpressionParser table term <?> "expression" term :: Parser L term = try (parens expr) <|> try (Top <$ choice [reserved "True", reserved "⊤"]) <|> try (Bot <$ choice [reserved "False", reserved "⊥"]) <|> try (Prop <$> upperIdentifier) <?> "simple expression"
diflying/logitext
Intuitionistic.hs
bsd-3-clause
4,996
0
14
1,350
1,426
776
650
104
1
module Main (main) where import qualified Language.Futhark.SyntaxTests import qualified Futhark.Representation.AST.Syntax.CoreTests import qualified Futhark.Representation.AST.AttributesTests import qualified Futhark.Optimise.AlgSimplifyTests import Test.Framework (defaultMain, testGroup, Test) allTests :: [Test] allTests = [ testGroup "external SyntaxTests" Language.Futhark.SyntaxTests.tests , testGroup "AttributesTests" Futhark.Representation.AST.AttributesTests.tests , testGroup "AlgSimplifyTests" Futhark.Optimise.AlgSimplifyTests.tests , testGroup "internal CoreTests" Futhark.Representation.AST.Syntax.CoreTests.tests ] main :: IO () main = defaultMain allTests
ihc/futhark
unittests/futhark_tests.hs
isc
687
0
7
67
138
87
51
14
1
{-# LANGUAGE TemplateHaskell #-} {-| Implementation of the Ganeti Ssconf interface. -} {- Copyright (C) 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Ssconf ( SSKey(..) , sSKeyToRaw , sSKeyFromRaw , getPrimaryIPFamily , getMasterCandidatesIps , keyToFilename , sSFilePrefix ) where import Ganeti.THH import Control.Exception import Control.Monad (liftM) import Data.Maybe (fromMaybe) import qualified Network.Socket as Socket import System.FilePath ((</>)) import System.IO.Error (isDoesNotExistError) import qualified Ganeti.Constants as C import qualified Ganeti.Path as Path import Ganeti.BasicTypes import Ganeti.Utils -- | Maximum ssconf file size we support. maxFileSize :: Int maxFileSize = 131072 -- | ssconf file prefix, re-exported from Constants. sSFilePrefix :: FilePath sSFilePrefix = C.ssconfFileprefix $(declareSADT "SSKey" [ ("SSClusterName", 'C.ssClusterName) , ("SSClusterTags", 'C.ssClusterTags) , ("SSFileStorageDir", 'C.ssFileStorageDir) , ("SSSharedFileStorageDir", 'C.ssSharedFileStorageDir) , ("SSMasterCandidates", 'C.ssMasterCandidates) , ("SSMasterCandidatesIps", 'C.ssMasterCandidatesIps) , ("SSMasterIp", 'C.ssMasterIp) , ("SSMasterNetdev", 'C.ssMasterNetdev) , ("SSMasterNetmask", 'C.ssMasterNetmask) , ("SSMasterNode", 'C.ssMasterNode) , ("SSNodeList", 'C.ssNodeList) , ("SSNodePrimaryIps", 'C.ssNodePrimaryIps) , ("SSNodeSecondaryIps", 'C.ssNodeSecondaryIps) , ("SSOfflineNodes", 'C.ssOfflineNodes) , ("SSOnlineNodes", 'C.ssOnlineNodes) , ("SSPrimaryIpFamily", 'C.ssPrimaryIpFamily) , ("SSInstanceList", 'C.ssInstanceList) , ("SSReleaseVersion", 'C.ssReleaseVersion) , ("SSHypervisorList", 'C.ssHypervisorList) , ("SSMaintainNodeHealth", 'C.ssMaintainNodeHealth) , ("SSUidPool", 'C.ssUidPool) , ("SSNodegroups", 'C.ssNodegroups) ]) -- | Convert a ssconf key into a (full) file path. keyToFilename :: FilePath -- ^ Config path root -> SSKey -- ^ Ssconf key -> FilePath -- ^ Full file name keyToFilename cfgpath key = cfgpath </> sSFilePrefix ++ sSKeyToRaw key -- | Runs an IO action while transforming any error into 'Bad' -- values. It also accepts an optional value to use in case the error -- is just does not exist. catchIOErrors :: Maybe a -- ^ Optional default -> IO a -- ^ Action to run -> IO (Result a) catchIOErrors def action = Control.Exception.catch (do result <- action return (Ok result) ) (\err -> let bad_result = Bad (show err) in return $ if isDoesNotExistError err then maybe bad_result Ok def else bad_result) -- | Read an ssconf file. readSSConfFile :: Maybe FilePath -- ^ Optional config path override -> Maybe String -- ^ Optional default value -> SSKey -- ^ Desired ssconf key -> IO (Result String) readSSConfFile optpath def key = do dpath <- Path.dataDir result <- catchIOErrors def . readFile . keyToFilename (fromMaybe dpath optpath) $ key return (liftM (take maxFileSize) result) -- | Parses a string containing an IP family parseIPFamily :: Int -> Result Socket.Family parseIPFamily fam | fam == C.ip4Family = Ok Socket.AF_INET | fam == C.ip6Family = Ok Socket.AF_INET6 | otherwise = Bad $ "Unknown af_family value: " ++ show fam -- | Read the primary IP family. getPrimaryIPFamily :: Maybe FilePath -> IO (Result Socket.Family) getPrimaryIPFamily optpath = do result <- readSSConfFile optpath (Just (show C.ip4Family)) SSPrimaryIpFamily return (liftM rStripSpace result >>= tryRead "Parsing af_family" >>= parseIPFamily) -- | Read the list of IP addresses of the master candidates of the cluster. getMasterCandidatesIps :: Maybe FilePath -> IO (Result [String]) getMasterCandidatesIps optPath = do result <- readSSConfFile optPath Nothing SSMasterCandidatesIps return $ liftM lines result
dblia/nosql-ganeti
src/Ganeti/Ssconf.hs
gpl-2.0
4,932
0
14
1,205
918
519
399
86
2
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} module OpenCog.Lojban.Syntax.Types where import Prelude hiding (id,(.),(<*>),(<$>),pure,(*>),(<*),foldl) import qualified Data.Map as M import Data.List (partition,isPrefixOf,isSuffixOf,nub,any,intercalate) import Data.Maybe (fromJust) import Control.Category (id,(.)) import Control.Isomorphism.Partial import Control.Isomorphism.Partial.Derived import Control.Isomorphism.Partial.Unsafe import Control.Isomorphism.Partial.TH import Text.Syntax import OpenCog.AtomSpace import OpenCog.Lojban.Util import Control.Monad.Trans.Reader import qualified Data.ListTrie.Patricia.Set.Ord as TS type StringSet = TS.TrieSet Char --The firs element of the tuple is a Atom that is part of the main Sentence/Link --The List are other atoms which have to be added to the Atomspace or are needed for printing type State a = (a,[Atom]) type Tag = String type Sumti = Tagged Atom type Selbri = (TruthVal,Atom) --STring represents TV type Tagged a = (a,Maybe Tag) type LCON = (Maybe String,(String,Maybe String)) type Con = (Maybe LCON,Maybe (Tagged Selbri)) type Bridi = ([Sumti],((Maybe Atom,(Maybe String,Tagged Selbri)),[Sumti])) type WordList = (M.Map String StringSet,StringSet,Iso String String,Int) type SyntaxReader a = forall delta. Syntax delta => ReaderT WordList delta a instance IsoFunctor f => IsoFunctor (ReaderT a f) where iso <$> r = ReaderT (\e -> iso <$> runReaderT r e) instance ProductFunctor f => ProductFunctor (ReaderT a f) where a <*> b = ReaderT (\e -> runReaderT a e <*> runReaderT b e) instance Alternative f => Alternative (ReaderT a f) where a <|> b = ReaderT (\e -> runReaderT a e <|> runReaderT b e) a <||> b = ReaderT (\e -> runReaderT a e <||> runReaderT b e) empty = ReaderT (const empty) instance Syntax f => Syntax (ReaderT a f) where pure x = ReaderT (\e -> pure x) token = ReaderT (const token) withText r = ReaderT (withText . runReaderT r) ptp r1 iso r2 = ReaderT (\e -> ptp (runReaderT r1 e) iso (runReaderT r2 e)) withOut r1 r2 = ReaderT (\e -> withOut (runReaderT r1 e) (runReaderT r2 e)) $(defineIsomorphisms ''Atom)
ruiting/opencog
opencog/nlp/lojban/HaskellLib/src/OpenCog/Lojban/Syntax/Types.hs
agpl-3.0
2,222
0
11
421
793
445
348
47
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE NoMonomorphismRestriction #-} module T15843a where import Language.Haskell.TH first_of_2 = [| (909,) |] second_of_2 = [| (,909) |] empty_2 = [| (,) |] full_2 = [| (909,606) |] third_of_3 = [| (,,909) |] first_of_2_T = [|| (909,) ||] second_of_2_T = [|| (,909) ||] empty_2_T = [|| (,) ||] full_2_T = [|| (909,606) ||] third_of_3_T = [|| (,,909) ||] unb0 = [| (# , #) |] unb1 = [| (# 'c', False #) |] unb2 = [| (# 'c', #) |] unb3 = [| (# ,False #) |] unb4 = [| (# ,False #) 'c' |]
sdiehl/ghc
testsuite/tests/th/T15843a.hs
bsd-3-clause
604
0
4
125
94
71
23
-1
-1
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DataKinds #-} module Bug where pattern PATTERN = () wrongLift :: PATTERN wrongLift = undefined
sdiehl/ghc
testsuite/tests/patsyn/should_fail/T9161-1.hs
bsd-3-clause
144
0
6
24
26
16
10
6
1
{-# LANGUAGE TypeFamilies, FlexibleContexts #-} -- | Expand allocations inside of maps when possible. module Futhark.Pass.ExpandAllocations ( expandAllocations ) where import Control.Applicative import Control.Monad.Except import Control.Monad.State import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.Maybe import Data.List import Data.Monoid import Prelude hiding (div, quot) import Futhark.MonadFreshNames import Futhark.Tools import Futhark.Util import Futhark.Pass import Futhark.Representation.AST import Futhark.Representation.ExplicitMemory hiding (Prog, Body, Stm, Pattern, PatElem, BasicOp, Exp, Lambda, ExtLambda, FunDef, FParam, LParam, RetType) import qualified Futhark.Representation.ExplicitMemory.IndexFunction as IxFun expandAllocations :: Pass ExplicitMemory ExplicitMemory expandAllocations = simplePass "expand allocations" "Expand allocations" $ intraproceduralTransformation transformFunDef transformFunDef :: MonadFreshNames m => FunDef ExplicitMemory -> m (FunDef ExplicitMemory) transformFunDef fundec = do body' <- modifyNameSource $ runState m return fundec { funDefBody = body' } where m = transformBody $ funDefBody fundec type ExpandM = State VNameSource transformBody :: Body ExplicitMemory -> ExpandM (Body ExplicitMemory) transformBody (Body () bnds res) = do bnds' <- concat <$> mapM transformStm bnds return $ Body () bnds' res transformStm :: Stm ExplicitMemory -> ExpandM [Stm ExplicitMemory] transformStm (Let pat aux e) = do (bnds, e') <- transformExp =<< mapExpM transform e return $ bnds ++ [Let pat aux e'] where transform = identityMapper { mapOnBody = const transformBody } transformExp :: Exp ExplicitMemory -> ExpandM ([Stm ExplicitMemory], Exp ExplicitMemory) transformExp (Op (Inner (Kernel desc space ts kbody))) | Right (kbody', thread_allocs) <- extractKernelBodyAllocations bound_in_kernel kbody = do num_threads64 <- newVName "num_threads64" let num_threads64_pat = Pattern [] [PatElem num_threads64 BindVar $ MemPrim int64] num_threads64_bnd = Let num_threads64_pat (defAux ()) $ BasicOp $ ConvOp (SExt Int32 Int64) (spaceNumThreads space) (alloc_bnds, alloc_offsets) <- expandedAllocations (Var num_threads64, spaceNumGroups space, spaceGroupSize space) (spaceGlobalId space, spaceGroupId space, spaceLocalId space) thread_allocs let kbody'' = offsetMemoryInKernelBody alloc_offsets kbody' return (num_threads64_bnd : alloc_bnds, Op $ Inner $ Kernel desc space ts kbody'') where bound_in_kernel = S.fromList $ M.keys $ scopeOfKernelSpace space <> scopeOf (kernelBodyStms kbody) transformExp e = return ([], e) -- | Extract allocations from 'Thread' statements with -- 'extractThreadAllocations'. extractKernelBodyAllocations :: Names -> KernelBody InKernel -> Either String (KernelBody InKernel, M.Map VName (SubExp, Space)) extractKernelBodyAllocations bound_before_body kbody = do (allocs, stms) <- mapAccumLM extract M.empty $ kernelBodyStms kbody return (kbody { kernelBodyStms = concat stms }, allocs) where extract allocs bnd = do (bnds, body_allocs) <- extractThreadAllocations bound_before_body [bnd] return (allocs <> body_allocs, bnds) extractThreadAllocations :: Names -> [Stm InKernel] -> Either String ([Stm InKernel], M.Map VName (SubExp, Space)) extractThreadAllocations bound_before_body bnds = do (allocs, bnds') <- mapAccumLM isAlloc M.empty bnds return (catMaybes bnds', allocs) where bound_here = bound_before_body `S.union` boundByStms bnds isAlloc _ (Let (Pattern [] [patElem]) _ (Op (Alloc (Var v) _))) | v `S.member` bound_here = throwError $ "Size " ++ pretty v ++ " for block " ++ pretty patElem ++ " is not lambda-invariant" isAlloc allocs (Let (Pattern [] [patElem]) _ (Op (Alloc size space))) = return (M.insert (patElemName patElem) (size, space) allocs, Nothing) isAlloc allocs bnd = return (allocs, Just bnd) expandedAllocations :: (SubExp,SubExp, SubExp) -> (VName, VName, VName) -> M.Map VName (SubExp, Space) -> ExpandM ([Stm ExplicitMemory], RebaseMap) expandedAllocations (num_threads64, num_groups, group_size) (_thread_index, group_id, local_id) thread_allocs = do -- We expand the allocations by multiplying their size with the -- number of kernel threads. (alloc_bnds, rebase_map) <- unzip <$> mapM expand (M.toList thread_allocs) -- Fix every reference to the memory blocks to be offset by the -- thread number. let alloc_offsets = RebaseMap { rebaseMap = mconcat rebase_map , indexVariable = (group_id, local_id) , kernelWidth = (num_groups, group_size) } return (concat alloc_bnds, alloc_offsets) where expand (mem, (per_thread_size, Space "local")) = do let allocpat = Pattern [] [PatElem mem BindVar $ MemMem per_thread_size $ Space "local"] return ([Let allocpat (defAux ()) $ Op $ Alloc per_thread_size $ Space "local"], mempty) expand (mem, (per_thread_size, space)) = do total_size <- newVName "total_size" let sizepat = Pattern [] [PatElem total_size BindVar $ MemPrim int64] allocpat = Pattern [] [PatElem mem BindVar $ MemMem (Var total_size) space] return ([Let sizepat (defAux ()) $ BasicOp $ BinOp (Mul Int64) num_threads64 per_thread_size, Let allocpat (defAux ()) $ Op $ Alloc (Var total_size) space], M.singleton mem newBase) newBase old_shape = let num_dims = length old_shape perm = [0, num_dims+1] ++ [1..num_dims] root_ixfun = IxFun.iota (primExpFromSubExp int32 num_groups : old_shape ++ [primExpFromSubExp int32 group_size]) permuted_ixfun = IxFun.permute root_ixfun perm untouched d = DimSlice 0 d 1 offset_ixfun = IxFun.slice permuted_ixfun $ [DimFix (LeafExp group_id int32), DimFix (LeafExp local_id int32)] ++ map untouched old_shape in offset_ixfun data RebaseMap = RebaseMap { rebaseMap :: M.Map VName ([PrimExp VName] -> IxFun) -- ^ A map from memory block names to new index function bases. , indexVariable :: (VName, VName) , kernelWidth :: (SubExp, SubExp) } lookupNewBase :: VName -> [PrimExp VName] -> RebaseMap -> Maybe IxFun lookupNewBase name dims = fmap ($dims) . M.lookup name . rebaseMap offsetMemoryInKernelBody :: RebaseMap -> KernelBody InKernel -> KernelBody InKernel offsetMemoryInKernelBody initial_offsets kbody = kbody { kernelBodyStms = stms' } where stms' = snd $ mapAccumL offsetMemoryInStm initial_offsets $ kernelBodyStms kbody offsetMemoryInBody :: RebaseMap -> Body InKernel -> Body InKernel offsetMemoryInBody offsets (Body attr bnds res) = Body attr (snd $ mapAccumL offsetMemoryInStm offsets bnds) res offsetMemoryInStm :: RebaseMap -> Stm InKernel -> (RebaseMap, Stm InKernel) offsetMemoryInStm offsets (Let pat attr e) = (offsets', Let pat' attr $ offsetMemoryInExp offsets e) where (offsets', pat') = offsetMemoryInPattern offsets pat offsetMemoryInPattern :: RebaseMap -> Pattern InKernel -> (RebaseMap, Pattern InKernel) offsetMemoryInPattern offsets (Pattern ctx vals) = (offsets', Pattern ctx vals') where offsets' = foldl inspectCtx offsets ctx vals' = map inspectVal vals inspectVal patElem = patElem { patElemAttr = offsetMemoryInMemBound offsets' $ patElemAttr patElem } inspectCtx ctx_offsets patElem | Mem _ _ <- patElemType patElem = error $ unwords ["Cannot deal with existential memory block", pretty (patElemName patElem), "when expanding inside kernels."] | otherwise = ctx_offsets offsetMemoryInParam :: RebaseMap -> Param (MemBound u) -> Param (MemBound u) offsetMemoryInParam offsets fparam = fparam { paramAttr = offsetMemoryInMemBound offsets $ paramAttr fparam } offsetMemoryInMemBound :: RebaseMap -> MemBound u -> MemBound u offsetMemoryInMemBound offsets (MemArray bt shape u (ArrayIn mem ixfun)) | Just new_base <- lookupNewBase mem (IxFun.base ixfun) offsets = MemArray bt shape u $ ArrayIn mem $ IxFun.rebase new_base ixfun offsetMemoryInMemBound _ summary = summary offsetMemoryInBodyReturns :: RebaseMap -> BodyReturns -> BodyReturns offsetMemoryInBodyReturns offsets (MemArray pt shape u (ReturnsInBlock mem ixfun)) | Just ixfun' <- isStaticIxFun ixfun, Just new_base <- lookupNewBase mem (IxFun.base ixfun') offsets = MemArray pt shape u $ ReturnsInBlock mem $ IxFun.rebase (fmap (fmap Free) new_base) ixfun offsetMemoryInBodyReturns _ br = br offsetMemoryInExp :: RebaseMap -> Exp InKernel -> Exp InKernel offsetMemoryInExp offsets (DoLoop ctx val form body) = DoLoop (zip ctxparams' ctxinit) (zip valparams' valinit) form body' where (ctxparams, ctxinit) = unzip ctx (valparams, valinit) = unzip val body' = offsetMemoryInBody offsets body ctxparams' = map (offsetMemoryInParam offsets) ctxparams valparams' = map (offsetMemoryInParam offsets) valparams offsetMemoryInExp offsets (Op (Inner (GroupStream w max_chunk lam accs arrs))) = Op (Inner (GroupStream w max_chunk lam' accs arrs)) where lam' = lam { groupStreamLambdaBody = offsetMemoryInBody offsets $ groupStreamLambdaBody lam , groupStreamAccParams = map (offsetMemoryInParam offsets) $ groupStreamAccParams lam , groupStreamArrParams = map (offsetMemoryInParam offsets) $ groupStreamArrParams lam } offsetMemoryInExp offsets (Op (Inner (GroupReduce w lam input))) = Op (Inner (GroupReduce w lam' input)) where lam' = lam { lambdaBody = offsetMemoryInBody offsets $ lambdaBody lam } offsetMemoryInExp offsets (Op (Inner (Combine cspace ts active body))) = Op $ Inner $ Combine cspace ts active $ offsetMemoryInBody offsets body offsetMemoryInExp offsets e = mapExp recurse e where recurse = identityMapper { mapOnBody = const $ return . offsetMemoryInBody offsets , mapOnBranchType = return . offsetMemoryInBodyReturns offsets }
ihc/futhark
src/Futhark/Pass/ExpandAllocations.hs
isc
11,134
0
18
2,976
3,122
1,588
1,534
199
3
{- Joseph Eremondi Program Verification UU# 4229924 March 4, 2015 -} module WLP where import Types import Z3Utils import Data.Data import Data.Generics import Data.List (sort) import qualified Data.Map as Map --trace _ x = x --Constants limiting how far we go trying to infer loop invariants fixpointDepth :: Int fixpointDepth = 10 unrollDepth :: Int unrollDepth = 20 {- Helper function to get the names of variables in an assignment -} getVarTargets :: [AssignTarget] -> [Name] getVarTargets targets = concatMap (\t -> case t of VarTarget n -> [n] _ -> []) targets {- Helper function to get array name/index pairs in an assignment -} getArrTargets :: [AssignTarget] -> [(Name, Expression)] getArrTargets targets = concatMap (\t -> case t of ArrTarget n i -> [(n, i)] _ -> []) targets {- Given postconditions for each possible function called, Parameter types for each possible function called, the "top-level" statement we're finding the WLP for, a "current" statement, and an expression, find the weakest condition which will imply the postcondition whenever the statement halts. We need the postconditions in order to allow function calls, since inferring Function postconditions is equivalent to inferring loop invariants, if we allow recursion We need the "top-level" statement to get its free vars, since Z3 is used to try to find loop invariants in this procedure. -} wlp :: (PostConds, ProgParams, Statement) -> Statement -> Expression -> (Expression, [Expression]) wlp pconds Skip q = (q, []) wlp pconds (Assert p) q = (BinOp p LAnd q, []) wlp pconds (Assume p) q = (BinOp p Implies q, []) wlp pconds (Assign targets exp) q = let sub1 = subExpForName (getVarTargets targets) exp q sub2 = subExpForArrName (getArrTargets targets) exp sub1 in (sub2, []) wlp pconds (Return expr) q = wlp pconds (Assign [VarTarget $ ToName "return"] expr) q wlp (postConds, progParams, _) (FnCallAssign target progName params) q = let targetExp = case target of VarTarget name -> EName name ArrTarget arrName expr -> ArrAccess arrName expr progPostcond = postConds Map.! progName paramNames = map (\(Variable _ name _) -> name)$ progParams Map.! progName paramPairs = zip paramNames params postCondWithParams = foldr (\(pname, pexp) pcond -> subExpForName [pname] pexp pcond) progPostcond paramPairs postCondWithRet = subExpForName [ToName "return"] targetExp postCondWithParams in (BinOp postCondWithRet Implies q, []) wlp pconds (NonDet s1 s2) q = let (sub1, checks1) = (wlp pconds s1 q) (sub2, checks2) = (wlp pconds s2 q) in (BinOp sub1 LAnd sub2, checks1 ++ checks2) wlp pconds (Seq s1 s2) q = let (sub1, checks1) = (wlp pconds s2 q) (sub2, checks2) = wlp pconds s1 sub1 in (sub2, checks1 ++ checks2) --In this case, we must check that our invariant holds, so we generate our checks wlp pconds (Loop (Just invar) guard body) q = let (subWLP, subConds) = wlp pconds body invar in (invar, [ BinOp (BinOp invar LAnd (LNot guard)) Implies q ,BinOp (BinOp invar LAnd guard) Implies subWLP ] ++ subConds) wlp pconds (Loop Nothing guard body) q = case (tryFindingInvar pconds guard body q) of Nothing -> wlp pconds (unrollLoop guard body) q Just invar -> let (subWLP, subConds) = wlp pconds body invar in (invar, [ (invar `land` (LNot guard)) `implies` q , (invar `land` guard) `implies` subWLP ] ++ subConds) wlp pconds (Var vars s) q = wlp pconds s q {- Test if a given name occurs as a free variable in an expression Used to resolve naming issues with foralls -} occursIn :: Name -> Expression -> Bool occursIn n (IntLit e) = False occursIn n (BoolLit e) = False occursIn n (EName e) = e == n occursIn n (BinOp e1 e2 e3) = (occursIn n e1) || (occursIn n e3) occursIn n (LNot e) = occursIn n e occursIn n (UninterpCall e1 e2) = (not . null) $ filter (== True) $ map (occursIn n) e2 occursIn n (Forall (n1, _) e2) = (n /= n1) && (occursIn n e2) --Exclude the bound variable occursIn n (ArrAccess e1 e2) = (e1 == n) || (occursIn n e2) occursIn n (IfThenElse e1 e2 e3) = (occursIn n e1) || (occursIn n e2) || (occursIn n e3) occursIn n (RepBy e1 e2 e3) = (occursIn n e1) || (occursIn n e2) || (occursIn n e3) {- Given a set of names to replace, an expression to replace them with, and an expression e, check if e is a name in our list, and if it is, replace it with the given substitution -} subOneLevel :: [Name] -> Expression -> Expression -> Expression subOneLevel names subExp e@(EName varName) = if (varName `elem` names) then subExp else e --subOneLevel names subExp e@(Forall _ _) = fixForall subExp e subOneLevel _ _ e = e {- Rename variables in a Forall expression that conflict with the given expression which is about to be substituted. Fixes the problems with assignment subsitution conflicting with foralls. -} fixForall :: Expression -> Expression -> Expression fixForall subExp e = case e of Forall (vn, vt) body -> if vn `occursIn` subExp --Recursively call to make sure our new name isn't also in the list then let genNewName n = if n `occursIn` subExp then genNewName (ToName $ "freshVar" ++ fromName n) else n newName = genNewName vn newBody = subExpForName [vn] (EName newName) body ret = Forall (newName, vt) newBody in ret else e _ -> e {- Use Scrap-Your-Boilerplate to recursively apply our substutitions to our expression, bottom-up -} subExpForName :: [Name] -> Expression -> Expression -> Expression subExpForName names subExp = let subAll = everywhere (mkT $ subOneLevel names subExp) fixAllForalls = everywhere (mkT $ fixForall subExp ) in (subAll . fixAllForalls) {- Given a list of array names and index expressions, an expression to subtitute, and an expression e, check if e is an array name in our list, and if it is, replace it with the approprate RepBy expression to denote a substitution -} subOneLevelArr :: [(Name, Expression)] -> Expression -> Expression -> Expression subOneLevelArr nameIndexPairs subExpr e@(EName varName) = let nameIndList = filter (\(n,_) -> n == varName) nameIndexPairs in foldr (\(_,i) expSoFar -> RepBy expSoFar i subExpr) e nameIndList subOneLevelArr l subExp e = e {- Use Scrap-Your-Boilerplate to recursively apply our substutitions to our expression, bottom-up -} subExpForArrName :: (Data a) => [(Name, Expression)] -> Expression -> a -> a subExpForArrName names subExp = let subAll = everywhere (mkT $ subOneLevelArr names subExp) fixAllForalls = everywhere (mkT $ fixForall subExp ) in (subAll . fixAllForalls) {- Given a loop guard and body, unroll the loop a constant number of times Used when we can't find a fixed-point invariant -} unrollLoop :: Expression -> Statement -> Statement unrollLoop guard body = helper unrollDepth (Assert $ LNot guard) where helper 0 accum = accum helper i accum = helper (i-1) $ ifelse guard (body `Seq` accum ) (Skip) {- Given program postconditions and parameters (for a multi-function program), a top-level statement, a loop guard and body, and a post-condition, use fixpoint iteration, up to a constant number of iterations, to try to infer an invariant for the loop The top-level statement is used to find free variables and their types for generating a Z3 expression. The Z3 program is invoked to test if two conditions are "equal" -} tryFindingInvar :: (PostConds, ProgParams, Statement) -> Expression -> Statement -> Expression -> Maybe Expression tryFindingInvar pconds@(_,_,topLevelStmt) guard body postCond = let f w = ( guard `land` (fst $ wlp pconds body w)) `lor` ((LNot guard) `land` postCond) iter w n = if (z3iff topLevelStmt (simplifyPred w) (simplifyPred (f w))) then (Just w) else if (n >= fixpointDepth) then Nothing else iter (f w) (n+1) in iter (BoolLit True) 0 {- Apply some heuristics, putting predicates in a regular form and simplify easy cases, so that our fix-point is likely to converge sooner, and so that it won't get too large in size -} simplifyOneLevelPred :: Expression -> Expression simplifyOneLevelPred (LNot (BoolLit True)) = BoolLit False simplifyOneLevelPred (LNot (BoolLit False)) = BoolLit True simplifyOneLevelPred (LNot (LNot e)) = e simplifyOneLevelPred (LNot (BinOp e1 LOr e2)) = BinOp (LNot e1) LAnd (LNot e2) simplifyOneLevelPred (LNot (BinOp e1 LOr e2)) = BinOp (LNot e1) LAnd (LNot e2) simplifyOneLevelPred (BinOp (BoolLit True) LAnd e) = e simplifyOneLevelPred (BinOp e LAnd(BoolLit True)) = e simplifyOneLevelPred (BinOp (BoolLit False) LOr e) = e simplifyOneLevelPred (BinOp e LOr (BoolLit False)) = e simplifyOneLevelPred (BinOp (IntLit 0) Plus e) = e simplifyOneLevelPred (BinOp e Plus (IntLit 0)) = e simplifyOneLevelPred (BinOp (IntLit 1) Times e) = e simplifyOneLevelPred (BinOp e Times (IntLit 1)) = e simplifyOneLevelPred (BinOp (IntLit 0) Times _e) = IntLit 0 simplifyOneLevelPred (BinOp _e Times (IntLit 0)) = IntLit 0 simplifyOneLevelPred (BinOp e1 op e2) = let [ee1, ee2] = sort [e1, e2] in if isCommutative op then BinOp ee1 op ee2 else BinOp e1 op e2 simplifyOneLevelPred e = e {- Use SYB to apply our simplification rules bottom-up on a whole expression -} simplifyPred :: Expression -> Expression simplifyPred = everywhere $ mkT simplifyOneLevelPred --Rules for which binary-operations can switch their arguments isCommutative op = op `elem` [Plus, Times, And, Or, LAnd, LOr, Eq] {- Find the WLP for a particular function (program), given post-conditions for all programs, and parameter types for all programs -} programWLP :: (PostConds, ProgParams) -> Program -> (Expression, [Expression]) programWLP (postConds, paramDict) (Program name params body _returnType) = let --Get our postcondition from the dictionary q = postConds Map.! name --Declare our parameters as variables s = Var params body in wlp (postConds, paramDict, s) s q --Generate the Z3 code checking if the given statement matches the given post-condition z3wlpSingle :: (Statement, Expression) -> (String, [String]) z3wlpSingle (s, q) = let varDecs vars = foldr (\v decs -> decs ++ "\n" ++ varDec v) "" vars (theWLP, conds) = wlp (Map.empty, Map.empty, s) s q formatPred p = (varDecs (freeVars s) ++ "\n") ++ (formatZ3 $ p ) in (formatPred theWLP, map formatPred conds) {- Generate the Z3 code checking if the given statement matches the given post-condition We do this by negating the proposition, then checkign if it is satisfiable. First we search for all free-variables in the program, so that we can declare them in our Z3 string. -} z3wlpMulti :: ([Program], (PostConds, ProgParams)) -> [(String, [String])] z3wlpMulti (progs, postConds) = let varDecs vars = foldr (\v decs -> decs ++ "\n" ++ varDec v) "" vars wlpsAndConds = map (programWLP postConds) progs progWlpConds = zip progs wlpsAndConds formatPred prog pred = (varDecs (progFreeVars prog) ++ "\n") ++ (formatZ3 $ pred ) formattedPreds = map (\(prog, (theWLP, conds)) -> (formatPred prog theWLP, (map (formatPred prog) conds) ) ) progWlpConds in formattedPreds
JoeyEremondi/utrecht-pv
WLP.hs
mit
11,517
0
17
2,537
3,301
1,744
1,557
184
4
module PageForkableWiki where import Protolude hiding (Meta, ignore) import Data.Aeson import Data.Default (def) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.List (isInfixOf) import qualified Data.Set as Set import Data.String (String) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Time as TM import Development.Shake import PageForkableWiki.HakyllExcerpts (withUrls) import PageForkableWiki.Types import System.FilePath import System.IO.Error (userError) import Text.Pandoc (Pandoc, Template, Extension(..)) import qualified Text.Pandoc as P readerOptions :: P.ReaderOptions readerOptions = def { P.readerExtensions = extensions } writerOptions :: P.WriterOptions writerOptions = def { P.writerEmailObfuscation = P.ReferenceObfuscation , P.writerExtensions = extensions } -- | Based on 'pandocExtensions': -- https://github.com/jgm/pandoc/blob/0d935bd081bb4013168dc114461ab7c47fec2f44/src/Text/Pandoc/Extensions.hs#L159 extensions :: P.Extensions extensions = P.extensionsFromList [ Ext_footnotes , Ext_inline_notes -- Metadata at top of file. -- , Ext_pandoc_title_block -- , Ext_yaml_metadata_block , Ext_table_captions , Ext_implicit_figures , Ext_simple_tables , Ext_multiline_tables , Ext_grid_tables , Ext_pipe_tables , Ext_citations -- , Ext_raw_tex , Ext_raw_html -- Disabled because `$$$$$` was being interpreted as LaTeX math: -- , Ext_tex_math_dollars , Ext_latex_macros -- Use three or more `~`s to start a code block. -- , Ext_fenced_code_blocks , Ext_fenced_code_attributes , Ext_backtick_code_blocks , Ext_inline_code_attributes , Ext_markdown_in_html_blocks , Ext_native_divs , Ext_native_spans , Ext_escaped_line_breaks , Ext_fancy_lists , Ext_startnum , Ext_definition_lists -- Use `@` to number lists. -- , Ext_example_lists , Ext_all_symbols_escapable , Ext_intraword_underscores , Ext_blank_before_blockquote , Ext_blank_before_header , Ext_strikeout , Ext_superscript , Ext_subscript , Ext_auto_identifiers , Ext_header_attributes , Ext_link_attributes , Ext_implicit_header_references , Ext_line_blocks , Ext_shortcut_reference_links , Ext_smart ] getPages :: FilePath -> Action (Set Page) getPages pageDir = do pageDirs <- fmap (pageDir </>) <$> getDirectoryDirs pageDir pageList <- traverse getSinglePage pageDirs foldM add mempty pageList where add :: Set Page -> Page -> Action (Set Page) add acc page = do when (Set.member page acc) $ panic ("Multiple pages with id " <> _metaId (_pageMeta page)) pure (Set.insert page acc) getSinglePage :: FilePath -> Action Page getSinglePage dir = do content <- readMarkdown . T.pack <$> readFile' (dir </> "page.md") metaNoTitle <- liftIO . either (throwIO . userError) pure . eitherDecodeStrict . encodeUtf8 . T.pack =<< readFile' (dir </> "meta.json") meta <- addTitle content metaNoTitle pure (Page meta content dir) where addTitle :: Pandoc -> Meta () -> Action (Meta Text) addTitle pandoc meta = do case titleFromPandoc pandoc of Left e -> liftIO (throwIO e) Right title -> pure $ meta { _metaTitle = title } data TitleError = DoesntStartWithHeader | CantWriteTitle P.PandocError deriving Show instance Exception TitleError titleFromPandoc :: Pandoc -> Either TitleError Text titleFromPandoc (P.Pandoc _ blocks) = case blocks of P.Header _ _ inlines : _ -> first CantWriteTitle . P.runPure $ P.writePlain writerOptions (P.Pandoc mempty [P.Plain inlines]) _ -> Left DoesntStartWithHeader writePage :: FilePath -> Site -> SiteTemplates -> Page -> Action () writePage = writePageSetIgnore defaultIgnore where defaultIgnore :: FilePath -> Bool defaultIgnore path = path == "page.md" || isInfixOf ".git" path || isInfixOf ".stack-work" path writePageSetIgnore :: (FilePath -> Bool) -> FilePath -> Site -> SiteTemplates -> Page -> Action () writePageSetIgnore ignore destDir site templates page = do resources <- getDirectoryFiles (_pageSourceDir page) ["//*"] void . forP (filter (not . ignore) resources) $ \resource -> copyFileChanged (_pageSourceDir page </> resource) (destDir </> pageUrl site page </> resource) -- This comes second in case there was an "index.html" -- hanging around in the page source directory -- (which might happen during local development of a page). writeFileChanged (destDir </> pageUrl site page </> "index.html") (T.unpack (fullContent site templates page)) renderedHomepage :: Site -> SiteTemplates -> Template -> Set Page -> String renderedHomepage site templates homeTemplate pages = P.renderTemplate (_templateBase templates) (object [ "body" .= renderedContent ]) where renderedContent :: Text renderedContent = either (panic . show) identity . P.runPure . P.writeHtml5String writerOptions . readMarkdown . P.renderTemplate homeTemplate $ object [ "page" .= pageHm ] pageHm :: HashMap Text Value pageHm = HM.fromList (pageEntry <$> Set.toList pages) -- The 'Text' is Pandoc template variable, prefixed with "id-" -- because they must start with a letter. pageEntry :: Page -> (Text, Value) pageEntry page = ( "id-" <> _metaId (_pageMeta page) , object [ "title" .= _metaTitle (_pageMeta page) , "url" .= ("/" </> pageUrl site page) ] ) fullContent :: Site -> SiteTemplates -> Page -> Text fullContent site templates page = P.renderTemplate (_templateBase templates) (object [ "body" .= renderedAfterFeed ]) where renderedAfterFeed :: Text renderedAfterFeed = P.renderTemplate (_templatePageAfterFeed templates) (object [ "body" .= coreContent site page , "pageId" .= idString page ]) coreContent :: Site -> Page -> Text coreContent site page = siteRelativize ("/" </> pageUrl site page) . either (panic . show :: P.PandocError -> Text) identity . P.runPure . P.writeHtml5String writerOptions . addDate $ _pageContent page where addDate :: Pandoc -> Pandoc addDate (P.Pandoc a blocks) = case blocks of header@(P.Header _ _ _) : rest -> let date = TM.formatTime TM.defaultTimeLocale fmtTime (_metaDate (_pageMeta page)) in P.Pandoc a (header : P.Para [P.Str date] : rest) _ -> panic "coreContent: page doesn't start with header" fmtTime :: String fmtTime = concat [ "%B" -- month name, long form (fst from months locale), January - December , " " , dropWhile (== ' ') "%e" -- day of month, space-padded to two chars, 1 - 31 , ", " , "%Y" -- year ] readMarkdown :: Text -> Pandoc readMarkdown = either (panic . show) identity . P.runPure . P.readMarkdown readerOptions constructTemplate :: String -> Template constructTemplate = either (panic . T.pack) identity . P.compileTemplate . T.pack -- NOTE: This doesn't work for document-relative URLs -- other than ones starting with "./" (e.g. not "../"). siteRelativize :: String -- ^ Identifier path -> Text -- ^ HTML to relativize -> Text -- ^ Resulting HTML siteRelativize path = T.pack . withUrls f . T.unpack where f ('.':'/':xs) = path </> xs f xs = xs
seagreen/housejeffries
page-forkable-wiki/src/PageForkableWiki.hs
mit
7,964
0
19
2,124
1,885
998
887
195
2
module Encoder where import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader import Control.Monad.Trans.State import qualified Data.Bimap as B import Data.Maybe (fromJust) import Types type Lit = Int type LitCount = Int type CNF = [Clause] type Clause = [Lit] data Environment = Env { bimap :: B.Bimap Lit (Server, VM) , servers :: [Server] , vms :: [VM] } deriving Show type Encoder = ReaderT Environment (State LitCount) lookupLit :: B.Bimap Lit (Server, VM) -> Server -> VM -> Lit lookupLit bm s v = fromJust (B.lookupR (s,v) bm) emptyEnv :: Environment emptyEnv = Env B.empty [] [] populate :: Problem -> Environment populate (servers, vms) = Env bimap servers vms where bimap = B.fromList $ zip [1..] [(s,v) | s <- servers, v <- vms] moreLits :: Int -> Maybe (Encoder (Int,Int)) moreLits x | x >= 0 = Just $ lift $ do n <- get put (n + x) return (n + 1, n + x) | otherwise = Nothing newLit :: Encoder Int newLit = lift $ do n <- get put (n+1) return (n+1) encode :: Environment -> Encoder a -> a encode env encoder = evalState (runReaderT encoder env) litCount where litCount = B.size (bimap env) __dummy_encode encoder litCount = evalState (runReaderT encoder emptyEnv) litCount
rodamber/vmc-hs
sat/Encoder.hs
mit
1,260
0
11
265
536
290
246
40
1
module Data.Set.Extensions where import Control.Exception.Base as Exception import Data.List as List import Data.List.Extensions as ListExt import Data.Map as Map import Data.Set as Set import Prelude.Extensions as PreludeExt notNull = ((.) not Set.null) deleteMin :: Ord a => Set a -> Set a deleteMin = \set -> (Set.delete (Set.findMin set) set) deleteMax :: Ord a => Set a -> Set a deleteMax = \set -> (Set.delete (Set.findMax set) set) insertOrDelete :: Ord a => a -> Bool -> Set a -> Set a insertOrDelete = \key insert set -> ((ifElse insert Set.insert Set.delete) key set) intersections :: Ord a => [Set a] -> (Set a) intersections = \sets -> let preconditions = (ListExt.notNull sets) result = (List.foldl Set.intersection (head sets) (tail sets)) in (assert preconditions result) toMap :: Ord a => (a -> b) -> (Set a) -> (Map a b) toMap = \toValue set -> (Map.fromAscList (List.map (\x -> (x, toValue x)) (Set.toList set))) toIdentityMap :: Ord a => (Set a) -> (Map a a) toIdentityMap = (toMap id)
stevedonnelly/haskell
code/Data/Set/Extensions.hs
mit
1,025
0
13
189
467
251
216
23
1
-- Copyright (c) 2016-present, SoundCloud Ltd. -- All rights reserved. -- -- This source code is distributed under the terms of a MIT license, -- found in the LICENSE file. {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} module Kubernetes.Model.V1.DownwardAPIVolumeSource ( DownwardAPIVolumeSource (..) , items , mkDownwardAPIVolumeSource ) where import Control.Lens.TH (makeLenses) import Data.Aeson.TH (defaultOptions, deriveJSON, fieldLabelModifier) import GHC.Generics (Generic) import Kubernetes.Model.V1.DownwardAPIVolumeFile (DownwardAPIVolumeFile) import Prelude hiding (drop, error, max, min) import qualified Prelude as P import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Instances () -- | DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling. data DownwardAPIVolumeSource = DownwardAPIVolumeSource { _items :: !(Maybe [DownwardAPIVolumeFile]) } deriving (Show, Eq, Generic) makeLenses ''DownwardAPIVolumeSource $(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''DownwardAPIVolumeSource) instance Arbitrary DownwardAPIVolumeSource where arbitrary = DownwardAPIVolumeSource <$> arbitrary -- | Use this method to build a DownwardAPIVolumeSource mkDownwardAPIVolumeSource :: DownwardAPIVolumeSource mkDownwardAPIVolumeSource = DownwardAPIVolumeSource Nothing
soundcloud/haskell-kubernetes
lib/Kubernetes/Model/V1/DownwardAPIVolumeSource.hs
mit
2,056
0
14
725
256
156
100
30
1
-- Polymorphic Data Types data List t = E | C t (List t) deriving Show lst1 :: List Int lst1 = C 3 (C 5 (C 2 E)) lst2 :: List Char lst2 = C 'x' (C 'y' (C 'z' E)) lst3 :: List Bool lst3 = C True (C False E) filterList :: (t -> Bool) -> List t -> List t filterList _ E = E filterList p (C x xs) | p x = C x (filterList p xs) | otherwise = filterList p xs filterListTest = print (filterList even myList) mapList :: (a -> b) -> List a -> List b mapList f (C x xs) = C (f x) (mapList f xs) mapList f E = E myList = C 2 (C (-3) (C 5 E)) double :: Num a => a -> a double x = 2 * x mapListTest = print (mapList double myList)
v0lkan/learning-haskell
001-polymorphism.hs
mit
644
0
9
178
374
186
188
20
1
module Main where {- 24bitbmp用 40bitinfo windows bitmap -} import System.Environment(getArgs) import qualified Data.ByteString.Lazy as Bl import Numeric (showHex) cfold = foldr (++) [] rsInt :: (Show a,Read a)=> a -> Int rsInt = read . show dropTake :: Int -> Int -> [a] -> [a] dropTake d t = (take t) . (drop d) dropTakeSame dt = dropTake dt dt tbgr 0 _ = [] tbgr _ [] = [] tbgr n xs = (take 3 xs) : tbgr (n-1) (drop 3 xs) plusp a [[]] = a plusp a b = a ++ b takeBGR _ [] = [] takeBGR n xs = ( lineData `plusp` [bs] ) : takeBGR n next where lineData = (tbgr n xs) ml4 = mod (length lineData) 4 ds = drop (n*3) xs bs = take ml4 ds next = drop ml4 ds -- (read . show) $ div (rsInt b) 2 bgr2Red (b:g:r:[]) = [0,0,r] --if and [(rsInt r) >= 128 , (rsInt b) < 100 , (rsInt g) < 100] -- then [b,g,r] -- else [0,0,0] bgr2Red as = as main = do a <- getArgs f <- Bl.readFile $ head a let file = Bl.unpack f let fileHeader = dropTake 0 14 file let infoHeader = dropTake 14 40 file --let color = dropTake 54 0 file let imgData = drop 54 file --print fileHeader --print infoHeader let xsize = rsInt (head $ dropTake 4 4 infoHeader) --let xsize = 4 --print $ takeBGR xsize imgData --let readData = Bl.pack $ fileHeader ++ infoHeader ++ imgData let readData = Bl.pack $ fileHeader ++ infoHeader ++ (cfold $ map cfold $ (map (map bgr2Red) ) $ takeBGR xsize imgData) Bl.writeFile (( (init . init . init . init) (head a) )++ "read.bmp") readData
HSU-MilitaryLogisticsClub/Free-Test
src/bmphask/bmpread24.hs
mit
1,551
0
17
413
619
322
297
34
1
{-# LANGUAGE PackageImports #-} import "fitd-web" Application (develMain) import Prelude (IO) main :: IO () main = develMain
silky/foot-in-the-door
app/devel.hs
mit
126
0
6
19
34
20
14
5
1
{-# LANGUAGE QuasiQuotes #-} module Blunt.App.Script where import Data.Function ((&)) import qualified Data.Text.Lazy as Text import Language.Javascript.JMacro import qualified Text.PrettyPrint.Leijen.Text as PrettyPrint script :: Text.Text script = js & renderJs & PrettyPrint.renderOneLine & PrettyPrint.displayT js :: JStat js = [jmacro| \ { var input = document.getElementById("input"); var pointfree = document.getElementById("pointfree"); var pointful = document.getElementById("pointful"); var socket = new WebSocket(window.location.origin.replace("http", "ws")); socket.onopen = \ { input.oninput = \ { window.location.replace( "#input=" + encodeURIComponent(input.value)); socket.send(input.value); }; if (input.value) { input.oninput(); } }; socket.onmessage = \ message { var response = JSON.parse(message.data); pointfree.textContent = response.pointfree.join("\n"); pointful.textContent = response.pointful.join("\n"); }; if (window.location.hash.indexOf("#input=") === 0) { input.value = decodeURIComponent(window.location.hash.substring(7)); } }(); |]
tfausak/blunt
library/Blunt/App/Script.hs
mit
1,216
0
7
256
87
58
29
11
1
-------------------------------------------------------------------------- -- Copyright (c) 2007-2010, ETH Zurich. -- All rights reserved. -- -- This file is distributed under the terms in the attached LICENSE file. -- If you do not find this file, copies can be found by writing to: -- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -- -- Architectural definitions for Barrelfish on ARMv5 ISA. -- -- The build target is the integratorcp board on QEMU with the default -- ARM926EJ-S cpu. -- -------------------------------------------------------------------------- module ArmGem5 where import HakeTypes import Path import qualified Config import qualified ArchDefaults ------------------------------------------------------------------------- -- -- Architecture specific definitions for ARM -- ------------------------------------------------------------------------- arch = "arm_gem5" archFamily = "arm" compiler = "arm-none-linux-gnueabi-gcc" objcopy = "arm-none-linux-gnueabi-objcopy" objdump = "arm-none-linux-gnueabi-objdump" ar = "arm-none-linux-gnueabi-ar" ranlib = "arm-none-linux-gnueabi-ranlib" cxxcompiler = "arm-none-linux-gnueabi-g++" ourCommonFlags = [ Str "-fno-unwind-tables", Str "-Wno-packed-bitfield-compat", Str "-mcpu=cortex-a9", Str "-march=armv7-a", Str "-mapcs", Str "-mabi=aapcs-linux", Str "-msingle-pic-base", Str "-mpic-register=r10", Str "-DPIC_REGISTER=R10", Str "-fpic", Str "-ffixed-r9", Str "-DTHREAD_REGISTER=R9", Str "-D__ARM_CORTEX__", Str "-D__ARM_ARCH_7A__", Str "-D__GEM5__", Str "-Wno-unused-but-set-variable", Str "-Wno-format" ] cFlags = ArchDefaults.commonCFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cxxFlags = ArchDefaults.commonCxxFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cDefines = ArchDefaults.cDefines options ourLdFlags = [ Str "-Wl,-section-start,.text=0x400000", Str "-Wl,-section-start,.data=0x600000" ] ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags stdLibs = ArchDefaults.stdLibs arch ++ [ Str "-lgcc" ] options = (ArchDefaults.options arch archFamily) { optFlags = cFlags, optCxxFlags = cxxFlags, optDefines = cDefines, optDependencies = [ PreDep InstallTree arch "/include/errors/errno.h", PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h", PreDep InstallTree arch "/include/asmoffsets.h", PreDep InstallTree arch "/include/romfs_size.h" ], optLdFlags = ldFlags, optLdCxxFlags = ldCxxFlags, optLibs = stdLibs, optInterconnectDrivers = ["lmp"], optFlounderBackends = ["lmp"] } -- -- Compilers -- cCompiler = ArchDefaults.cCompiler arch compiler cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler makeDepend = ArchDefaults.makeDepend arch compiler makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler cToAssembler = ArchDefaults.cToAssembler arch compiler assembler = ArchDefaults.assembler arch compiler archive = ArchDefaults.archive arch linker = ArchDefaults.linker arch compiler cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler -- -- The kernel is "different" -- kernelCFlags = [ Str s | s <- [ "-fno-builtin", "-fno-unwind-tables", "-nostdinc", "-std=c99", "-mcpu=cortex-a9", "-mapcs", "-mabi=aapcs-linux", "-fPIE", "-U__linux__", "-Wall", "-Wshadow", "-Wstrict-prototypes", "-Wold-style-definition", "-Wmissing-prototypes", "-Wmissing-declarations", "-Wmissing-field-initializers", "-Wredundant-decls", "-Werror", "-imacros deputy/nodeputy.h", "-fpie", "-fno-stack-check", "-ffreestanding", "-fomit-frame-pointer", "-mno-long-calls", "-Wmissing-noreturn", "-mno-apcs-stack-check", "-mno-apcs-reentrant", "-msingle-pic-base", "-mpic-register=r10", "-DPIC_REGISTER=R10", "-ffixed-r9", "-DTHREAD_REGISTER=R9", "-D__ARM_CORTEX__", "-D__ARM_ARCH_7A__", "-D__GEM5__", "-Wno-unused-but-set-variable", "-Wno-format" ]] kernelLdFlags = [ Str "-Wl,-N", NStr "-Wl,-Map,", Out arch "kernel.map", Str "-fno-builtin", Str "-nostdlib", Str "-Wl,--fatal-warnings" ] -- -- Link the kernel (CPU Driver) -- linkKernel :: Options -> [String] -> [String] -> String -> HRule linkKernel opts objs libs kbin = let linkscript = "/kernel/linker.lds" kbootable = kbin ++ ".bin" in Rules [ Rule ([ Str compiler, Str Config.cOptFlags, NStr "-T", In BuildTree arch linkscript, Str "-o", Out arch kbin ] ++ (optLdFlags opts) ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ [ Str "-lgcc" ] ), -- Edit ELF header so qemu-system-arm will treat it as a Linux kernel -- Rule [ In SrcTree "src" "/tools/arm-mkbootelf.sh", -- Str objdump, In BuildTree arch kbin, Out arch (kbootable)], -- Generate kernel assembly dump Rule [ Str (objdump ++ " -d -M reg-names-raw"), In BuildTree arch kbin, Str ">", Out arch (kbin ++ ".asm")], Rule [ Str "cpp", NStr "-I", NoDep SrcTree "src" "/kernel/include/arch/arm_gem5", Str "-D__ASSEMBLER__", Str "-P", In SrcTree "src" "/kernel/arch/arm_gem5/linker.lds.in", Out arch linkscript ] ]
modeswitch/barrelfish
hake/ArmGem5.hs
mit
7,239
18
17
2,874
1,009
563
446
128
1
-- | Definitions for use of LaTeXMathML in HTML. -- (See <http://math.etsu.edu/LaTeXMathML/>) module Text.Pandoc.LaTeXMathML ( latexMathMLScript ) where import System.FilePath ( (</>) ) import Text.Pandoc.Shared (readDataFile) -- | String containing LaTeXMathML javascript. latexMathMLScript :: Maybe FilePath -> IO String latexMathMLScript datadir = do jsCom <- readDataFile datadir $ "data" </> "LaTeXMathML.js.comment" jsPacked <- readDataFile datadir $ "data" </> "LaTeXMathML.js.packed" return $ "<script type=\"text/javascript\">\n" ++ jsCom ++ jsPacked ++ "</script>\n"
kowey/pandoc-old
src/Text/Pandoc/LaTeXMathML.hs
gpl-2.0
593
0
10
85
116
62
54
9
1
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE MultiParamTypeClasses , CPP , TemplateHaskell #-} module Gx.Internal.Backend.GLFW where #ifdef WITHGLFW import Gx.Internal.Backend.Types import Gx.Data.Input (Key (..), MouseButton (..)) import qualified Gx.Data.Input as I import Gx.Data.Window import Control.Concurrent import Control.Lens import qualified Control.Exception as X import Control.Monad import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT) import Data.IORef import Gx.Data.IORef.Lens import Data.Char (toLower) import Data.List (intercalate) import Data.Maybe (catMaybes, fromMaybe) import Linear import Text.PrettyPrint import qualified System.Mem as System import qualified Graphics.UI.GLFW as GLFW import qualified Graphics.Rendering.OpenGL as GL -- | State of the GLFW backend library. data GLFWState = GLFWState { -- | Action that draws on the screen _display :: IO () -- | Window in use by the backend , _glfwWindow :: Maybe GLFW.Window } makeLenses ''GLFWState -- | Initial GLFW state. glfwStateInit :: GLFWState glfwStateInit = GLFWState { _display = return () , _glfwWindow = Nothing } whenWindow :: IORef GLFWState -> (GLFW.Window -> IO a) -> IO (Maybe a) whenWindow ref f = do maybeWindow <- ref ^@ glfwWindow forM maybeWindow f whenWindow_ :: IORef GLFWState -> (GLFW.Window -> IO a) -> IO () whenWindow_ ref = void . whenWindow ref instance Backend GLFWState where initBackendState = glfwStateInit initializeBackend = initializeGLFW exitBackend = exitGLFW openWindow = openWindowGLFW dumpBackendState = dumpStateGLFW installCallbacks ref callbacks = mapM_ (\f -> f ref callbacks) [ installDisplayCallbackGLFW , installWindowFocusCallbackGLFW , installWindowCloseCallbackGLFW , installReshapeCallbackGLFW , installKeyboardCallbackGLFW , installMouseMoveCallbackGLFW , installMouseButtonCallbackGLFW , installScrollCallbackGLFW ] runMainLoop = runMainLoopGLFW getWindowDimensions ref = whenWindow ref $ \win -> do (winW, winH) <- GLFW.getWindowSize win return $ V2 winW winH --getMousePosition ref = whenWindow ref GLFW.getCursorPos elapsedTime _ = liftM (fromMaybe 0) GLFW.getTime sleep _ = threadDelay . round . (* 1000000) -- Initialise ----------------------------------------------------------------- -- | Initialise the GLFW backend. initializeGLFW :: IORef GLFWState -> Bool-> IO () initializeGLFW _ debug = do GLFW.init glfwVersion <- GLFW.getVersion when debug . putStrLn $ " glfwVersion = " ++ show glfwVersion -- Exit ----------------------------------------------------------------------- -- | Tell the GLFW backend to close the window and exit. exitGLFW :: IORef GLFWState -> IO () exitGLFW ref = do glfwWin <- ref ^@ glfwWindow mapM_ (`GLFW.setWindowShouldClose` True) glfwWin -- Open Window ---------------------------------------------------------------- -- | Open a new window. openWindowGLFW :: IORef GLFWState -> Window -> IO () openWindowGLFW ref win = do --GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3 --GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 2 --GLFW.windowHint $ GLFW.WindowHint'OpenGLForwardCompat False --GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core --GLFW.windowHint $ GLFW.WindowHint'Resizable False let (sizeX, sizeY) = win^.windowSize maybeMonitor <- case win^.windowState of WindowFullscreen -> GLFW.getPrimaryMonitor WindowFloating -> return Nothing glfwWin <- GLFW.createWindow sizeX sizeY (win^.windowName) maybeMonitor Nothing ref & glfwWindow @~ glfwWin GLFW.makeContextCurrent glfwWin -- Try to enable sync-to-vertical-refresh by setting the number -- of buffer swaps per vertical refresh to 1. GLFW.swapInterval 1 -- Dump State ----------------------------------------------------------------- -- | Print out the internal GLFW state. -- This code is taken from a sample in the GLFW repository. -- TODO: Implement a standard state dump across all backends. dumpStateGLFW :: IORef GLFWState -> IO () dumpStateGLFW ref = do maybeWin <- ref ^@ glfwWindow case maybeWin of Nothing -> return () Just glfwWin -> do version <- GLFW.getVersion versionString <- GLFW.getVersionString monitorInfos <- runMaybeT getMonitorInfos joystickNames <- getJoystickNames clientAPI <- GLFW.getWindowClientAPI glfwWin cv0 <- GLFW.getWindowContextVersionMajor glfwWin cv1 <- GLFW.getWindowContextVersionMinor glfwWin cv2 <- GLFW.getWindowContextVersionRevision glfwWin robustness <- GLFW.getWindowContextRobustness glfwWin forwardCompat <- GLFW.getWindowOpenGLForwardCompat glfwWin debug <- GLFW.getWindowOpenGLDebugContext glfwWin profile <- GLFW.getWindowOpenGLProfile glfwWin putStrLn $ render $ nest 4 ( text "------------------------------------------------------------" $+$ text "GLFW C library:" $+$ nest 4 ( text "Version:" <+> renderVersion version $+$ text "Version string:" <+> renderVersionString versionString ) $+$ text "Monitors:" $+$ nest 4 ( renderMonitorInfos monitorInfos ) $+$ text "Joysticks:" $+$ nest 4 ( renderJoystickNames joystickNames ) $+$ text "OpenGL context:" $+$ nest 4 ( text "Client API:" <+> renderClientAPI clientAPI $+$ text "Version:" <+> renderContextVersion cv0 cv1 cv2 $+$ text "Robustness:" <+> renderContextRobustness robustness $+$ text "Forward compatibility:" <+> renderForwardCompat forwardCompat $+$ text "Debug:" <+> renderDebug debug $+$ text "Profile:" <+> renderProfile profile ) $+$ text "------------------------------------------------------------" ) where renderVersion (GLFW.Version v0 v1 v2) = text $ intercalate "." $ map show [v0, v1, v2] renderVersionString = text . show renderMonitorInfos = maybe (text "(error)") (vcat . map renderMonitorInfo) renderMonitorInfo (name, (x,y), (w,h), vms) = text (show name) $+$ nest 4 ( location <+> size $+$ fsep (map renderVideoMode vms) ) where location = int x <> text "," <> int y size = int w <> text "x" <> int h <> text "mm" renderVideoMode (GLFW.VideoMode w h r g b rr) = brackets $ res <+> rgb <+> hz where res = int w <> text "x" <> int h rgb = int r <> text "x" <> int g <> text "x" <> int b hz = int rr <> text "Hz" renderJoystickNames pairs = vcat $ map (\(js, name) -> text (show js) <+> text (show name)) pairs renderContextVersion v0 v1 v2 = hcat [int v0, text ".", int v1, text ".", int v2] renderClientAPI = text . show renderContextRobustness = text . show renderForwardCompat = text . show renderDebug = text . show renderProfile = text . show type MonitorInfo = (String, (Int,Int), (Int,Int), [GLFW.VideoMode]) getMonitorInfos :: MaybeT IO [MonitorInfo] getMonitorInfos = getMonitors >>= mapM getMonitorInfo where getMonitors :: MaybeT IO [GLFW.Monitor] getMonitors = MaybeT GLFW.getMonitors getMonitorInfo :: GLFW.Monitor -> MaybeT IO MonitorInfo getMonitorInfo mon = do name <- getMonitorName mon vms <- getVideoModes mon MaybeT $ do pos <- liftIO $ GLFW.getMonitorPos mon size <- liftIO $ GLFW.getMonitorPhysicalSize mon return $ Just (name, pos, size, vms) getMonitorName :: GLFW.Monitor -> MaybeT IO String getMonitorName mon = MaybeT $ GLFW.getMonitorName mon getVideoModes :: GLFW.Monitor -> MaybeT IO [GLFW.VideoMode] getVideoModes mon = MaybeT $ GLFW.getVideoModes mon getJoystickNames :: IO [(GLFW.Joystick, String)] getJoystickNames = catMaybes `fmap` mapM getJoystick joysticks where getJoystick js = fmap (maybe Nothing (\name -> Just (js, name))) (GLFW.getJoystickName js) -- Display Callback ----------------------------------------------------------- -- | Callback for when GLFW needs us to redraw the contents of the window. installDisplayCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installDisplayCallbackGLFW ref callbacks = ref & display @~ callbackDisplay ref callbacks callbackDisplay :: IORef GLFWState -> Callbacks -> IO () callbackDisplay ref callbacks = do GL.clear [GL.ColorBuffer, GL.DepthBuffer] GL.color $ GL.Color4 0 0 0 (1 :: GL.GLfloat) displayCallback callbacks ref -- Focus Callback ------------------------------------------------------------- -- | Callback for when the user is focus/defocused on the window. -- Used to control pause/resume. installWindowFocusCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installWindowFocusCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setWindowFocusCallback glfwWin $ Just (callbackWindowFocus ref callbacks) callbackWindowFocus :: IORef GLFWState -> Callbacks -> GLFW.Window -> GLFW.FocusState -> IO () callbackWindowFocus ref callbacks _ focusState = case focusState of GLFW.FocusState'Focused -> resumeCallback callbacks ref GLFW.FocusState'Defocused -> pauseCallback callbacks ref -- Close Callback ------------------------------------------------------------- -- | Callback for when the user closes the window. -- We can do some cleanup here. installWindowCloseCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installWindowCloseCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setWindowCloseCallback glfwWin $ Just (callbackWindowClose ref callbacks) callbackWindowClose :: IORef GLFWState -> Callbacks -> GLFW.Window -> IO () callbackWindowClose ref callbacks _ = do closeCallback callbacks ref -- Reshape -------------------------------------------------------------------- -- | Callback for when the user reshapes the window. installReshapeCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installReshapeCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setWindowSizeCallback glfwWin $ Just (callbackReshape ref callbacks) callbackReshape :: Backend a => IORef a -> Callbacks -> GLFW.Window -> Int -> Int -> IO () callbackReshape ref callbacks _ sW sH = reshapeCallback callbacks ref $ V2 sW sH -- Keyboard Callback ---------------------------------------------------------- installKeyboardCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installKeyboardCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setKeyCallback glfwWin $ Just (callbackKeyboard ref callbacks) callbackKeyboard :: IORef GLFWState -> Callbacks -> GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () callbackKeyboard ref callbacks _ key scancode state mods = keyboardCallback callbacks ref key' state' where state' = fromGLFW state key' = if GLFW.modifierKeysShift mods then I.shiftKey . fromGLFW $ key else fromGLFW key -- Mouse Movement Callback ---------------------------------------------------- installMouseMoveCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installMouseMoveCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setCursorPosCallback glfwWin $ Just (callbackMouseMove ref callbacks) callbackMouseMove :: IORef GLFWState -> Callbacks -> GLFW.Window -> Double -> Double -> IO () callbackMouseMove ref callbacks _ pX pY = mouseMoveCallback callbacks ref $ V2 pX pY -- Mouse Button Callback ------------------------------------------------------ installMouseButtonCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installMouseButtonCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setMouseButtonCallback glfwWin $ Just (callbackMouseButton ref callbacks) callbackMouseButton :: IORef GLFWState -> Callbacks -> GLFW.Window -> GLFW.MouseButton -> GLFW.MouseButtonState -> GLFW.ModifierKeys -> IO () callbackMouseButton ref callbacks _ button state _ = whenWindow_ ref $ \glfwWin -> do (posX, posY) <- GLFW.getCursorPos glfwWin mouseButtonCallback callbacks ref button' state' $ V2 posX posY where button' = fromGLFW button state' = fromGLFW state -- Scroll Callback ------------------------------------------------------------ installScrollCallbackGLFW :: IORef GLFWState -> Callbacks -> IO () installScrollCallbackGLFW ref callbacks = whenWindow_ ref $ \glfwWin -> GLFW.setScrollCallback glfwWin $ Just (callbackScroll ref callbacks) callbackScroll :: IORef GLFWState -> Callbacks -> GLFW.Window -> Double -> Double -> IO () callbackScroll ref callbacks _ amountX amountY = scrollCallback callbacks ref $ V2 amountX amountY -- Main Loop ------------------------------------------------------------------ runMainLoopGLFW :: IORef GLFWState -> IO () runMainLoopGLFW ref = whenWindow_ ref $ \glfwWin -> do winShouldClose <- GLFW.windowShouldClose glfwWin winFocus <- GLFW.getWindowFocused glfwWin if winShouldClose then do GLFW.destroyWindow glfwWin GLFW.terminate else do case winFocus of GLFW.FocusState'Defocused -> GLFW.waitEvents GLFW.FocusState'Focused -> do GLFW.pollEvents join $ ref ^@ display GLFW.swapBuffers glfwWin runMainLoopGLFW ref -- GLFW type Conversion ------------------------------------------------------- class GLFWConv a b where fromGLFW :: a -> b instance GLFWConv GLFW.KeyState InputState where fromGLFW keystate = case keystate of GLFW.KeyState'Pressed -> Down GLFW.KeyState'Repeating -> Down GLFW.KeyState'Released -> Up instance GLFWConv GLFW.MouseButtonState InputState where fromGLFW keystate = case keystate of GLFW.MouseButtonState'Pressed -> Down GLFW.MouseButtonState'Released -> Up instance GLFWConv GLFW.Key I.Key where fromGLFW key = case key of GLFW.Key'Unknown -> Key'Unknown GLFW.Key'GraveAccent -> Key'GraveAccent GLFW.Key'1 -> Key'1 GLFW.Key'2 -> Key'2 GLFW.Key'3 -> Key'3 GLFW.Key'4 -> Key'4 GLFW.Key'5 -> Key'5 GLFW.Key'6 -> Key'6 GLFW.Key'7 -> Key'7 GLFW.Key'8 -> Key'8 GLFW.Key'9 -> Key'9 GLFW.Key'0 -> Key'0 GLFW.Key'Minus -> Key'Minus GLFW.Key'Equal -> Key'Equal GLFW.Key'A -> Key'a GLFW.Key'B -> Key'b GLFW.Key'C -> Key'c GLFW.Key'D -> Key'd GLFW.Key'E -> Key'e GLFW.Key'F -> Key'f GLFW.Key'G -> Key'g GLFW.Key'H -> Key'h GLFW.Key'I -> Key'i GLFW.Key'J -> Key'j GLFW.Key'K -> Key'k GLFW.Key'L -> Key'l GLFW.Key'M -> Key'm GLFW.Key'N -> Key'n GLFW.Key'O -> Key'o GLFW.Key'P -> Key'p GLFW.Key'Q -> Key'q GLFW.Key'R -> Key'r GLFW.Key'S -> Key's GLFW.Key'T -> Key't GLFW.Key'U -> Key'u GLFW.Key'V -> Key'v GLFW.Key'W -> Key'w GLFW.Key'X -> Key'x GLFW.Key'Y -> Key'y GLFW.Key'Z -> Key'z GLFW.Key'LeftBracket -> Key'LeftBracket GLFW.Key'RightBracket -> Key'RightBracket GLFW.Key'Backslash -> Key'Backslash GLFW.Key'Semicolon -> Key'Semicolon GLFW.Key'Apostrophe -> Key'Apostrophe GLFW.Key'Comma -> Key'Comma GLFW.Key'Period -> Key'Period GLFW.Key'Slash -> Key'Slash GLFW.Key'World1 -> Key'World1 GLFW.Key'World2 -> Key'World2 GLFW.Key'Space -> Key'Space GLFW.Key'Escape -> Key'Escape GLFW.Key'Enter -> Key'Enter GLFW.Key'Tab -> Key'Tab GLFW.Key'Backspace -> Key'Backspace GLFW.Key'Insert -> Key'Insert GLFW.Key'Delete -> Key'Delete GLFW.Key'Right -> Key'Right GLFW.Key'Left -> Key'Left GLFW.Key'Up -> Key'Up GLFW.Key'Down -> Key'Down GLFW.Key'PageUp -> Key'PageUp GLFW.Key'PageDown -> Key'PageDown GLFW.Key'Home -> Key'Home GLFW.Key'End -> Key'End GLFW.Key'CapsLock -> Key'CapsLock GLFW.Key'ScrollLock -> Key'ScrollLock GLFW.Key'NumLock -> Key'NumLock GLFW.Key'PrintScreen -> Key'PrintScreen GLFW.Key'Pause -> Key'Pause GLFW.Key'F1 -> Key'F1 GLFW.Key'F2 -> Key'F2 GLFW.Key'F3 -> Key'F3 GLFW.Key'F4 -> Key'F4 GLFW.Key'F5 -> Key'F5 GLFW.Key'F6 -> Key'F6 GLFW.Key'F7 -> Key'F7 GLFW.Key'F8 -> Key'F8 GLFW.Key'F9 -> Key'F9 GLFW.Key'F10 -> Key'F10 GLFW.Key'F11 -> Key'F11 GLFW.Key'F12 -> Key'F12 GLFW.Key'F13 -> Key'F13 GLFW.Key'F14 -> Key'F14 GLFW.Key'F15 -> Key'F15 GLFW.Key'F16 -> Key'F16 GLFW.Key'F17 -> Key'F17 GLFW.Key'F18 -> Key'F18 GLFW.Key'F19 -> Key'F19 GLFW.Key'F20 -> Key'F20 GLFW.Key'F21 -> Key'F21 GLFW.Key'F22 -> Key'F22 GLFW.Key'F23 -> Key'F23 GLFW.Key'F24 -> Key'F24 GLFW.Key'F25 -> Key'F25 GLFW.Key'Pad0 -> Key'Pad0 GLFW.Key'Pad1 -> Key'Pad1 GLFW.Key'Pad2 -> Key'Pad2 GLFW.Key'Pad3 -> Key'Pad3 GLFW.Key'Pad4 -> Key'Pad4 GLFW.Key'Pad5 -> Key'Pad5 GLFW.Key'Pad6 -> Key'Pad6 GLFW.Key'Pad7 -> Key'Pad7 GLFW.Key'Pad8 -> Key'Pad8 GLFW.Key'Pad9 -> Key'Pad9 GLFW.Key'PadDecimal -> Key'PadDecimal GLFW.Key'PadDivide -> Key'PadDivide GLFW.Key'PadMultiply -> Key'PadMultiply GLFW.Key'PadSubtract -> Key'PadSubtract GLFW.Key'PadAdd -> Key'PadAdd GLFW.Key'PadEnter -> Key'PadEnter GLFW.Key'PadEqual -> Key'PadEqual GLFW.Key'LeftShift -> Key'LeftShift GLFW.Key'LeftControl -> Key'LeftControl GLFW.Key'LeftAlt -> Key'LeftAlt GLFW.Key'LeftSuper -> Key'LeftSuper GLFW.Key'RightShift -> Key'RightShift GLFW.Key'RightControl -> Key'RightControl GLFW.Key'RightAlt -> Key'RightAlt GLFW.Key'RightSuper -> Key'RightSuper GLFW.Key'Menu -> Key'Menu instance GLFWConv GLFW.MouseButton MouseButton where fromGLFW mouse = case mouse of GLFW.MouseButton'1 -> Left'Button GLFW.MouseButton'2 -> Right'Button GLFW.MouseButton'3 -> Middle'Button GLFW.MouseButton'4 -> Additional'Button 3 GLFW.MouseButton'5 -> Additional'Button 4 GLFW.MouseButton'6 -> Additional'Button 5 GLFW.MouseButton'7 -> Additional'Button 6 GLFW.MouseButton'8 -> Additional'Button 7 joysticks :: [GLFW.Joystick] joysticks = [ GLFW.Joystick'1 , GLFW.Joystick'2 , GLFW.Joystick'3 , GLFW.Joystick'4 , GLFW.Joystick'5 , GLFW.Joystick'6 , GLFW.Joystick'7 , GLFW.Joystick'8 , GLFW.Joystick'9 , GLFW.Joystick'10 , GLFW.Joystick'11 , GLFW.Joystick'12 , GLFW.Joystick'13 , GLFW.Joystick'14 , GLFW.Joystick'15 , GLFW.Joystick'16 ] -- WITHGLFW #endif
andgate/GXK
src/Gx/Internal/Backend/GLFW.hs
gpl-2.0
19,957
0
30
5,150
4,655
2,339
2,316
5
0
----------------------------------------------------------------------------- -- -- Module : App.Screen -- Copyright : -- License : AllRightsReserved -- -- Maintainer : -- Stability : -- Portability : -- -- | -- ----------------------------------------------------------------------------- module App.Screen ( Screen ( .. ) , ScreenSurface , renderImage , screenInit , screenQuit , screenRefresh ) where import qualified Graphics.UI.SDL as SDL import App.Image type ScreenSurface = SDL.Surface data Screen = Screen { screenSurface :: ScreenSurface , screenWidth :: Int , screenHeight :: Int , screenBpp :: Int } renderImage :: Int -> Int -> Image -> ScreenSurface -> Maybe SDL.Rect -> IO Bool renderImage x y src dst clip = SDL.blitSurface src clip dst (Just $ SDL.Rect x y 0 0) screenRefresh :: ScreenSurface -> IO () screenRefresh = SDL.flip screenInit :: Int -> Int -> Int -> String -> IO Screen screenInit width height bpp caption = do SDL.init [SDL.InitEverything] surface <- SDL.setVideoMode width height bpp [SDL.SWSurface] SDL.setCaption caption "" return $ Screen surface width height bpp screenQuit :: IO () screenQuit = SDL.quit
triplepointfive/hegine
src/App/Screen.hs
gpl-2.0
1,278
0
11
304
314
174
140
26
1
---------------------------------------------------------------------- -- | -- Module : Main -- Maintainer : Markus Forsberg -- Stability : (stability) -- Portability : (portability) -- -- > CVS $Date: 2006/03/03 17:22:23 $ -- > CVS $Author: markus $ -- > CVS $Revision: 1.5 $ -- -- Main file of FM backend. ----------------------------------------------------------------------------- module Command where import Distribution.GetOpt import Maybe(fromMaybe) import List(isSuffixOf) {- |Does the filename end with the suffix .dict? -} is_dictionary :: FilePath -> Bool is_dictionary = isSuffixOf ".dict" {- |Does the filename end with the suffix .lex? -} is_lexicon :: FilePath -> Bool is_lexicon = isSuffixOf ".lexicon" {- |Have an output file (-o) been given? -} output :: [Flag] -> Maybe FilePath output xs = case [f | Output f <- xs] of [f] -> Just f _ -> Nothing fullformflag :: [Flag] -> Bool fullformflag xs = case [p | p@(Print "lex") <- xs] of [_] -> True _ -> False {-|Data type for the Command line arguments. -} data Flag = Help | Version | Input String | Output String | Print String | Mode String | Lex String | Paradigms | Synth | Inflect | InflectB deriving (Show,Eq) {- |Lists all possible arguments and their explainations -} options :: [OptDescr Flag] options = [ Option ['h'] ["help"] (NoArg Help) "display this message" , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" , Option ['p'] ["printer"] (ReqArg Print "PRINTER") "Print using PRINTER" , Option ['t'] ["tables"] (NoArg Paradigms) "Print paradigms" , Option ['m'] ["mode"] (ReqArg Mode "MODE") "Analysis mode" , Option ['f'] ["fullform"] (ReqArg Lex "FULLFORM") "Input fullform lexicon" , Option ['i'] ["inflection"] (NoArg Inflect) "Inflection mode" , Option ['b'] ["batch"] (NoArg InflectB) "Inflection batch mode" , Option ['s'] ["synthesizer"] (NoArg Synth) "Synthesizer mode" ] inp,outp :: Maybe String -> Flag outp = Output . fromMaybe "stdout" inp = Input . fromMaybe "stdin" {- |Collect the valid arguments. Raises an IO error if it fails. -} compilerOpts :: [String] -> ([Flag], [String]) compilerOpts argv = case getOpt Permute options argv of (o,fs,[] ) -> (o,fs) (_,_,errs) -> error (usageInfo [] options) -- where header = "Usage: fm [OPTION...] dictionary_file(s)..."
isido/functional-morphology-for-koine-greek
lib/Options.hs
gpl-3.0
2,657
0
11
736
627
354
273
49
2
{-# LANGUAGE Rank2Types, NoMonomorphismRestriction, ScopedTypeVariables #-} module Database.Design.Ampersand.Test.TestScripts (getTestScripts,testAmpersandScripts) where import Data.List import Data.Char(toUpper) import System.FilePath ((</>),takeExtension) import Control.Monad --(filterM, forM_, foldM,when) import Control.Exception.Base import System.IO.Error (tryIOError) import System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist) import Control.Monad.Trans.Class (lift) import Data.Conduit import Database.Design.Ampersand.Test.RunAmpersand (ampersand) import Database.Design.Ampersand.Input.ADL1.CtxError endswith :: String -> String -> Bool endswith a b = drop (length a - length b) a == b -- Returns tuple with files and subdirectories inside the given directory getDirectory :: FilePath -> IO ([FilePath],[FilePath]) getDirectory path = do contents <- getDirectoryContents path let valid = filter (\x-> x /= "." && x /= "..") contents let paths = map (path ++) valid files <- filterM doesFileExist paths subdirs <- filterM doesDirectoryExist paths return (sort files, sort subdirs) getFiles :: String -> FilePath -> IO [FilePath] getFiles ext dir = do (fs, ds) <- getDirectory (dir++"/") let files = filter (`endswith` ext) fs foldM recursive files ds where recursive rs d = do ms <- getFiles ext d return $ ms ++ rs getTestScripts :: IO [FilePath] getTestScripts = do fs <- getFiles ".adl" "ArchitectureAndDesign" ss <- getFiles ".adl" $ ".." </> "ampersand-models" </> "Tests" </> "ShouldSucceed" ds <- getFiles ".adl" $ "AmpersandData" </> "FormalAmpersand" return $ fs ++ ss ++ ds --enabling these test as a single testcase will stop the sentinel from working. Was: fs ++ ss ++ ds -- ++ models data DirContent = DirList [FilePath] [FilePath] | DirError IOError data DirData = DirData FilePath DirContent testAmpersandScripts :: IO () testAmpersandScripts = do walk baseDir $$ myVisitor where baseDir = ".." </> "ampersand-models" -- Produces directory data walk :: FilePath -> Source IO DirData walk path = do result <- lift $ tryIOError listdir case result of Right dl -> case dl of DirList subdirs _ -> do yield (DirData path dl) forM_ subdirs (walk . (path </>)) DirError err -> yield (DirData path (DirError err)) Left err -> yield (DirData path (DirError err)) where listdir = do entries <- getDirectoryContents path >>= filterHidden subdirs <- filterM isDir entries files <- filterM isFile entries return $ DirList subdirs (filter isRelevant files) where isFile entry = doesFileExist (path </> entry) isDir entry = doesDirectoryExist (path </> entry) filterHidden paths = return $ filter (not.isHidden) paths isRelevant f = map toUpper (takeExtension f) `elem` [".ADL"] isHidden dir = head dir == '.' -- Consume directories myVisitor :: Sink DirData IO () myVisitor = addCleanup (\_ -> putStrLn "Finished.") $ loop 1 where loop :: Int -> ConduitM DirData a IO () loop n = do lift $ putStr $ ">> " ++ show n ++ ". " mr <- await case mr of Nothing -> return () Just r -> lift (process r) >> loop (n + 1) process (DirData path (DirError err)) = do putStrLn $ "I've tried to look in " ++ path ++ "." putStrLn $ " There was an error: " putStrLn $ " " ++ show err process (DirData path (DirList dirs files)) = do putStrLn $ path ++ ". ("++ show (length dirs) ++ " directorie(s) and " ++ show (length files) ++ " relevant file(s):" forM_ files (runATest path) runATest :: FilePath -> FilePath -> IO() runATest path file = catch (runATest' path file) showError where showError :: SomeException -> IO() showError err = do putStrLn "***** ERROR: Fatal error was thrown: *****" putStrLn $ (path </> file) putStrLn $ show err putStrLn "******************************************" runATest' :: FilePath -> FilePath -> IO() runATest' path file = do [(_,errs)] <- ampersand [path </> file] putStrLn ( file ++": "++ case (shouldFail,errs) of (False, []) -> "OK. => Pass" (False, _ ) -> "Fail => NOT PASSED:" (True , []) -> "Ok. => NOT PASSED" (True , _ ) -> "Fail => Pass" ) when (not shouldFail) $ mapM_ putStrLn (map showErr (take 1 errs)) --for now, only show the first error where shouldFail = "SHOULDFAIL" `isInfixOf` map toUpper (path </> file)
4ZP6Capstone2015/ampersand
src/Database/Design/Ampersand/Test/TestScripts.hs
gpl-3.0
4,952
0
18
1,426
1,491
752
739
106
4
{-# LANGUAGE DeriveFunctor #-} module FractalComonad where import Control.Comonad import Control.Applicative data Layer a = Layer a deriving (Show, Read, Eq, Functor) instance Comonad Layer where -- duplicate :: w a -> w (w a) duplicate (Layer l) = Layer (Layer l) -- extract :: w a -> a extract (Layer l) = l checkComLaws1 = (extract . duplicate $ test) == test checkComLaws2 = (fmap extract . duplicate $ test) == test checkComLaws3 = (duplicate . duplicate $ test) == (fmap duplicate . duplicate $ test) cLaws = [checkComLaws1, checkComLaws2, checkComLaws3] comonadCantorRule :: Layer Segments -> Segments comonadCantorRule layer = --concatMap cantorRule . extract let segments = extract layer in concatMap cantorRule segments type Segment = (Float, Float) type Segments = [(Float, Float)] cantorRule :: Segment -> Segments cantorRule (x1, x2) = let len = x2 - x1 oneThird = len / 3.0 in [(x1, x1 + oneThird), (x2 - oneThird, x2)] cantorCustomGen :: Segments -> Segments cantorCustomGen segs = concatMap cantorRule segs cantorStartSegment x1 x2 = [(x1, x2)] test = mkCantor 0.0 9.0 mkCantor :: Float -> Float -> Layer Segments mkCantor x1 x2 = Layer $ cantorStartSegment x1 x2 cantorGen = (=>> comonadCantorRule) fractal = iterate cantorGen test {- LYAH -} {- data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show) data TreeZ a = L a (Tree a) | R a (Tree a) deriving (Show) type TreeZS a = [TreeZ a] type TreeZipper a = (Tree a, TreeZS a) left, right :: TreeZipper a -> TreeZipper a left (Node x l r, bs) = (l, L x r:bs) right (Node x l r, bs) = (r, R x l:bs) type CantorTree = Tree Segment genLSegment x = Node (head $ cantorGen x) Empty Empty genRSegment x = Node (head $ tail $ cantorGen x) Empty Empty cantorLeft (Node x Empty r, bs) = (genLSegment x, L x r : bs) cantorLeft (Node x l r, bs) = (l, L x r : bs) cantorRight (Node x l Empty, bs) = (genRSegment x, R x l : bs) -}
graninas/Haskell-Algorithms
Tests/Fractal/FractalOfFrcactals.hs
gpl-3.0
1,981
0
9
437
429
235
194
32
1
module DL3001 (tests) where import Helpers import Test.Hspec tests :: SpecWith () tests = do let ?rulesConfig = mempty describe "DL3001 - invalid CMD rules" $ do it "invalid cmd" $ do ruleCatches "DL3001" "RUN top" onBuildRuleCatches "DL3001" "RUN top" it "install ssh" $ do ruleCatchesNot "DL3001" "RUN apt-get install ssh" onBuildRuleCatchesNot "DL3001" "RUN apt-get install ssh"
lukasmartinelli/hadolint
test/DL3001.hs
gpl-3.0
421
0
13
96
103
47
56
-1
-1
{-# LANGUAGE OverloadedStrings, FlexibleContexts, TypeOperators #-} import Control.Monad.Exception import qualified Data.ByteString.Lazy as B import qualified Data.Map as M import JVM.ClassFile import JVM.Converter import JVM.Assembler import JVM.Builder hiding (generate) import qualified JVM.Builder as J import JVM.Exceptions import Java.ClassPath import qualified Java.Lang import qualified Java.IO import Language.Pascal.Types import Language.Pascal.JVM.CodeGen x :: Symbol x = Symbol { symbolName = "x", symbolType = TInteger, symbolConstValue = Nothing, symbolContext = Outside, symbolIndex = 0, symbolDefLine = 0, symbolDefCol = 0 } y :: Symbol y = Symbol { symbolName = "y", symbolType = TInteger, symbolConstValue = Nothing, symbolContext = InFunction "test" TVoid, symbolIndex = 0, symbolDefLine = 0, symbolDefCol = 0 } testType :: TypeAnn testType = TypeAnn { srcPos = SrcPos 0 0, typeOf = TInteger, localSymbols = M.empty, allSymbols = [M.singleton "y" y, M.singleton "x" x] } expr :: Expression :~ TypeAnn expr = Annotate { content = Op Add (Annotate (Variable "x") testType) (Annotate (Literal (LInteger 1)) testType), annotation = testType } assignment :: Statement :~ TypeAnn assignment = Annotate { content = Assign (Annotate (LVariable "y") testType) expr, annotation = testType } this :: Id -> Annotate Symbol SrcPos this name = Annotate { content = Symbol { symbolName = "this", symbolType = TRecord (Just name) [], symbolConstValue = Nothing, symbolContext = Outside, symbolIndex = 0, symbolDefLine = 0, symbolDefCol = 0 }, annotation = SrcPos 0 0 } test :: (Throws ENotFound e, Throws ENotLoaded e, Throws UnexpectedEndMethod e, Throws (Located GeneratorError) e) => Generate e () test = do x <- newField [ACC_PUBLIC] "x" IntType -- Initializer method. Just calls java.lang.Object.<init> init <- newMethod [ACC_PUBLIC] "<init>" [] ReturnsVoid $ do setStackSize 4 aload_ I0 invokeSpecial Java.Lang.object Java.Lang.objectInit aload_ I0 iconst_2 putField "Test" x i0 RETURN testMethod <- newMethod [ACC_PUBLIC] "test" [] ReturnsVoid $ do setStackSize 20 setMaxLocals 3 generateJvm "Test" $ generate assignment getStaticField Java.Lang.system Java.IO.out loadString "Result: %d\n" iconst_1 allocArray Java.Lang.object dup iconst_0 iload_ I1 invokeStatic Java.Lang.integer Java.Lang.valueOfInteger aastore invokeVirtual Java.IO.printStream Java.IO.printf i0 RETURN newMethod [ACC_PUBLIC, ACC_STATIC] "main" [arrayOf Java.Lang.stringClass] ReturnsVoid $ do setStackSize 3 new "Test" dup invokeSpecial "Test" init invokeVirtual "Test" testMethod i0 RETURN return () main :: IO () main = do let testClass = J.generate [] "Test" test B.writeFile "Test.class" (encodeClass testClass)
portnov/simple-pascal-compiler
spc-jvm/Test.hs
lgpl-3.0
3,162
0
13
832
892
473
419
99
1
module ProjectM36.WCWidth where import Data.Set.Range import Data.Char wIDEEASTASIAN :: RangeSet Int wIDEEASTASIAN = foldr insertRange empty [ (0x1100, 0x115f), -- Hangul Choseong Kiyeok ..Hangul Choseong Filler (0x231a, 0x231b), -- Watch ..Hourglass (0x2329, 0x232a), -- Left-pointing Angle Brac..Right-pointing Angle Bra (0x23e9, 0x23ec), -- Black Right-pointing Dou..Black Down-pointing Doub (0x23f0, 0x23f0), -- Alarm Clock ..Alarm Clock (0x23f3, 0x23f3), -- Hourglass With Flowing S..Hourglass With Flowing S (0x25fd, 0x25fe), -- White Medium Small Squar..Black Medium Small Squar (0x2614, 0x2615), -- Umbrella With Rain Drops..Hot Beverage (0x2648, 0x2653), -- Aries ..Pisces (0x267f, 0x267f), -- Wheelchair Symbol ..Wheelchair Symbol (0x2693, 0x2693), -- Anchor ..Anchor (0x26a1, 0x26a1), -- High Voltage Sign ..High Voltage Sign (0x26aa, 0x26ab), -- Medium White Circle ..Medium Black Circle (0x26bd, 0x26be), -- Soccer Ball ..Baseball (0x26c4, 0x26c5), -- Snowman Without Snow ..Sun Behind Cloud (0x26ce, 0x26ce), -- Ophiuchus ..Ophiuchus (0x26d4, 0x26d4), -- No Entry ..No Entry (0x26ea, 0x26ea), -- Church ..Church (0x26f2, 0x26f3), -- Fountain ..Flag In Hole (0x26f5, 0x26f5), -- Sailboat ..Sailboat (0x26fa, 0x26fa), -- Tent ..Tent (0x26fd, 0x26fd), -- Fuel Pump ..Fuel Pump (0x2705, 0x2705), -- White Heavy Check Mark ..White Heavy Check Mark (0x270a, 0x270b), -- Raised Fist ..Raised Hand (0x2728, 0x2728), -- Sparkles ..Sparkles (0x274c, 0x274c), -- Cross Mark ..Cross Mark (0x274e, 0x274e), -- Negative Squared Cross M..Negative Squared Cross M (0x2753, 0x2755), -- Black Question Mark Orna..White Exclamation Mark O (0x2757, 0x2757), -- Heavy Exclamation Mark S..Heavy Exclamation Mark S (0x2795, 0x2797), -- Heavy Plus Sign ..Heavy Division Sign (0x27b0, 0x27b0), -- Curly Loop ..Curly Loop (0x27bf, 0x27bf), -- Double Curly Loop ..Double Curly Loop (0x2b1b, 0x2b1c), -- Black Large Square ..White Large Square (0x2b50, 0x2b50), -- White Medium Star ..White Medium Star (0x2b55, 0x2b55), -- Heavy Large Circle ..Heavy Large Circle (0x2e80, 0x2e99), -- Cjk Radical Repeat ..Cjk Radical Rap (0x2e9b, 0x2ef3), -- Cjk Radical Choke ..Cjk Radical C-simplified (0x2f00, 0x2fd5), -- Kangxi Radical One ..Kangxi Radical Flute (0x2ff0, 0x2ffb), -- Ideographic Description ..Ideographic Description (0x3000, 0x303e), -- Ideographic Space ..Ideographic Variation In (0x3041, 0x3096), -- Hiragana Letter Small A ..Hiragana Letter Small Ke (0x3099, 0x30ff), -- Combining Katakana-hirag..Katakana Digraph Koto (0x3105, 0x312d), -- Bopomofo Letter B ..Bopomofo Letter Ih (0x3131, 0x318e), -- Hangul Letter Kiyeok ..Hangul Letter Araeae (0x3190, 0x31ba), -- Ideographic Annotation L..Bopomofo Letter Zy (0x31c0, 0x31e3), -- Cjk Stroke T ..Cjk Stroke Q (0x31f0, 0x321e), -- Katakana Letter Small Ku..Parenthesized Korean Cha (0x3220, 0x3247), -- Parenthesized Ideograph ..Circled Ideograph Koto (0x3250, 0x32fe), -- Partnership Sign ..Circled Katakana Wo (0x3300, 0x4dbf), -- Square Apaato .. (0x4e00, 0xa48c), -- Cjk Unified Ideograph-4e..Yi Syllable Yyr (0xa490, 0xa4c6), -- Yi Radical Qot ..Yi Radical Ke (0xa960, 0xa97c), -- Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo (0xac00, 0xd7a3), -- Hangul Syllable Ga ..Hangul Syllable Hih (0xf900, 0xfaff), -- Cjk Compatibility Ideogr.. (0xfe10, 0xfe19), -- Presentation Form For Ve..Presentation Form For Ve (0xfe30, 0xfe52), -- Presentation Form For Ve..Small Full Stop (0xfe54, 0xfe66), -- Small Semicolon ..Small Equals Sign (0xfe68, 0xfe6b), -- Small Reverse Solidus ..Small Commercial At (0xff01, 0xff60), -- Fullwidth Exclamation Ma..Fullwidth Right White Pa (0xffe0, 0xffe6), -- Fullwidth Cent Sign ..Fullwidth Won Sign (0x16fe0, 0x16fe0), -- (nil) .. (0x17000, 0x187ec), -- (nil) .. (0x18800, 0x18af2), -- (nil) .. (0x1b000, 0x1b001), -- Katakana Letter Archaic ..Hiragana Letter Archaic (0x1f004, 0x1f004), -- Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon (0x1f0cf, 0x1f0cf), -- Playing Card Black Joker..Playing Card Black Joker (0x1f18e, 0x1f18e), -- Negative Squared Ab ..Negative Squared Ab (0x1f191, 0x1f19a), -- Squared Cl ..Squared Vs (0x1f200, 0x1f202), -- Square Hiragana Hoka ..Squared Katakana Sa (0x1f210, 0x1f23b), -- Squared Cjk Unified Ideo.. (0x1f240, 0x1f248), -- Tortoise Shell Bracketed..Tortoise Shell Bracketed (0x1f250, 0x1f251), -- Circled Ideograph Advant..Circled Ideograph Accept (0x1f300, 0x1f320), -- Cyclone ..Shooting Star (0x1f32d, 0x1f335), -- Hot Dog ..Cactus (0x1f337, 0x1f37c), -- Tulip ..Baby Bottle (0x1f37e, 0x1f393), -- Bottle With Popping Cork..Graduation Cap (0x1f3a0, 0x1f3ca), -- Carousel Horse ..Swimmer (0x1f3cf, 0x1f3d3), -- Cricket Bat And Ball ..Table Tennis Paddle And (0x1f3e0, 0x1f3f0), -- House Building ..European Castle (0x1f3f4, 0x1f3f4), -- Waving Black Flag ..Waving Black Flag (0x1f3f8, 0x1f43e), -- Badminton Racquet And Sh..Paw Prints (0x1f440, 0x1f440), -- Eyes ..Eyes (0x1f442, 0x1f4fc), -- Ear ..Videocassette (0x1f4ff, 0x1f53d), -- Prayer Beads ..Down-pointing Small Red (0x1f54b, 0x1f54e), -- Kaaba ..Menorah With Nine Branch (0x1f550, 0x1f567), -- Clock Face One Oclock ..Clock Face Twelve-thirty (0x1f57a, 0x1f57a), -- (nil) .. (0x1f595, 0x1f596), -- Reversed Hand With Middl..Raised Hand With Part Be (0x1f5a4, 0x1f5a4), -- (nil) .. (0x1f5fb, 0x1f64f), -- Mount Fuji ..Person With Folded Hands (0x1f680, 0x1f6c5), -- Rocket ..Left Luggage (0x1f6cc, 0x1f6cc), -- Sleeping Accommodation ..Sleeping Accommodation (0x1f6d0, 0x1f6d2), -- Place Of Worship .. (0x1f6eb, 0x1f6ec), -- Airplane Departure ..Airplane Arriving (0x1f6f4, 0x1f6f6), -- (nil) .. (0x1f910, 0x1f91e), -- Zipper-mouth Face .. (0x1f920, 0x1f927), -- (nil) .. (0x1f930, 0x1f930), -- (nil) .. (0x1f933, 0x1f93e), -- (nil) .. (0x1f940, 0x1f94b), -- (nil) .. (0x1f950, 0x1f95e), -- (nil) .. (0x1f980, 0x1f991), -- Crab .. (0x1f9c0, 0x1f9c0), -- Cheese Wedge ..Cheese Wedge (0x20000, 0x2fffd), -- Cjk Unified Ideograph-20.. (0x30000, 0x3fffd) -- (nil) .. ] zEROWIDTH :: RangeSet Int zEROWIDTH = foldr insertRange empty [ (0x0300, 0x036f), -- Combining Grave Accent ..Combining Latin Small Le (0x0483, 0x0489), -- Combining Cyrillic Titlo..Combining Cyrillic Milli (0x0591, 0x05bd), -- Hebrew Accent Etnahta ..Hebrew Point Meteg (0x05bf, 0x05bf), -- Hebrew Point Rafe ..Hebrew Point Rafe (0x05c1, 0x05c2), -- Hebrew Point Shin Dot ..Hebrew Point Sin Dot (0x05c4, 0x05c5), -- Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot (0x05c7, 0x05c7), -- Hebrew Point Qamats Qata..Hebrew Point Qamats Qata (0x0610, 0x061a), -- Arabic Sign Sallallahou ..Arabic Small Kasra (0x064b, 0x065f), -- Arabic Fathatan ..Arabic Wavy Hamza Below (0x0670, 0x0670), -- Arabic Letter Superscrip..Arabic Letter Superscrip (0x06d6, 0x06dc), -- Arabic Small High Ligatu..Arabic Small High Seen (0x06df, 0x06e4), -- Arabic Small High Rounde..Arabic Small High Madda (0x06e7, 0x06e8), -- Arabic Small High Yeh ..Arabic Small High Noon (0x06ea, 0x06ed), -- Arabic Empty Centre Low ..Arabic Small Low Meem (0x0711, 0x0711), -- Syriac Letter Superscrip..Syriac Letter Superscrip (0x0730, 0x074a), -- Syriac Pthaha Above ..Syriac Barrekh (0x07a6, 0x07b0), -- Thaana Abafili ..Thaana Sukun (0x07eb, 0x07f3), -- Nko Combining Short High..Nko Combining Double Dot (0x0816, 0x0819), -- Samaritan Mark In ..Samaritan Mark Dagesh (0x081b, 0x0823), -- Samaritan Mark Epentheti..Samaritan Vowel Sign A (0x0825, 0x0827), -- Samaritan Vowel Sign Sho..Samaritan Vowel Sign U (0x0829, 0x082d), -- Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa (0x0859, 0x085b), -- Mandaic Affrication Mark..Mandaic Gemination Mark (0x08d4, 0x08e1), -- (nil) .. (0x08e3, 0x0902), -- Arabic Turned Damma Belo..Devanagari Sign Anusvara (0x093a, 0x093a), -- Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe (0x093c, 0x093c), -- Devanagari Sign Nukta ..Devanagari Sign Nukta (0x0941, 0x0948), -- Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai (0x094d, 0x094d), -- Devanagari Sign Virama ..Devanagari Sign Virama (0x0951, 0x0957), -- Devanagari Stress Sign U..Devanagari Vowel Sign Uu (0x0962, 0x0963), -- Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo (0x0981, 0x0981), -- Bengali Sign Candrabindu..Bengali Sign Candrabindu (0x09bc, 0x09bc), -- Bengali Sign Nukta ..Bengali Sign Nukta (0x09c1, 0x09c4), -- Bengali Vowel Sign U ..Bengali Vowel Sign Vocal (0x09cd, 0x09cd), -- Bengali Sign Virama ..Bengali Sign Virama (0x09e2, 0x09e3), -- Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal (0x0a01, 0x0a02), -- Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi (0x0a3c, 0x0a3c), -- Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta (0x0a41, 0x0a42), -- Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu (0x0a47, 0x0a48), -- Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai (0x0a4b, 0x0a4d), -- Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama (0x0a51, 0x0a51), -- Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat (0x0a70, 0x0a71), -- Gurmukhi Tippi ..Gurmukhi Addak (0x0a75, 0x0a75), -- Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash (0x0a81, 0x0a82), -- Gujarati Sign Candrabind..Gujarati Sign Anusvara (0x0abc, 0x0abc), -- Gujarati Sign Nukta ..Gujarati Sign Nukta (0x0ac1, 0x0ac5), -- Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand (0x0ac7, 0x0ac8), -- Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai (0x0acd, 0x0acd), -- Gujarati Sign Virama ..Gujarati Sign Virama (0x0ae2, 0x0ae3), -- Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca (0x0b01, 0x0b01), -- Oriya Sign Candrabindu ..Oriya Sign Candrabindu (0x0b3c, 0x0b3c), -- Oriya Sign Nukta ..Oriya Sign Nukta (0x0b3f, 0x0b3f), -- Oriya Vowel Sign I ..Oriya Vowel Sign I (0x0b41, 0x0b44), -- Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic (0x0b4d, 0x0b4d), -- Oriya Sign Virama ..Oriya Sign Virama (0x0b56, 0x0b56), -- Oriya Ai Length Mark ..Oriya Ai Length Mark (0x0b62, 0x0b63), -- Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic (0x0b82, 0x0b82), -- Tamil Sign Anusvara ..Tamil Sign Anusvara (0x0bc0, 0x0bc0), -- Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii (0x0bcd, 0x0bcd), -- Tamil Sign Virama ..Tamil Sign Virama (0x0c00, 0x0c00), -- Telugu Sign Combining Ca..Telugu Sign Combining Ca (0x0c3e, 0x0c40), -- Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii (0x0c46, 0x0c48), -- Telugu Vowel Sign E ..Telugu Vowel Sign Ai (0x0c4a, 0x0c4d), -- Telugu Vowel Sign O ..Telugu Sign Virama (0x0c55, 0x0c56), -- Telugu Length Mark ..Telugu Ai Length Mark (0x0c62, 0x0c63), -- Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali (0x0c81, 0x0c81), -- Kannada Sign Candrabindu..Kannada Sign Candrabindu (0x0cbc, 0x0cbc), -- Kannada Sign Nukta ..Kannada Sign Nukta (0x0cbf, 0x0cbf), -- Kannada Vowel Sign I ..Kannada Vowel Sign I (0x0cc6, 0x0cc6), -- Kannada Vowel Sign E ..Kannada Vowel Sign E (0x0ccc, 0x0ccd), -- Kannada Vowel Sign Au ..Kannada Sign Virama (0x0ce2, 0x0ce3), -- Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal (0x0d01, 0x0d01), -- Malayalam Sign Candrabin..Malayalam Sign Candrabin (0x0d41, 0x0d44), -- Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc (0x0d4d, 0x0d4d), -- Malayalam Sign Virama ..Malayalam Sign Virama (0x0d62, 0x0d63), -- Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc (0x0dca, 0x0dca), -- Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna (0x0dd2, 0x0dd4), -- Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti (0x0dd6, 0x0dd6), -- Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga (0x0e31, 0x0e31), -- Thai Character Mai Han-a..Thai Character Mai Han-a (0x0e34, 0x0e3a), -- Thai Character Sara I ..Thai Character Phinthu (0x0e47, 0x0e4e), -- Thai Character Maitaikhu..Thai Character Yamakkan (0x0eb1, 0x0eb1), -- Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan (0x0eb4, 0x0eb9), -- Lao Vowel Sign I ..Lao Vowel Sign Uu (0x0ebb, 0x0ebc), -- Lao Vowel Sign Mai Kon ..Lao Semivowel Sign Lo (0x0ec8, 0x0ecd), -- Lao Tone Mai Ek ..Lao Niggahita (0x0f18, 0x0f19), -- Tibetan Astrological Sig..Tibetan Astrological Sig (0x0f35, 0x0f35), -- Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung (0x0f37, 0x0f37), -- Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung (0x0f39, 0x0f39), -- Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru (0x0f71, 0x0f7e), -- Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga (0x0f80, 0x0f84), -- Tibetan Vowel Sign Rever..Tibetan Mark Halanta (0x0f86, 0x0f87), -- Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags (0x0f8d, 0x0f97), -- Tibetan Subjoined Sign L..Tibetan Subjoined Letter (0x0f99, 0x0fbc), -- Tibetan Subjoined Letter..Tibetan Subjoined Letter (0x0fc6, 0x0fc6), -- Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda (0x102d, 0x1030), -- Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu (0x1032, 0x1037), -- Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below (0x1039, 0x103a), -- Myanmar Sign Virama ..Myanmar Sign Asat (0x103d, 0x103e), -- Myanmar Consonant Sign M..Myanmar Consonant Sign M (0x1058, 0x1059), -- Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal (0x105e, 0x1060), -- Myanmar Consonant Sign M..Myanmar Consonant Sign M (0x1071, 0x1074), -- Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah (0x1082, 0x1082), -- Myanmar Consonant Sign S..Myanmar Consonant Sign S (0x1085, 0x1086), -- Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan (0x108d, 0x108d), -- Myanmar Sign Shan Counci..Myanmar Sign Shan Counci (0x109d, 0x109d), -- Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton (0x135d, 0x135f), -- Ethiopic Combining Gemin..Ethiopic Combining Gemin (0x1712, 0x1714), -- Tagalog Vowel Sign I ..Tagalog Sign Virama (0x1732, 0x1734), -- Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod (0x1752, 0x1753), -- Buhid Vowel Sign I ..Buhid Vowel Sign U (0x1772, 0x1773), -- Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U (0x17b4, 0x17b5), -- Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa (0x17b7, 0x17bd), -- Khmer Vowel Sign I ..Khmer Vowel Sign Ua (0x17c6, 0x17c6), -- Khmer Sign Nikahit ..Khmer Sign Nikahit (0x17c9, 0x17d3), -- Khmer Sign Muusikatoan ..Khmer Sign Bathamasat (0x17dd, 0x17dd), -- Khmer Sign Atthacan ..Khmer Sign Atthacan (0x180b, 0x180d), -- Mongolian Free Variation..Mongolian Free Variation (0x1885, 0x1886), -- Mongolian Letter Ali Gal..Mongolian Letter Ali Gal (0x18a9, 0x18a9), -- Mongolian Letter Ali Gal..Mongolian Letter Ali Gal (0x1920, 0x1922), -- Limbu Vowel Sign A ..Limbu Vowel Sign U (0x1927, 0x1928), -- Limbu Vowel Sign E ..Limbu Vowel Sign O (0x1932, 0x1932), -- Limbu Small Letter Anusv..Limbu Small Letter Anusv (0x1939, 0x193b), -- Limbu Sign Mukphreng ..Limbu Sign Sa-i (0x1a17, 0x1a18), -- Buginese Vowel Sign I ..Buginese Vowel Sign U (0x1a1b, 0x1a1b), -- Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae (0x1a56, 0x1a56), -- Tai Tham Consonant Sign ..Tai Tham Consonant Sign (0x1a58, 0x1a5e), -- Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign (0x1a60, 0x1a60), -- Tai Tham Sign Sakot ..Tai Tham Sign Sakot (0x1a62, 0x1a62), -- Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai (0x1a65, 0x1a6c), -- Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B (0x1a73, 0x1a7c), -- Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue (0x1a7f, 0x1a7f), -- Tai Tham Combining Crypt..Tai Tham Combining Crypt (0x1ab0, 0x1abe), -- Combining Doubled Circum..Combining Parentheses Ov (0x1b00, 0x1b03), -- Balinese Sign Ulu Ricem ..Balinese Sign Surang (0x1b34, 0x1b34), -- Balinese Sign Rerekan ..Balinese Sign Rerekan (0x1b36, 0x1b3a), -- Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R (0x1b3c, 0x1b3c), -- Balinese Vowel Sign La L..Balinese Vowel Sign La L (0x1b42, 0x1b42), -- Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe (0x1b6b, 0x1b73), -- Balinese Musical Symbol ..Balinese Musical Symbol (0x1b80, 0x1b81), -- Sundanese Sign Panyecek ..Sundanese Sign Panglayar (0x1ba2, 0x1ba5), -- Sundanese Consonant Sign..Sundanese Vowel Sign Pan (0x1ba8, 0x1ba9), -- Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan (0x1bab, 0x1bad), -- Sundanese Sign Virama ..Sundanese Consonant Sign (0x1be6, 0x1be6), -- Batak Sign Tompi ..Batak Sign Tompi (0x1be8, 0x1be9), -- Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee (0x1bed, 0x1bed), -- Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O (0x1bef, 0x1bf1), -- Batak Vowel Sign U For S..Batak Consonant Sign H (0x1c2c, 0x1c33), -- Lepcha Vowel Sign E ..Lepcha Consonant Sign T (0x1c36, 0x1c37), -- Lepcha Sign Ran ..Lepcha Sign Nukta (0x1cd0, 0x1cd2), -- Vedic Tone Karshana ..Vedic Tone Prenkha (0x1cd4, 0x1ce0), -- Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash (0x1ce2, 0x1ce8), -- Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda (0x1ced, 0x1ced), -- Vedic Sign Tiryak ..Vedic Sign Tiryak (0x1cf4, 0x1cf4), -- Vedic Tone Candra Above ..Vedic Tone Candra Above (0x1cf8, 0x1cf9), -- Vedic Tone Ring Above ..Vedic Tone Double Ring A (0x1dc0, 0x1df5), -- Combining Dotted Grave A..Combining Up Tack Above (0x1dfb, 0x1dff), -- (nil) ..Combining Right Arrowhea (0x20d0, 0x20f0), -- Combining Left Harpoon A..Combining Asterisk Above (0x2cef, 0x2cf1), -- Coptic Combining Ni Abov..Coptic Combining Spiritu (0x2d7f, 0x2d7f), -- Tifinagh Consonant Joine..Tifinagh Consonant Joine (0x2de0, 0x2dff), -- Combining Cyrillic Lette..Combining Cyrillic Lette (0x302a, 0x302d), -- Ideographic Level Tone M..Ideographic Entering Ton (0x3099, 0x309a), -- Combining Katakana-hirag..Combining Katakana-hirag (0xa66f, 0xa672), -- Combining Cyrillic Vzmet..Combining Cyrillic Thous (0xa674, 0xa67d), -- Combining Cyrillic Lette..Combining Cyrillic Payer (0xa69e, 0xa69f), -- Combining Cyrillic Lette..Combining Cyrillic Lette (0xa6f0, 0xa6f1), -- Bamum Combining Mark Koq..Bamum Combining Mark Tuk (0xa802, 0xa802), -- Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva (0xa806, 0xa806), -- Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant (0xa80b, 0xa80b), -- Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva (0xa825, 0xa826), -- Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign (0xa8c4, 0xa8c5), -- Saurashtra Sign Virama .. (0xa8e0, 0xa8f1), -- Combining Devanagari Dig..Combining Devanagari Sig (0xa926, 0xa92d), -- Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop (0xa947, 0xa951), -- Rejang Vowel Sign I ..Rejang Consonant Sign R (0xa980, 0xa982), -- Javanese Sign Panyangga ..Javanese Sign Layar (0xa9b3, 0xa9b3), -- Javanese Sign Cecak Telu..Javanese Sign Cecak Telu (0xa9b6, 0xa9b9), -- Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku (0xa9bc, 0xa9bc), -- Javanese Vowel Sign Pepe..Javanese Vowel Sign Pepe (0xa9e5, 0xa9e5), -- Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw (0xaa29, 0xaa2e), -- Cham Vowel Sign Aa ..Cham Vowel Sign Oe (0xaa31, 0xaa32), -- Cham Vowel Sign Au ..Cham Vowel Sign Ue (0xaa35, 0xaa36), -- Cham Consonant Sign La ..Cham Consonant Sign Wa (0xaa43, 0xaa43), -- Cham Consonant Sign Fina..Cham Consonant Sign Fina (0xaa4c, 0xaa4c), -- Cham Consonant Sign Fina..Cham Consonant Sign Fina (0xaa7c, 0xaa7c), -- Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T (0xaab0, 0xaab0), -- Tai Viet Mai Kang ..Tai Viet Mai Kang (0xaab2, 0xaab4), -- Tai Viet Vowel I ..Tai Viet Vowel U (0xaab7, 0xaab8), -- Tai Viet Mai Khit ..Tai Viet Vowel Ia (0xaabe, 0xaabf), -- Tai Viet Vowel Am ..Tai Viet Tone Mai Ek (0xaac1, 0xaac1), -- Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho (0xaaec, 0xaaed), -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign (0xaaf6, 0xaaf6), -- Meetei Mayek Virama ..Meetei Mayek Virama (0xabe5, 0xabe5), -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign (0xabe8, 0xabe8), -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign (0xabed, 0xabed), -- Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek (0xfb1e, 0xfb1e), -- Hebrew Point Judeo-spani..Hebrew Point Judeo-spani (0xfe00, 0xfe0f), -- Variation Selector-1 ..Variation Selector-16 (0xfe20, 0xfe2f), -- Combining Ligature Left ..Combining Cyrillic Titlo (0x101fd, 0x101fd), -- Phaistos Disc Sign Combi..Phaistos Disc Sign Combi (0x102e0, 0x102e0), -- Coptic Epact Thousands M..Coptic Epact Thousands M (0x10376, 0x1037a), -- Combining Old Permic Let..Combining Old Permic Let (0x10a01, 0x10a03), -- Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo (0x10a05, 0x10a06), -- Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O (0x10a0c, 0x10a0f), -- Kharoshthi Vowel Length ..Kharoshthi Sign Visarga (0x10a38, 0x10a3a), -- Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo (0x10a3f, 0x10a3f), -- Kharoshthi Virama ..Kharoshthi Virama (0x10ae5, 0x10ae6), -- Manichaean Abbreviation ..Manichaean Abbreviation (0x11001, 0x11001), -- Brahmi Sign Anusvara ..Brahmi Sign Anusvara (0x11038, 0x11046), -- Brahmi Vowel Sign Aa ..Brahmi Virama (0x1107f, 0x11081), -- Brahmi Number Joiner ..Kaithi Sign Anusvara (0x110b3, 0x110b6), -- Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai (0x110b9, 0x110ba), -- Kaithi Sign Virama ..Kaithi Sign Nukta (0x11100, 0x11102), -- Chakma Sign Candrabindu ..Chakma Sign Visarga (0x11127, 0x1112b), -- Chakma Vowel Sign A ..Chakma Vowel Sign Uu (0x1112d, 0x11134), -- Chakma Vowel Sign Ai ..Chakma Maayyaa (0x11173, 0x11173), -- Mahajani Sign Nukta ..Mahajani Sign Nukta (0x11180, 0x11181), -- Sharada Sign Candrabindu..Sharada Sign Anusvara (0x111b6, 0x111be), -- Sharada Vowel Sign U ..Sharada Vowel Sign O (0x111ca, 0x111cc), -- Sharada Sign Nukta ..Sharada Extra Short Vowe (0x1122f, 0x11231), -- Khojki Vowel Sign U ..Khojki Vowel Sign Ai (0x11234, 0x11234), -- Khojki Sign Anusvara ..Khojki Sign Anusvara (0x11236, 0x11237), -- Khojki Sign Nukta ..Khojki Sign Shadda (0x1123e, 0x1123e), -- (nil) .. (0x112df, 0x112df), -- Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara (0x112e3, 0x112ea), -- Khudawadi Vowel Sign U ..Khudawadi Sign Virama (0x11300, 0x11301), -- Grantha Sign Combining A..Grantha Sign Candrabindu (0x1133c, 0x1133c), -- Grantha Sign Nukta ..Grantha Sign Nukta (0x11340, 0x11340), -- Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii (0x11366, 0x1136c), -- Combining Grantha Digit ..Combining Grantha Digit (0x11370, 0x11374), -- Combining Grantha Letter..Combining Grantha Letter (0x11438, 0x1143f), -- (nil) .. (0x11442, 0x11444), -- (nil) .. (0x11446, 0x11446), -- (nil) .. (0x114b3, 0x114b8), -- Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal (0x114ba, 0x114ba), -- Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short (0x114bf, 0x114c0), -- Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara (0x114c2, 0x114c3), -- Tirhuta Sign Virama ..Tirhuta Sign Nukta (0x115b2, 0x115b5), -- Siddham Vowel Sign U ..Siddham Vowel Sign Vocal (0x115bc, 0x115bd), -- Siddham Sign Candrabindu..Siddham Sign Anusvara (0x115bf, 0x115c0), -- Siddham Sign Virama ..Siddham Sign Nukta (0x115dc, 0x115dd), -- Siddham Vowel Sign Alter..Siddham Vowel Sign Alter (0x11633, 0x1163a), -- Modi Vowel Sign U ..Modi Vowel Sign Ai (0x1163d, 0x1163d), -- Modi Sign Anusvara ..Modi Sign Anusvara (0x1163f, 0x11640), -- Modi Sign Virama ..Modi Sign Ardhacandra (0x116ab, 0x116ab), -- Takri Sign Anusvara ..Takri Sign Anusvara (0x116ad, 0x116ad), -- Takri Vowel Sign Aa ..Takri Vowel Sign Aa (0x116b0, 0x116b5), -- Takri Vowel Sign U ..Takri Vowel Sign Au (0x116b7, 0x116b7), -- Takri Sign Nukta ..Takri Sign Nukta (0x1171d, 0x1171f), -- Ahom Consonant Sign Medi..Ahom Consonant Sign Medi (0x11722, 0x11725), -- Ahom Vowel Sign I ..Ahom Vowel Sign Uu (0x11727, 0x1172b), -- Ahom Vowel Sign Aw ..Ahom Sign Killer (0x11c30, 0x11c36), -- (nil) .. (0x11c38, 0x11c3d), -- (nil) .. (0x11c3f, 0x11c3f), -- (nil) .. (0x11c92, 0x11ca7), -- (nil) .. (0x11caa, 0x11cb0), -- (nil) .. (0x11cb2, 0x11cb3), -- (nil) .. (0x11cb5, 0x11cb6), -- (nil) .. (0x16af0, 0x16af4), -- Bassa Vah Combining High..Bassa Vah Combining High (0x16b30, 0x16b36), -- Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta (0x16f8f, 0x16f92), -- Miao Tone Right ..Miao Tone Below (0x1bc9d, 0x1bc9e), -- Duployan Thick Letter Se..Duployan Double Mark (0x1d167, 0x1d169), -- Musical Symbol Combining..Musical Symbol Combining (0x1d17b, 0x1d182), -- Musical Symbol Combining..Musical Symbol Combining (0x1d185, 0x1d18b), -- Musical Symbol Combining..Musical Symbol Combining (0x1d1aa, 0x1d1ad), -- Musical Symbol Combining..Musical Symbol Combining (0x1d242, 0x1d244), -- Combining Greek Musical ..Combining Greek Musical (0x1da00, 0x1da36), -- Signwriting Head Rim ..Signwriting Air Sucking (0x1da3b, 0x1da6c), -- Signwriting Mouth Closed..Signwriting Excitement (0x1da75, 0x1da75), -- Signwriting Upper Body T..Signwriting Upper Body T (0x1da84, 0x1da84), -- Signwriting Location Hea..Signwriting Location Hea (0x1da9b, 0x1da9f), -- Signwriting Fill Modifie..Signwriting Fill Modifie (0x1daa1, 0x1daaf), -- Signwriting Rotation Mod..Signwriting Rotation Mod (0x1e000, 0x1e006), -- (nil) .. (0x1e008, 0x1e018), -- (nil) .. (0x1e01b, 0x1e021), -- (nil) .. (0x1e023, 0x1e024), -- (nil) .. (0x1e026, 0x1e02a), -- (nil) .. (0x1e8d0, 0x1e8d6), -- Mende Kikakui Combining ..Mende Kikakui Combining (0x1e944, 0x1e94a), -- (nil) .. (0xe0100, 0xe01ef) -- Variation Selector-17 ..Variation Selector-256 ] basicZero :: RangeSet Int basicZero = foldr insertRange empty [ (0, 0), (0x034f, 0x034f), (0x200b, 0x200f), (0x2028, 0x2029), (0x202a, 0x202e), (0x2060, 0x2063) ] ctrlChars :: RangeSet Int ctrlChars = foldr insertRange empty [ (1, 32), (0x07f, 0x09F) ] wcwidth :: Char -> Int wcwidth c | queryPoint v basicZero = 0 | queryPoint v ctrlChars = -1 | queryPoint v wIDEEASTASIAN = 2 | queryPoint v zEROWIDTH = 0 | otherwise = 1 where v = ord c
agentm/project-m36
src/lib/ProjectM36/WCWidth.hs
unlicense
28,798
0
8
7,304
4,150
2,863
1,287
415
1
module EKG.A169849Spec (main, spec) where import Test.Hspec import EKG.A169849 (a169849) main :: IO () main = hspec spec spec :: Spec spec = describe "A169849" $ it "correctly computes the first 20 elements" $ take 20 (map a169849 [1..]) `shouldBe` expectedValue where expectedValue = [9,3,6,2,4,8,10,5,15,12,14,7,21,18,16,20,22,11,33,24]
peterokagey/haskellOEIS
test/EKG/A169849Spec.hs
apache-2.0
353
0
10
59
160
95
65
10
1
import Prelude data DataInt = D Int deriving (Show, Eq, Ord) type ID = Int showID :: ID -> String showID = show newtype NewTypeInt = N Int deriving(Show, Ord, Eq)
EricYT/Haskell
src/chapter-6-5.hs
apache-2.0
201
0
6
69
71
40
31
8
1
module ForthEvaluator where import Prelude import qualified Data.Map as Map data NativeFunc = Drop | Plus | Apply | Eval | Define deriving (Show, Eq) data ProgramUnit = Word String | Symbol String | Native NativeFunc | ForthInt Int | ForthString String | ForthLambda [ProgramUnit] deriving (Show, Eq) type ProgramStack = [ProgramUnit] type Dict = (Map.Map String ProgramUnit) data ProgramState = ProgramState { programStack :: ProgramStack, dataStack :: ProgramStack, dict :: Dict } deriving (Show, Eq) parse :: String -> Either String ProgramState parse = undefined evalNativeFunc :: NativeFunc -> ProgramState -> Either String ProgramState evalNativeFunc Drop (ProgramState {dataStack = []}) = Left "error, cannot drop from empty stack" evalNativeFunc Drop (p@(ProgramState {dataStack = (_:a)})) = Right $ p { dataStack = a } evalNativeFunc Plus p@(ProgramState { dataStack = ((ForthInt a):(ForthInt b):c)}) = Right $ p { dataStack = (ForthInt (a + b)):c } evalNativeFunc Plus a = Left $ "error, cannot add " ++ show a evalNativeFunc Eval p@ProgramState { programStack = prog, dataStack = ((ForthLambda l):datast) } = Right $ p { programStack = l ++ prog, dataStack = datast } evalNativeFunc Eval p = Left $ "error cannot eval non lambda: " ++ show p evalNativeFunc Define p@ProgramState { dataStack = ((Symbol symbolName):definition:rest), dict = oldDict } = let newDict = Map.insert symbolName definition oldDict in Right $ p {dataStack = rest, dict = newDict} evalNativeFunc Define p = Left "cannot define" evalNativeFunc a stack = undefined eval :: ProgramState -> Either String ProgramState eval program = if null . programStack $ program then Right program else evalOneStep program >>= eval getDefinition :: Dict -> String -> Either String ProgramUnit getDefinition dict key = case (Map.lookup key dict) of Just expr -> Right expr Nothing -> Left $ "Word " ++ key ++ " not defined" evalOneStep :: ProgramState -> Either String ProgramState evalOneStep p@ProgramState { programStack = [] } = Right p evalOneStep p@ProgramState { programStack = ((Native n):prog)} = evalNativeFunc n (p {programStack = prog}) evalOneStep p@ProgramState { programStack = ((Word word):prog) , dict = d } = getDefinition d word >>= \programUnit -> Right $ p { programStack = (programUnit:prog) } evalOneStep p@ProgramState { programStack = (a:prog), dataStack = d }= Right $ p { programStack = prog, dataStack = (a:d) } exampleProgramState = ProgramState [(ForthInt 5), (Symbol "y"), (Native Define), (Word "y")] [] (Map.fromList [("x", ForthInt 6 )])
niilohlin/ForthEvaluator
ForthEvaluator.hs
apache-2.0
2,628
0
15
486
963
527
436
37
2
module Delahaye.A337974Spec (main, spec) where import Test.Hspec import Delahaye.A337974 (a337974) main :: IO () main = hspec spec spec :: Spec spec = describe "A337974" $ it "correctly computes the first 20 elements" $ take 20 (map a337974 [1..]) `shouldBe` expectedValue where expectedValue = [1, 3, 9, 7, 21, 49, 12, 36, 84, 144, 22, 66, 154, 264, 484, 30, 90, 210, 360, 660]
peterokagey/haskellOEIS
test/Delahaye/A337974Spec.hs
apache-2.0
393
0
10
78
160
95
65
10
1
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-} {-| Utility functions. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 Ganeti.Utils ( debug , debugFn , debugXy , sepSplit , findFirst , stdDev , if' , select , applyIf , commaJoin , ensureQuoted , tryRead , readMaybe , formatTable , printTable , parseUnit , parseUnitAssumeBinary , plural , niceSort , niceSortKey , exitIfBad , exitErr , exitWhen , exitUnless , logWarningIfBad , rStripSpace , newUUID , isUUID , getCurrentTime , getCurrentTimeUSec , clockTimeToString , clockTimeToCTime , clockTimeToUSec , cTimeToClockTime , diffClockTimes , chompPrefix , warn , wrap , trim , defaultHead , exitIfEmpty , splitEithers , recombineEithers , resolveAddr , monadicThe , setOwnerAndGroupFromNames , setOwnerWGroupR , formatOrdinal , tryAndLogIOError , withDefaultOnIOError , lockFile , FStat , nullFStat , getFStat , getFStatSafe , needsReload , watchFile , watchFileBy , safeRenameFile , FilePermissions(..) , ensurePermissions , ordNub , isSubsequenceOf ) where import Control.Applicative import Control.Concurrent import Control.Exception (try, bracket) import Control.Monad import Control.Monad.Error import qualified Data.Attoparsec.ByteString as A import qualified Data.ByteString.UTF8 as UTF8 import Data.Char (toUpper, isAlphaNum, isDigit, isSpace) import qualified Data.Either as E import Data.Function (on) import Data.IORef import Data.List import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Data.Set as S import Foreign.C.Types (CTime(..)) import Numeric (showOct) import System.Directory (renameFile, createDirectoryIfMissing) import System.FilePath.Posix (takeDirectory) import System.INotify import System.Posix.Types import Debug.Trace import Network.Socket import Ganeti.BasicTypes import qualified Ganeti.ConstantUtils as ConstantUtils import Ganeti.Logging import Ganeti.Runtime import System.IO import System.Exit import System.Posix.Files import System.Posix.IO import System.Posix.User import System.Time (ClockTime(..), getClockTime, TimeDiff(..)) import qualified System.Time as STime -- * Debug functions -- | To be used only for debugging, breaks referential integrity. debug :: Show a => a -> a debug x = trace (show x) x -- | Displays a modified form of the second parameter before returning -- it. debugFn :: Show b => (a -> b) -> a -> a debugFn fn x = debug (fn x) `seq` x -- | Show the first parameter before returning the second one. debugXy :: Show a => a -> b -> b debugXy = seq . debug -- * Miscellaneous -- | Apply the function if condition holds, otherwise use default value. applyIf :: Bool -> (a -> a) -> a -> a applyIf b f x = if b then f x else x -- | Comma-join a string list. commaJoin :: [String] -> String commaJoin = intercalate "," -- | Split a list on a separator and return a list of lists. sepSplit :: Eq a => a -> [a] -> [[a]] sepSplit sep s | null s = [] | null xs = [x] | null ys = [x,[]] | otherwise = x:sepSplit sep ys where (x, xs) = break (== sep) s ys = drop 1 xs -- | Finds the first unused element in a set starting from a given base. findFirst :: (Ord a, Enum a) => a -> S.Set a -> a findFirst base xs = case S.splitMember base xs of (_, False, _) -> base (_, True, ys) -> fromMaybe (succ base) $ (fmap fst . find (uncurry (<)) . zip [succ base..] . S.toAscList $ ys) `mplus` fmap (succ . fst) (S.maxView ys) -- | Simple pluralize helper plural :: Int -> String -> String -> String plural 1 s _ = s plural _ _ p = p -- | Ensure a value is quoted if needed. ensureQuoted :: String -> String ensureQuoted v = if not (all (\c -> isAlphaNum c || c == '.') v) then '\'':v ++ "'" else v -- * Mathematical functions -- Simple and slow statistical functions, please replace with better -- versions -- | Standard deviation function. stdDev :: [Double] -> Double stdDev lst = -- first, calculate the list length and sum lst in a single step, -- for performance reasons let (ll', sx) = foldl' (\(rl, rs) e -> let rl' = rl + 1 rs' = rs + e in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst ll = fromIntegral ll'::Double mv = sx / ll av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst in sqrt (av / ll) -- stddev -- * Logical functions -- Avoid syntactic sugar and enhance readability. These functions are proposed -- by some for inclusion in the Prelude, and at the moment they are present -- (with various definitions) in the utility-ht package. Some rationale and -- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else> -- | \"if\" as a function, rather than as syntactic sugar. if' :: Bool -- ^ condition -> a -- ^ \"then\" result -> a -- ^ \"else\" result -> a -- ^ \"then\" or "else" result depending on the condition if' True x _ = x if' _ _ y = y -- * Parsing utility functions -- | Parse results from readsPrec. parseChoices :: Monad m => String -> String -> [(a, String)] -> m a parseChoices _ _ [(v, "")] = return v parseChoices name s [(_, e)] = fail $ name ++ ": leftover characters when parsing '" ++ s ++ "': '" ++ e ++ "'" parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'" -- | Safe 'read' function returning data encapsulated in a Result. tryRead :: (Monad m, Read a) => String -> String -> m a tryRead name s = parseChoices name s $ reads s -- | Parse a string using the 'Read' instance. -- Succeeds if there is exactly one valid result. -- -- /Backport from Text.Read introduced in base-4.6.0.0/ readMaybe :: Read a => String -> Maybe a readMaybe s = case reads s of [(a, "")] -> Just a _ -> Nothing -- | Format a table of strings to maintain consistent length. formatTable :: [[String]] -> [Bool] -> [[String]] formatTable vals numpos = let vtrans = transpose vals -- transpose, so that we work on rows -- rather than columns mlens = map (maximum . map length) vtrans expnd = map (\(flds, isnum, ml) -> map (\val -> let delta = ml - length val filler = replicate delta ' ' in if delta > 0 then if isnum then filler ++ val else val ++ filler else val ) flds ) (zip3 vtrans numpos mlens) in transpose expnd -- | Constructs a printable table from given header and rows printTable :: String -> [String] -> [[String]] -> [Bool] -> String printTable lp header rows isnum = unlines . map ((++) lp . (:) ' ' . unwords) $ formatTable (header:rows) isnum -- | Converts a unit (e.g. m or GB) into a scaling factor. parseUnitValue :: (Monad m) => Bool -> String -> m Rational parseUnitValue noDecimal unit -- binary conversions first | null unit = return 1 | unit == "m" || upper == "MIB" = return 1 | unit == "g" || upper == "GIB" = return kbBinary | unit == "t" || upper == "TIB" = return $ kbBinary * kbBinary -- SI conversions | unit == "M" || upper == "MB" = return mbFactor | unit == "G" || upper == "GB" = return $ mbFactor * kbDecimal | unit == "T" || upper == "TB" = return $ mbFactor * kbDecimal * kbDecimal | otherwise = fail $ "Unknown unit '" ++ unit ++ "'" where upper = map toUpper unit kbBinary = 1024 :: Rational kbDecimal = if noDecimal then kbBinary else 1000 decToBin = kbDecimal / kbBinary -- factor for 1K conversion mbFactor = decToBin * decToBin -- twice the factor for just 1K -- | Tries to extract number and scale from the given string. -- -- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is -- specified, it defaults to MiB. Return value is always an integral -- value in MiB; if the first argument is True, all kilos are binary. parseUnitEx :: (Monad m, Integral a, Read a) => Bool -> String -> m a parseUnitEx noDecimal str = -- TODO: enhance this by splitting the unit parsing code out and -- accepting floating-point numbers case (reads str::[(Int, String)]) of [(v, suffix)] -> let unit = dropWhile (== ' ') suffix in do scaling <- parseUnitValue noDecimal unit return $ truncate (fromIntegral v * scaling) _ -> fail $ "Can't parse string '" ++ str ++ "'" -- | Tries to extract number and scale from the given string. -- -- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is -- specified, it defaults to MiB. Return value is always an integral -- value in MiB. parseUnit :: (Monad m, Integral a, Read a) => String -> m a parseUnit = parseUnitEx False -- | Tries to extract a number and scale from a given string, taking -- all kilos to be binary. parseUnitAssumeBinary :: (Monad m, Integral a, Read a) => String -> m a parseUnitAssumeBinary = parseUnitEx True -- | Unwraps a 'Result', exiting the program if it is a 'Bad' value, -- otherwise returning the actual contained value. exitIfBad :: String -> Result a -> IO a exitIfBad msg (Bad s) = exitErr (msg ++ ": " ++ s) exitIfBad _ (Ok v) = return v -- | Exits immediately with an error message. exitErr :: String -> IO a exitErr errmsg = do hPutStrLn stderr $ "Error: " ++ errmsg exitWith (ExitFailure 1) -- | Exits with an error message if the given boolean condition if true. exitWhen :: Bool -> String -> IO () exitWhen True msg = exitErr msg exitWhen False _ = return () -- | Exits with an error message /unless/ the given boolean condition -- if true, the opposite of 'exitWhen'. exitUnless :: Bool -> String -> IO () exitUnless cond = exitWhen (not cond) -- | Unwraps a 'Result', logging a warning message and then returning a default -- value if it is a 'Bad' value, otherwise returning the actual contained value. logWarningIfBad :: String -> a -> Result a -> IO a logWarningIfBad msg defVal (Bad s) = do logWarning $ msg ++ ": " ++ s return defVal logWarningIfBad _ _ (Ok v) = return v -- | Try an IO interaction, log errors and unfold as a 'Result'. tryAndLogIOError :: IO a -> String -> (a -> Result b) -> IO (Result b) tryAndLogIOError io msg okfn = try io >>= either (\ e -> do let combinedmsg = msg ++ ": " ++ show (e :: IOError) logError combinedmsg return . Bad $ combinedmsg) (return . okfn) -- | Try an IO interaction and return a default value if the interaction -- throws an IOError. withDefaultOnIOError :: a -> IO a -> IO a withDefaultOnIOError a io = try io >>= either (\ (_ :: IOError) -> return a) return -- | Print a warning, but do not exit. warn :: String -> IO () warn = hPutStrLn stderr . (++) "Warning: " -- | Helper for 'niceSort'. Computes the key element for a given string. extractKey :: [Either Integer String] -- ^ Current (partial) key, reversed -> String -- ^ Remaining string -> ([Either Integer String], String) extractKey ek [] = (reverse ek, []) extractKey ek xs@(x:_) = let (span_fn, conv_fn) = if isDigit x then (isDigit, Left . read) else (not . isDigit, Right) (k, rest) = span span_fn xs in extractKey (conv_fn k:ek) rest {-| Sort a list of strings based on digit and non-digit groupings. Given a list of names @['a1', 'a10', 'a11', 'a2']@ this function will sort the list in the logical order @['a1', 'a2', 'a10', 'a11']@. The sort algorithm breaks each name in groups of either only-digits or no-digits, and sorts based on each group. Internally, this is not implemented via regexes (like the Python version), but via actual splitting of the string in sequences of either digits or everything else, and converting the digit sequences in /Left Integer/ and the non-digit ones in /Right String/, at which point sorting becomes trivial due to the built-in 'Either' ordering; we only need one extra step of dropping the key at the end. -} niceSort :: [String] -> [String] niceSort = niceSortKey id -- | Key-version of 'niceSort'. We use 'sortBy' and @compare `on` fst@ -- since we don't want to add an ordering constraint on the /a/ type, -- hence the need to only compare the first element of the /(key, a)/ -- tuple. niceSortKey :: (a -> String) -> [a] -> [a] niceSortKey keyfn = map snd . sortBy (compare `on` fst) . map (\s -> (fst . extractKey [] $ keyfn s, s)) -- | Strip space characthers (including newline). As this is -- expensive, should only be run on small strings. rStripSpace :: String -> String rStripSpace = reverse . dropWhile isSpace . reverse -- | Returns a random UUID. -- This is a Linux-specific method as it uses the /proc filesystem. newUUID :: IO String newUUID = do contents <- readFile ConstantUtils.randomUuidFile return $! rStripSpace $ take 128 contents -- | Parser that doesn't fail on a valid UUIDs (same as -- "Ganeti.Constants.uuidRegex"). uuidCheckParser :: A.Parser () uuidCheckParser = do -- Not using Attoparsec.Char8 because "all attempts to use characters -- above code point U+00FF will give wrong answers" and we don't -- want such things to be accepted as UUIDs. let lowerHex = A.satisfy (\c -> (48 <= c && c <= 57) || -- 0-9 (97 <= c && c <= 102)) -- a-f hx n = A.count n lowerHex d = A.word8 45 -- '-' void $ hx 8 >> d >> hx 4 >> d >> hx 4 >> d >> hx 4 >> d >> hx 12 -- | Checks if the string is a valid UUID as in "Ganeti.Constants.uuidRegex". isUUID :: String -> Bool isUUID = isRight . A.parseOnly (uuidCheckParser <* A.endOfInput) . UTF8.fromString -- | Returns the current time as an 'Integer' representing the number -- of seconds from the Unix epoch. getCurrentTime :: IO Integer getCurrentTime = do TOD ctime _ <- getClockTime return ctime -- | Returns the current time as an 'Integer' representing the number -- of microseconds from the Unix epoch (hence the need for 'Integer'). getCurrentTimeUSec :: IO Integer getCurrentTimeUSec = liftM clockTimeToUSec getClockTime -- | Convert a ClockTime into a (seconds-only) timestamp. clockTimeToString :: ClockTime -> String clockTimeToString (TOD t _) = show t -- | Convert a ClockTime into a (seconds-only) 'EpochTime' (AKA @time_t@). clockTimeToCTime :: ClockTime -> EpochTime clockTimeToCTime (TOD secs _) = fromInteger secs -- | Convert a ClockTime the number of microseconds since the epoch. clockTimeToUSec :: ClockTime -> Integer clockTimeToUSec (TOD ctime pico) = -- pico: 10^-12, micro: 10^-6, so we have to shift seconds left and -- picoseconds right ctime * 1000000 + pico `div` 1000000 -- | Convert a ClockTime into a (seconds-only) 'EpochTime' (AKA @time_t@). cTimeToClockTime :: EpochTime -> ClockTime cTimeToClockTime (CTime timet) = TOD (toInteger timet) 0 -- | A version of `diffClockTimes` that works around ghc bug #2519. diffClockTimes :: ClockTime -> ClockTime -> TimeDiff diffClockTimes t1 t2 = let delta = STime.diffClockTimes t1 t2 secondInPicoseconds = 1000000000000 in if tdPicosec delta < 0 then delta { tdSec = tdSec delta - 1 , tdPicosec = tdPicosec delta + secondInPicoseconds } else delta {-| Strip a prefix from a string, allowing the last character of the prefix (which is assumed to be a separator) to be absent from the string if the string terminates there. \>>> chompPrefix \"foo:bar:\" \"a:b:c\" Nothing \>>> chompPrefix \"foo:bar:\" \"foo:bar:baz\" Just \"baz\" \>>> chompPrefix \"foo:bar:\" \"foo:bar:\" Just \"\" \>>> chompPrefix \"foo:bar:\" \"foo:bar\" Just \"\" \>>> chompPrefix \"foo:bar:\" \"foo:barbaz\" Nothing -} chompPrefix :: String -> String -> Maybe String chompPrefix pfx str = if pfx `isPrefixOf` str || str == init pfx then Just $ drop (length pfx) str else Nothing -- | Breaks a string in lines with length \<= maxWidth. -- -- NOTE: The split is OK if: -- -- * It doesn't break a word, i.e. the next line begins with space -- (@isSpace . head $ rest@) or the current line ends with space -- (@null revExtra@); -- -- * It breaks a very big word that doesn't fit anyway (@null revLine@). wrap :: Int -- ^ maxWidth -> String -- ^ string that needs wrapping -> [String] -- ^ string \"broken\" in lines wrap maxWidth = filter (not . null) . map trim . wrap0 where wrap0 :: String -> [String] wrap0 text | length text <= maxWidth = [text] | isSplitOK = line : wrap0 rest | otherwise = line' : wrap0 rest' where (line, rest) = splitAt maxWidth text (revExtra, revLine) = break isSpace . reverse $ line (line', rest') = (reverse revLine, reverse revExtra ++ rest) isSplitOK = null revLine || null revExtra || startsWithSpace rest startsWithSpace (x:_) = isSpace x startsWithSpace _ = False -- | Removes surrounding whitespace. Should only be used in small -- strings. trim :: String -> String trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace -- | A safer head version, with a default value. defaultHead :: a -> [a] -> a defaultHead def [] = def defaultHead _ (x:_) = x -- | A 'head' version in the I/O monad, for validating parameters -- without which we cannot continue. exitIfEmpty :: String -> [a] -> IO a exitIfEmpty _ (x:_) = return x exitIfEmpty s [] = exitErr s -- | Obtain the unique element of a list in an arbitrary monad. monadicThe :: (Eq a, Monad m) => String -> [a] -> m a monadicThe s [] = fail s monadicThe s (x:xs) | all (x ==) xs = return x | otherwise = fail s -- | Split an 'Either' list into two separate lists (containing the -- 'Left' and 'Right' elements, plus a \"trail\" list that allows -- recombination later. -- -- This is splitter; for recombination, look at 'recombineEithers'. -- The sum of \"left\" and \"right\" lists should be equal to the -- original list length, and the trail list should be the same length -- as well. The entries in the resulting lists are reversed in -- comparison with the original list. splitEithers :: [Either a b] -> ([a], [b], [Bool]) splitEithers = foldl' splitter ([], [], []) where splitter (l, r, t) e = case e of Left v -> (v:l, r, False:t) Right v -> (l, v:r, True:t) -- | Recombines two \"left\" and \"right\" lists using a \"trail\" -- list into a single 'Either' list. -- -- This is the counterpart to 'splitEithers'. It does the opposite -- transformation, and the output list will be the reverse of the -- input lists. Since 'splitEithers' also reverses the lists, calling -- these together will result in the original list. -- -- Mismatches in the structure of the lists (e.g. inconsistent -- lengths) are represented via 'Bad'; normally this function should -- not fail, if lists are passed as generated by 'splitEithers'. recombineEithers :: (Show a, Show b) => [a] -> [b] -> [Bool] -> Result [Either a b] recombineEithers lefts rights trail = foldM recombiner ([], lefts, rights) trail >>= checker where checker (eithers, [], []) = Ok eithers checker (_, lefts', rights') = Bad $ "Inconsistent results after recombination, l'=" ++ show lefts' ++ ", r'=" ++ show rights' recombiner (es, l:ls, rs) False = Ok (Left l:es, ls, rs) recombiner (es, ls, r:rs) True = Ok (Right r:es, ls, rs) recombiner (_, ls, rs) t = Bad $ "Inconsistent trail log: l=" ++ show ls ++ ", r=" ++ show rs ++ ",t=" ++ show t -- | Default hints for the resolver resolveAddrHints :: Maybe AddrInfo resolveAddrHints = Just defaultHints { addrFlags = [AI_NUMERICHOST, AI_NUMERICSERV] } -- | Resolves a numeric address. resolveAddr :: Int -> String -> IO (Result (Family, SockAddr)) resolveAddr port str = do resolved <- getAddrInfo resolveAddrHints (Just str) (Just (show port)) return $ case resolved of [] -> Bad "Invalid results from lookup?" best:_ -> Ok (addrFamily best, addrAddress best) -- | Set the owner and the group of a file (given as names, not numeric id). setOwnerAndGroupFromNames :: FilePath -> GanetiDaemon -> GanetiGroup -> IO () setOwnerAndGroupFromNames filename daemon dGroup = do -- TODO: it would be nice to rework this (or getEnts) so that runtimeEnts -- is read only once per daemon startup, and then cached for further usage. runtimeEnts <- runResultT getEnts ents <- exitIfBad "Can't find required user/groups" runtimeEnts -- note: we use directly ! as lookup failures shouldn't happen, due -- to the map construction let uid = reUserToUid ents M.! daemon let gid = reGroupToGid ents M.! dGroup setOwnerAndGroup filename uid gid -- | Resets permissions so that the owner can read/write and the group only -- read. All other permissions are cleared. setOwnerWGroupR :: FilePath -> IO () setOwnerWGroupR path = setFileMode path mode where mode = foldl unionFileModes nullFileMode [ownerReadMode, ownerWriteMode, groupReadMode] -- | Formats an integral number, appending a suffix. formatOrdinal :: (Integral a, Show a) => a -> String formatOrdinal num | num > 10 && num < 20 = suffix "th" | tens == 1 = suffix "st" | tens == 2 = suffix "nd" | tens == 3 = suffix "rd" | otherwise = suffix "th" where tens = num `mod` 10 suffix s = show num ++ s -- | Attempt, in a non-blocking way, to obtain a lock on a given file; report -- back success. -- Returns the file descriptor so that the lock can be released by closing lockFile :: FilePath -> IO (Result Fd) lockFile path = runResultT . liftIO $ do handle <- openFile path WriteMode fd <- handleToFd handle setLock fd (WriteLock, AbsoluteSeek, 0, 0) return fd -- | File stat identifier. type FStat = (EpochTime, FileID, FileOffset) -- | Null 'FStat' value. nullFStat :: FStat nullFStat = (-1, -1, -1) -- | Computes the file cache data from a FileStatus structure. buildFileStatus :: FileStatus -> FStat buildFileStatus ofs = let modt = modificationTime ofs inum = fileID ofs fsize = fileSize ofs in (modt, inum, fsize) -- | Wrapper over 'buildFileStatus'. This reads the data from the -- filesystem and then builds our cache structure. getFStat :: FilePath -> IO FStat getFStat p = liftM buildFileStatus (getFileStatus p) -- | Safe version of 'getFStat', that ignores IOErrors. getFStatSafe :: FilePath -> IO FStat getFStatSafe fpath = liftM (either (const nullFStat) id) ((try $ getFStat fpath) :: IO (Either IOError FStat)) -- | Check if the file needs reloading needsReload :: FStat -> FilePath -> IO (Maybe FStat) needsReload oldstat path = do newstat <- getFStat path return $ if newstat /= oldstat then Just newstat else Nothing -- | Until the given point in time (useconds since the epoch), wait -- for the output of a given method to change and return the new value; -- make use of the promise that the output only changes if the reference -- has a value different than the given one. watchFileEx :: (Eq b) => Integer -> b -> IORef b -> (a -> Bool) -> IO a -> IO a watchFileEx endtime base ref check read_fn = do current <- getCurrentTimeUSec if current > endtime then read_fn else do val <- readIORef ref if val /= base then do new <- read_fn if check new then return new else do logDebug "Observed change not relevant" threadDelay 100000 watchFileEx endtime val ref check read_fn else do threadDelay 100000 watchFileEx endtime base ref check read_fn -- | Within the given timeout (in seconds), wait for for the output -- of the given method to satisfy a given predicate and return the new value; -- make use of the promise that the method will only change its value, if -- the given file changes on disk. If the file does not exist on disk, return -- immediately. watchFileBy :: FilePath -> Int -> (a -> Bool) -> IO a -> IO a watchFileBy fpath timeout check read_fn = do current <- getCurrentTimeUSec let endtime = current + fromIntegral timeout * 1000000 fstat <- getFStatSafe fpath ref <- newIORef fstat bracket initINotify killINotify $ \inotify -> do let do_watch e = do logDebug $ "Notified of change in " ++ fpath ++ "; event: " ++ show e when (e == Ignored) (addWatch inotify [Modify, Delete] fpath do_watch >> return ()) fstat' <- getFStatSafe fpath writeIORef ref fstat' _ <- addWatch inotify [Modify, Delete] fpath do_watch newval <- read_fn if check newval then do logDebug $ "File " ++ fpath ++ " changed during setup of inotify" return newval else watchFileEx endtime fstat ref check read_fn -- | Within the given timeout (in seconds), wait for for the output -- of the given method to change and return the new value; make use of -- the promise that the method will only change its value, if -- the given file changes on disk. If the file does not exist on disk, return -- immediately. watchFile :: Eq a => FilePath -> Int -> a -> IO a -> IO a watchFile fpath timeout old = watchFileBy fpath timeout (/= old) -- | Type describing ownership and permissions of newly generated -- directories and files. All parameters are optional, with nothing -- meaning that the default value should be left untouched. data FilePermissions = FilePermissions { fpOwner :: Maybe String , fpGroup :: Maybe String , fpPermissions :: FileMode } -- | Ensure that a given file or directory has the permissions, and -- possibly ownerships, as required. ensurePermissions :: FilePath -> FilePermissions -> IO (Result ()) ensurePermissions fpath perms = do eitherFileStatus <- try $ getFileStatus fpath :: IO (Either IOError FileStatus) (flip $ either (return . Bad . show)) eitherFileStatus $ \fstat -> do ownertry <- case fpOwner perms of Nothing -> return $ Right () Just owner -> try $ do ownerid <- userID `liftM` getUserEntryForName owner unless (ownerid == fileOwner fstat) $ do logDebug $ "Changing owner of " ++ fpath ++ " to " ++ owner setOwnerAndGroup fpath ownerid (-1) grouptry <- case fpGroup perms of Nothing -> return $ Right () Just grp -> try $ do groupid <- groupID `liftM` getGroupEntryForName grp unless (groupid == fileGroup fstat) $ do logDebug $ "Changing group of " ++ fpath ++ " to " ++ grp setOwnerAndGroup fpath (-1) groupid let fp = fpPermissions perms permtry <- if fileMode fstat == fp then return $ Right () else try $ do logInfo $ "Changing permissions of " ++ fpath ++ " to " ++ showOct fp "" setFileMode fpath fp let errors = E.lefts ([ownertry, grouptry, permtry] :: [Either IOError ()]) if null errors then return $ Ok () else return . Bad $ show errors -- | Safely rename a file, creating the target directory, if needed. safeRenameFile :: FilePermissions -> FilePath -> FilePath -> IO (Result ()) safeRenameFile perms from to = do directtry <- try $ renameFile from to case (directtry :: Either IOError ()) of Right () -> return $ Ok () Left _ -> do result <- try $ do let dir = takeDirectory to createDirectoryIfMissing True dir _ <- ensurePermissions dir perms renameFile from to return $ either (Bad . show) Ok (result :: Either IOError ()) -- | Removes duplicates, preserving order. ordNub :: (Ord a) => [a] -> [a] ordNub = let go _ [] = [] go s (x:xs) = if x `S.member` s then go s xs else x : go (S.insert x s) xs in go S.empty -- | `isSubsequenceOf a b`: Checks if a is a subsequence of b. isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool isSubsequenceOf [] _ = True isSubsequenceOf _ [] = False isSubsequenceOf a@(x:a') (y:b) | x == y = isSubsequenceOf a' b | otherwise = isSubsequenceOf a b
dimara/ganeti
src/Ganeti/Utils.hs
bsd-2-clause
30,095
0
24
7,586
6,966
3,667
3,299
496
5
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QFontComboBox.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:15 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QFontComboBox ( QqFontComboBox(..) ,fontFilters ,setFontFilters ,setWritingSystem ,writingSystem ,qFontComboBox_delete ,qFontComboBox_deleteLater ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QFontDatabase import Qtc.Enums.Gui.QFontComboBox import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QFontComboBox ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QFontComboBox_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QFontComboBox_userMethod" qtc_QFontComboBox_userMethod :: Ptr (TQFontComboBox a) -> CInt -> IO () instance QuserMethod (QFontComboBoxSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QFontComboBox_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QFontComboBox ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QFontComboBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QFontComboBox_userMethodVariant" qtc_QFontComboBox_userMethodVariant :: Ptr (TQFontComboBox a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QFontComboBoxSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QFontComboBox_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqFontComboBox x1 where qFontComboBox :: x1 -> IO (QFontComboBox ()) instance QqFontComboBox (()) where qFontComboBox () = withQFontComboBoxResult $ qtc_QFontComboBox foreign import ccall "qtc_QFontComboBox" qtc_QFontComboBox :: IO (Ptr (TQFontComboBox ())) instance QqFontComboBox ((QWidget t1)) where qFontComboBox (x1) = withQFontComboBoxResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox1 cobj_x1 foreign import ccall "qtc_QFontComboBox1" qtc_QFontComboBox1 :: Ptr (TQWidget t1) -> IO (Ptr (TQFontComboBox ())) instance QcurrentFont (QFontComboBox a) (()) where currentFont x0 () = withQFontResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_currentFont cobj_x0 foreign import ccall "qtc_QFontComboBox_currentFont" qtc_QFontComboBox_currentFont :: Ptr (TQFontComboBox a) -> IO (Ptr (TQFont ())) instance Qevent (QFontComboBox ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_event_h" qtc_QFontComboBox_event_h :: Ptr (TQFontComboBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QFontComboBoxSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_event_h cobj_x0 cobj_x1 fontFilters :: QFontComboBox a -> (()) -> IO (FontFilters) fontFilters x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_fontFilters cobj_x0 foreign import ccall "qtc_QFontComboBox_fontFilters" qtc_QFontComboBox_fontFilters :: Ptr (TQFontComboBox a) -> IO CLong instance QsetCurrentFont (QFontComboBox a) ((QFont t1)) where setCurrentFont x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_setCurrentFont cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_setCurrentFont" qtc_QFontComboBox_setCurrentFont :: Ptr (TQFontComboBox a) -> Ptr (TQFont t1) -> IO () setFontFilters :: QFontComboBox a -> ((FontFilters)) -> IO () setFontFilters x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setFontFilters cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QFontComboBox_setFontFilters" qtc_QFontComboBox_setFontFilters :: Ptr (TQFontComboBox a) -> CLong -> IO () setWritingSystem :: QFontComboBox a -> ((WritingSystem)) -> IO () setWritingSystem x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setWritingSystem cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFontComboBox_setWritingSystem" qtc_QFontComboBox_setWritingSystem :: Ptr (TQFontComboBox a) -> CLong -> IO () instance QqsizeHint (QFontComboBox ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sizeHint_h cobj_x0 foreign import ccall "qtc_QFontComboBox_sizeHint_h" qtc_QFontComboBox_sizeHint_h :: Ptr (TQFontComboBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QFontComboBoxSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sizeHint_h cobj_x0 instance QsizeHint (QFontComboBox ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QFontComboBox_sizeHint_qth_h" qtc_QFontComboBox_sizeHint_qth_h :: Ptr (TQFontComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QFontComboBoxSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h writingSystem :: QFontComboBox a -> (()) -> IO (WritingSystem) writingSystem x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_writingSystem cobj_x0 foreign import ccall "qtc_QFontComboBox_writingSystem" qtc_QFontComboBox_writingSystem :: Ptr (TQFontComboBox a) -> IO CLong qFontComboBox_delete :: QFontComboBox a -> IO () qFontComboBox_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_delete cobj_x0 foreign import ccall "qtc_QFontComboBox_delete" qtc_QFontComboBox_delete :: Ptr (TQFontComboBox a) -> IO () qFontComboBox_deleteLater :: QFontComboBox a -> IO () qFontComboBox_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_deleteLater cobj_x0 foreign import ccall "qtc_QFontComboBox_deleteLater" qtc_QFontComboBox_deleteLater :: Ptr (TQFontComboBox a) -> IO () instance QchangeEvent (QFontComboBox ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_changeEvent_h" qtc_QFontComboBox_changeEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QFontComboBoxSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_changeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QFontComboBox ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_contextMenuEvent_h" qtc_QFontComboBox_contextMenuEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QFontComboBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_contextMenuEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QFontComboBox ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_focusInEvent_h" qtc_QFontComboBox_focusInEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QFontComboBoxSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QFontComboBox ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_focusOutEvent_h" qtc_QFontComboBox_focusOutEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QFontComboBoxSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_focusOutEvent_h cobj_x0 cobj_x1 instance QhideEvent (QFontComboBox ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_hideEvent_h" qtc_QFontComboBox_hideEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QFontComboBoxSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_hideEvent_h cobj_x0 cobj_x1 instance QhidePopup (QFontComboBox ()) (()) where hidePopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_hidePopup_h cobj_x0 foreign import ccall "qtc_QFontComboBox_hidePopup_h" qtc_QFontComboBox_hidePopup_h :: Ptr (TQFontComboBox a) -> IO () instance QhidePopup (QFontComboBoxSc a) (()) where hidePopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_hidePopup_h cobj_x0 instance QinitStyleOption (QFontComboBox ()) ((QStyleOptionComboBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_initStyleOption" qtc_QFontComboBox_initStyleOption :: Ptr (TQFontComboBox a) -> Ptr (TQStyleOptionComboBox t1) -> IO () instance QinitStyleOption (QFontComboBoxSc a) ((QStyleOptionComboBox t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_initStyleOption cobj_x0 cobj_x1 instance QinputMethodEvent (QFontComboBox ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_inputMethodEvent" qtc_QFontComboBox_inputMethodEvent :: Ptr (TQFontComboBox a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QFontComboBoxSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QFontComboBox ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFontComboBox_inputMethodQuery" qtc_QFontComboBox_inputMethodQuery :: Ptr (TQFontComboBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QFontComboBoxSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyPressEvent (QFontComboBox ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_keyPressEvent_h" qtc_QFontComboBox_keyPressEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QFontComboBoxSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QFontComboBox ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_keyReleaseEvent_h" qtc_QFontComboBox_keyReleaseEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QFontComboBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_keyReleaseEvent_h cobj_x0 cobj_x1 instance QqminimumSizeHint (QFontComboBox ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QFontComboBox_minimumSizeHint_h" qtc_QFontComboBox_minimumSizeHint_h :: Ptr (TQFontComboBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QFontComboBoxSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QFontComboBox ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QFontComboBox_minimumSizeHint_qth_h" qtc_QFontComboBox_minimumSizeHint_qth_h :: Ptr (TQFontComboBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QFontComboBoxSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmousePressEvent (QFontComboBox ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_mousePressEvent_h" qtc_QFontComboBox_mousePressEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QFontComboBoxSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QFontComboBox ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_mouseReleaseEvent_h" qtc_QFontComboBox_mouseReleaseEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QFontComboBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QpaintEvent (QFontComboBox ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_paintEvent_h" qtc_QFontComboBox_paintEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QFontComboBoxSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_paintEvent_h cobj_x0 cobj_x1 instance QresizeEvent (QFontComboBox ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_resizeEvent_h" qtc_QFontComboBox_resizeEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QFontComboBoxSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_resizeEvent_h cobj_x0 cobj_x1 instance QshowEvent (QFontComboBox ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_showEvent_h" qtc_QFontComboBox_showEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QFontComboBoxSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_showEvent_h cobj_x0 cobj_x1 instance QshowPopup (QFontComboBox ()) (()) where showPopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_showPopup_h cobj_x0 foreign import ccall "qtc_QFontComboBox_showPopup_h" qtc_QFontComboBox_showPopup_h :: Ptr (TQFontComboBox a) -> IO () instance QshowPopup (QFontComboBoxSc a) (()) where showPopup x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_showPopup_h cobj_x0 instance QwheelEvent (QFontComboBox ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_wheelEvent_h" qtc_QFontComboBox_wheelEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QFontComboBoxSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_wheelEvent_h cobj_x0 cobj_x1 instance QactionEvent (QFontComboBox ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_actionEvent_h" qtc_QFontComboBox_actionEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QFontComboBoxSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QFontComboBox ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_addAction" qtc_QFontComboBox_addAction :: Ptr (TQFontComboBox a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QFontComboBoxSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_addAction cobj_x0 cobj_x1 instance QcloseEvent (QFontComboBox ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_closeEvent_h" qtc_QFontComboBox_closeEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QFontComboBoxSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_closeEvent_h cobj_x0 cobj_x1 instance Qcreate (QFontComboBox ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_create cobj_x0 foreign import ccall "qtc_QFontComboBox_create" qtc_QFontComboBox_create :: Ptr (TQFontComboBox a) -> IO () instance Qcreate (QFontComboBoxSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_create cobj_x0 instance Qcreate (QFontComboBox ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_create1" qtc_QFontComboBox_create1 :: Ptr (TQFontComboBox a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QFontComboBoxSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create1 cobj_x0 cobj_x1 instance Qcreate (QFontComboBox ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QFontComboBox_create2" qtc_QFontComboBox_create2 :: Ptr (TQFontComboBox a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QFontComboBoxSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QFontComboBox ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QFontComboBox_create3" qtc_QFontComboBox_create3 :: Ptr (TQFontComboBox a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QFontComboBoxSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QFontComboBox ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy cobj_x0 foreign import ccall "qtc_QFontComboBox_destroy" qtc_QFontComboBox_destroy :: Ptr (TQFontComboBox a) -> IO () instance Qdestroy (QFontComboBoxSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy cobj_x0 instance Qdestroy (QFontComboBox ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_destroy1" qtc_QFontComboBox_destroy1 :: Ptr (TQFontComboBox a) -> CBool -> IO () instance Qdestroy (QFontComboBoxSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QFontComboBox ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QFontComboBox_destroy2" qtc_QFontComboBox_destroy2 :: Ptr (TQFontComboBox a) -> CBool -> CBool -> IO () instance Qdestroy (QFontComboBoxSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QFontComboBox ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_devType_h cobj_x0 foreign import ccall "qtc_QFontComboBox_devType_h" qtc_QFontComboBox_devType_h :: Ptr (TQFontComboBox a) -> IO CInt instance QdevType (QFontComboBoxSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_devType_h cobj_x0 instance QdragEnterEvent (QFontComboBox ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_dragEnterEvent_h" qtc_QFontComboBox_dragEnterEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QFontComboBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QFontComboBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_dragLeaveEvent_h" qtc_QFontComboBox_dragLeaveEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QFontComboBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QFontComboBox ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_dragMoveEvent_h" qtc_QFontComboBox_dragMoveEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QFontComboBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QFontComboBox ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_dropEvent_h" qtc_QFontComboBox_dropEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QFontComboBoxSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QFontComboBox ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_enabledChange" qtc_QFontComboBox_enabledChange :: Ptr (TQFontComboBox a) -> CBool -> IO () instance QenabledChange (QFontComboBoxSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QFontComboBox ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_enterEvent_h" qtc_QFontComboBox_enterEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QFontComboBoxSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QFontComboBox ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusNextChild cobj_x0 foreign import ccall "qtc_QFontComboBox_focusNextChild" qtc_QFontComboBox_focusNextChild :: Ptr (TQFontComboBox a) -> IO CBool instance QfocusNextChild (QFontComboBoxSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusNextChild cobj_x0 instance QfocusNextPrevChild (QFontComboBox ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_focusNextPrevChild" qtc_QFontComboBox_focusNextPrevChild :: Ptr (TQFontComboBox a) -> CBool -> IO CBool instance QfocusNextPrevChild (QFontComboBoxSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusPreviousChild (QFontComboBox ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusPreviousChild cobj_x0 foreign import ccall "qtc_QFontComboBox_focusPreviousChild" qtc_QFontComboBox_focusPreviousChild :: Ptr (TQFontComboBox a) -> IO CBool instance QfocusPreviousChild (QFontComboBoxSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_focusPreviousChild cobj_x0 instance QfontChange (QFontComboBox ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_fontChange" qtc_QFontComboBox_fontChange :: Ptr (TQFontComboBox a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QFontComboBoxSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QFontComboBox ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QFontComboBox_heightForWidth_h" qtc_QFontComboBox_heightForWidth_h :: Ptr (TQFontComboBox a) -> CInt -> IO CInt instance QheightForWidth (QFontComboBoxSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_heightForWidth_h cobj_x0 (toCInt x1) instance QlanguageChange (QFontComboBox ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_languageChange cobj_x0 foreign import ccall "qtc_QFontComboBox_languageChange" qtc_QFontComboBox_languageChange :: Ptr (TQFontComboBox a) -> IO () instance QlanguageChange (QFontComboBoxSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_languageChange cobj_x0 instance QleaveEvent (QFontComboBox ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_leaveEvent_h" qtc_QFontComboBox_leaveEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QFontComboBoxSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QFontComboBox ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFontComboBox_metric" qtc_QFontComboBox_metric :: Ptr (TQFontComboBox a) -> CLong -> IO CInt instance Qmetric (QFontComboBoxSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QmouseDoubleClickEvent (QFontComboBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_mouseDoubleClickEvent_h" qtc_QFontComboBox_mouseDoubleClickEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QFontComboBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QFontComboBox ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_mouseMoveEvent_h" qtc_QFontComboBox_mouseMoveEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QFontComboBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_mouseMoveEvent_h cobj_x0 cobj_x1 instance Qmove (QFontComboBox ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QFontComboBox_move1" qtc_QFontComboBox_move1 :: Ptr (TQFontComboBox a) -> CInt -> CInt -> IO () instance Qmove (QFontComboBoxSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QFontComboBox ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QFontComboBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QFontComboBox_move_qth" qtc_QFontComboBox_move_qth :: Ptr (TQFontComboBox a) -> CInt -> CInt -> IO () instance Qmove (QFontComboBoxSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QFontComboBox_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QFontComboBox ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_move cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_move" qtc_QFontComboBox_move :: Ptr (TQFontComboBox a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QFontComboBoxSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_move cobj_x0 cobj_x1 instance QmoveEvent (QFontComboBox ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_moveEvent_h" qtc_QFontComboBox_moveEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QFontComboBoxSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QFontComboBox ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_paintEngine_h cobj_x0 foreign import ccall "qtc_QFontComboBox_paintEngine_h" qtc_QFontComboBox_paintEngine_h :: Ptr (TQFontComboBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QFontComboBoxSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_paintEngine_h cobj_x0 instance QpaletteChange (QFontComboBox ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_paletteChange" qtc_QFontComboBox_paletteChange :: Ptr (TQFontComboBox a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QFontComboBoxSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QFontComboBox ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_repaint cobj_x0 foreign import ccall "qtc_QFontComboBox_repaint" qtc_QFontComboBox_repaint :: Ptr (TQFontComboBox a) -> IO () instance Qrepaint (QFontComboBoxSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_repaint cobj_x0 instance Qrepaint (QFontComboBox ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QFontComboBox_repaint2" qtc_QFontComboBox_repaint2 :: Ptr (TQFontComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QFontComboBoxSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QFontComboBox ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_repaint1" qtc_QFontComboBox_repaint1 :: Ptr (TQFontComboBox a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QFontComboBoxSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QFontComboBox ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_resetInputContext cobj_x0 foreign import ccall "qtc_QFontComboBox_resetInputContext" qtc_QFontComboBox_resetInputContext :: Ptr (TQFontComboBox a) -> IO () instance QresetInputContext (QFontComboBoxSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_resetInputContext cobj_x0 instance Qresize (QFontComboBox ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QFontComboBox_resize1" qtc_QFontComboBox_resize1 :: Ptr (TQFontComboBox a) -> CInt -> CInt -> IO () instance Qresize (QFontComboBoxSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QFontComboBox ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_resize" qtc_QFontComboBox_resize :: Ptr (TQFontComboBox a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QFontComboBoxSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_resize cobj_x0 cobj_x1 instance Qresize (QFontComboBox ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QFontComboBox_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QFontComboBox_resize_qth" qtc_QFontComboBox_resize_qth :: Ptr (TQFontComboBox a) -> CInt -> CInt -> IO () instance Qresize (QFontComboBoxSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QFontComboBox_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QsetGeometry (QFontComboBox ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QFontComboBox_setGeometry1" qtc_QFontComboBox_setGeometry1 :: Ptr (TQFontComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QFontComboBoxSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QFontComboBox ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_setGeometry" qtc_QFontComboBox_setGeometry :: Ptr (TQFontComboBox a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QFontComboBoxSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QFontComboBox ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QFontComboBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QFontComboBox_setGeometry_qth" qtc_QFontComboBox_setGeometry_qth :: Ptr (TQFontComboBox a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QFontComboBoxSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QFontComboBox_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QFontComboBox ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_setMouseTracking" qtc_QFontComboBox_setMouseTracking :: Ptr (TQFontComboBox a) -> CBool -> IO () instance QsetMouseTracking (QFontComboBoxSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QFontComboBox ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_setVisible_h" qtc_QFontComboBox_setVisible_h :: Ptr (TQFontComboBox a) -> CBool -> IO () instance QsetVisible (QFontComboBoxSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_setVisible_h cobj_x0 (toCBool x1) instance QtabletEvent (QFontComboBox ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_tabletEvent_h" qtc_QFontComboBox_tabletEvent_h :: Ptr (TQFontComboBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QFontComboBoxSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QFontComboBox ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_updateMicroFocus cobj_x0 foreign import ccall "qtc_QFontComboBox_updateMicroFocus" qtc_QFontComboBox_updateMicroFocus :: Ptr (TQFontComboBox a) -> IO () instance QupdateMicroFocus (QFontComboBoxSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_updateMicroFocus cobj_x0 instance QwindowActivationChange (QFontComboBox ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QFontComboBox_windowActivationChange" qtc_QFontComboBox_windowActivationChange :: Ptr (TQFontComboBox a) -> CBool -> IO () instance QwindowActivationChange (QFontComboBoxSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QFontComboBox ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_childEvent" qtc_QFontComboBox_childEvent :: Ptr (TQFontComboBox a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QFontComboBoxSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QFontComboBox ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QFontComboBox_connectNotify" qtc_QFontComboBox_connectNotify :: Ptr (TQFontComboBox a) -> CWString -> IO () instance QconnectNotify (QFontComboBoxSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QFontComboBox ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_customEvent" qtc_QFontComboBox_customEvent :: Ptr (TQFontComboBox a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QFontComboBoxSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QFontComboBox ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QFontComboBox_disconnectNotify" qtc_QFontComboBox_disconnectNotify :: Ptr (TQFontComboBox a) -> CWString -> IO () instance QdisconnectNotify (QFontComboBoxSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QFontComboBox ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFontComboBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QFontComboBox_eventFilter_h" qtc_QFontComboBox_eventFilter_h :: Ptr (TQFontComboBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QFontComboBoxSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFontComboBox_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QFontComboBox ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QFontComboBox_receivers" qtc_QFontComboBox_receivers :: Ptr (TQFontComboBox a) -> CWString -> IO CInt instance Qreceivers (QFontComboBoxSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFontComboBox_receivers cobj_x0 cstr_x1 instance Qsender (QFontComboBox ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sender cobj_x0 foreign import ccall "qtc_QFontComboBox_sender" qtc_QFontComboBox_sender :: Ptr (TQFontComboBox a) -> IO (Ptr (TQObject ())) instance Qsender (QFontComboBoxSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFontComboBox_sender cobj_x0 instance QtimerEvent (QFontComboBox ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFontComboBox_timerEvent" qtc_QFontComboBox_timerEvent :: Ptr (TQFontComboBox a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QFontComboBoxSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFontComboBox_timerEvent cobj_x0 cobj_x1
uduki/hsQt
Qtc/Gui/QFontComboBox.hs
bsd-2-clause
48,116
0
14
7,518
15,140
7,677
7,463
-1
-1
{-| Logical Volumes data collector. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 Ganeti.DataCollectors.Lv ( main , options , arguments , dcName , dcVersion , dcFormatVersion , dcCategory , dcKind , dcReport ) where import qualified Control.Exception as E import Control.Monad import Data.Attoparsec.Text.Lazy as A import Data.List import Data.Text.Lazy (pack, unpack) import Network.BSD (getHostName) import System.Process import qualified Text.JSON as J import qualified Ganeti.BasicTypes as BT import Ganeti.Common import Ganeti.Confd.ClientFunctions import Ganeti.DataCollectors.CLI import Ganeti.DataCollectors.Types import Ganeti.JSON import Ganeti.Objects import Ganeti.Storage.Lvm.LVParser import Ganeti.Storage.Lvm.Types import Ganeti.Utils -- | The default setting for the maximum amount of not parsed character to -- print in case of error. -- It is set to use most of the screen estate on a standard 80x25 terminal. -- TODO: add the possibility to set this with a command line parameter. defaultCharNum :: Int defaultCharNum = 80*20 -- | The name of this data collector. dcName :: String dcName = "lv" -- | The version of this data collector. dcVersion :: DCVersion dcVersion = DCVerBuiltin -- | The version number for the data format of this data collector. dcFormatVersion :: Int dcFormatVersion = 1 -- | The category of this data collector. dcCategory :: Maybe DCCategory dcCategory = Just DCStorage -- | The kind of this data collector. dcKind :: DCKind dcKind = DCKPerf -- | The data exported by the data collector, taken from the default location. dcReport :: IO DCReport dcReport = buildDCReport defaultOptions -- * Command line options options :: IO [OptType] options = return [ oInputFile , oConfdAddr , oConfdPort , oInstances ] -- | The list of arguments supported by the program. arguments :: [ArgCompletion] arguments = [ArgCompletion OptComplFile 0 (Just 0)] -- | Get information about logical volumes from file (if specified) or -- by actually running the command to get it from a live cluster. getLvInfo :: Maybe FilePath -> IO [LVInfo] getLvInfo inputFile = do let cmd = lvCommand params = lvParams fromLvs = ((E.try $ readProcess cmd params "") :: IO (Either IOError String)) >>= exitIfBad "running command" . either (BT.Bad . show) BT.Ok contents <- maybe fromLvs (\fn -> ((E.try $ readFile fn) :: IO (Either IOError String)) >>= exitIfBad "reading from file" . either (BT.Bad . show) BT.Ok) inputFile case A.parse lvParser $ pack contents of A.Fail unparsedText contexts errorMessage -> exitErr $ show (Prelude.take defaultCharNum $ unpack unparsedText) ++ "\n" ++ show contexts ++ "\n" ++ errorMessage A.Done _ lvinfoD -> return lvinfoD -- | Get the list of instances on the current node (both primary and secondary) -- either from a provided file or by querying Confd. getInstanceList :: Options -> IO ([Instance], [Instance]) getInstanceList opts = do let srvAddr = optConfdAddr opts srvPort = optConfdPort opts instFile = optInstances opts fromConfdUnchecked :: IO (BT.Result ([Instance], [Instance])) fromConfdUnchecked = getHostName >>= \n -> getInstances n srvAddr srvPort fromConfd :: IO (BT.Result ([Instance], [Instance])) fromConfd = liftM (either (BT.Bad . show) id) (E.try fromConfdUnchecked :: IO (Either IOError (BT.Result ([Instance], [Instance])))) fromFile :: FilePath -> IO (BT.Result ([Instance], [Instance])) fromFile inputFile = do contents <- ((E.try $ readFile inputFile) :: IO (Either IOError String)) >>= exitIfBad "reading from file" . either (BT.Bad . show) BT.Ok return . fromJResult "Not a list of instances" $ J.decode contents instances <- maybe fromConfd fromFile instFile exitIfBad "Unable to obtain the list of instances" instances -- | Adds the name of the instance to the information about one logical volume. addInstNameToOneLv :: [Instance] -> LVInfo -> LVInfo addInstNameToOneLv instances lvInfo = let vg_name = lviVgName lvInfo lv_name = lviName lvInfo instanceHasDisk = any (includesLogicalId vg_name lv_name) . instDisks rightInstance = find instanceHasDisk instances in case rightInstance of Nothing -> lvInfo Just i -> lvInfo { lviInstance = Just $ instName i } -- | Adds the name of the instance to the information about logical volumes. addInstNameToLv :: [Instance] -> [LVInfo] -> [LVInfo] addInstNameToLv instances = map (addInstNameToOneLv instances) -- | This function computes the JSON representation of the LV status. buildJsonReport :: Options -> IO J.JSValue buildJsonReport opts = do let inputFile = optInputFile opts lvInfo <- getLvInfo inputFile (prim, sec) <- getInstanceList opts return . J.showJSON $ addInstNameToLv (prim ++ sec) lvInfo -- | This function computes the DCReport for the logical volumes. buildDCReport :: Options -> IO DCReport buildDCReport opts = buildJsonReport opts >>= buildReport dcName dcVersion dcFormatVersion dcCategory dcKind -- | Main function. main :: Options -> [String] -> IO () main opts args = do unless (null args) . exitErr $ "This program takes exactly zero" ++ " arguments, got '" ++ unwords args ++ "'" report <- buildDCReport opts putStrLn $ J.encode report
apyrgio/snf-ganeti
src/Ganeti/DataCollectors/Lv.hs
bsd-2-clause
6,701
0
19
1,314
1,315
702
613
113
2
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, RankNTypes, CPP #-} module Graphics.UI.FormsCompose ( GtkForm(..), Widget (..), widgetNetwork, WidgetNetwork(..), widgetAddToBin, Layout (..), gtkWindow, gtkWidgetWindow, gtkMessageBox, gtkDialog, gtkLabel, gtkReactLabel, gtkSpinner, gtkButton, stackLayout, gtkButtonLayout, gtkButtonLayoutWithSecondary, Orientation (..), -- Alignment, HorizontalAlignment (HALeft, HACenter, HARight), VerticalAlignment (VABottom, VACenter, VATop), TextAlignment, ) where import qualified Graphics.UI.Gtk as Gtk import Control.Applicative (liftA2) import qualified Reactive.Banana as React import Control.Monad.IO.Class (liftIO) import Data.IORef (newIORef, writeIORef, readIORef) import Graphics.Rendering.Pango (EllipsizeMode(..)) data GtkForm a = GtkForm { -- | The IO action that displays the form and yields its result (blocking). gtkFormRunModal :: IO a } gtkWindow :: a -- ^ Default value to return if the window is closed using the close button. -> React.NetworkDescription (Gtk.Window, React.Event a) -- ^ The window to show. The result 'React.Event' closes the window. -> GtkForm a gtkWindow dft innerNetwork = GtkForm { gtkFormRunModal = do result <- newIORef dft Gtk.initGUI network <- React.compile $ do (window, theResult) <- innerNetwork evImplicitClose <- fmap (fmap (const dft)) (_windowCloseEvent window) liftIO $ do Gtk.widgetShowAll window -- For some reason, the default widget is not taken care of correctly by GTK. -- Reset it after the window is shown. Gtk.windowGetDefaultWidget window >>= Gtk.windowSetDefault window React.reactimate $ fmap (\x -> do writeIORef result x Gtk.mainQuit) (theResult `React.union` evImplicitClose) React.actuate network Gtk.mainGUI readIORef result } gtkWidgetWindow :: a -- ^ Default value to return if the window is closed using the close button. -> Widget (React.Event a) -- ^ Composite widget to show. The result 'React.Event' closes the window. -- Its value is used as the result value of the form. -> GtkForm a gtkWidgetWindow dft widget = gtkWindow dft $ do window <- liftIO $ do window <- Gtk.windowNew Gtk.windowSetPosition window Gtk.WinPosCenter Gtk.containerSetBorderWidth window 8 return window evExplicitClose <- widgetAddToBin window widget return (window, evExplicitClose) _windowCloseEvent :: Gtk.Window -> React.NetworkDescription (React.Event ()) _windowCloseEvent window = React.fromAddHandler add where add :: React.AddHandler () add handler = do cid <- window `Gtk.on` Gtk.deleteEvent $ Gtk.tryEvent (liftIO (handler ())) return (Gtk.signalDisconnect cid) -- | Turns a 'Widget' producing 'Discrete' values of type @a@ into a form returning either: -- -- * 'Just' the value of the widget at the time the /Ok/ button was pressed; -- -- * 'Nothing'; in case the /Cancel/ button was pressed, or the dialog was closed using the close button. gtkDialog :: Widget (React.Discrete a) -> GtkForm (Maybe a) gtkDialog widget = gtkWidgetWindow Nothing widget' where widget' = stackLayout Vertical `layoutApply` do result <- fmap (fmap Just) (widgetNetwork widget) widgetNetwork $ gtkLabel Gtk.JustifyLeft "" -- Line break widgetNetwork $ gtkButtonLayout Horizontal Gtk.ButtonboxEnd $ do cancel <- widgetNetwork $ fmap (fmap (const Nothing)) (gtkButtonStock Gtk.stockCancel False) ok <- widgetNetwork $ fmap (result React.<@) (gtkButtonStock Gtk.stockOk True) return $ React.union ok cancel -- | A form that displays a text message and an Ok button. gtkMessageBox :: Gtk.MessageType -> String -> GtkForm () gtkMessageBox msgType text = GtkForm { gtkFormRunModal = do Gtk.initGUI dlg <- Gtk.messageDialogNew Nothing [] msgType Gtk.ButtonsOk text -- Bah, does not appear on the taskbar. Gtk.dialogRun dlg return () } data Widget a = Widget { widgetRealize :: React.NetworkDescription (Gtk.Widget, a) } instance Functor Widget where fmap f (Widget r) = Widget (fmap (\(w, x) -> (w, f x)) r) widgetNetwork :: Widget a -> WidgetNetwork a widgetNetwork wdg = WidgetNetwork { widgetNetworkRealize = \realize -> do (widget, result) <- widgetRealize wdg liftIO (realize widget) return result } -- | Embeds the given widget in a Gtk bin. widgetAddToBin :: Gtk.BinClass c => c -> Widget a -> React.NetworkDescription a widgetAddToBin bin wdg = do (backing, result) <- widgetRealize wdg liftIO (Gtk.containerAdd bin backing) return result data Layout = Layout { layoutApply :: forall a. WidgetNetwork a -> Widget a } -- TODO: delete this data type data WidgetNetwork a = WidgetNetwork { -- | Constructs all controls, registers events, etc. -- The first argument is an action that adds Gtk widgets to a parent container. widgetNetworkRealize :: (Gtk.Widget -> IO ()) -> React.NetworkDescription a } -- TODO: Right-To-Left, Bottom-To-Top orientations data Orientation = Horizontal | Vertical type Alignment = (HorizontalAlignment, VerticalAlignment) -- | Note: when regional settings indicate right-to-left reading, 'HALeft' actually -- aligns to the right, and 'HARight' aligns to the left. data HorizontalAlignment = HALeft | HACenter | HARight | HAFill data VerticalAlignment = VATop | VACenter | VABottom | VAFill -- | The 'Layout' that stacks the network widgets in the passed 'Orientation'. stackLayout :: Orientation -> Layout stackLayout Horizontal = Layout { layoutApply = _layoutInBox $ Gtk.hBoxNew False 6 } stackLayout Vertical = Layout { layoutApply = _layoutInBox $ Gtk.vBoxNew False 6 } _layoutInBox :: Gtk.BoxClass b => IO b -> WidgetNetwork a -> Widget a _layoutInBox boxNew (WidgetNetwork innerWidgetPack) = Widget { widgetRealize = do box <- liftIO boxNew result <- innerWidgetPack (_addToBox Gtk.PackGrow box) return (Gtk.toWidget box, result) } -- | GTK's button box layout. Specially suited for, uh, buttons, although it can be used with any other widget as well. -- A 'gtkButtonLayout' differs from a 'stackLayout' in the following ways: -- -- * All widgets in a 'gtkButtonLayout' are allocated equal screen space. -- -- * Widgets are allocated a minimum size. gtkButtonLayout :: Orientation -> Gtk.ButtonBoxStyle -> WidgetNetwork a -> Widget a gtkButtonLayout orientation style prim = fmap fst $ gtkButtonLayoutWithSecondary orientation style prim (return ()) -- | Same as 'gtkButtonLayout', but 'gtkButtonLayoutWithSecondary' supports /primary/ and /secondary/ widget networks. -- The primary network is allocated the most prominent portion of the button layout, while the secondary network -- is alloted lesser valued space. Both the primary and the secondary widget networks can contain zero or more buttons -- or other widgets. gtkButtonLayoutWithSecondary :: Orientation -> Gtk.ButtonBoxStyle -> WidgetNetwork a -- ^ The primary widget network. -> WidgetNetwork b -- ^ The secondary widget network. -> Widget (a, b) gtkButtonLayoutWithSecondary Horizontal = _layoutInButtonBox Gtk.hButtonBoxNew gtkButtonLayoutWithSecondary Vertical = _layoutInButtonBox Gtk.vButtonBoxNew _layoutInButtonBox :: Gtk.ButtonBoxClass bb => IO bb -> Gtk.ButtonBoxStyle -> WidgetNetwork a -> WidgetNetwork b -> Widget (a, b) _layoutInButtonBox boxNew style (WidgetNetwork primPack) (WidgetNetwork secPack) = Widget { widgetRealize = do btnBox <- liftIO $ do btnBox <- boxNew Gtk.buttonBoxSetLayout btnBox style Gtk.boxSetSpacing btnBox 6 return btnBox result <- liftA2 (,) (primPack (_addToBox Gtk.PackGrow btnBox)) (secPack (_addToBoxSec btnBox)) return (Gtk.toWidget btnBox, result) } where _addToBoxSec btnBox child = do _addToBox Gtk.PackGrow btnBox child Gtk.buttonBoxSetChildSecondary btnBox child True _addToBox :: (Gtk.BoxClass b, Gtk.WidgetClass w) => Gtk.Packing -> b -> w -> IO () _addToBox packing box wdg = Gtk.boxPackStart box wdg packing 0 _alignmentNew :: Alignment -> IO Gtk.Alignment _alignmentNew (ha, va) = Gtk.alignmentNew (_xAlign ha) (_yAlign va) (_xScale ha) (_yScale va) _xAlign HALeft = 0 _xAlign HACenter = 0.5 _xAlign HARight = 1 _xAlign HAFill = 0 _xScale HALeft = 0 _xScale HACenter = 0 _xScale HARight = 0 _xScale HAFill = 1 _yAlign VATop = 0 _yAlign VACenter = 0.5 _yAlign VABottom = 1 _yAlign VAFill = 0 _yScale VATop = 0 _yScale VACenter = 0 _yScale VABottom = 0 _yScale VAFill = 1 type TextAlignment = Gtk.Justification -- | A widget containing non-interactive text. gtkLabel :: TextAlignment -> String -> Widget () gtkLabel textAlignment text = Widget { widgetRealize = liftIO $ do lbl <- Gtk.labelNew (Just text) Gtk.labelSetLineWrap lbl True Gtk.labelSetJustify lbl textAlignment return (Gtk.toWidget lbl, ()) } -- | A widget containing non-interactive text that reacts to changes. To prevent changes in GUI layout -- when the text changes, a maximum number of characters must be given. The label will request space -- for exactly that number of characters. If the input string contains more characters than can be -- displayed by the label, ellipsis (...) will be used. gtkReactLabel :: Int -- ^ The maximum number of characters. Note: In GTK, values less than 3 are treated as 3. -> TextAlignment -> React.Discrete String -- ^ Transient text message. -> Widget () gtkReactLabel maxChars textAlignment stream = Widget { widgetRealize = do lbl <- liftIO $ do lbl <- Gtk.labelNew (Just (React.initial stream)) Gtk.labelSetLineWrap lbl True Gtk.labelSetWidthChars lbl maxChars Gtk.set lbl [ Gtk.miscXalign Gtk.:= _xAlign (_horizontalAlignmentFromTextAlignment textAlignment) ] Gtk.labelSetJustify lbl textAlignment Gtk.labelSetEllipsize lbl EllipsizeEnd return lbl React.reactimate (fmap (Gtk.labelSetText lbl) (React.changes stream)) return (Gtk.toWidget lbl, ()) } _horizontalAlignmentFromTextAlignment :: TextAlignment -> HorizontalAlignment _horizontalAlignmentFromTextAlignment Gtk.JustifyLeft = HALeft _horizontalAlignmentFromTextAlignment Gtk.JustifyCenter = HACenter _horizontalAlignmentFromTextAlignment Gtk.JustifyRight = HARight _horizontalAlignmentFromTextAlignment Gtk.JustifyFill = HAFill -- | Spinner for integer values. gtkSpinner :: Int -- ^ Min value -> Int -- ^ Max value -> WidgetNetwork (React.Discrete Int) gtkSpinner min max = WidgetNetwork { widgetNetworkRealize = \realize -> do sb <- liftIO $ Gtk.spinButtonNewWithRange (fromIntegral min) (fromIntegral max) (fromIntegral 1) liftIO $ do realize (Gtk.toWidget sb) let valueChanges = React.fromAddHandler add add handler = do cid <- Gtk.afterValueSpinned sb (Gtk.spinButtonGetValueAsInt sb >>= handler) return (Gtk.signalDisconnect cid) fmap (React.stepperD min) valueChanges } -- | A button that fires an event when clicked. gtkButton :: String -- ^ Caption -> Bool -- ^ Whether this is the default button -> Widget (React.Event ()) gtkButton caption isDefault = _button isDefault (Gtk.buttonNewWithMnemonic caption) gtkButtonStock :: Gtk.StockId -> Bool -- ^ Whether this is the default button -> Widget (React.Event ()) gtkButtonStock stockId isDefault = _button isDefault (Gtk.buttonNewFromStock stockId) _button :: Bool -> IO Gtk.Button -> Widget (React.Event ()) _button isDefault constr = Widget { widgetRealize = do btn <- liftIO $ do btn <- constr Gtk.set btn [ Gtk.widgetCanDefault Gtk.:= isDefault ] return btn React.liftIOLater $ Gtk.set btn [ Gtk.widgetHasDefault Gtk.:= isDefault ] let add handler = do cid <- btn `Gtk.on` Gtk.buttonActivated $ handler () return (Gtk.signalDisconnect cid) result <- React.fromAddHandler add return (Gtk.toWidget btn, result) } instance Functor WidgetNetwork where fmap f xs = xs >>= return . f instance Monad WidgetNetwork where return x = WidgetNetwork { widgetNetworkRealize = const (return x) } widgetA >>= f = WidgetNetwork { widgetNetworkRealize = \box -> do out <- widgetNetworkRealize widgetA box widgetNetworkRealize (f out) box }
jvmap/Forms-compose
src/Graphics/UI/FormsCompose.hs
bsd-3-clause
13,348
0
20
3,392
3,073
1,555
1,518
-1
-1
module IptAdmin.AccessControl where import Control.Exception (catch, SomeException) import Control.Monad.Error import Control.Monad.State import Data.IORef import Data.Map import Data.Maybe import Happstack.Server.SimpleHTTP import IptAdmin.LoginPage as LoginPage (pageHandlers) import IptAdmin.Static as Static import IptAdmin.Types import IptAdmin.Utils import Prelude hiding (catch) import System.Posix.PAM as PAM -- import System.Posix.Syslog import System.Posix.User -- verify that client is allowed to access server authorize :: IORef Sessions -> IptAdminConfig -> IptAdmin Response -> IptAdminAuth Response authorize sessionsIORef config requestHandler = -- allow 'static' dir without authorisation (dir "static" Static.pageHandlers) `mplus` do clientIdE <- getDataFn $ lookCookieValue "sessionId" isAuthorised <- case clientIdE of Left _ -> -- liftIO $ syslog Notice $ "sessionId cookie get error: " ++ show e return False Right a -> do sessions <- liftIO $ readIORef sessionsIORef let session = Data.Map.lookup a sessions case session of Nothing -> -- liftIO $ syslog Notice $ "session was not found: " ++ a -- liftIO $ syslog Notice $ "sessions: " ++ show sessions return False Just _ -> return True if isAuthorised then -- Run IptAdmin monad with state mapServerPartT (addStateToStack (either undefined id clientIdE, sessionsIORef, config)) requestHandler else msum [ dir "login" $ LoginPage.pageHandlers (IptAdmin.AccessControl.authenticate $ cPamName config) sessionsIORef , redir "/login" ] where addStateToStack :: (Monad m) => MainState -> UnWebT (ErrorT String (StateT MainState m)) a -> UnWebT (ErrorT String m) a addStateToStack mainState statefulAction = mapErrorT (addStateToStack' mainState) statefulAction addStateToStack' :: (Monad m) => MainState -> StateT MainState m (Either String a) -> m (Either String a) addStateToStack' mainState statefulAction = evalStateT statefulAction mainState logout :: IptAdmin Response logout = do (sessionId, sessionsIORef, _) <- lift get _ <- liftIO $ atomicModifyIORef sessionsIORef (\ m -> (delete sessionId m, ())) expireCookie "sessionId" redir "/" {- Nothing - authentication is successful -- or Just error message -} authenticate :: String -> String -> String -> IO (Maybe String) authenticate pamName login password = do authRes <- PAM.authenticate pamName login password case authRes of Left a -> return $ Just $ "Pam message: " ++ pamCodeToMessage a Right () -> {- The user exists in system and password is correct - Next authentication stage: check if it's permitted to work with firewall for the user -} if login == "root" then return Nothing else do groupEntryMay <- catch (Just `fmap` getGroupEntryForName "iptadmin") ((\ _ -> return Nothing) :: (SomeException -> IO (Maybe GroupEntry))) case groupEntryMay of Nothing -> return $ Just "The user is not allowed to access iptables" Just groupEntry -> if login `elem` groupMembers groupEntry then return Nothing else return $ Just "The user is not allowed to access iptables"
etarasov/iptadmin
src/IptAdmin/AccessControl.hs
bsd-3-clause
3,968
0
20
1,401
796
409
387
68
5
module Generics.SOP.NP ( module Data.SOP.NP ) where import Data.SOP.NP
well-typed/generics-sop
generics-sop/src/Generics/SOP/NP.hs
bsd-3-clause
79
0
5
17
22
15
7
4
0
module Problem3 where import Data.Char import Data.List import Control.Applicative import System.IO -- Given two sequences a1, a2.. an (ai is the profit per click of the i-th ad) and b1, b2, . . . , bn (bi is -- the average number of clicks per day of the i-th slot), we need to partition them into n pairs (ai, bi)) -- such that the sum of their products is maximized. main :: IO () main = hSetBuffering stdin NoBuffering >>= \_ -> nextNum >>= \n -> nextNums n >>= \pc -> nextNums n >>= \ac -> let sortedPc = sortBy (flip compare) pc sortedAc = sortBy (flip compare) ac result = sum $ zipWith (*) sortedPc sortedAc in putStrLn $ show $ result nextNums n = sequence $ take n $ repeat nextNum nextNum :: (Integral a, Read a) => IO a nextNum = nextNum' "" nextNum' n = getChar >>= \char -> if(isDigit char || (null n && char == '-')) then nextNum' $ char:n else if(null n) then nextNum' n else pure $ read $ reverse n
msosnicki/algorithms
app/week3/Problem3.hs
bsd-3-clause
954
0
19
217
291
152
139
23
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.GeoJSON.Geometries -- Copyright : (C) 2016 Markus Barenhoff -- License : BSD-style (see the file LICENSE) -- Maintainer : Markus Barenhoff <[email protected]> -- Stability : provisional -- Portability : FlexibleInstances, MultiParamTypeClasses, TypeFamilies -- ---------------------------------------------------------------------------- module Data.GeoJSON.Geometries ( Point, _Point , MultiPoint, _MultiPoint, _MultiPoints , LineString, _LineString, _LineStringPoints , Polygon, _Polygon, _PolygonPoints , MultiLineString, _MultiLineString, _MultiLineStrings , MultiPolygon, _MultiPolygon, _MultiPolygons , GeometryObject, _GeometryObject , _PointObject, _MultiPointObject, _LineStringObject, _PolygonObject , _MultiLineStringObject, _MultiPolygonObject, _GeometryCollection ) where import Control.Applicative import Control.Lens.Iso import Control.Lens.Prism import Control.Lens.Review import Data.Aeson as Aeson import Data.Aeson.Types as Aeson import Data.GeoJSON.Classes import Data.GeoJSON.Intern import Data.GeoJSON.Position import Data.Map (Map) import qualified Data.Map as Map import Data.Text (Text) import Data.Vector (Vector) import qualified Data.Vector as V class HasGeometryObject g where toGeometryObject :: Geometry g a -> GeometryObject a fromGeometryObject :: GeometryObject a -> Maybe (Geometry g a) _GeometryObject :: HasGeometryObject g => Prism' (GeometryObject a) (Geometry g a) _GeometryObject = prism' toGeometryObject fromGeometryObject data Point instance BaseType a => IsGeometry Point (Position a) a where data Geometry Point a = Point (Position a) deriving (Eq, Show) type GeometryStructure Point a fv fc = PositionStructure fc a _Geometry = iso Point (\(Point a) -> a) geometryType = const _point _Point :: (PositionStructureClass fc a) => Prism' (GeometryStructure Point a fv fc) (Geometry Point a) _Point = _Position . _Geometry instance HasGeometryObject Point where toGeometryObject = GeometryPoint fromGeometryObject (GeometryPoint a) = pure a fromGeometryObject _ = empty instance Functor (Geometry Point) where fmap f (Point a) = Point $ fmap f a instance BaseType a => HasBoundingBox (Geometry Point a) a where boundingBox (Point a) = boundingBox a data MultiPoint instance BaseType a => IsGeometry MultiPoint (PositionVector a) a where data Geometry MultiPoint a = MultiPoint (PositionVector a) deriving (Eq, Show) type GeometryStructure MultiPoint a fv fc = PositionVectorStructure fv fc a _Geometry = iso MultiPoint (\(MultiPoint a) -> a) geometryType = const _multiPoint _MultiPoint :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiPoint a fv fc) (Geometry MultiPoint a) _MultiPoint = _PositionVector . _Geometry _MultiPoints :: (BaseType a, ListLike f (Geometry Point a)) => Iso' (f (Geometry Point a)) (Geometry MultiPoint a) _MultiPoints = iso (MultiPoint . foldMap (pure . review _Geometry)) (foldMap (pure . Point) . review _Geometry) instance HasGeometryObject MultiPoint where toGeometryObject = GeometryMultiPoint fromGeometryObject (GeometryMultiPoint a) = pure a fromGeometryObject _ = empty instance Functor (Geometry MultiPoint) where fmap f (MultiPoint a) = MultiPoint $ fmap (fmap f) a instance BaseType a => HasBoundingBox (Geometry MultiPoint a) a where boundingBox (MultiPoint a) = foldMap boundingBox a data LineString instance BaseType a => IsGeometry LineString (PositionVector a) a where data Geometry LineString a = LineString (PositionVector a) deriving (Eq, Show) type GeometryStructure LineString a fv fc = PositionVectorStructure fv fc a _Geometry = iso LineString (\(LineString a) -> a) geometryType = const _lineString _LineString :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure LineString a fv fc) (Geometry LineString a) _LineString = _PositionVector . _Geometry _LineStringPoints :: (BaseType a, ListLike f (Geometry Point a)) => Iso' (f (Geometry Point a)) (Geometry LineString a) _LineStringPoints = iso (LineString . foldMap (pure . review _Geometry)) (foldMap (pure . Point) . review _Geometry) instance HasGeometryObject LineString where toGeometryObject = GeometryLineString fromGeometryObject (GeometryLineString a) = pure a fromGeometryObject _ = empty instance Functor (Geometry LineString) where fmap f (LineString a) = LineString $ fmap (fmap f) a instance BaseType a => HasBoundingBox (Geometry LineString a) a where boundingBox (LineString a) = foldMap boundingBox a data Polygon instance BaseType a => IsGeometry Polygon (PositionVector a) a where data Geometry Polygon a = Polygon (PositionVector a) deriving (Eq, Show) type GeometryStructure Polygon a fv fc = PositionVectorStructure fv fc a _Geometry = iso Polygon (\(Polygon a) -> a) geometryType = const _polygon _Polygon :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure Polygon a fv fc) (Geometry Polygon a) _Polygon = _PositionVector . _Geometry -- TODO: check for closed ring _PolygonPoints :: (BaseType a, ListLike f (Geometry Point a)) => Prism' (f (Geometry Point a)) (Geometry Polygon a) _PolygonPoints = prism' (foldMap (pure . Point) . review _Geometry) (pure . Polygon . foldMap (pure . review _Geometry)) -- TODO check for closed ring instance HasGeometryObject Polygon where toGeometryObject = GeometryPolygon fromGeometryObject (GeometryPolygon a) = pure a fromGeometryObject _ = empty instance Functor (Geometry Polygon) where fmap f (Polygon a) = Polygon $ fmap (fmap f) a instance BaseType a => HasBoundingBox (Geometry Polygon a) a where boundingBox (Polygon a) = foldMap boundingBox a data MultiLineString instance BaseType a => IsGeometry MultiLineString (PositionVector2 a) a where data Geometry MultiLineString a = MultiLineString (PositionVector2 a) deriving (Eq, Show) type GeometryStructure MultiLineString a fv fc = PositionVector2Structure fv fc a _Geometry = iso MultiLineString (\(MultiLineString a) -> a) geometryType = const _multiLineString _MultiLineString :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiLineString a fv fc) (Geometry MultiLineString a) _MultiLineString = _PositionVector2 . _Geometry _MultiLineStrings :: (BaseType a, ListLike f (Geometry LineString a)) => Iso' (f (Geometry LineString a)) (Geometry MultiLineString a) _MultiLineStrings = iso (MultiLineString . foldMap (pure . review _Geometry)) (foldMap (pure . LineString) . review _Geometry) instance HasGeometryObject MultiLineString where toGeometryObject = GeometryMultiLineString fromGeometryObject (GeometryMultiLineString a) = pure a fromGeometryObject _ = empty instance Functor (Geometry MultiLineString) where fmap f (MultiLineString a) = MultiLineString $ fmap (fmap (fmap f)) a instance BaseType a => HasBoundingBox (Geometry MultiLineString a) a where boundingBox (MultiLineString a) = mconcat (foldMap boundingBox <$> V.toList a) data MultiPolygon instance BaseType a => IsGeometry MultiPolygon (PositionVector2 a) a where data Geometry MultiPolygon a = MultiPolygon (PositionVector2 a) deriving (Eq, Show) type GeometryStructure MultiPolygon a fv fc = PositionVector2Structure fv fc a _Geometry = iso MultiPolygon (\(MultiPolygon a) -> a) geometryType = const _multiPolygon _MultiPolygons :: (BaseType a, ListLike f (Geometry Polygon a)) => Iso' (f (Geometry Polygon a)) (Geometry MultiPolygon a) _MultiPolygons = iso (MultiPolygon . foldMap (pure . review _Geometry)) (foldMap (pure . Polygon) . review _Geometry) instance HasGeometryObject MultiPolygon where toGeometryObject = GeometryMultiPolygon fromGeometryObject (GeometryMultiPolygon a) = pure a fromGeometryObject _ = empty instance Functor (Geometry MultiPolygon) where fmap f (MultiPolygon a) = MultiPolygon $ fmap (fmap (fmap f)) a instance BaseType a => HasBoundingBox (Geometry MultiPolygon a) a where boundingBox (MultiPolygon a) = mconcat (foldMap boundingBox <$> V.toList a) _MultiPolygon :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiPolygon a fv fc) (Geometry MultiPolygon a) _MultiPolygon = _PositionVector2 . _Geometry -- TODO: check for closed ring -- -- Geometry Object -- data GeometryObject a = GeometryPoint (Geometry Point a) | GeometryMultiPoint (Geometry MultiPoint a) | GeometryLineString (Geometry LineString a) | GeometryPolygon (Geometry Polygon a) | GeometryMultiLineString (Geometry MultiLineString a) | GeometryMultiPolygon (Geometry MultiPolygon a) | GeometryCollection (Vector (GeometryObject a)) deriving (Eq, Show) instance Functor GeometryObject where fmap f (GeometryPoint a) = GeometryPoint $ fmap f a fmap f (GeometryMultiPoint a) = GeometryMultiPoint $ fmap f a fmap f (GeometryLineString a) = GeometryLineString $ fmap f a fmap f (GeometryPolygon a) = GeometryPolygon $ fmap f a fmap f (GeometryMultiLineString a) = GeometryMultiLineString $ fmap f a fmap f (GeometryMultiPolygon a) = GeometryMultiPolygon $ fmap f a fmap f (GeometryCollection a) = GeometryCollection $ fmap (fmap f) a instance BaseType a => HasBoundingBox (GeometryObject a) a where boundingBox (GeometryPoint a) = boundingBox a boundingBox (GeometryMultiPoint a) = boundingBox a boundingBox (GeometryLineString a) = boundingBox a boundingBox (GeometryPolygon a) = boundingBox a boundingBox (GeometryMultiLineString a) = boundingBox a boundingBox (GeometryMultiPolygon a) = boundingBox a boundingBox (GeometryCollection a) = foldMap boundingBox a _PointObject :: (PositionStructureClass fc a) => Prism' (GeometryStructure Point a fv fc) (GeometryObject a) _PointObject = _Point . iso GeometryPoint (\(GeometryPoint a) -> a) _MultiPointObject :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiPoint a fv fc) (GeometryObject a) _MultiPointObject = _MultiPoint . iso GeometryMultiPoint (\(GeometryMultiPoint a) -> a) _LineStringObject :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure LineString a fv fc) (GeometryObject a) _LineStringObject = _LineString . iso GeometryLineString (\(GeometryLineString a) -> a) _PolygonObject :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure Polygon a fv fc) (GeometryObject a) _PolygonObject = _Polygon . iso GeometryPolygon (\(GeometryPolygon a) -> a) _MultiLineStringObject :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiLineString a fv fc) (GeometryObject a) _MultiLineStringObject = _MultiLineString . iso GeometryMultiLineString (\(GeometryMultiLineString a) -> a) _MultiPolygonObject :: (VectorStructureClass fv fc a) => Prism' (GeometryStructure MultiPolygon a fv fc) (GeometryObject a) _MultiPolygonObject = _MultiPolygon . iso GeometryMultiPolygon (\(GeometryMultiPolygon a) -> a) _GeometryCollection :: (BaseType a, ListLike f (GeometryObject a)) => Prism' (GeometryObject a) (f (GeometryObject a)) _GeometryCollection = prism' f t where f = GeometryCollection . foldMap pure t (GeometryCollection a) = pure $ foldMap pure a t _ = empty instance BaseType a => ToJSON (GeometryObject a) where toJSON (GeometryPoint a) = toJSON a toJSON (GeometryMultiPoint a) = toJSON a toJSON (GeometryLineString a) = toJSON a toJSON (GeometryPolygon a) = toJSON a toJSON (GeometryMultiLineString a) = toJSON a toJSON (GeometryMultiPolygon a) = toJSON a toJSON (GeometryCollection a) = object [ typeField .= _geometryCollection , geometriesField .= toJSON a ] objectTable :: BaseType a => Map Text (Value -> Parser (GeometryObject a)) objectTable = Map.fromList [ ( _point, fmap GeometryPoint . parseJSON) , ( _multiPoint, fmap GeometryMultiPoint . parseJSON) , ( _lineString, fmap GeometryLineString . parseJSON) , ( _polygon, fmap GeometryPolygon . parseJSON) , ( _multiLineString, fmap GeometryMultiLineString . parseJSON) , ( _multiPolygon, fmap GeometryMultiPolygon . parseJSON) , ( _geometryCollection, parseGeometryCollection) ] parseGeometryCollection :: (BaseType a) => Value -> Parser (GeometryObject a) parseGeometryCollection (Object a) = GeometryCollection <$> a .: geometriesField parseGeometryCollection _ = empty instance BaseType a => FromJSON (GeometryObject a) where parseJSON obj@(Object a) = do t <- (a .: typeField) :: Parser Text maybe empty (\f -> f obj) (Map.lookup t objectTable) parseJSON _ = empty
alios/geojson-types
src/Data/GeoJSON/Geometries.hs
bsd-3-clause
13,227
0
11
2,568
4,043
2,075
1,968
-1
-1
module ThreadLanguage where type Name = String ---------------------- --- Command syntax --- ---------------------- --- Top-level program is a collection of communicating subprocesses. data Prog = PL [Comm] data Exp = Plus Exp Exp | Var Name | Lit Int | GetPID data BoolExp = Equal Exp Exp | Leq Exp Exp | TrueExp | FalseExp data Comm = Assign Name Exp | Seq Comm Comm | If BoolExp Comm Comm | While BoolExp Comm | Skip | Print String Exp | Psem --- Semaphore test ("proberen") : P mutex | Vsem --- Semaphore release ("verlegen"): V mutex | Inc Name | Sleep | Fork Comm | Broadcast Name | Receive Name | Kill Exp instance Show Prog where show (PL []) = "" show (PL (p:[])) = show p show (PL (p:ps)) = show p ++ "\n||\n " ++ show (PL ps) instance Show Exp where show (Plus e1 e2) = show e1++"+"++show e2 show (Var n) = n show (Lit i) = show i show GetPID = "getpid" instance Show BoolExp where show (Equal e1 e2) = show e1 ++ "==" ++ show e2 show (Leq e1 e2) = show e1 ++ "<=" ++ show e2 show TrueExp = "true" show FalseExp = "false" instance Show Comm where show (Assign n e) = n ++ ":=" ++ show e show (Seq c1 c2) = " "++show c1 ++ " ;\n " ++ show c2 show (If b c1 c2) = "(if " ++ show b ++ " then " ++ show c1 ++ " else " ++ show c2 ++")" show (While b c) = "(while " ++ show b ++ " do " ++ show c ++ ")" show (Print msg e) = "print '" ++ msg ++ "' " ++ show e show Skip = "skip" show Psem = "P(mutex)" -- should generalize to multiple semaphores show Vsem = "V(mutex)" show (Inc x) = x ++ ":=" ++ x ++ "+1" show Sleep = "sleep" show (Fork c) = "fork(" ++ show c ++ ")" show (Broadcast name) = "broadcast(" ++ name ++ ")" show (Receive name) = "receive(" ++ name ++ ")" show (Kill e) = "kill(" ++ show e ++ ")"
palexand/interpreters
ResumptionMonad/ThreadLanguage.hs
bsd-3-clause
2,096
38
12
749
786
401
385
51
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Test.BulkAPI (spec) where import Data.Function ((&)) #if MIN_VERSION_base(4,11,0) import Data.Functor ((<&>)) #endif import Test.Common import Test.Import import qualified Data.HashMap.Strict as HM import qualified Data.Vector as V import qualified Lens.Micro.Aeson as LMA newtype BulkTest = BulkTest Text deriving (Eq, Show) instance ToJSON BulkTest where toJSON (BulkTest name') = object ["name" .= name'] instance FromJSON BulkTest where parseJSON = withObject "BulkTest" parse where parse o = do t <- o .: "name" BulkTest <$> parseJSON t data BulkScriptTest = BulkScriptTest { bstName :: Text , bstCounter :: Int } deriving (Eq, Show) instance ToJSON BulkScriptTest where toJSON (BulkScriptTest name' count) = object ["name" .= name', "counter" .= count] instance FromJSON BulkScriptTest where parseJSON = withObject "BulkScriptTest" $ \v -> BulkScriptTest <$> v.: "name" <*> v .: "counter" assertDocs :: (FromJSON a, Show a, Eq a) => [(DocId, a)] -> BH IO () assertDocs as = do let (ids, docs) = unzip as res <- ids & traverse (getDocument testIndex) <&> traverse (fmap getSource . eitherDecode . responseBody) liftIO $ res `shouldBe` Right (Just <$> docs) upsertDocs :: (ToJSON a, Show a, Eq a) => (Value -> UpsertPayload) -> [(DocId, a)] -> BH IO () upsertDocs f as = do let batch = as <&> (\(id_, doc) -> BulkUpsert testIndex id_ (f $ toJSON doc) []) & V.fromList bulk batch >> refreshIndex testIndex >> pure () spec :: Spec spec = describe "Bulk API" $ do it "upsert operations" $ withTestEnv $ do _ <- insertData -- Upserting in a to a fresh index should insert let toInsert = [(DocId "3", BulkTest "stringer"), (DocId "5", BulkTest "sobotka"), (DocId "7", BulkTest "snoop")] upsertDocs UpsertDoc toInsert assertDocs toInsert -- Upserting existing documents should update let toUpsert = [(DocId "3", BulkTest "bell"), (DocId "5", BulkTest "frank"), (DocId "7", BulkTest "snoop")] upsertDocs UpsertDoc toUpsert assertDocs toUpsert it "upsert with a script" $ withTestEnv $ do _ <- insertData -- first insert the batch let batch = [(DocId "3", BulkScriptTest "stringer" 0), (DocId "5", BulkScriptTest "sobotka" 3)] upsertDocs UpsertDoc batch -- then upsert with the script let script = Script { scriptLanguage = Just $ ScriptLanguage "painless" , scriptSource = ScriptInline "ctx._source.counter += params.count" , scriptParams = Just $ ScriptParams $ HM.fromList [("count", Number 2)] } upsertDocs (UpsertScript False script) batch assertDocs (batch <&> (\(i, v) -> (i, v { bstCounter = bstCounter v + 2 }))) it "script upsert without scripted_upsert" $ withTestEnv $ do _ <- insertData let batch = [(DocId "3", BulkScriptTest "stringer" 0), (DocId "5", BulkScriptTest "sobotka" 3)] let script = Script { scriptLanguage = Just $ ScriptLanguage "painless" , scriptSource = ScriptInline "ctx._source.counter += params.count" , scriptParams = Just $ ScriptParams $ HM.fromList [("count", Number 2)] } -- Without "script_upsert" flag new documents are simply inserted and are not handled by the script upsertDocs (UpsertScript False script) batch assertDocs batch it "script upsert with scripted_upsert -- will fail if a bug on elasticsearch is fix, delete patch line" $ withTestEnv $ do _ <- insertData let batch = [(DocId "3", BulkScriptTest "stringer" 0), (DocId "5", BulkScriptTest "sobotka" 3)] let script = Script { scriptLanguage = Just $ ScriptLanguage "painless" , scriptSource = ScriptInline "ctx._source.counter += params.count" , scriptParams = Just $ ScriptParams $ HM.fromList [("count", Number 2)] } -- Without "script_upsert" flag new documents are simply inserted and are not handled by the script upsertDocs (UpsertScript True script) batch -- if this test fails due to a bug in ES7: https://github.com/elastic/elasticsearch/issues/48670, delete next line when it is solved. let batch = [(DocId "3", BulkScriptTest "stringer" 2), (DocId "5", BulkScriptTest "sobotka" 3)] assertDocs (batch <&> (\(i, v) -> (i, v { bstCounter = bstCounter v + 2 }))) it "inserts all documents we request" $ withTestEnv $ do _ <- insertData let firstTest = BulkTest "blah" let secondTest = BulkTest "bloo" let thirdTest = BulkTest "graffle" let fourthTest = BulkTest "garabadoo" let fifthTest = BulkTest "serenity" let firstDoc = BulkIndex testIndex (DocId "2") (toJSON firstTest) let secondDoc = BulkCreate testIndex (DocId "3") (toJSON secondTest) let thirdDoc = BulkCreateEncoding testIndex (DocId "4") (toEncoding thirdTest) let fourthDoc = BulkIndexAuto testIndex (toJSON fourthTest) let fifthDoc = BulkIndexEncodingAuto testIndex (toEncoding fifthTest) let stream = V.fromList [firstDoc, secondDoc, thirdDoc, fourthDoc, fifthDoc] _ <- bulk stream -- liftIO $ pPrint bulkResp _ <- refreshIndex testIndex -- liftIO $ pPrint refreshResp fDoc <- getDocument testIndex (DocId "2") sDoc <- getDocument testIndex (DocId "3") tDoc <- getDocument testIndex (DocId "4") -- note that we cannot query for fourthDoc and fifthDoc since we -- do not know their autogenerated ids. let maybeFirst = eitherDecode $ responseBody fDoc :: Either String (EsResult BulkTest) let maybeSecond = eitherDecode $ responseBody sDoc :: Either String (EsResult BulkTest) let maybeThird = eitherDecode $ responseBody tDoc :: Either String (EsResult BulkTest) -- liftIO $ pPrint [maybeFirst, maybeSecond, maybeThird] liftIO $ do fmap getSource maybeFirst `shouldBe` Right (Just firstTest) fmap getSource maybeSecond `shouldBe` Right (Just secondTest) fmap getSource maybeThird `shouldBe` Right (Just thirdTest) -- Since we can't get the docs by doc id, we check for their existence in -- a match all query. let query = MatchAllQuery Nothing let search = mkSearch (Just query) Nothing resp <- searchByIndex testIndex search parsed <- parseEsResponse resp :: BH IO (Either EsError (SearchResult Value)) case parsed of Left e -> liftIO $ expectationFailure ("Expected a script-transformed result but got: " <> show e) (Right sr) -> do liftIO $ hitsTotal (searchHits sr) `shouldBe` HitsTotal 6 HTR_EQ let nameList :: [Text] nameList = hits (searchHits sr) ^.. traverse . to hitSource . _Just . LMA.key "name" . _String liftIO $ nameList `shouldBe` ["blah","bloo","graffle","garabadoo","serenity"]
bitemyapp/bloodhound
tests/Test/BulkAPI.hs
bsd-3-clause
7,434
0
26
2,132
2,046
1,029
1,017
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module TokenGenerator where import Types import Data.Bool import Data.Text (unpack, pack, Text) import Data.Aeson hiding ((.=)) import Data.Time (UTCTime, NominalDiffTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Control.Lens import Data.Time import Crypto.JWT --import Web.JWT (def, StringOrURI, stringOrURI, encodeSigned, secret, ClaimsMap, JWTClaimsSet(..), JSON, Algorithm(HS256)) makeClaim :: Int -> [(String, String)] -> FireJWT makeClaim iat d = FireJWT 0 iat d Nothing Nothing Nothing Nothing makeWholeClaim :: Int -> [(String, String)] -> Maybe Int -> Maybe Int -> Maybe Bool -> Maybe Bool -> FireJWT makeWholeClaim iat d nbf exp admin debug = FireJWT 0 iat d nbf exp admin debug --generate :: String -> ClaimsSet -> JSON --generate scrt claims = encodeSigned HS256 (secret $ pack scrt) claims maybeToBool :: Maybe Bool -> Bool maybeToBool (Just a) = a maybeToBool Nothing = False maybeToInt :: Maybe Int -> Int maybeToInt (Just a) = a maybeToInt Nothing = 0 --TODO: JWTClaimsSet and ClaimsMap constructors not in scope (solution needed or change approach) --claimsFromFireJWT (FireJWT v iat d nbf exp admin debug) -- = emptyClaimsSet -- & claimIat .~ (realToFrac ()) -- & claimNbf .~ (realToFrac $ maybeToInt nbf) -- & addClaim "v" (toJSON v) -- & addClaim "d" (toJSON d) -- & addClaim "admin" (Bool (maybeToBool admin)) -- & addClaim "debug" (Bool (maybeToBool debug)) --helper function from the hs-jose tests intDate :: String -> Maybe NumericDate intDate = fmap NumericDate . parseTimeM True defaultTimeLocale "%F %T" claimsFromScratch :: ClaimsSet claimsFromScratch = emptyClaimsSet & claimIss .~ Just (fromString "[email protected]") & claimSub .~ Just (fromString "[email protected]") & claimAud .~ Just (fromString "some audience") & claimIat .~ intDate "2011-03-22 18:43:00" & claimExp .~ intDate "2011-03-22 19:43:00" & addClaim "uid" (Just (fromString "user1")) & addClaim "http://example.com/is_root" (Bool True)
sphaso/firebase-haskell-client
src/TokenGenerator.hs
bsd-3-clause
2,133
2
18
412
446
240
206
34
1
{-# LANGUAGE ConstraintKinds #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <[email protected]> -- Stability : experimental -- Portability : portable -- -- Logging interface module. -- -- Logging uses "Control.Monad.Journal" (hence the 'MonadJournal' -- typeclass). However, this module exposes a few combinators that might -- help you a lot: -- -- - 'deb' is used to log debug messages ; -- - 'info' is used to log informational messages ; -- - 'warn' is used to log warnings ; -- - 'err' is used to log errors. -- -- You also have a pretty neat 'sinkLogs', which is a default 'sink' -- implementation for 'MonadJournal'. Of course, you can use you're own if -- you want to. -- -- If you intend to handle the logs yourself, you have to understand what -- logs look like. Logs gather three things: -- -- - a committer ('LogCommitter'), which is the entity responsible of the -- log ; -- - a type ('LogType'), which is the type of the log (debug, -- informational, warning and so on and so forth) ; -- - a 'String' message. -- -- Logs are gathered in a 'Traversable' queue ('LogQueue'). Feel free to -- traverse it and handle logs anyway you want then! ---------------------------------------------------------------------------- module Quaazar.Utils.Log ( -- * MonadLogger MonadLogger -- * Logs , Log(..) , LogQueue , LogType(..) , LogCommitter(..) -- * Logging functions , log_ , deb , info , warn , err , throwLog -- * Sinking , sinkLogs ) where import Control.Monad.Error.Class ( MonadError(..) ) import Control.Monad.Trans ( MonadIO ) import Control.Monad.Trans.Journal import Data.Foldable ( traverse_ ) import Data.Vector ( Vector, fromList ) -- |Monad used to log. type MonadLogger m = (MonadJournal LogQueue m) -- |A plain log with meta-information. data Log = Log LogType LogCommitter String deriving (Eq) -- FIXME: use DList instead -- |Logs queue. type LogQueue = Vector Log -- |Type of log. data LogType = DebLog -- ^ A debug/trace log | InfoLog -- ^ An informational log | WarningLog -- ^ A warning log | ErrorLog -- ^ An error log deriving (Eq) -- |Committer of a log. data LogCommitter = CoreLog -- Core committer | RendererLog -- Renderer committer | BackendLog String -- Specific backend committer | UserLog -- User committer deriving (Eq) instance Show Log where show (Log lt lc msg) = show lt ++ " [" ++ show lc ++ "] > " ++ msg instance Show LogType where show t = case t of DebLog -> "deb" InfoLog -> "inf" WarningLog -> "war" ErrorLog -> "err" instance Show LogCommitter where show c = case c of CoreLog -> "core" RendererLog -> "rndr" BackendLog impl -> take 4 $ impl ++ repeat ' ' UserLog -> "user" -- |Create a log. log_ :: (MonadLogger m) => LogType -> LogCommitter -> String -> m () log_ t c m = journal_ (Log t c m) -- |Create a debug log. deb :: (MonadLogger m) => LogCommitter -> String -> m () deb = log_ DebLog -- |Create an informational log. info :: (MonadLogger m) => LogCommitter -> String -> m () info = log_ InfoLog -- |Create a warning log. warn :: (MonadLogger m) => LogCommitter -> String -> m () warn = log_ WarningLog -- |Create an error log. err :: (MonadLogger m) => LogCommitter -> String -> m () err = log_ ErrorLog -- |Alternative way of outputting logs, through 'MonadError'. throwLog :: (MonadError Log m) => LogCommitter -> String -> m a throwLog lc msg = throwError (Log ErrorLog lc msg) journal_ :: (MonadLogger m) => Log -> m () journal_ = journal . fromList . discardNewlines discardNewlines :: Log -> [Log] discardNewlines (Log lt lc msg) = map (Log lt lc) (lines msg) sinkLogs :: (MonadLogger m,MonadIO m) => m () sinkLogs = sink (traverse_ print)
phaazon/quaazar
src/Quaazar/Utils/Log.hs
bsd-3-clause
3,969
0
11
873
790
454
336
-1
-1
{-# LANGUAGE MagicHash #-} module Doublee where import GHC.Exts f :: Double# -> Double f x = D# (x +## 1.324##)
dterei/Scraps
haskell/Doublee.hs
bsd-3-clause
115
0
7
24
37
21
16
5
1
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.TransformFeedback -- Copyright : (c) Sven Panne, Lars Corbijn 2011-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- ----------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.TransformFeedback ( -- * starting and ending beginTransformFeedback, endTransformFeedback, -- * TransformFeedbackBufferMode TransformFeedbackBufferMode(..), marshalTransformFeedbackBufferMode, unmarshalTransformFeedbackBufferMode, -- * Shader related transformFeedbackBufferMode, transformFeedbackVaryings, setTransformFeedbackVaryings, -- * limits maxTransformFeedbackSeparateAttribs, maxTransformFeedbackInterleavedComponents, maxTransformFeedbackSeparateComponents ) where import Foreign.Marshal.Array import Graphics.Rendering.OpenGL.GL.ByteString import Graphics.Rendering.OpenGL.GL.DataType import Graphics.Rendering.OpenGL.GL.PrimitiveMode import Graphics.Rendering.OpenGL.GL.PrimitiveModeInternal import Graphics.Rendering.OpenGL.GL.QueryUtils import Graphics.Rendering.OpenGL.GL.Shaders.Program import Graphics.Rendering.OpenGL.GL.Shaders.Variables import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- beginTransformFeedback :: PrimitiveMode -> IO () beginTransformFeedback = glBeginTransformFeedback . marshalPrimitiveMode endTransformFeedback :: IO () endTransformFeedback = glEndTransformFeedback -------------------------------------------------------------------------------- data TransformFeedbackBufferMode = InterleavedAttribs | SeperateAttribs deriving ( Eq, Ord, Show ) marshalTransformFeedbackBufferMode :: TransformFeedbackBufferMode -> GLenum marshalTransformFeedbackBufferMode x = case x of InterleavedAttribs -> gl_INTERLEAVED_ATTRIBS SeperateAttribs -> gl_SEPARATE_ATTRIBS unmarshalTransformFeedbackBufferMode :: GLenum -> TransformFeedbackBufferMode unmarshalTransformFeedbackBufferMode x | x == gl_INTERLEAVED_ATTRIBS = InterleavedAttribs | x == gl_SEPARATE_ATTRIBS = SeperateAttribs | otherwise = error $ "unmarshalTransformFeedbackBufferMode: illegal value " ++ show x -- limits -- | Max number of seprate atributes or varyings than can be captured -- in transformfeedback, initial value 4 maxTransformFeedbackSeparateAttribs :: GettableStateVar GLint maxTransformFeedbackSeparateAttribs = makeGettableStateVar $ getInteger1 fromIntegral GetMaxTransformFeedbackSeparateAttribs -- | Max number of components to write to a single buffer in -- interleaved mod, initial value 64 maxTransformFeedbackInterleavedComponents :: GettableStateVar GLint maxTransformFeedbackInterleavedComponents = makeGettableStateVar $ getInteger1 fromIntegral GetMaxTransformFeedbackInterleavedComponents -- | Max number of components per attribute or varying in seperate mode -- initial value 4 maxTransformFeedbackSeparateComponents :: GettableStateVar GLint maxTransformFeedbackSeparateComponents = makeGettableStateVar $ getInteger1 fromIntegral GetMaxTransformFeedbackSeparateComponents -------------------------------------------------------------------------------- -- | Set all the transform feedbacks varyings for this program -- it overwrites any previous call to this function setTransformFeedbackVaryings :: Program -> [String] -> TransformFeedbackBufferMode -> IO () setTransformFeedbackVaryings (Program program) sts tfbm = do ptSts <- mapM (\x -> withGLstring x return) sts stsPtrs <- newArray ptSts glTransformFeedbackVaryings program (fromIntegral . length $ sts) stsPtrs (marshalTransformFeedbackBufferMode tfbm) -- | Get the currently used transformFeedbackBufferMode transformFeedbackBufferMode :: Program -> GettableStateVar TransformFeedbackBufferMode transformFeedbackBufferMode = programVar1 (unmarshalTransformFeedbackBufferMode . fromIntegral) TransformFeedbackBufferMode -- | The number of varyings that are currently recorded when in -- transform feedback mode numTransformFeedbackVaryings :: Program -> GettableStateVar GLuint numTransformFeedbackVaryings = programVar1 fromIntegral TransformFeedbackVaryings -- | The maximum length of a varying's name for transform feedback mode transformFeedbackVaryingMaxLength :: Program -> GettableStateVar GLsizei transformFeedbackVaryingMaxLength = programVar1 fromIntegral TransformFeedbackVaryingMaxLength -- | The name, datatype and size of the transform feedback varyings. transformFeedbackVaryings :: Program -> GettableStateVar [(GLint, DataType, String)] transformFeedbackVaryings = activeVars numTransformFeedbackVaryings transformFeedbackVaryingMaxLength glGetTransformFeedbackVarying unmarshalDataType
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/TransformFeedback.hs
bsd-3-clause
5,003
0
11
593
599
346
253
71
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} module Database.Relational.Schema.MySQLInfo.KeyColumnUsage where import Data.Int (Int16) import Database.Record.TH (derivingShow) import Database.Relational.Query.TH (defineTableTypesAndRecordDefault) import Database.Relational.Schema.MySQLInfo.Config (config) $(defineTableTypesAndRecordDefault config "INFORMATION_SCHEMA" "key_column_usage" [ ("constraint_name" , [t| String |]) , ("table_schema" , [t| String |]) , ("table_name" , [t| String |]) , ("column_name" , [t| String |]) , ("ordinal_position" , [t| Int16 |]) ] [derivingShow])
krdlab/haskell-relational-record-driver-mysql
src/Database/Relational/Schema/MySQLInfo/KeyColumnUsage.hs
bsd-3-clause
698
0
9
150
143
99
44
15
0
{-# LANGUAGE StandaloneDeriving, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <[email protected]> -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Quaazar.Utils.Scoped ( -- * Scoped monad MonadScoped(..) -- * IO scoped monad transformer , IOScopedT , runIOScopedT -- * Re-exported , module Control.Monad.Base ) where import Control.Monad.Base ( MonadBase(..) ) import Control.Monad.Error.Class ( MonadError ) import Control.Monad.Journal ( MonadJournal ) import Control.Monad.Reader ( MonadReader ) import Control.Monad.State ( MonadState(..) ) import Control.Monad.Trans import Control.Monad.Trans.Either ( EitherT ) import Control.Monad.Trans.Journal ( JournalT ) import Control.Monad.Trans.Reader ( ReaderT ) import Control.Monad.Trans.State ( StateT, modify, runStateT ) import Control.Monad.Trans.Writer ( WriterT ) import Control.Monad.Writer ( MonadWriter ) class (MonadBase b m) => MonadScoped b m where scoped :: b () -> m () instance (MonadScoped b m,Monoid w) => MonadScoped b (JournalT w m) where scoped = lift . scoped instance (MonadScoped b m) => MonadScoped b (EitherT e m) where scoped = lift . scoped instance (MonadScoped b m) => MonadScoped b (ReaderT r m) where scoped = lift . scoped instance (MonadScoped b m) => MonadScoped b (StateT r m) where scoped = lift . scoped instance (MonadScoped b m,Monoid w) => MonadScoped b (WriterT w m) where scoped = lift . scoped newtype IOScopedT m a = IOScopedT { unIOScopedT :: StateT (IO ()) m a } deriving (Applicative,Functor,Monad,MonadTrans) deriving instance (MonadBase b m) => MonadBase b (IOScopedT m) deriving instance (MonadIO m) => MonadIO (IOScopedT m) deriving instance (MonadJournal w m,Monoid w) => MonadJournal w (IOScopedT m) deriving instance (MonadError e m) => MonadError e (IOScopedT m) deriving instance (MonadReader r m) => MonadReader r (IOScopedT m) instance (MonadState s m) => MonadState s (IOScopedT m) where get = lift get put = lift . put state = lift . state deriving instance (MonadWriter w m) => MonadWriter w (IOScopedT m) instance (MonadBase IO m) => MonadScoped IO (IOScopedT m) where scoped a = IOScopedT $ modify (>>a) runIOScopedT :: (MonadIO m) => IOScopedT m a -> m a runIOScopedT scope = do (a,cleanup) <- runStateT (unIOScopedT scope) (return ()) liftIO cleanup return a
phaazon/quaazar
src/Quaazar/Utils/Scoped.hs
bsd-3-clause
2,604
0
11
435
823
459
364
-1
-1
{-# LANGUAGE CPP #-} ------------------------------------------------------------------------------- -- -- | Command-line parser -- -- This is an abstract command-line parser used by both StaticFlags and -- DynFlags. -- -- (c) The University of Glasgow 2005 -- ------------------------------------------------------------------------------- module CmdLineParser ( processArgs, OptKind(..), CmdLineP(..), getCmdLineState, putCmdLineState, Flag(..), errorsToGhcException, EwM, addErr, addWarn, getArg, getCurLoc, liftEwM, deprecate ) where #include "HsVersions.h" import Util import Outputable import Panic import Bag import SrcLoc import Data.Function import Data.List import Control.Monad (liftM, ap) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif -------------------------------------------------------- -- The Flag and OptKind types -------------------------------------------------------- data Flag m = Flag { flagName :: String, -- Flag, without the leading "-" flagOptKind :: OptKind m -- What to do if we see it } data OptKind m -- Suppose the flag is -f = NoArg (EwM m ()) -- -f all by itself | HasArg (String -> EwM m ()) -- -farg or -f arg | SepArg (String -> EwM m ()) -- -f arg | Prefix (String -> EwM m ()) -- -farg | OptPrefix (String -> EwM m ()) -- -f or -farg (i.e. the arg is optional) | OptIntSuffix (Maybe Int -> EwM m ()) -- -f or -f=n; pass n to fn | IntSuffix (Int -> EwM m ()) -- -f or -f=n; pass n to fn | FloatSuffix (Float -> EwM m ()) -- -f or -f=n; pass n to fn | PassFlag (String -> EwM m ()) -- -f; pass "-f" fn | AnySuffix (String -> EwM m ()) -- -f or -farg; pass entire "-farg" to fn | PrefixPred (String -> Bool) (String -> EwM m ()) | AnySuffixPred (String -> Bool) (String -> EwM m ()) | VersionSuffix (Int -> Int -> EwM m ()) -- -f or -f=maj.min; pass major and minor version to fn -------------------------------------------------------- -- The EwM monad -------------------------------------------------------- type Err = Located String type Warn = Located String type Errs = Bag Err type Warns = Bag Warn -- EwM ("errors and warnings monad") is a monad -- transformer for m that adds an (err, warn) state newtype EwM m a = EwM { unEwM :: Located String -- Current parse arg -> Errs -> Warns -> m (Errs, Warns, a) } instance Monad m => Functor (EwM m) where fmap = liftM instance Monad m => Applicative (EwM m) where pure = return (<*>) = ap instance Monad m => Monad (EwM m) where (EwM f) >>= k = EwM (\l e w -> do (e', w', r) <- f l e w unEwM (k r) l e' w') return v = EwM (\_ e w -> return (e, w, v)) setArg :: Monad m => Located String -> EwM m () -> EwM m () setArg l (EwM f) = EwM (\_ es ws -> f l es ws) addErr :: Monad m => String -> EwM m () addErr e = EwM (\(L loc _) es ws -> return (es `snocBag` L loc e, ws, ())) addWarn :: Monad m => String -> EwM m () addWarn msg = EwM (\(L loc _) es ws -> return (es, ws `snocBag` L loc msg, ())) deprecate :: Monad m => String -> EwM m () deprecate s = do arg <- getArg addWarn (arg ++ " is deprecated: " ++ s) getArg :: Monad m => EwM m String getArg = EwM (\(L _ arg) es ws -> return (es, ws, arg)) getCurLoc :: Monad m => EwM m SrcSpan getCurLoc = EwM (\(L loc _) es ws -> return (es, ws, loc)) liftEwM :: Monad m => m a -> EwM m a liftEwM action = EwM (\_ es ws -> do { r <- action; return (es, ws, r) }) -------------------------------------------------------- -- A state monad for use in the command-line parser -------------------------------------------------------- -- (CmdLineP s) typically instantiates the 'm' in (EwM m) and (OptKind m) newtype CmdLineP s a = CmdLineP { runCmdLine :: s -> (a, s) } instance Functor (CmdLineP s) where fmap = liftM instance Applicative (CmdLineP s) where pure = return (<*>) = ap instance Monad (CmdLineP s) where m >>= k = CmdLineP $ \s -> let (a, s') = runCmdLine m s in runCmdLine (k a) s' return a = CmdLineP $ \s -> (a, s) getCmdLineState :: CmdLineP s s getCmdLineState = CmdLineP $ \s -> (s,s) putCmdLineState :: s -> CmdLineP s () putCmdLineState s = CmdLineP $ \_ -> ((),s) -------------------------------------------------------- -- Processing arguments -------------------------------------------------------- processArgs :: Monad m => [Flag m] -- cmdline parser spec -> [Located String] -- args -> m ( [Located String], -- spare args [Located String], -- errors [Located String] ) -- warnings processArgs spec args = do (errs, warns, spare) <- unEwM action (panic "processArgs: no arg yet") emptyBag emptyBag return (spare, bagToList errs, bagToList warns) where action = process args [] -- process :: [Located String] -> [Located String] -> EwM m [Located String] process [] spare = return (reverse spare) process (locArg@(L _ ('-' : arg)) : args) spare = case findArg spec arg of Just (rest, opt_kind) -> case processOneArg opt_kind rest arg args of Left err -> let b = process args spare in (setArg locArg $ addErr err) >> b Right (action,rest) -> let b = process rest spare in (setArg locArg $ action) >> b Nothing -> process args (locArg : spare) process (arg : args) spare = process args (arg : spare) processOneArg :: OptKind m -> String -> String -> [Located String] -> Either String (EwM m (), [Located String]) processOneArg opt_kind rest arg args = let dash_arg = '-' : arg rest_no_eq = dropEq rest in case opt_kind of NoArg a -> ASSERT(null rest) Right (a, args) HasArg f | notNull rest_no_eq -> Right (f rest_no_eq, args) | otherwise -> case args of [] -> missingArgErr dash_arg (L _ arg1:args1) -> Right (f arg1, args1) -- See Trac #9776 SepArg f -> case args of [] -> missingArgErr dash_arg (L _ arg1:args1) -> Right (f arg1, args1) Prefix f | notNull rest_no_eq -> Right (f rest_no_eq, args) | otherwise -> unknownFlagErr dash_arg PrefixPred _ f | notNull rest_no_eq -> Right (f rest_no_eq, args) | otherwise -> unknownFlagErr dash_arg PassFlag f | notNull rest -> unknownFlagErr dash_arg | otherwise -> Right (f dash_arg, args) OptIntSuffix f | null rest -> Right (f Nothing, args) | Just n <- parseInt rest_no_eq -> Right (f (Just n), args) | otherwise -> Left ("malformed integer argument in " ++ dash_arg) IntSuffix f | Just n <- parseInt rest_no_eq -> Right (f n, args) | otherwise -> Left ("malformed integer argument in " ++ dash_arg) FloatSuffix f | Just n <- parseFloat rest_no_eq -> Right (f n, args) | otherwise -> Left ("malformed float argument in " ++ dash_arg) OptPrefix f -> Right (f rest_no_eq, args) AnySuffix f -> Right (f dash_arg, args) AnySuffixPred _ f -> Right (f dash_arg, args) VersionSuffix f | [maj_s, min_s] <- split '.' rest_no_eq, Just maj <- parseInt maj_s, Just min <- parseInt min_s -> Right (f maj min, args) | [maj_s] <- split '.' rest_no_eq, Just maj <- parseInt maj_s -> Right (f maj 0, args) | null rest_no_eq -> Right (f 1 0, args) | otherwise -> Left ("malformed version argument in " ++ dash_arg) findArg :: [Flag m] -> String -> Maybe (String, OptKind m) findArg spec arg = case sortBy (compare `on` (length . fst)) -- prefer longest matching flag [ (removeSpaces rest, optKind) | flag <- spec, let optKind = flagOptKind flag, Just rest <- [stripPrefix (flagName flag) arg], arg_ok optKind rest arg ] of [] -> Nothing (one:_) -> Just one arg_ok :: OptKind t -> [Char] -> String -> Bool arg_ok (NoArg _) rest _ = null rest arg_ok (HasArg _) _ _ = True arg_ok (SepArg _) rest _ = null rest arg_ok (Prefix _) rest _ = notNull rest arg_ok (PrefixPred p _) rest _ = notNull rest && p (dropEq rest) arg_ok (OptIntSuffix _) _ _ = True arg_ok (IntSuffix _) _ _ = True arg_ok (FloatSuffix _) _ _ = True arg_ok (OptPrefix _) _ _ = True arg_ok (PassFlag _) rest _ = null rest arg_ok (AnySuffix _) _ _ = True arg_ok (AnySuffixPred p _) _ arg = p arg arg_ok (VersionSuffix _) _ _ = True -- | Parse an Int -- -- Looks for "433" or "=342", with no trailing gubbins -- * n or =n => Just n -- * gibberish => Nothing parseInt :: String -> Maybe Int parseInt s = case reads s of ((n,""):_) -> Just n _ -> Nothing parseFloat :: String -> Maybe Float parseFloat s = case reads s of ((n,""):_) -> Just n _ -> Nothing -- | Discards a leading equals sign dropEq :: String -> String dropEq ('=' : s) = s dropEq s = s unknownFlagErr :: String -> Either String a unknownFlagErr f = Left ("unrecognised flag: " ++ f) missingArgErr :: String -> Either String a missingArgErr f = Left ("missing argument for flag: " ++ f) -------------------------------------------------------- -- Utils -------------------------------------------------------- errorsToGhcException :: [Located String] -> GhcException errorsToGhcException errs = UsageError $ intercalate "\n" [ showUserSpan True l ++ ": " ++ e | L l e <- errs ]
jstolarek/ghc
compiler/main/CmdLineParser.hs
bsd-3-clause
10,480
0
18
3,399
3,344
1,722
1,622
185
15
{-# LANGUAGE FlexibleContexts #-} module Data.Array.Unboxed.YC ( Unboxed(..) , modifySTUArray ) where import Control.Monad.ST (ST) import Data.Array.IArray (IArray) import Data.Array.MArray (newArray, readArray, writeArray, unsafeFreeze) import Data.Array.ST (STUArray) import Data.Array.Unboxed (UArray) import Data.Ix (Ix) class IArray UArray a => Unboxed a where newSTUArray :: Ix i => (i, i) -> a -> ST s (STUArray s i a) newSTUArrayDef :: Ix i => (i, i) -> ST s (STUArray s i a) readSTUArray :: Ix i => STUArray s i a -> i -> ST s a writeSTUArray :: Ix i => STUArray s i a -> i -> a -> ST s () unsafeFreezeSTU :: Ix i => STUArray s i a -> ST s (UArray i a) instance Unboxed Float where newSTUArray = newArray newSTUArrayDef = (`newArray` 0) readSTUArray = readArray writeSTUArray = writeArray unsafeFreezeSTU = unsafeFreeze instance Unboxed Double where newSTUArray = newArray newSTUArrayDef = (`newArray` 0) readSTUArray = readArray writeSTUArray = writeArray unsafeFreezeSTU = unsafeFreeze modifySTUArray :: (Unboxed a, Ix i) => STUArray s i a -> i -> (a -> a) -> ST s () modifySTUArray arr idx func = readSTUArray arr idx >>= writeSTUArray arr idx . func
yairchu/hmm
src/Data/Array/Unboxed/YC.hs
bsd-3-clause
1,208
0
12
238
458
249
209
31
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} module Unit.CommitQueue ( tests ) where import Control.Concurrent (forkIO, threadDelay) import qualified Control.Logging as Logging import Control.Monad.Free import Control.Monad.IO.Class import FeedGipeda.GitShell (SHA) import FeedGipeda.Master.CommitQueue (CommitQueue) import qualified FeedGipeda.Master.CommitQueue as CommitQueue import FeedGipeda.Repo (Repo (..)) import qualified FeedGipeda.Repo as Repo import System.Timeout (timeout) import Test.Tasty import Test.Tasty.HUnit data QueueF a = Update Repo [SHA] (Bool -> a) | TryDequeue (Maybe (Repo, SHA) -> a) | forall r. EmbedIO (IO r) (r -> a) instance Functor QueueF where fmap f (Update repo commits g) = Update repo commits (f . g) fmap f (TryDequeue g) = TryDequeue (f . g) fmap f (EmbedIO action g) = EmbedIO action (f . g) type Queue = Free QueueF instance MonadIO (Free QueueF) where liftIO action = liftF (EmbedIO action id) update :: Repo -> [SHA] -> Queue Bool update repo commits = liftF (Update repo commits id) tryDequeue :: Queue (Maybe (Repo, SHA)) tryDequeue = liftF (TryDequeue id) timeoutDelay :: Int timeoutDelay = 1000 -- 1 ms runQueue :: CommitQueue -> Queue r -> IO r runQueue queue = iterM run where run (Update repo commits k) = CommitQueue.updateRepoBacklog queue repo commits >>= k run (TryDequeue k) = timeout timeoutDelay (CommitQueue.dequeue queue) >>= k run (EmbedIO action k) = action >>= k runEmptyQueue :: (CommitQueue -> Queue r) -> IO r runEmptyQueue st = Logging.withStdoutLogging $ do Logging.setLogLevel Logging.LevelError q <- CommitQueue.new runQueue q (st q) pipes, conduit, servant :: Repo pipes = Repo.unsafeFromString "https://github.com/Gabriel439/Haskell-Pipes-Library" conduit = Repo.unsafeFromString "https://github.com/snoyberg/conduit" servant = Repo.unsafeFromString "https://github.com/haskell-servant/servant" assertJust :: String -> Maybe a -> IO a assertJust _ (Just a) = return a assertJust msg _ = assertFailure msg >> error "Should never hit this" assertNothing :: String -> Maybe a -> IO () assertNothing _ Nothing = return () assertNothing msg _ = assertFailure msg assertDequeuedCommitFromRepo :: Repo -> SHA -> Queue () assertDequeuedCommitFromRepo repo commit = do (actualRepo, actualCommit) <- tryDequeue >>= liftIO . assertJust "dequeue should not time out" liftIO $ assertEqual "dequeued from wrong repo" repo actualRepo liftIO $ assertEqual "dequeued wrong commit" commit actualCommit updateNonEmpty :: Repo -> [SHA] -> Queue () updateNonEmpty repo commits = update repo commits >>= liftIO . assertBool "queue was empty" . not updateEmpty :: Repo -> Queue () updateEmpty repo = update repo [] >>= liftIO . assertBool "queue was not empty" tests :: TestTree tests = testGroup "CommitQueue" [ testGroup "single repo" [ testCase "update then dequeue and empty queue" $ runEmptyQueue $ \_ -> do updateNonEmpty pipes ["1", "3", "2"] assertDequeuedCommitFromRepo pipes "1" assertDequeuedCommitFromRepo pipes "3" assertDequeuedCommitFromRepo pipes "2" tryDequeue >>= liftIO . assertNothing "empty queue should lead to blocking" -- Even if we there aren't any more items to dequeue, the queue might not -- not be empty, since items are just blacklisted, meaning they are executing -- right now. We have to clear all items for that repo to effectively have -- an empty CommitQueue. updateEmpty pipes , testCase "concurrent update leads to unblocking of the dequeuer" $ runEmptyQueue $ \q -> do liftIO . forkIO . runQueue q $ updateNonEmpty pipes ["1"] assertDequeuedCommitFromRepo pipes "1" ] , testGroup "multiple repos" [ testCase "fairness" $ runEmptyQueue $ \_ -> do updateNonEmpty pipes ["1", "2"] assertDequeuedCommitFromRepo pipes "1" updateNonEmpty conduit ["4", "3"] -- we point now to what comes after pipes entry, so we wrap around assertDequeuedCommitFromRepo conduit "4" updateNonEmpty servant ["7", "5", "6"] -- lastRepo was conduit, so we continue with pipes assertDequeuedCommitFromRepo pipes "2" updateNonEmpty pipes ["8", "9"] -- pipes -> servant assertDequeuedCommitFromRepo servant "7" -- servant -> conduit assertDequeuedCommitFromRepo conduit "3" -- conduit -> pipes assertDequeuedCommitFromRepo pipes "8" -- pipes -> servant assertDequeuedCommitFromRepo servant "5" -- servant -> conduit, which is depleted, so -> pipes assertDequeuedCommitFromRepo pipes "9" -- pipes -> servant assertDequeuedCommitFromRepo servant "6" -- that should be all, see if dequeue blocks tryDequeue >>= liftIO . assertNothing "empty queue should lead to blocking" -- now tear down the queue updateNonEmpty conduit [] updateNonEmpty pipes [] updateEmpty servant ] ]
sgraf812/feed-gipeda
tests/Unit/CommitQueue.hs
bsd-3-clause
5,349
0
15
1,355
1,285
651
634
97
3
module Aws.S3.Commands ( module Aws.S3.Commands.CopyObject , module Aws.S3.Commands.DeleteBucket , module Aws.S3.Commands.DeleteObject , module Aws.S3.Commands.DeleteObjects , module Aws.S3.Commands.GetBucket , module Aws.S3.Commands.GetBucketLocation , module Aws.S3.Commands.GetObject , module Aws.S3.Commands.GetService , module Aws.S3.Commands.HeadObject , module Aws.S3.Commands.PutBucket , module Aws.S3.Commands.PutObject ) where import Aws.S3.Commands.CopyObject import Aws.S3.Commands.DeleteBucket import Aws.S3.Commands.DeleteObject import Aws.S3.Commands.DeleteObjects import Aws.S3.Commands.GetBucket import Aws.S3.Commands.GetBucketLocation import Aws.S3.Commands.GetObject import Aws.S3.Commands.GetService import Aws.S3.Commands.HeadObject import Aws.S3.Commands.PutBucket import Aws.S3.Commands.PutObject
Soostone/aws
Aws/S3/Commands.hs
bsd-3-clause
824
0
5
62
174
127
47
24
0
import Control.Parallel import Data.Word -- Gain a lot of speed here using Word32 type and `mod` for parity checking -- instead of `even`. This is all since it keeps the values unboxed. collatzLen :: Int -> Word32 -> Int collatzLen c 1 = c collatzLen c n = collatzLen (c+1) $ if n `mod` 2 == 0 then n `div` 2 else 3*n+1 pmax x n = x `max` (collatzLen 1 n, n) main = print soln where solve xs = foldl pmax (1,1) xs s1 = solve [2..500000] s2 = solve [500001..999999] soln = s2 `par` (s1 `pseq` max s1 s2)
dterei/Scraps
euler/p14/p14_par.hs
bsd-3-clause
543
0
10
142
201
111
90
11
2