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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- | This module implements a compiler pass that removes unused
-- @let@-bindings.
module Futhark.Optimise.DeadVarElim
( deadCodeElim
, deadCodeElimFun
, deadCodeElimBody
, deadCodeElimLambda
)
where
import Control.Applicative
import Control.Monad.Writer
import qualified Data.Set as S
import Prelude
import Futhark.Representation.AST
-----------------------------------------------------------------
-----------------------------------------------------------------
---- This file implements Dead-Variable Elimination ----
-----------------------------------------------------------------
-----------------------------------------------------------------
data DCElimRes = DCElimRes {
resSuccess :: Bool
-- ^ Whether we have changed something.
, resMap :: Names
-- ^ The hashtable recording the uses
}
instance Monoid DCElimRes where
DCElimRes s1 m1 `mappend` DCElimRes s2 m2 =
DCElimRes (s1 || s2) (m1 `S.union` m2) --(io1 || io2)
mempty = DCElimRes False S.empty -- False
type DCElimM = Writer DCElimRes
runDCElimM :: DCElimM a -> (a, DCElimRes)
runDCElimM = runWriter
collectRes :: [VName] -> DCElimM a -> DCElimM (a, Bool)
collectRes mvars m = pass collect
where wasNotUsed hashtab vnm =
return $ not (S.member vnm hashtab)
collect = do
(x,res) <- listen m
tmps <- mapM (wasNotUsed (resMap res)) mvars
return ( (x, and tmps), const res )
changed :: DCElimM a -> DCElimM a
changed m = pass collect
where
collect = do
(x, res) <- listen m
return (x, const $ res { resSuccess = True })
-- | Applies Dead-Code Elimination to an entire program.
deadCodeElim :: Attributes lore => Prog lore -> Prog lore
deadCodeElim = Prog . map deadCodeElimFun . progFunctions
-- | Applies Dead-Code Elimination to just a single function.
deadCodeElimFun :: Attributes lore => FunDef lore -> FunDef lore
deadCodeElimFun (FunDef entry fname rettype args body) =
let body' = deadCodeElimBody body
in FunDef entry fname rettype args body'
-- | Applies Dead-Code Elimination to just a single body.
deadCodeElimBody :: Attributes lore => Body lore -> Body lore
deadCodeElimBody = fst . runDCElimM . deadCodeElimBodyM
-- | Applies Dead-Code Elimination to just a single lambda.
deadCodeElimLambda :: Attributes lore => Lambda lore -> Lambda lore
deadCodeElimLambda lam =
lam { lambdaBody = fst $ runDCElimM $ deadCodeElimBodyM $ lambdaBody lam }
--------------------------------------------------------------------
--------------------------------------------------------------------
---- Main Function: Dead-Code Elimination for exps ----
--------------------------------------------------------------------
--------------------------------------------------------------------
deadCodeElimSubExp :: SubExp -> DCElimM SubExp
deadCodeElimSubExp (Var ident) = Var <$> deadCodeElimVName ident
deadCodeElimSubExp (Constant v) = return $ Constant v
deadCodeElimBodyM :: Attributes lore => Body lore -> DCElimM (Body lore)
deadCodeElimBodyM (Body bodylore (Let pat explore e:bnds) res) = do
let idds = patternNames pat
seen $ freeIn explore
(Body _ bnds' res', noref) <-
collectRes idds $ do
deadCodeElimPat pat
deadCodeElimBodyM $ Body bodylore bnds res
if noref
then changed $ return $ Body bodylore bnds' res'
else do e' <- deadCodeElimExp e
return $ Body bodylore
(Let pat explore e':bnds') res'
deadCodeElimBodyM (Body bodylore [] es) = do
seen $ freeIn bodylore
Body bodylore [] <$> mapM deadCodeElimSubExp es
deadCodeElimExp :: Attributes lore => Exp lore -> DCElimM (Exp lore)
deadCodeElimExp = mapExpM mapper
where mapper = Mapper {
mapOnBody = const deadCodeElimBodyM
, mapOnSubExp = deadCodeElimSubExp
, mapOnVName = deadCodeElimVName
, mapOnCertificates = \(Certificates cs) ->
Certificates <$> mapM deadCodeElimVName cs
, mapOnRetType = \rt -> seen (freeIn rt) >> return rt
, mapOnBranchType = \rt -> seen (freeIn rt) >> return rt
, mapOnFParam = \fparam -> seen (freeIn fparam) >> return fparam
, mapOnLParam = \lparam -> seen (freeIn lparam) >> return lparam
, mapOnOp = \op -> seen (freeIn op) >> return op
}
deadCodeElimVName :: VName -> DCElimM VName
deadCodeElimVName vnm = do
seen $ S.singleton vnm
return vnm
deadCodeElimPat :: FreeIn attr => PatternT attr -> DCElimM ()
deadCodeElimPat = mapM_ deadCodeElimPatElem . patternElements
deadCodeElimPatElem :: FreeIn attr => PatElemT attr -> DCElimM ()
deadCodeElimPatElem patelem =
seen $ patElemName patelem `S.delete` freeIn patelem
seen :: Names -> DCElimM ()
seen = tell . DCElimRes False
| ihc/futhark | src/Futhark/Optimise/DeadVarElim.hs | isc | 4,888 | 0 | 14 | 1,075 | 1,268 | 644 | 624 | 87 | 2 |
module Hickory.Utils.Resources where
import Data.Hashable
import qualified Data.HashMap.Strict as HashMap
type RefStore a b = HashMap.HashMap a (b, Int)
emptyRefStore :: RefStore a b
emptyRefStore = HashMap.empty
reserve :: (Hashable a, Eq a, Monad m) => RefStore a b -> a -> (a -> m (Maybe b)) -> m (RefStore a b, Maybe b)
reserve store name loadfunc = do
let val = HashMap.lookup name store
case val of
Nothing -> do
val' <- loadfunc name
case val' of
Nothing -> return (store, Nothing)
Just v -> return $ (HashMap.insert name (v, 0) store, Just v)
Just (val', i) -> do
return $ (HashMap.insert name (val', i + 1) store, Just val')
release :: (Hashable a, Eq a, Monad m) => RefStore a b -> a -> (b -> m ()) -> m (RefStore a b)
release store name deletefunc = do
let val = HashMap.lookup name store
case val of
Nothing -> return store
Just (val', 0) -> do
deletefunc val'
return $ (HashMap.delete name store)
Just (val', i) -> do
return $ (HashMap.insert name (val', i - 1) store)
| asivitz/Hickory | Hickory/Utils/Resources.hs | mit | 1,215 | 4 | 22 | 414 | 490 | 248 | 242 | 27 | 3 |
{-
-}
module Game.Title
( pg13
, titleLoop
) where
import Control.Monad (forM_)
import Control.Monad.Trans.State
import Control.Monad.Trans (liftIO)
import Graphics.UI.SDL
import Data.Word
-- Internal modules import
import Game.Graphics
import Game.Input (inUserInput)
import Resources.Gfxv_wl6 as WL6
import Game.State
import Resources
import Resources.Map
pg13BgColor :: GameColor
pg13BgColor = 0x82 -- acid blue for PG13 logo background
-- | Display PG13 logo
--
pg13 :: StateT GameState IO ()
pg13 = do
gstate <- get
vwFadeOut
-- clear the screen
vwbBar (Rect 0 0 320 200) pg13BgColor
-- display PG13 logo
vwbDrawPic (Point 216 110) PG13PIC
vwFadeIn
inUserInput 3000
vwFadeOut
-- | Shows title pages in loop
--
titleLoop :: StateT GameState IO ()
titleLoop = do
gstate <- get
-- title page
vwbDrawPic (Point 0 0) TITLEPIC
vwFadeIn
titleAck <- inUserInput 3000
if titleAck
then return ()
else do
vwFadeOut
-- credits page
vwbDrawPic (Point 0 0) CREDITSPIC
vwFadeIn
creditsAck <- inUserInput 3000
if creditsAck
then return ()
else do
vwFadeOut
-- high scores
-- TODO
-- demo
-- TODO
--
-- check playstate
-- startCPMusic
titleLoop
| vTurbine/w3dhs | src/Game/Title.hs | mit | 1,522 | 0 | 12 | 564 | 318 | 170 | 148 | 43 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{- |
Module : Language.Scheme.Parser
Copyright : Justin Ethier
Licence : MIT (see LICENSE in the distribution)
Maintainer : github.com/justinethier
Stability : experimental
Portability : portable
This module implements parsing of Scheme code.
-}
module Language.Scheme.Parser
(
lispDef
-- *Higher level parsing
, mainParser
, readOrThrow
, readExpr
, readExprList
-- *Low level parsing
, parseExpr
, parseAtom
, parseBool
, parseChar
, parseOctalNumber
, parseBinaryNumber
, parseHexNumber
, parseDecimalNumber
, parseNumber
, parseRealNumber
, parseRationalNumber
, parseComplexNumber
, parseEscapedChar
, parseString
, parseVector
, parseByteVector
, parseHashTable
, parseList
, parseDottedList
, parseQuoted
, parseQuasiQuoted
, parseUnquoted
, parseUnquoteSpliced
) where
import Language.Scheme.Types
import Control.Monad.Except
import Data.Array
import qualified Data.ByteString as BS
import qualified Data.Char as DC
import Data.Complex
import qualified Data.Map
import Data.Ratio
import Data.Word
import Numeric
import Text.ParserCombinators.Parsec hiding (spaces)
import Text.Parsec.Language
import qualified Text.Parsec.Token as P
#if __GLASGOW_HASKELL__ >= 702
import Data.Functor.Identity (Identity)
import Text.Parsec.Prim (ParsecT)
#endif
-- This was added by pull request #63 as part of a series of fixes
-- to get husk to build on ghc 7.2.2
--
-- For now this has been removed to allow husk to support the older
-- GHC 6.x.x series.
--
--import Data.Functor.Identity (Identity)
-- |Language definition for Scheme
lispDef :: LanguageDef ()
lispDef
= emptyDef
{ P.commentStart = "#|"
, P.commentEnd = "|#"
, P.commentLine = ";"
, P.nestedComments = True
, P.identStart = letter <|> symbol
, P.identLetter = letter <|> digit <|> symbol
, P.reservedNames = []
, P.caseSensitive = True
}
#if __GLASGOW_HASKELL__ >= 702
lexer :: P.GenTokenParser String () Data.Functor.Identity.Identity
#endif
lexer = P.makeTokenParser lispDef
#if __GLASGOW_HASKELL__ >= 702
dot :: ParsecT String () Identity String
#endif
dot = P.dot lexer
#if __GLASGOW_HASKELL__ >= 702
parens :: ParsecT String () Identity a -> ParsecT String () Identity a
#endif
parens = P.parens lexer
#if __GLASGOW_HASKELL__ >= 702
brackets :: ParsecT String () Identity a -> ParsecT String () Identity a
#endif
brackets = P.brackets lexer
#if __GLASGOW_HASKELL__ >= 702
identifier :: ParsecT String () Identity String
#endif
identifier = P.identifier lexer
#if __GLASGOW_HASKELL__ >= 702
whiteSpace :: ParsecT String () Identity ()
#endif
whiteSpace = P.whiteSpace lexer
#if __GLASGOW_HASKELL__ >= 702
lexeme :: ParsecT String () Identity a -> ParsecT String () Identity a
#endif
lexeme = P.lexeme lexer
-- |Match a special character
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~."
-- |Parse an atom (scheme symbol)
parseAtom :: Parser LispVal
parseAtom = do
atom <- identifier
if atom == "."
then pzero -- Do not match this form
else return $ Atom atom
-- |Parse a boolean
parseBool :: Parser LispVal
parseBool = do _ <- string "#"
x <- oneOf "tf"
return $ case x of
't' -> Bool True
'f' -> Bool False
_ -> Bool False
-- |Parse a character
parseChar :: Parser LispVal
parseChar = do
_ <- try (string "#\\")
c <- anyChar
r <- many (letter <|> digit)
let pchr = c : r
case pchr of
"space" -> return $ Char ' '
"newline" -> return $ Char '\n'
"alarm" -> return $ Char '\a'
"backspace" -> return $ Char '\b'
"delete" -> return $ Char '\DEL'
"escape" -> return $ Char '\ESC'
"null" -> return $ Char '\0'
"return" -> return $ Char '\n'
"tab" -> return $ Char '\t'
_ -> case (c : r) of
[ch] -> return $ Char ch
('x' : hexs) -> do
rv <- parseHexScalar hexs
return $ Char rv
_ -> pzero
-- |Parse an integer in octal notation, base 8
parseOctalNumber :: Parser LispVal
parseOctalNumber = do
_ <- try (string "#o")
sign <- many (oneOf "-")
num <- many1 (oneOf "01234567")
case (length sign) of
0 -> return $ Number $ fst $ head (Numeric.readOct num)
1 -> return $ Number $ fromInteger $ (*) (-1) $ fst $ head (Numeric.readOct num)
_ -> pzero
-- |Parse an integer in binary notation, base 2
parseBinaryNumber :: Parser LispVal
parseBinaryNumber = do
_ <- try (string "#b")
sign <- many (oneOf "-")
num <- many1 (oneOf "01")
case (length sign) of
0 -> return $ Number $ fst $ head (Numeric.readInt 2 (`elem` "01") DC.digitToInt num)
1 -> return $ Number $ fromInteger $ (*) (-1) $ fst $ head (Numeric.readInt 2 (`elem` "01") DC.digitToInt num)
_ -> pzero
-- |Parse an integer in hexadecimal notation, base 16
parseHexNumber :: Parser LispVal
parseHexNumber = do
_ <- try (string "#x")
sign <- many (oneOf "-")
num <- many1 (digit <|> oneOf "abcdefABCDEF")
case (length sign) of
0 -> return $ Number $ fst $ head (Numeric.readHex num)
1 -> return $ Number $ fromInteger $ (*) (-1) $ fst $ head (Numeric.readHex num)
_ -> pzero
-- |Parser for Integer, base 10
parseDecimalNumber :: Parser LispVal
parseDecimalNumber = do
_ <- try (many (string "#d"))
sign <- many (oneOf "-")
num <- many1 digit
if (length sign) > 1
then pzero
else return $ (Number . read) $ sign ++ num
-- |Parser for a base 10 Integer that will also
-- check to see if the number is followed by
-- an exponent (scientific notation). If so,
-- the integer is converted to a float of the
-- given magnitude.
parseDecimalNumberMaybeExponent :: Parser LispVal
parseDecimalNumberMaybeExponent = do
num <- parseDecimalNumber
parseNumberExponent num
-- |Parse an integer in any base
parseNumber :: Parser LispVal
parseNumber = parseDecimalNumberMaybeExponent <|>
parseHexNumber <|>
parseBinaryNumber <|>
parseOctalNumber <?>
"Unable to parse number"
-- |Parse a floating point number
parseRealNumber :: Parser LispVal
parseRealNumber = do
sign <- many (oneOf "-+")
num <- many digit
_ <- char '.'
frac <- many1 digit
let dec = if not (null num)
then num ++ "." ++ frac
else "0." ++ frac
f <- case (length sign) of
0 -> return $ Float $ fst $ head (Numeric.readFloat dec)
-- Bit of a hack, but need to support the + sign as well as the minus.
1 -> if sign == "-"
then return $ Float $ (*) (-1.0) $ fst $ head (Numeric.readFloat dec)
else return $ Float $ fst $ head (Numeric.readFloat dec)
_ -> pzero
parseNumberExponent f
-- | Parse the exponent section of a floating point number
-- in scientific notation. Eg "e10" from "1.0e10"
parseNumberExponent :: LispVal -> Parser LispVal
parseNumberExponent n = do
expnt <- many $ oneOf "Ee"
case (length expnt) of
0 -> return n
1 -> do
num <- try parseDecimalNumber
case num of
Number nexp -> buildResult n nexp
_ -> pzero
_ -> pzero
where
buildResult (Number num) nexp = return $ Float $ (fromIntegral num) * (10 ** (fromIntegral nexp))
buildResult (Float num) nexp = return $ Float $ num * (10 ** (fromIntegral nexp))
buildResult _ _ = pzero
-- |Parse a rational number
parseRationalNumber :: Parser LispVal
parseRationalNumber = do
pnumerator <- parseDecimalNumber
case pnumerator of
Number n -> do
_ <- char '/'
sign <- many (oneOf "-")
num <- many1 digit
if (length sign) > 1
then pzero
else do
let pdenominator = read $ sign ++ num
if pdenominator == 0
then return $ Number 0 -- TODO: Prevents a div-by-zero error, but not really correct either
else return $ Rational $ n % pdenominator
_ -> pzero
-- |Parse a complex number
parseComplexNumber :: Parser LispVal
parseComplexNumber = do
lispreal <- (try parseRealNumber <|> try parseRationalNumber <|> parseDecimalNumber)
let real = case lispreal of
Number n -> fromInteger n
Rational r -> fromRational r
Float f -> f
_ -> 0
_ <- char '+'
lispimag <- (try parseRealNumber <|> try parseRationalNumber <|> parseDecimalNumber)
let imag = case lispimag of
Number n -> fromInteger n
Rational r -> fromRational r
Float f -> f
_ -> 0 -- Case should never be reached
_ <- char 'i'
return $ Complex $ real :+ imag
-- |Parse an escaped character
parseEscapedChar :: forall st .
GenParser Char st Char
parseEscapedChar = do
_ <- char '\\'
c <- anyChar
case c of
'a' -> return '\a'
'b' -> return '\b'
'n' -> return '\n'
't' -> return '\t'
'r' -> return '\r'
'x' -> do
num <- many $ letter <|> digit
_ <- char ';'
parseHexScalar num
_ -> return c
-- |Parse a hexidecimal scalar
parseHexScalar :: String -> GenParser Char st Char
parseHexScalar num = do
let ns = Numeric.readHex num
case ns of
[] -> fail $ "Unable to parse hex value " ++ show num
_ -> return $ DC.chr $ fst $ head ns
-- |Parse a string
parseString :: Parser LispVal
parseString = do
_ <- char '"'
x <- many (parseEscapedChar <|> noneOf "\"")
_ <- char '"'
return $ String x
-- |Parse a vector
parseVector :: Parser LispVal
parseVector = do
vals <- sepBy parseExpr whiteSpace
return $ Vector (listArray (0, (length vals - 1)) vals)
-- |Parse a bytevector
parseByteVector :: Parser LispVal
parseByteVector = do
ns <- sepBy parseNumber whiteSpace
return $ ByteVector $ BS.pack $ map conv ns
where
conv (Number n) = fromInteger n :: Word8
conv _ = 0 :: Word8
-- |Parse a hash table. The table is either empty or is made up of
-- an alist (associative list)
parseHashTable :: Parser LispVal
parseHashTable = do
-- This function uses explicit recursion to loop over the parsed list:
-- As long as it is an alist, the members are appended to an accumulator
-- so they can be added to the hash table. However, if the input list is
-- determined not to be an alist, Nothing is returned, letting the parser
-- know that a valid hashtable was not read.
let f :: [(LispVal, LispVal)] -> [LispVal] -> Maybe [(LispVal, LispVal)]
f acc [] = Just acc
f acc (List [a, b] :ls) = f (acc ++ [(a, b)]) ls
f acc (DottedList [a] b :ls) = f (acc ++ [(a, b)]) ls
f _ (_:_) = Nothing
vals <- sepBy parseExpr whiteSpace
let mvals = f [] vals
case mvals of
Just m -> return $ HashTable $ Data.Map.fromList m
Nothing -> pzero
-- |Parse a list
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr whiteSpace
-- TODO: wanted to use endBy (or a variant) above, but it causes an error such that dotted lists are not parsed
-- |Parse a dotted list (scheme pair)
parseDottedList :: Parser LispVal
parseDottedList = do
phead <- endBy parseExpr whiteSpace
case phead of
[] -> pzero -- car is required; no match
_ -> do
ptail <- dot >> parseExpr
case ptail of
DottedList ls l -> return $ DottedList (phead ++ ls) l
-- Issue #41
-- Improper lists are tricky because if an improper list ends in a
-- proper list, then it becomes proper as well. The following cases
-- handle that, as well as preserving necessary functionality when
-- appropriate, such as for unquoting.
--
-- FUTURE: I am not sure if this is complete, in fact the "unquote"
-- seems like it could either be incorrect or one special case among
-- others. Anyway, for the 3.3 release this is good enough to pass all
-- test cases. It will be revisited later if necessary.
--
List (Atom "unquote" : _) -> return $ DottedList phead ptail
List ls -> return $ List $ phead ++ ls
{- Regarding above, see
http://community.schemewiki.org/?scheme-faq-language#dottedapp
Note, however, that most Schemes expand literal lists occurring in
function applications, e.g. (foo bar . (1 2 3)) is expanded into
(foo bar 1 2 3) by the reader. It is not entirely clear whether this
is a consequence of the standard - the notation is not part of the
R5RS grammar but there is strong evidence to suggest a Scheme
implementation cannot comply with all of R5RS without performing this
transformation. -}
_ -> return $ DottedList phead ptail
-- |Parse a quoted expression
parseQuoted :: Parser LispVal
parseQuoted = do
_ <- lexeme $ char '\''
x <- parseExpr
return $ List [Atom "quote", x]
-- |Parse a quasi-quoted expression
parseQuasiQuoted :: Parser LispVal
parseQuasiQuoted = do
_ <- lexeme $ char '`'
x <- parseExpr
return $ List [Atom "quasiquote", x]
-- |Parse an unquoted expression (a quasiquotated expression preceded
-- by a comma)
parseUnquoted :: Parser LispVal
parseUnquoted = do
_ <- try (lexeme $ char ',')
x <- parseExpr
return $ List [Atom "unquote", x]
-- |Parse an unquote-spliced expression
parseUnquoteSpliced :: Parser LispVal
parseUnquoteSpliced = do
_ <- try (lexeme $ string ",@")
x <- parseExpr
return $ List [Atom "unquote-splicing", x]
-- FUTURE: should be able to use the grammar from R5RS
-- to make parsing more efficient (mostly by minimizing
-- or eliminating the number of try's below)
-- |Parse an expression
parseExpr :: Parser LispVal
parseExpr =
try (lexeme parseComplexNumber)
<|> try (lexeme parseRationalNumber)
<|> try (lexeme parseRealNumber)
<|> try (lexeme parseNumber)
<|> lexeme parseChar
<|> parseUnquoteSpliced
<|> do _ <- try (lexeme $ string "#(")
x <- parseVector
_ <- lexeme $ char ')'
return x
<|> do _ <- try (lexeme $ string "#u8(")
x <- parseByteVector
_ <- lexeme $ char ')'
return x
-- <|> do _ <- try (lexeme $ string "#hash(")
-- x <- parseHashTable
-- _ <- lexeme $ char ')'
-- return x
<|> try parseAtom
<|> lexeme parseString
<|> lexeme parseBool
<|> parseQuoted
<|> parseQuasiQuoted
<|> parseUnquoted
<|> try (parens parseList)
<|> parens parseDottedList
<|> try (brackets parseList)
<|> brackets parseDottedList
<?> "Expression"
-- |Initial parser used by the high-level parse functions
mainParser :: Parser LispVal
mainParser = do
_ <- whiteSpace
parseExpr
-- |Use a parser to parse the given text, throwing an error
-- if there is a problem parsing the text.
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow parser input = case parse parser "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
-- |Parse an expression from a string of text
readExpr :: String -> ThrowsError LispVal
readExpr = readOrThrow mainParser
-- |Parse many expressions from a string of text
readExprList :: String -> ThrowsError [LispVal]
readExprList = readOrThrow (endBy mainParser whiteSpace)
| justinethier/husk-scheme | hs-src/Language/Scheme/Parser.hs | mit | 15,396 | 0 | 25 | 4,039 | 3,926 | 1,977 | 1,949 | 331 | 12 |
main = do
contents <- readFile "./main.hs"
return (lines contents)
| doylew/practice | haskell/main.hs | mit | 71 | 0 | 9 | 14 | 28 | 12 | 16 | 3 | 1 |
{-# htermination enumFromThenTo :: Float -> Float -> Float -> [Float] #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFromThenTo_5.hs | mit | 74 | 0 | 2 | 12 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE RankNTypes #-}
import Control.Applicative
import Control.Monad.Free
import Control.Monad.State
import Control.Monad.Writer
import Prelude hiding (print)
-- http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html
-- http://www.haskellforall.com/2012/07/purify-code-using-free-monads.html
-- | This represents a symbolic reference to a variable in our DSL. It is what allows threading
-- several monadic statements with each other. In general, a DSL may have more than one type, but
-- for our purposes one will do. For now we will assume that each variable is internally represented
-- by a single integer, but other representations are possible (e.g. strings, memory addresses,
-- etc.).
newtype Var = Var Int
-- | Define a function for displaying the symbolic name of a variable.
instance Show Var where
show (Var n) = "v" ++ show n
newtype BoolV = BoolV Int
instance Show BoolV where
show (BoolV n) = "b" ++ show n
-- | This is the core definition of the syntax of our DSL, also encoding their return types. The
-- last argument of each non-terminal instruction represents the next instruction in the monadic
-- sequence. Note how instructions that introduce new variable in the scope accept a parameter of
-- type `Var -> next`, while others simply accept a `next`.
data OpF next
= Def Int (Var -> next)
| Add Var Var (Var -> next)
| Print Var next
| Eq Var Var (BoolV -> next)
| End
-- | We create various convenience combinator lifting each of the syntax elements into the "free"
-- monadic context. Note that this is nothing more than a mechanical transformation; no behaviour or
-- meaning is associated to the instructions at this point. Note also the last argument to each
-- statement is either `id` or `()`; why?
def :: Int -> Op Var
def n = liftF $ Def n id
add :: Var -> Var -> Op Var
add v1 v2 = liftF $ Add v1 v2 id
print :: Var -> Op ()
print v = liftF $ Print v ()
eq :: Var -> Var -> Op BoolV
eq v1 v2 = liftF $ Eq v1 v2 id
end :: Op a
end = liftF $ End
-- | We define the behaviour of OpF as a Functor. Note that it is possible for Haskell to derive
-- this automatically using an extension.
instance Functor OpF where
fmap f (Def n k) = Def n (f . k)
fmap f (Add v1 v2 k) = Add v1 v2 (f . k)
fmap f (Print v next) = Print v (f next)
fmap f (Eq v1 v2 k) = Eq v1 v2 (f . k)
fmap f End = End
-- | Shorthand notation.
type Op = Free OpF
-- | A sample program written in our new DSL.
test :: Op ()
test = do
a <- def 111
print a
b <- def 222
print b
c <- add a b
print c
d <- def 333
e <- eq c d
print d
assign :: String
assign =
"<-"
-- | Manual continuation.
pp1 :: Op a -> Int -> String
pp1 (Pure r) i =
"return"
pp1 (Free op) i =
case op of
Def n k ->
(line [show v, assign, show n]) ++ (pp1 (k v) (succ i))
where
v = Var i
Add v1 v2 k ->
(line [show v, assign, show v1, "+", show v2]) ++ (pp1 (k v) (succ i ))
where
v = Var i
Print v k ->
(line ["print", show v]) ++ (pp1 k i)
Eq v1 v2 k ->
(line [show v, assign, show v1, "==", show v2]) ++ (pp1 (k v) (succ i))
where
v = BoolV i
End ->
"end"
-- | Applicative style (needs to work for both StateT and State).
newVar :: (Monad a, Functor a) => StateT Int a Var
newVar =
Var <$> get <* modify succ
{- Monadic style:
newVar = do
i <- get
modify succ
return $ Var i
-}
newBoolV :: (Monad a, Functor a) => StateT Int a BoolV
newBoolV =
BoolV <$> get <* modify succ
-- | State Monad only.
pp2 :: Op a -> State Int String
pp2 (Pure r) =
return $ "return"
pp2 (Free op) = do
case op of
Def n k -> do
v <- newVar
next <- pp2 $ k v
return $ (line [show v, assign, show n]) ++ next
Add v1 v2 k -> do
v <- newVar
next <- pp2 $ k v
return $ (line [show v, assign, show v1, "+", show v2]) ++ next
Print v k -> do
next <- pp2 $ k
return $ (line ["print", show v]) ++ next
Eq v1 v2 k -> do
v <- newBoolV
next <- pp2 $ k v
return $ (line [show v, assign, show v1, "==", show v2]) ++ next
-- | Writer Monad only.
pp3 :: Op a -> Int -> Writer String ()
pp3 (Pure r) i =
tell "return"
pp3 (Free op) i =
case op of
Def n k -> do
let v = Var i
tell $ line [show v, assign, show n]
pp3 (k v) (succ i)
Add v1 v2 k -> do
let v = Var i
tell $ line [show v, assign, show v1, "+", show v2]
pp3 (k v) (succ i)
Print v k -> do
tell $ line ["print", show v]
pp3 k i
Eq v1 v2 k -> do
let v = BoolV i
tell $ line [show v, assign, show v1, "==", show v2]
line :: [String] -> String
line vs =
(unwords vs) ++ "\n"
-- | Monad transformers (StateT + Writer).
pp4 :: Op a -> StateT Int (Writer String) ()
pp4 (Pure r) =
tell "return"
pp4 (Free op) =
case op of
Def n k -> do
v <- newVar
tell $ line [show v, assign, show n]
pp4 $ k v
Add v1 v2 k -> do
v <- newVar
tell $ line [show v, assign, show v1, "+", show v2]
pp4 $ k v
Print v k -> do
tell $ line ["print", show v]
pp4 $ k
Eq v1 v2 k -> do
v <- newBoolV
tell $ line [show v, assign, show v1, "==", show v2]
pp4 $ k v
data RunState = RunState
{ _intVar :: [Int]
, _boolVar :: [Bool]
}
setVal :: Monad a => Int -> StateT RunState a Var
setVal v = do
modify $ \state -> state { _intVar = (_intVar state) ++ [v] }
vv <- gets _intVar
return $ Var $ pred (length vv)
getVal :: Monad a => Var -> StateT RunState a Int
getVal (Var n) = do
vv <- gets _intVar
return $ vv !! n
initialRunState :: RunState
initialRunState = RunState { _intVar = [] , _boolVar = [] }
runOp :: Op a -> StateT RunState IO a
runOp (Pure k) =
return k
runOp (Free op) =
case op of
Def n k -> do
v <- setVal n
runOp (k v)
Add v1 v2 k -> do
n1 <- getVal v1
n2 <- getVal v2
v <- setVal (n1 + n2)
runOp (k v)
Print v k -> do
val <- getVal v
(liftIO . putStrLn) (show val)
runOp k
Eq (Var n1) (Var n2) k -> do
runOp (k $ BoolV 1)
-- End -> return ()
main :: IO ()
main = do
let listing1 = pp1 test 0
putStr $ "pp1: {\n" ++ listing1 ++ "}\n\n"
let listing2 = evalState (pp2 test) 0
putStr $ "pp2: {\n" ++ listing2 ++ "}\n\n"
let listing3 = execWriter (pp3 test 0)
putStr $ "pp3: {\n" ++ listing3 ++ "}\n\n"
let listing4 = execWriter (evalStateT (pp4 test) 0)
putStr $ "pp4: {\n" ++ listing4 ++ "}\n\n"
putStr $ "run: {\n"
runStateT (runOp test) initialRunState
putStr $ "}\n\n"
| tiziano88/free-monad-parser | free.hs | mit | 7,154 | 0 | 17 | 2,396 | 2,568 | 1,260 | 1,308 | 181 | 5 |
module Y2017.M03.D07.Exercise where
-- below import available via 1HaskellADay git repository
import Analytics.Math.Combinatorics (choose)
{--
url: http://rosalind.info/problems/aspc/
Introduction to Alternative Splicing solved by 927 as of February 28th, 2017
The Baby and the Bathwater
In “RNA Splicing”, we described the process by which the exons are spliced out
from a molecule of pre-mRNA and reassembled to yield a final mRNA for the
purposes of protein translation.
However, the chaining of exons does not always proceed in the same manner;
alternative splicing describes the fact that all the exons from a gene are not
necessarily joined together in order to produce an mRNA. The most common form
of alternative splicing is exon skipping, in which certain exons are omitted
along with introns.
Alternative splicing serves a vital evolutionary purpose, as it greatly
increases the number of different proteins that can be translated from a given
gene; different proteins produced from the same gene as a result of alternative
splicing are called protein isoforms; see Figure 1.
Figure 1. Alternative splicing induces different protein isoforms.
In fact, about 95% of human genes are commonly spliced in more than one way. At
the same time, when alternative splicing goes wrong, it can create the same
negative effects caused by mutations, and it has been blamed for a number of
genetic disorders.
In this problem, we will consider a simplified model of alternative splicing in
which any of a collection of exons can be chained together to create a final
molecule of mRNA, under the condition that we use a minimum number of exons (m)
whose order is fixed. Because the exons are not allowed to move around, we need
only select a subset of at least m of our exons to chain into an mRNA.
The implied computational question is to count the total number of such subsets,
which will provide us with the total possible number of alternatively spliced
isoforms for this model.
Problem
In “Counting Subsets”, we saw that the total number of subsets of a set S
containing n elements is equal to 2n
However, if we intend to count the total number of subsets of S having a fixed
size k, then we use the combination statistic C(n,k).
Given: Positive integers n and m with 0 <= m <= n <= 2000
Return: The sum of combinations C(n,k) for all k satisfying m <= k <= n,
modulo 1,000,000.
--}
sample :: String
sample = "6 3"
result :: Integer
result = 42
aspc :: Integer -> Integer -> Integer
aspc n m = undefined
{--
>>> aspc 6 3
42
--}
-- BONUS -----------------------------------------------------------------
-- What is the sum of combinations for (n,m) in:
biggus :: String
biggus = "1662 1307"
{--
>>> aspc 1662 1307
357204
--}
| geophf/1HaskellADay | exercises/HAD/Y2017/M03/D06/Exercise.hs | mit | 2,774 | 0 | 6 | 503 | 78 | 49 | 29 | 10 | 1 |
module Zwerg.Generator.Player.TestPlayer where
import Zwerg.Generator
import Zwerg.Generator.Default
import Zwerg.Generator.Item.Weapon
testPlayer :: Generator
testPlayer =
Generator testPlayerHatcher []
+> assignUniformRandomStats (zip (enumFrom STR) (repeat (1,100)))
+> generateAndEquip sword
testPlayerHatcher :: EntityHatcher
testPlayerHatcher = MkEntityHatcher $ do
generatePlayerSkeleton
let (<@-) :: Component a -> a -> MonadCompState ()
(<@-) = addComp playerUUID
name <@- "Bob"
description <@- "It's you."
entityType <@- Player
viewRange <@- 7
ticks <@- 50
hp <@- unsafeWrap (100,100)
return playerUUID
-- putOnRandomEmptyTile startLevelUUID playerUUID
-- generateAndHoldN 3 sword playerUUID
| zmeadows/zwerg | lib/Zwerg/Generator/Player/TestPlayer.hs | mit | 801 | 0 | 14 | 180 | 196 | 102 | 94 | 21 | 1 |
{-# htermination fmToList_LE :: FiniteMap Ordering b -> Ordering -> [(Ordering,b)] #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_fmToList_LE_11.hs | mit | 105 | 0 | 3 | 15 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Network.Monitoring.Riemann.TCP
( tcpConnection
, sendEvents
, sendMsg
, TCPConnection
, Port
) where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (TVar, newTVarIO, readTVarIO, writeTVar)
import Control.Exception (IOException, try)
import Data.Bifunctor (first)
import qualified Data.Binary.Put as Put
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BC
import qualified Data.Maybe as Maybe
import Data.Monoid ((<>))
import Data.Sequence (Seq)
import qualified Network.Monitoring.Riemann.Event as Event
import qualified Network.Monitoring.Riemann.Proto.Event as PE
import qualified Network.Monitoring.Riemann.Proto.Msg as Msg
import Network.Socket
( AddrInfo
, AddrInfoFlag(AI_NUMERICSERV)
, Family(AF_INET)
, HostName
, Socket
, SocketType(Stream)
, addrAddress
, addrFamily
, addrFlags
, connect
, defaultHints
, defaultProtocol
, getAddrInfo
, socket
)
import qualified Network.Socket.ByteString.Lazy as NSB
import System.IO (hPutStrLn, stderr)
import qualified Text.ProtocolBuffers.Header as P'
import qualified Text.ProtocolBuffers.WireMessage as WM
data ClientInfo = ClientInfo
{ _hostname :: HostName
, _port :: Port
, _status :: TCPStatus
}
type TCPConnection = TVar ClientInfo
data TCPStatus
= CnxClosed
| CnxOpen (Socket, AddrInfo)
deriving (Show)
type Port = Int
tcpConnection :: HostName -> Port -> IO TCPConnection
tcpConnection _hostname _port = do
clientInfo <- doConnect $ ClientInfo {_status = CnxClosed, ..}
newTVarIO clientInfo
doConnect :: ClientInfo -> IO ClientInfo
doConnect clientInfo@(_status -> CnxOpen _) = pure clientInfo
doConnect clientInfo = do
hPutStrLn stderr $
"(Re)connecting to Riemann: " <> _hostname clientInfo <> ":" <>
show (_port clientInfo)
addrs <-
try $
getAddrInfo
(Just $ defaultHints {addrFlags = [AI_NUMERICSERV], addrFamily = AF_INET})
(Just (_hostname clientInfo))
(Just . show . _port $ clientInfo)
let family = AF_INET
case addrs of
Right [] -> fail ("No accessible addresses in " ++ show addrs)
Right (addy:_) -> do
s <- socket family Stream defaultProtocol
result <- try $ connect s (addrAddress addy)
case result of
Left err -> handleError err
Right () -> pure $ clientInfo {_status = CnxOpen (s, addy)}
Left err -> handleError err
where
handleError :: IOError -> IO ClientInfo
handleError err = do
hPutStrLn stderr $ "Connection to Riemann failed: " <> show err
pure $ clientInfo {_status = CnxClosed}
msgToByteString :: Msg.Msg -> BC.ByteString
msgToByteString msg =
Put.runPut $ do
Put.putWord32be $ fromIntegral $ WM.messageSize msg
WM.messagePutM msg
decodeMsg :: BC.ByteString -> Either String Msg.Msg
decodeMsg bs =
let result = WM.messageGet (BS.drop 4 bs)
in case result of
Left e -> Left e
Right (m, _) ->
if Maybe.isNothing (Msg.ok m)
then Left "error"
else Right m
{-| Attempts to send a message and return the response.
If the connection is down, this function will trigger one reconnection attempt.
If that succeeds the message will be sent.
If it fails, the message is dropped and will need to be resent by you.
-}
sendMsg :: TCPConnection -> Msg.Msg -> IO (Either Msg.Msg Msg.Msg)
sendMsg client msg = go True
where
go reconnect = do
clientInfo <- readTVarIO client
case (_status clientInfo, reconnect) of
(CnxClosed, True) -> do
newInfo <- doConnect clientInfo
atomically $ writeTVar client newInfo
go False
(CnxClosed, False) -> pure $ Left msg
(CnxOpen (s, _), _) -> do
response <-
first (show :: IOException -> String) <$>
try
(do NSB.sendAll s $ msgToByteString msg
NSB.recv s 4096)
case decodeMsg =<< response of
Left _ -> do
atomically $ writeTVar client (clientInfo {_status = CnxClosed})
pure $ Left msg
Right m -> pure $ Right m
{-|
Send a list of Riemann events
Host and Time will be added if they do not exist on the Event
-}
sendEvents :: TCPConnection -> Seq PE.Event -> IO ()
sendEvents connection events = do
eventsWithDefaults <- Event.withDefaults events
result <-
sendMsg connection $ P'.defaultValue {Msg.events = eventsWithDefaults}
case result of
Left msg -> hPutStrLn stderr $ "failed to send" ++ show msg
Right _ -> pure ()
| shmish111/hriemann | src/Network/Monitoring/Riemann/TCP.hs | mit | 4,711 | 0 | 23 | 1,098 | 1,316 | 703 | 613 | 125 | 4 |
{-# LANGUAGE NoMonomorphismRestriction #-}
module Anima.Parser where
import Anima.Types
import Control.Applicative hiding ((<|>), many)
import Text.ParserCombinators.Parsec
{-
General syntax, a la LISP: (fn arg1)
0, 1, 2, ... represent De Bruijn indices
Base values:
Unit -- The value of the unit type
TUnit -- The type of the unit type
Type -- The type of types
Special forms:
(Lam ty expr) -- s -> t
(Pi ty expr) -- (x:t) -> M x
(N expr) -- (N expr) where N = 0, 1, ...
-}
ws = many (oneOf " \r\t\n")
nt p = string p <* ws
base = (Base Unit <$ nt "Unit")
<|> try (Base TUnit <$ nt "TUnit")
<|> try (Base ATrue <$ nt "True")
<|> (Base AFalse <$ nt "False")
<|> (Base TBool <$ nt "Bool")
<|> (Base TNat <$ nt "Nat")
<|> (Base Type <$ nt "Type")
<|> (Var . read <$> (many1 (oneOf "0123456789") <* ws))
lambda = Binder Lam <$> (nt "lam" *> expr) <*> expr
pi' = Binder Pi <$> (nt "pi" *> expr) <*> expr
apply = Apply <$> expr <*> expr
nat = (Base (ANat Z) <$ nt "Z")
<|> try (inc <$> (nt "(" *> nt "S" *> nat <* nt ")"))
where inc (Base (ANat k)) = Base (ANat (S k))
form = lambda
<|> pi'
<|> apply
<|> nat
expr = try nat <|> (nt "(" *> form <* nt ")") <|> base | forestbelton/anima | Anima/Parser.hs | mit | 1,236 | 0 | 15 | 314 | 435 | 219 | 216 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Heather -- the library for interfacing with the OpenWeatherMap API
import System.Console.ArgParser -- parse arguments with the argparser library
data MyArg = -- arguments consist of a query string and an optional zip code
MyArg String Int deriving (Eq, Show)
myParser :: ParserSpec MyArg -- create the argument parser
myParser = MyArg
`parsedBy` optPos "" "query" `Descr` "The desired query, either `current` for the current forecast or `forecast` for a list of predicted temperatures over the next three days"
`andBy` optPos 94305 "zipcode" `Descr` "A 5-digit zip code (Default: 94305)"
app :: MyArg -> IO ()
app (MyArg q z)
| q == "" = putStrLn "Forecast: `heather forecast`\nCurrent weather: `heather current`\n(add an additional argument to change the zip code, e.g. `heather forecast 27708`)"
| q == "current" = do
result <- getCurrent z -- get the current weather
case result of
Left ex -> print $ "\nCaught exception!\n\n" ++ show ex
Right val -> print $ temperature val
| q == "forecast" = do
result <- getForecast z -- get the current forecast
case result of
Left ex -> print $ "\nCaught exception!\n\n" ++ show ex
Right val -> putStrLn $ collect val
where collect (Forecast _ ws) = unwords $ map (show . temperature) ws
| otherwise = error "Invalid argument"
main :: IO ()
main = do
interface <- mkApp myParser -- create our command line interface
runApp interface app -- run the app
| nirum/heather | main.hs | mit | 1,547 | 0 | 16 | 338 | 345 | 172 | 173 | 29 | 3 |
module Cenary.Options where
------------------------------------------------------
import Control.Applicative
import Data.Monoid ((<>))
import Data.String (IsString, fromString)
import Options.Applicative
------------------------------------------------------
------------------------------------------------------
data Options = Options
{ _mode :: Mode
, _inputFile :: FilePath
}
data Mode = Ast | ByteCode | Run | Disasm | Deploy | RewindDeploy
deriving Show
instance IsString Mode where
fromString "ast" = Ast
fromString "bytecode" = ByteCode
fromString "run" = Run
fromString "disasm" = Disasm
fromString "deploy" = Deploy
fromString "rewind-deploy" = RewindDeploy
fromString _ = Run
parseMode :: Parser Mode
parseMode =
fromString <$> strOption (long "mode" <> short 'm' <> help "Mode of the execution. Available options: ast, bytecode, run, disasm, asm")
optParser :: Parser Options
optParser = Options
<$> parseMode
<*> strOption (long "input" <> short 'i' <> help "Input file that contains cenary code" )
parseOptions :: IO Options
parseOptions =
execParser (info (optParser <**> helper) (fullDesc <> progDesc "Cenary" ))
| yigitozkavci/ivy | src/Cenary/Options.hs | mit | 1,277 | 0 | 10 | 293 | 279 | 151 | 128 | 28 | 1 |
module Playground.Playground (bmiCalc, bmiJustTel, cookieEater) where
addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
addVectors a b = (fst a + fst b, snd a + snd b)
bmiCalc :: (RealFloat a) => a -> a -> a
bmiCalc weight height = weight / height ** 2
bmiJustTel :: (RealFloat a) => a -> String
bmiJustTel bmi
| bmi <= 18.5 = "You're underweight, you emo, you!"
| bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
bmiTell1 :: (RealFloat a) => a -> a -> String
bmiTell1 weight height
| weight / height ** 2 <= 18.5 = "You're underweight, you emo, you!"
| weight / height ** 2 <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| weight / height ** 2 <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
bmiTell2 :: (RealFloat a) => a -> a -> String
bmiTell2 weight height
| bmi <= 18.5 = "You're underweight, you emo, you!"
| bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = bmiCalc weight height
bmiTell3 :: (RealFloat a) => a -> a -> String
bmiTell3 weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = bmiCalc weight height
skinny = 18.5
normal = 25.0
fat = 30.0
bmiTell4 :: (RealFloat a) => a -> a -> String
bmiTell4 weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = bmiCalc weight height
(skinny, normal, fat) = (18.5, 25.0, 30.0)
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell = bmiTell4
bmis :: (RealFloat a) => [(a, a)] -> [a]
bmis xs = [bmiCalc w h | (w, h) <- xs]
bmisTell :: (RealFloat a) => [(a, a)] -> [String]
bmisTell xs = [bmi w h | (w, h) <- xs]
where bmi = bmiTell
charName :: Char -> String
charName 'a' = "Alan"
charName 'b' = "Bob"
charName 'c' = "Caroline"
charName 'd' = "Don"
charName _ = "Bad luck"
cookieEater :: String -> String
cookieEater cookie
| cookie == "cookie" = "Yummi"
| otherwise = "Not a cookie!" | korczis/skull-haskell | src/Lib/Playground/Playground.hs | mit | 2,599 | 0 | 10 | 600 | 850 | 438 | 412 | 59 | 1 |
-- Enter your code here. Read input from STDIN. Print output to STDOUT
main :: IO()
main = do
putStrLn "Primitive : double"
putStrLn "Primitive : char"
putStrLn "Primitive : boolean"
putStrLn "Primitive : int"
putStrLn "Referenced : String"
putStrLn "Primitive : boolean"
putStrLn "Primitive : double"
putStrLn "Primitive : char"
putStrLn "Referenced : String"
| advancedxy/hackerrank | 30-days-of-code/haskell/d1.hs | mit | 379 | 0 | 7 | 73 | 71 | 27 | 44 | 11 | 1 |
-- Note: This is a modified version of DEMO-S5 by Jan van Eijck.
-- For the original, see http://homepages.cwi.nl/~jve/software/demo_s5/
module SMCDEL.Explicit.DEMO_S5 where
import Control.Arrow (first,second)
import Data.List (sortBy)
import SMCDEL.Internal.Help (apply,restrict,Erel,bl)
newtype Agent = Ag Int deriving (Eq,Ord,Show)
data DemoPrp = DemoP Int | DemoQ Int | DemoR Int | DemoS Int deriving (Eq,Ord)
instance Show DemoPrp where
show (DemoP 0) = "p"; show (DemoP i) = "p" ++ show i
show (DemoQ 0) = "q"; show (DemoQ i) = "q" ++ show i
show (DemoR 0) = "r"; show (DemoR i) = "r" ++ show i
show (DemoS 0) = "s"; show (DemoS i) = "s" ++ show i
data EpistM state = Mo
[state]
[Agent]
[(state,[DemoPrp])]
[(Agent,Erel state)]
[state] deriving (Eq)
instance Show state => Show (EpistM state) where
show (Mo worlds ags val accs points) = concat
[ "Mo\n "
, show worlds, "\n "
, show ags, "\n "
, show val, "\n "
, show accs, "\n "
, show points, "\n"
]
rel :: Show a => Agent -> EpistM a -> Erel a
rel ag (Mo _ _ _ rels _) = apply rels ag
initM :: (Num state, Enum state) => [Agent] -> [DemoPrp] -> EpistM state
initM ags props = Mo worlds ags val accs points where
worlds = [0..(2^k-1)]
k = length props
val = zip worlds (sortL (powerList props))
accs = [ (ag,[worlds]) | ag <- ags ]
points = worlds
powerList :: [a] -> [[a]]
powerList [] = [[]]
powerList (x:xs) =
powerList xs ++ map (x:) (powerList xs)
sortL :: Ord a => [[a]] -> [[a]]
sortL = sortBy
(\ xs ys -> if length xs < length ys
then LT
else if length xs > length ys
then GT
else compare xs ys)
data DemoForm a = Top
| Info a
| Prp DemoPrp
| Ng (DemoForm a)
| Conj [DemoForm a]
| Disj [DemoForm a]
| Kn Agent (DemoForm a)
| PA (DemoForm a) (DemoForm a)
| PAW (DemoForm a) (DemoForm a)
deriving (Eq,Ord,Show)
impl :: DemoForm a -> DemoForm a -> DemoForm a
impl form1 form2 = Disj [Ng form1, form2]
-- | semantics: truth at a world in a model
isTrueAt :: (Show state, Ord state) => EpistM state -> state -> DemoForm state -> Bool
isTrueAt _ _ Top = True
isTrueAt _ w (Info x) = w == x
isTrueAt (Mo _ _ val _ _) w (Prp p) = p `elem` apply val w
isTrueAt m w (Ng f) = not (isTrueAt m w f)
isTrueAt m w (Conj fs) = all (isTrueAt m w) fs
isTrueAt m w (Disj fs) = any (isTrueAt m w) fs
isTrueAt m w (Kn ag f) = all (flip (isTrueAt m) f) (bl (rel ag m) w)
isTrueAt m w (PA f g) = not (isTrueAt m w f) || isTrueAt (updPa m f) w g
isTrueAt m w (PAW f g) = not (isTrueAt m w f) || isTrueAt (updPaW m f) w g
-- | global truth in a model
isTrue :: Show a => Ord a => EpistM a -> DemoForm a -> Bool
isTrue m@(Mo _ _ _ _ points) f = all (\w -> isTrueAt m w f) points
-- | public announcement
updPa :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state
updPa m@(Mo states agents val rels actual) f = Mo states' agents val' rels' actual' where
states' = [ s | s <- states, isTrueAt m s f ]
val' = [ (s, ps) | (s,ps) <- val, s `elem` states' ]
rels' = [ (ag,restrict states' r) | (ag,r) <- rels ]
actual' = [ s | s <- actual, s `elem` states' ]
updsPa :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state
updsPa = foldl updPa
-- | public announcement-whether
updPaW :: (Show state, Ord state) => EpistM state -> DemoForm state -> EpistM state
updPaW m@(Mo states agents val rels actual) f = Mo states agents val rels' actual where
rels' = [ (ag, sortL $ concatMap split r) | (ag,r) <- rels ]
split ws = filter (/= []) [ filter (\w -> isTrueAt m w f) ws, filter (\w -> not $ isTrueAt m w f) ws ]
updsPaW :: (Show state, Ord state) => EpistM state -> [DemoForm state] -> EpistM state
updsPaW = foldl updPaW
-- | safe substitutions
sub :: Show a => [(DemoPrp,DemoForm a)] -> DemoPrp -> DemoForm a
sub subst p | p `elem` map fst subst = apply subst p
| otherwise = Prp p
-- | public factual change
updPc :: (Show state, Ord state) => [DemoPrp] -> EpistM state -> [(DemoPrp,DemoForm state)] -> EpistM state
updPc ps m@(Mo states agents _ rels actual) sb = Mo states agents val' rels actual where
val' = [ (s, [p | p <- ps, isTrueAt m s (sub sb p)]) | s <- states ]
updsPc :: Show state => Ord state => [DemoPrp] -> EpistM state
-> [[(DemoPrp,DemoForm state)]] -> EpistM state
updsPc ps = foldl (updPc ps)
updPi :: (state1 -> state2) -> EpistM state1 -> EpistM state2
updPi f (Mo states agents val rels actual) =
Mo
(map f states)
agents
(map (first f) val)
(map (second (map (map f))) rels)
(map f actual)
bTables :: Int -> [[Bool]]
bTables 0 = [[]]
bTables n = map (True:) (bTables (n-1)) ++ map (False:) (bTables (n-1))
initN :: Int -> EpistM [Bool]
initN n = Mo states agents [] rels points where
states = bTables n
agents = map Ag [1..n]
rels = [(Ag i, [[tab1++[True]++tab2,tab1++[False]++tab2] |
tab1 <- bTables (i-1),
tab2 <- bTables (n-i) ]) | i <- [1..n] ]
points = [False: replicate (n-1) True]
fatherN :: Int -> DemoForm [Bool]
fatherN n = Ng (Info (replicate n False))
kn :: Int -> Int -> DemoForm [Bool]
kn n i = Disj [Kn (Ag i) (Disj [ Info (tab1++[True]++tab2)
| tab1 <- bTables (i-1)
, tab2 <- bTables (n-i)
] ),
Kn (Ag i) (Disj [ Info (tab1++[False]++tab2)
| tab1 <- bTables (i-1)
, tab2 <- bTables (n-i)
] )
]
dont :: Int -> DemoForm [Bool]
dont n = Conj [Ng (kn n i) | i <- [1..n] ]
knowN :: Int -> DemoForm [Bool]
knowN n = Conj [kn n i | i <- [2..n] ]
solveN :: Int -> EpistM [Bool]
solveN n = updsPa (initN n) (f:istatements ++ [knowN n]) where
f = fatherN n
istatements = replicate (n-2) (dont n)
| jrclogic/SMCDEL | src/SMCDEL/Explicit/DEMO_S5.hs | gpl-2.0 | 6,106 | 0 | 15 | 1,788 | 2,950 | 1,535 | 1,415 | -1 | -1 |
module SpacialGameEnv.SGModelEnv where
import System.Random
import Data.Maybe
import qualified Data.Map as Map
import Control.Concurrent.STM.TVar
import Control.Monad.STM
import qualified PureAgentsConc as PA
data SGState = Defector | Cooperator deriving (Eq, Show)
data SGMsg = NoMsg deriving (Eq, Show)
data SGAgentState = SIRSAgentState {
sgCurrState :: SGState,
sgPrevState :: SGState
} deriving (Show)
type SGEnvironment = Map.Map PA.AgentId (TVar (Double, SGState))
type SGAgent = PA.Agent SGMsg SGAgentState SGEnvironment
type SGTransformer = PA.AgentTransformer SGMsg SGAgentState SGEnvironment
type SGSimHandle = PA.SimHandle SGMsg SGAgentState SGEnvironment
bParam :: Double
bParam = 1.9
sParam :: Double
sParam = 0.0
pParam :: Double
pParam = 0.0
rParam :: Double
rParam = 1.0
sgTransformer :: SGTransformer
sgTransformer (a, _) PA.Start = return a
sgTransformer ae (PA.Dt dt) = sgDt ae dt
sgTransformer (a, _) (PA.Message m) = return a
payoffWithEnv :: SGState -> PA.AgentId -> SGEnvironment -> STM Double
payoffWithEnv aSg eId e = do
(ePo, eSg) <- readTVar eVar
let po = payoff aSg eSg
return po
where
eVar = fromJust (Map.lookup eId e)
compareWithEnv :: STM (Double, SGState) -> PA.AgentId -> SGEnvironment -> STM (Double, SGState)
compareWithEnv bestPoSgSTM eId e = do
bestPoSg@(bestPo, _) <- bestPoSgSTM
envPoSg@(ePo, _) <- readTVar eVar
if (ePo > bestPo) then
return envPoSg
else
return bestPoSg
where
eVar = fromJust (Map.lookup eId e)
payoff :: SGState -> SGState -> Double
payoff Defector Defector = pParam
payoff Cooperator Defector = sParam
payoff Defector Cooperator = bParam
payoff Cooperator Cooperator = rParam
stmAdd :: STM Double -> STM Double -> STM Double
stmAdd xM yM = do
x <- xM
y <- yM
return (x+y)
sgDt :: (SGAgent, SGEnvironment) -> Double -> STM SGAgent
sgDt (a, e) dt = do
localPayoff <- foldl (\payoffSum nId -> stmAdd payoffSum (payoffWithEnv aSg nId e)) (return 0.0) neighbourIds
(bestPayoff, bestState) <- foldl (\best nId -> compareWithEnv best nId e) (return (localPayoff, aSg)) neighbourIds
let a' = PA.updateState a (\s -> s { sgCurrState = bestState, sgPrevState = aSg })
let eVar = fromJust (Map.lookup aid e)
writeTVar eVar (localPayoff, bestState)
return a'
where
aid = PA.agentId a
aSg = sgCurrState (PA.state a)
neighbourIds = Map.keys (PA.neighbours a)
sgEnvironmentFromAgents :: [SGAgent] -> STM SGEnvironment
sgEnvironmentFromAgents as = foldl insertCell (return Map.empty) as
where
insertCell :: STM (Map.Map PA.AgentId (TVar (Double, SGState))) -> SGAgent -> STM (Map.Map PA.AgentId (TVar (Double, SGState)))
insertCell m a = do
let aid = PA.agentId a
let tup = (0.0, (sgCurrState (PA.state a)))
cVar <- newTVar tup
m' <- m
return (Map.insert aid cVar m')
createRandomSGAgents :: StdGen -> (Int, Int) -> Double -> STM ([SGAgent], StdGen)
createRandomSGAgents gInit cells@(x,y) p = do
as <- mapM (\idx -> PA.createAgent idx (randStates !! idx) sgTransformer) [0..n-1]
let as' = map (\a -> PA.addNeighbours a (agentNeighbours a as cells) ) as
return (as', g')
where
n = x * y
(randStates, g') = createRandomStates gInit n p
createRandomStates :: StdGen -> Int -> Double -> ([SGAgentState], StdGen)
createRandomStates g 0 p = ([], g)
createRandomStates g n p = (rands, g'')
where
(randState, g') = randomAgentState g p
(ras, g'') = createRandomStates g' (n-1) p
rands = randState : ras
randomAgentState :: StdGen -> Double -> (SGAgentState, StdGen)
randomAgentState g p = (SIRSAgentState{ sgCurrState = s, sgPrevState = s }, g')
where
(isDefector, g') = randomThresh g p
(g'', _) = split g'
s = if isDefector then
Defector
else
Cooperator
randomThresh :: StdGen -> Double -> (Bool, StdGen)
randomThresh g p = (flag, g')
where
(thresh, g') = randomR(0.0, 1.0) g
flag = thresh <= p
agentNeighbours :: SGAgent -> [SGAgent] -> (Int, Int) -> [SGAgent]
agentNeighbours a as cells = filter (\a' -> any (==(agentToCell a' cells)) neighbourCells ) as
where
aCell = agentToCell a cells
neighbourCells = neighbours aCell
agentToCell :: SGAgent -> (Int, Int) -> (Int, Int)
agentToCell a (xCells, yCells) = (ax, ay)
where
aid = PA.agentId a
ax = mod aid yCells
ay = floor((fromIntegral aid) / (fromIntegral xCells))
neighbourhood :: [(Int, Int)]
neighbourhood = [topLeft, top, topRight,
left, center, right,
bottomLeft, bottom, bottomRight]
where
topLeft = (-1, -1)
top = (0, -1)
topRight = (1, -1)
left = (-1, 0)
center = (0, 0)
right = (1, 0)
bottomLeft = (-1, 1)
bottom = (0, 1)
bottomRight = (1, 1)
neighbours :: (Int, Int) -> [(Int, Int)]
neighbours (x,y) = map (\(x', y') -> (x+x', y+y')) neighbourhood
| thalerjonathan/phd | public/ArtIterating/code/haskell/PureAgentsConc/src/SpacialGameEnv/SGModelEnv.hs | gpl-3.0 | 5,769 | 0 | 17 | 1,937 | 1,963 | 1,062 | 901 | 121 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Jumpie.GameObject where
import Jumpie.Player
import Jumpie.SensorLine
import Jumpie.Particle
import Jumpie.MoveableObject
import ClassyPrelude hiding(Real)
import Jumpie.Platform
import Control.Lens.TH
data GameObject = ObjectPlayer Player
| ObjectPlatform Platform
| ObjectSensorLine SensorLine
| ObjectParticle Particle
deriving(Show)
$(makePrisms ''GameObject)
instance MoveableObject GameObject where
moveObject (ObjectPlayer p) v = ObjectPlayer (moveObject p v)
moveObject (ObjectPlatform p) v = ObjectPlatform (moveObject p v)
moveObject (ObjectSensorLine p) v = ObjectSensorLine (moveObject p v)
moveObject (ObjectParticle p) v = ObjectParticle (moveObject p v)
maybePlatform :: GameObject -> Maybe Platform
maybePlatform (ObjectPlatform b) = Just b
maybePlatform _ = Nothing
isPlatform :: GameObject -> Bool
isPlatform (ObjectPlatform _) = True
isPlatform _ = False
isPlayer :: GameObject -> Bool
isPlayer (ObjectPlayer _) = True
isPlayer _ = False
isSensorLine :: GameObject -> Bool
isSensorLine (ObjectSensorLine _) = True
isSensorLine _ = False
isParticle :: GameObject -> Bool
isParticle (ObjectParticle _) = True
isParticle _ = False
| pmiddend/jumpie | lib/Jumpie/GameObject.hs | gpl-3.0 | 1,373 | 0 | 8 | 266 | 369 | 193 | 176 | 37 | 1 |
{- Copyright (C) 2009 John Millikin <jmillikin@gmail.com>
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 3 of the License, or
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, see <http://www.gnu.org/licenses/>.
-}
module Network.Protocol.XMPP.JID (
JID(..)
,JIDNode
,JIDDomain
,JIDResource
,jidNodeStr
,jidDomainStr
,jidResourceStr
,mkJIDNode
,mkJIDDomain
,mkJIDResource
,mkJID
,jidNode
,jidDomain
,jidResource
,jidParse
,jidFormat
) where
data JID = JID (Maybe JIDNode) JIDDomain (Maybe JIDResource)
deriving (Eq, Show)
newtype JIDNode = JIDNode String
deriving (Eq, Show)
newtype JIDDomain = JIDDomain String
deriving (Eq, Show)
newtype JIDResource = JIDResource String
deriving (Eq, Show)
jidNodeStr :: JIDNode -> String
jidNodeStr (JIDNode s) = s
jidDomainStr :: JIDDomain -> String
jidDomainStr (JIDDomain s) = s
jidResourceStr :: JIDResource -> String
jidResourceStr (JIDResource s) = s
mkJIDNode :: String -> Maybe JIDNode
mkJIDNode "" = Nothing
mkJIDNode s = Just (JIDNode s) -- TODO: stringprep, validation
mkJIDDomain :: String -> Maybe JIDDomain
mkJIDDomain "" = Nothing
mkJIDDomain s = Just (JIDDomain s) -- TODO: stringprep, validation
mkJIDResource :: String -> Maybe JIDResource
mkJIDResource "" = Nothing
mkJIDResource s = Just (JIDResource s) -- TODO: stringprep, validation
mkJID :: String -> String -> String -> Maybe JID
mkJID nodeStr domainStr resourceStr = let
node = mkJIDNode nodeStr
resource = mkJIDResource resourceStr
in do
domain <- mkJIDDomain domainStr
Just (JID node domain resource)
jidNode :: JID -> String
jidNode (JID x _ _) = maybe "" jidNodeStr x
jidDomain :: JID -> String
jidDomain (JID _ x _) = jidDomainStr x
jidResource :: JID -> String
jidResource (JID _ _ x) = maybe "" jidResourceStr x
-- TODO: validate input according to RFC 3920, section 3.1
jidParse :: String -> Maybe JID
jidParse s = let
(nodeStr, postNode) = if '@' `elem` s then split s '@' else ("", s)
(domainStr, resourceStr) = if '/' `elem` postNode then split postNode '/' else (postNode, "")
in mkJID nodeStr domainStr resourceStr
jidFormat :: JID -> String
jidFormat (JID node (JIDDomain domain) resource) = let
nodeStr = maybe "" (\(JIDNode s) -> s ++ "@") node
resourceStr = maybe "" (\(JIDResource s) -> "/" ++ s) resource
in concat [nodeStr, domain, resourceStr]
split :: (Eq a) => [a] -> a -> ([a], [a])
split xs final = let
(before, rawAfter) = span (/= final) xs
after = safeTail rawAfter
in (before, after)
safeTail :: [a] -> [a]
safeTail [] = []
safeTail (_:xs) = xs
| astro/network-protocol-xmpp | Network/Protocol/XMPP/JID.hs | gpl-3.0 | 3,035 | 16 | 13 | 576 | 882 | 472 | 410 | 71 | 3 |
module Prelude ( module ClassyPrelude
) where
import ClassyPrelude
| glittershark/stegosaurus | Prelude.hs | gpl-3.0 | 83 | 0 | 4 | 25 | 13 | 9 | 4 | 2 | 0 |
-- Copyright (C) 2013 Che-Liang Chiou.
module Screen.Utils (
isCjkCodePoint,
) where
-- Chapter 12, East Asian Scripts, The Unicode Standard, Version 5.0.
-- Table 12-2. Blocks Containing Han Ideographs
isCjkCodePoint :: Char -> Bool
isCjkCodePoint c =
'\x4e00' <= c && c <= '\x9fff' ||
'\x3400' <= c && c <= '\x4dff' ||
'\x20000' <= c && c <= '\x2a6df' ||
'\xf900' <= c && c <= '\xfaff' ||
'\x2f800' <= c && c <= '\x2fa1f'
| clchiou/gwab | lib/Screen/Utils.hs | gpl-3.0 | 457 | 0 | 23 | 110 | 108 | 58 | 50 | 9 | 1 |
{-|
Description : Root of test suite
-}
module Main (main) where
import qualified Control.Applicative as Applicative
import qualified Data.Set as Set
import qualified Language.Haskell.Formatter.Internal.Tests as Internal
import qualified Language.Haskell.Formatter.Tests as Formatter
import qualified Language.Haskell.Formatter.Toolkit.TestTool as TestTool
import qualified System.FilePath as FilePath
import qualified System.FilePath.Find as Find
import qualified Test.Tasty as Tasty
main :: IO ()
main = sequence tests >>= Tasty.defaultMain . Tasty.testGroup name
where name = "Root"
tests :: [IO Tasty.TestTree]
tests
= [sourceCodeStandardTests, documentationTests, Formatter.tests,
Internal.tests]
sourceCodeStandardTests :: IO Tasty.TestTree
sourceCodeStandardTests
= createTestTree TestTool.standardSourceCodeTest Find.always name
where name = "Source code standard"
createTestTree ::
(FilePath -> Tasty.TestTree) ->
Find.RecursionPredicate -> Tasty.TestName -> IO Tasty.TestTree
createTestTree test recurse rootName
= do files <- concat Applicative.<$> mapM (collectSourceFiles recurse) roots
return . Tasty.testGroup rootName $ fmap test files
collectSourceFiles :: Find.RecursionPredicate -> FilePath -> IO [FilePath]
collectSourceFiles recurse = Find.find recurse isSourceFile
where isSourceFile = isFile Find.&&? hasSourceExtension
isFile = Find.fileType Find.==? Find.RegularFile
hasSourceExtension = fmap (`Set.member` sourceExtensions) Find.extension
sourceExtensions = Set.fromList [".hs", ".lhs"]
roots :: [FilePath]
roots
= ["src" FilePath.</> "library", "src" FilePath.</> "executable",
"testsuite" FilePath.</> "src"]
documentationTests :: IO Tasty.TestTree
documentationTests
= createTestTree (TestTool.documentationTest roots) noRecursion name
where noRecursion = Find.depth Find.==? rootDepth
rootDepth = 0
name = "Documentation (doctest)"
| evolutics/haskell-formatter | testsuite/src/Main.hs | gpl-3.0 | 1,976 | 0 | 11 | 317 | 477 | 271 | 206 | 42 | 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.Books.Volumes.UserUploaded.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return a list of books uploaded by the current user.
--
-- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.volumes.useruploaded.list@.
module Network.Google.Resource.Books.Volumes.UserUploaded.List
(
-- * REST Resource
VolumesUserUploadedListResource
-- * Creating a Request
, volumesUserUploadedList
, VolumesUserUploadedList
-- * Request Lenses
, vuulProcessingState
, vuulXgafv
, vuulUploadProtocol
, vuulLocale
, vuulAccessToken
, vuulUploadType
, vuulVolumeId
, vuulSource
, vuulStartIndex
, vuulMaxResults
, vuulCallback
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.volumes.useruploaded.list@ method which the
-- 'VolumesUserUploadedList' request conforms to.
type VolumesUserUploadedListResource =
"books" :>
"v1" :>
"volumes" :>
"useruploaded" :>
QueryParams "processingState"
VolumesUserUploadedListProcessingState
:>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "locale" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParams "volumeId" Text :>
QueryParam "source" Text :>
QueryParam "startIndex" (Textual Word32) :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] Volumes
-- | Return a list of books uploaded by the current user.
--
-- /See:/ 'volumesUserUploadedList' smart constructor.
data VolumesUserUploadedList =
VolumesUserUploadedList'
{ _vuulProcessingState :: !(Maybe [VolumesUserUploadedListProcessingState])
, _vuulXgafv :: !(Maybe Xgafv)
, _vuulUploadProtocol :: !(Maybe Text)
, _vuulLocale :: !(Maybe Text)
, _vuulAccessToken :: !(Maybe Text)
, _vuulUploadType :: !(Maybe Text)
, _vuulVolumeId :: !(Maybe [Text])
, _vuulSource :: !(Maybe Text)
, _vuulStartIndex :: !(Maybe (Textual Word32))
, _vuulMaxResults :: !(Maybe (Textual Word32))
, _vuulCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VolumesUserUploadedList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vuulProcessingState'
--
-- * 'vuulXgafv'
--
-- * 'vuulUploadProtocol'
--
-- * 'vuulLocale'
--
-- * 'vuulAccessToken'
--
-- * 'vuulUploadType'
--
-- * 'vuulVolumeId'
--
-- * 'vuulSource'
--
-- * 'vuulStartIndex'
--
-- * 'vuulMaxResults'
--
-- * 'vuulCallback'
volumesUserUploadedList
:: VolumesUserUploadedList
volumesUserUploadedList =
VolumesUserUploadedList'
{ _vuulProcessingState = Nothing
, _vuulXgafv = Nothing
, _vuulUploadProtocol = Nothing
, _vuulLocale = Nothing
, _vuulAccessToken = Nothing
, _vuulUploadType = Nothing
, _vuulVolumeId = Nothing
, _vuulSource = Nothing
, _vuulStartIndex = Nothing
, _vuulMaxResults = Nothing
, _vuulCallback = Nothing
}
-- | The processing state of the user uploaded volumes to be returned.
vuulProcessingState :: Lens' VolumesUserUploadedList [VolumesUserUploadedListProcessingState]
vuulProcessingState
= lens _vuulProcessingState
(\ s a -> s{_vuulProcessingState = a})
. _Default
. _Coerce
-- | V1 error format.
vuulXgafv :: Lens' VolumesUserUploadedList (Maybe Xgafv)
vuulXgafv
= lens _vuulXgafv (\ s a -> s{_vuulXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
vuulUploadProtocol :: Lens' VolumesUserUploadedList (Maybe Text)
vuulUploadProtocol
= lens _vuulUploadProtocol
(\ s a -> s{_vuulUploadProtocol = a})
-- | ISO-639-1 language and ISO-3166-1 country code. Ex: \'en_US\'. Used for
-- generating recommendations.
vuulLocale :: Lens' VolumesUserUploadedList (Maybe Text)
vuulLocale
= lens _vuulLocale (\ s a -> s{_vuulLocale = a})
-- | OAuth access token.
vuulAccessToken :: Lens' VolumesUserUploadedList (Maybe Text)
vuulAccessToken
= lens _vuulAccessToken
(\ s a -> s{_vuulAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
vuulUploadType :: Lens' VolumesUserUploadedList (Maybe Text)
vuulUploadType
= lens _vuulUploadType
(\ s a -> s{_vuulUploadType = a})
-- | The ids of the volumes to be returned. If not specified all that match
-- the processingState are returned.
vuulVolumeId :: Lens' VolumesUserUploadedList [Text]
vuulVolumeId
= lens _vuulVolumeId (\ s a -> s{_vuulVolumeId = a})
. _Default
. _Coerce
-- | String to identify the originator of this request.
vuulSource :: Lens' VolumesUserUploadedList (Maybe Text)
vuulSource
= lens _vuulSource (\ s a -> s{_vuulSource = a})
-- | Index of the first result to return (starts at 0)
vuulStartIndex :: Lens' VolumesUserUploadedList (Maybe Word32)
vuulStartIndex
= lens _vuulStartIndex
(\ s a -> s{_vuulStartIndex = a})
. mapping _Coerce
-- | Maximum number of results to return.
vuulMaxResults :: Lens' VolumesUserUploadedList (Maybe Word32)
vuulMaxResults
= lens _vuulMaxResults
(\ s a -> s{_vuulMaxResults = a})
. mapping _Coerce
-- | JSONP
vuulCallback :: Lens' VolumesUserUploadedList (Maybe Text)
vuulCallback
= lens _vuulCallback (\ s a -> s{_vuulCallback = a})
instance GoogleRequest VolumesUserUploadedList where
type Rs VolumesUserUploadedList = Volumes
type Scopes VolumesUserUploadedList =
'["https://www.googleapis.com/auth/books"]
requestClient VolumesUserUploadedList'{..}
= go (_vuulProcessingState ^. _Default) _vuulXgafv
_vuulUploadProtocol
_vuulLocale
_vuulAccessToken
_vuulUploadType
(_vuulVolumeId ^. _Default)
_vuulSource
_vuulStartIndex
_vuulMaxResults
_vuulCallback
(Just AltJSON)
booksService
where go
= buildClient
(Proxy :: Proxy VolumesUserUploadedListResource)
mempty
| brendanhay/gogol | gogol-books/gen/Network/Google/Resource/Books/Volumes/UserUploaded/List.hs | mpl-2.0 | 7,279 | 0 | 23 | 1,813 | 1,181 | 677 | 504 | 167 | 1 |
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------------
-- |
-- Module : Crypto.Noise.Cipher.AESGCM
-- Maintainer : John Galt <jgalt@centromere.net>
-- Stability : experimental
-- Portability : POSIX
module Crypto.Noise.Cipher.AESGCM
( -- * Types
AESGCM
) where
import Crypto.Error (throwCryptoError)
import Crypto.Cipher.AES (AES256)
import Crypto.Cipher.Types (AuthTag(..), AEADMode(AEAD_GCM), cipherInit,
aeadInit, aeadSimpleEncrypt, aeadSimpleDecrypt)
import Data.ByteArray (ByteArray, Bytes, ScrubbedBytes, convert, take,
drop, length, copyAndFreeze, zero, append,
replicate)
import Data.Word (Word8)
import Foreign.Ptr
import Foreign.Storable
import Prelude hiding (drop, length, replicate, take)
import Crypto.Noise.Cipher
-- | Represents the AES256 cipher with GCM for AEAD.
data AESGCM
instance Cipher AESGCM where
newtype Ciphertext AESGCM = CTAES (AuthTag, ScrubbedBytes)
newtype SymmetricKey AESGCM = SKAES ScrubbedBytes
newtype Nonce AESGCM = NAES Bytes
cipherName _ = "AESGCM"
cipherEncrypt = encrypt
cipherDecrypt = decrypt
cipherZeroNonce = zeroNonce
cipherMaxNonce = maxNonce
cipherIncNonce = incNonce
cipherNonceEq = nonceEq
cipherNonceCmp = nonceCmp
cipherBytesToSym = bytesToSym
cipherSymToBytes = symToBytes
cipherTextToBytes = ctToBytes
cipherBytesToText = bytesToCt
encrypt :: SymmetricKey AESGCM
-> Nonce AESGCM
-> AssocData
-> Plaintext
-> Ciphertext AESGCM
encrypt (SKAES k) (NAES n) ad plaintext =
CTAES $ aeadSimpleEncrypt aead ad plaintext 16
where
state = throwCryptoError . cipherInit $ k :: AES256
aead = throwCryptoError $ aeadInit AEAD_GCM state n
decrypt :: SymmetricKey AESGCM
-> Nonce AESGCM
-> AssocData
-> Ciphertext AESGCM
-> Maybe Plaintext
decrypt (SKAES k) (NAES n) ad (CTAES (authTag, ct)) =
aeadSimpleDecrypt aead ad ct authTag
where
state = throwCryptoError . cipherInit $ k :: AES256
aead = throwCryptoError $ aeadInit AEAD_GCM state n
zeroNonce :: Nonce AESGCM
zeroNonce = NAES . zero $ 12
maxNonce :: Nonce AESGCM
maxNonce = NAES $ zero 4 `append` replicate 8 255
incNonce :: Nonce AESGCM
-> Nonce AESGCM
incNonce (NAES n) = NAES $ ivAdd n 1
nonceEq :: Nonce AESGCM
-> Nonce AESGCM
-> Bool
nonceEq (NAES a) (NAES b) = a == b
nonceCmp :: Nonce AESGCM
-> Nonce AESGCM
-> Ordering
nonceCmp (NAES a) (NAES b) = compare a b
bytesToSym :: ScrubbedBytes
-> SymmetricKey AESGCM
bytesToSym = SKAES . take 32
symToBytes :: SymmetricKey AESGCM
-> ScrubbedBytes
symToBytes (SKAES sk) = sk
ctToBytes :: Ciphertext AESGCM
-> ScrubbedBytes
ctToBytes (CTAES (a, ct)) = ct `mappend` convert a
bytesToCt :: ScrubbedBytes
-> Ciphertext AESGCM
bytesToCt bytes =
CTAES ( AuthTag . convert $ drop (length bytes - 16) bytes
, take (length bytes - 16) bytes
)
-- Adapted from cryptonite's Crypto.Cipher.Types.Block module.
ivAdd :: ByteArray b
=> b
-> Int
-> b
ivAdd b i = copy b
where copy :: ByteArray bs => bs -> bs
copy bs = copyAndFreeze bs $ loop i (length bs - 1)
loop :: Int -> Int -> Ptr Word8 -> IO ()
loop acc ofs p
| ofs < 0 = return ()
| otherwise = do
v <- peek (p `plusPtr` ofs) :: IO Word8
let accv = acc + fromIntegral v
(hi,lo) = accv `divMod` 256
poke (p `plusPtr` ofs) (fromIntegral lo :: Word8)
loop hi (ofs - 1) p
| centromere/cacophony | src/Crypto/Noise/Cipher/AESGCM.hs | unlicense | 3,752 | 0 | 14 | 1,059 | 1,078 | 571 | 507 | -1 | -1 |
#!/usr/bin/env runhaskell
module Main where
solve n 1 = 1
solve n x = d + 10 * (solve n (x `div` 10 + d * n))
where d = x `mod` 10
main = do
print (solve 2 2)
print (solve 3 3)
print (solve 4 4)
print (solve 5 5)
print (solve 6 6)
print (solve 7 7)
print (solve 8 8)
print (solve 9 9)
| sergev/vak-opensource | languages/haskell/problem-xn.hs | apache-2.0 | 364 | 0 | 11 | 147 | 188 | 91 | 97 | 13 | 1 |
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- 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 GUI.Widget.LayoutWidget
(
LayoutWidget,
makeLayoutWidget,
makeLayoutWidgetStatic,
module GUI.Widget.ChildWidget,
module GUI.Widget.LayoutWidget.StaticLayout,
) where
import MyPrelude
import GUI.Widget
import GUI.Widget.Output
import GUI.Widget.Helpers
import GUI.Widget.ChildWidget
import GUI.Widget.LayoutWidget.StaticLayout
data LayoutWidget a =
LayoutWidget
{
layoutElements :: ![LayoutElement a],
layoutShape :: !GUIShape
}
data LayoutElement a =
LayoutElement
{
lePos :: !GUIPos,
leChild :: !(ChildWidget a)
}
instance Widget LayoutWidget where
widgetShape = \gd gs w -> layoutShape w
widgetBegin = layoutBegin
widgetEatInput = layoutEatInput
widgetIterate = layoutIterate
--------------------------------------------------------------------------------
-- Widget structure
layoutBegin :: GUIData -> GUIState -> LayoutWidget a -> IO (LayoutWidget a)
layoutBegin gd gs layout = do
let es = layoutElements layout
es' <- mapESBegin es
return $ layout { layoutElements = es' }
where
mapESBegin es = case es of
[] -> return []
(e:es) -> do
child' <- widgetBegin gd gs (leChild e)
es' <- mapESBegin es
return (e { leChild = child' } : es')
layoutEatInput :: GUIData -> GUIState -> LayoutWidget a -> WidgetInput -> LayoutWidget a
layoutEatInput gd gs layout wi =
let es' = mapESEatInput (layoutElements layout)
in layout { layoutElements = es' }
where
mapESEatInput es = case es of
[] ->
[]
(e:es) ->
let child = leChild e
pos = lePos e
shape = widgetShape gd gs child
in case gdgsIsInputInside gd gs pos shape wi of
Nothing ->
(e:mapESEatInput es)
Just gs' ->
let child' = widgetEatInput gd gs' child wi
in (e { leChild = child' } : mapESEatInput es)
--in (e { leChild = child' } : es)
layoutIterate :: GUIData -> GUIState -> LayoutWidget a -> a -> IO (LayoutWidget a, a)
layoutIterate gd gs layout a = do
-- iterate children
let es = layoutElements layout
(es', a') <- mapESIterate gd gs es a
return (layout { layoutElements = es' }, a')
where
mapESIterate gd gs es a = case es of
[] -> return ([], a)
(e:es) -> do
-- iterate child
gs' <- plusPos gd gs (lePos e)
(child', a') <- widgetIterate gd gs' (leChild e) a
resetPos gd gs
-- iterate children
(es', a'') <- mapESIterate gd gs es a'
return (e { leChild = child' } : es', a'')
--------------------------------------------------------------------------------
-- make
makeLayoutWidget :: GUIData -> GUIShape -> [(GUIPos, ChildWidget a)] -> LayoutWidget a
makeLayoutWidget gd shape = \pws ->
LayoutWidget
{
layoutShape = shape,
layoutElements = map (\(pos, w) -> LayoutElement pos w) pws
}
makeLayoutWidgetStatic :: StaticLayout layout => GUIData -> layout a -> LayoutWidget a
makeLayoutWidgetStatic gd = \slayout ->
makeLayoutWidget gd (slayoutShape gd slayout) (slayoutChildren gd slayout)
| karamellpelle/MEnv | source/GUI/Widget/LayoutWidget.hs | bsd-2-clause | 4,916 | 0 | 20 | 1,436 | 991 | 528 | 463 | 83 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module WebSocket (process) where
import Text.Printf
import Control.Monad (forever)
import qualified Control.Concurrent.Chan as Chan
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Network.WebSockets as WS
process :: Chan.Chan String -> String -> String -> Int -> IO ()
process chan name addr port = WS.runServer addr port (app chan name)
app :: Chan.Chan String -> String -> WS.ServerApp
app chan name pendingConn = forever $ do
conn <- WS.acceptRequest pendingConn
putStrLn "Received connection"
forever $ do
msg <- Chan.readChan chan
putStrLn $ printf "WebSocket (%s) sending %s to browser" name msg
WS.sendDataMessage conn (WS.Text $ BS.pack msg)
| christianlavoie/haskell-midi | src-hs/WebSocket.hs | bsd-2-clause | 746 | 0 | 15 | 142 | 225 | 117 | 108 | 17 | 1 |
-- http://www.codewars.com/kata/542c0f198e077084c0000c2e
module Divisors where
divisors :: Integral a => a -> Int
divisors x = length $ filter ((==0).(x`mod`)) [1..x] | Bodigrim/katas | src/haskell/7-Find-divisors-number.hs | bsd-2-clause | 167 | 1 | 9 | 21 | 60 | 35 | 25 | 3 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Build
-- Copyright : Isaac Jones 2003-2005,
-- Ross Paterson 2006,
-- Duncan Coutts 2007-2008, 2012
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This is the entry point to actually building the modules in a package. It
-- doesn't actually do much itself, most of the work is delegated to
-- compiler-specific actions. It does do some non-compiler specific bits like
-- running pre-processors.
--
module Distribution.Simple.Build (
build, repl,
startInterpreter,
initialBuildSteps,
writeAutogenFiles,
) where
import Distribution.Package
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.GHCJS as GHCJS
import qualified Distribution.Simple.JHC as JHC
import qualified Distribution.Simple.LHC as LHC
import qualified Distribution.Simple.UHC as UHC
import qualified Distribution.Simple.HaskellSuite as HaskellSuite
import qualified Distribution.Simple.Build.Macros as Build.Macros
import qualified Distribution.Simple.Build.PathsModule as Build.PathsModule
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.PackageDescription hiding (Flag)
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Setup
import Distribution.Simple.BuildTarget
import Distribution.Simple.PreProcess
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program.Types
import Distribution.Simple.Program.Db
import Distribution.Simple.BuildPaths
import Distribution.Simple.Register
import Distribution.Simple.Test.LibV09
import Distribution.Simple.Utils
import Distribution.System
import Distribution.Text
import Distribution.Verbosity
import qualified Data.Set as Set
import Data.List
( intersect )
import Control.Monad
( when, unless )
import System.FilePath
( (</>), (<.>) )
import System.Directory
( getCurrentDirectory )
-- -----------------------------------------------------------------------------
-- |Build the libraries and executables in this package.
build :: PackageDescription -- ^ Mostly information from the .cabal file
-> LocalBuildInfo -- ^ Configuration information
-> BuildFlags -- ^ Flags that the user passed to build
-> [ PPSuffixHandler ] -- ^ preprocessors to run before compiling
-> IO ()
build pkg_descr lbi flags suffixes
| fromFlag (buildAssumeDepsUpToDate flags) = do
-- TODO: if checkBuildTargets ignores a target we may accept
-- a --assume-deps-up-to-date with multiple arguments. Arguably, we should
-- error early in this case.
targets <- readBuildTargets pkg_descr (buildArgs flags)
(cname, _) <- checkBuildTargets verbosity pkg_descr targets >>= \r -> case r of
[] -> die "In --assume-deps-up-to-date mode you must specify a target"
[target'] -> return target'
_ -> die "In --assume-deps-up-to-date mode you can only build a single target"
-- NB: do NOT 'createInternalPackageDB'; we don't want to delete it.
-- But this means we have to be careful about unregistering
-- ourselves.
let dbPath = internalPackageDBPath lbi distPref
internalPackageDB = SpecificPackageDB dbPath
clbi = getComponentLocalBuildInfo lbi cname
comp = getComponent pkg_descr cname
-- TODO: do we need to unregister libraries? In any case, this would
-- need to be done in the buildLib functionality.
-- Do the build
initialBuildSteps distPref pkg_descr lbi clbi verbosity
let bi = componentBuildInfo comp
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
buildComponent verbosity (buildNumJobs flags) pkg_descr
lbi' suffixes comp clbi distPref
| otherwise = do
targets <- readBuildTargets pkg_descr (buildArgs flags)
targets' <- checkBuildTargets verbosity pkg_descr targets
let componentsToBuild = componentsInBuildOrder lbi (map fst targets')
info verbosity $ "Component build order: "
++ intercalate ", " (map (showComponentName . componentLocalName) componentsToBuild)
when (null targets) $
-- Only bother with this message if we're building the whole package
setupMessage verbosity "Building" (packageId pkg_descr)
internalPackageDB <- createInternalPackageDB verbosity lbi distPref
-- TODO: we're computing this twice, do it once!
withComponentsInBuildOrder pkg_descr lbi (map fst targets') $ \comp clbi -> do
initialBuildSteps distPref pkg_descr lbi clbi verbosity
let bi = componentBuildInfo comp
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
buildComponent verbosity (buildNumJobs flags) pkg_descr
lbi' suffixes comp clbi distPref
where
distPref = fromFlag (buildDistPref flags)
verbosity = fromFlag (buildVerbosity flags)
repl :: PackageDescription -- ^ Mostly information from the .cabal file
-> LocalBuildInfo -- ^ Configuration information
-> ReplFlags -- ^ Flags that the user passed to build
-> [ PPSuffixHandler ] -- ^ preprocessors to run before compiling
-> [String]
-> IO ()
repl pkg_descr lbi flags suffixes args = do
let distPref = fromFlag (replDistPref flags)
verbosity = fromFlag (replVerbosity flags)
targets <- readBuildTargets pkg_descr args
targets' <- case targets of
[] -> return $ take 1 [ componentName c
| c <- pkgEnabledComponents pkg_descr ]
[target] -> fmap (map fst) (checkBuildTargets verbosity pkg_descr [target])
_ -> die $ "The 'repl' command does not support multiple targets at once."
let componentsToBuild = componentsInBuildOrder lbi targets'
componentForRepl = last componentsToBuild
debug verbosity $ "Component build order: "
++ intercalate ", "
[ showComponentName (componentLocalName clbi) | clbi <- componentsToBuild ]
internalPackageDB <- createInternalPackageDB verbosity lbi distPref
let lbiForComponent comp lbi' =
lbi' {
withPackageDB = withPackageDB lbi ++ [internalPackageDB],
withPrograms = addInternalBuildTools pkg_descr lbi'
(componentBuildInfo comp) (withPrograms lbi')
}
-- build any dependent components
sequence_
[ do let cname = componentLocalName clbi
comp = getComponent pkg_descr cname
lbi' = lbiForComponent comp lbi
initialBuildSteps distPref pkg_descr lbi clbi verbosity
buildComponent verbosity NoFlag
pkg_descr lbi' suffixes comp clbi distPref
| clbi <- init componentsToBuild ]
-- REPL for target components
let clbi = componentForRepl
cname = componentLocalName clbi
comp = getComponent pkg_descr cname
lbi' = lbiForComponent comp lbi
initialBuildSteps distPref pkg_descr lbi clbi verbosity
replComponent verbosity pkg_descr lbi' suffixes comp clbi distPref
-- | Start an interpreter without loading any package files.
startInterpreter :: Verbosity -> ProgramDb -> Compiler -> Platform
-> PackageDBStack -> IO ()
startInterpreter verbosity programDb comp platform packageDBs =
case compilerFlavor comp of
GHC -> GHC.startInterpreter verbosity programDb comp platform packageDBs
GHCJS -> GHCJS.startInterpreter verbosity programDb comp platform packageDBs
_ -> die "A REPL is not supported with this compiler."
buildComponent :: Verbosity
-> Flag (Maybe Int)
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> Component
-> ComponentLocalBuildInfo
-> FilePath
-> IO ()
buildComponent verbosity numJobs pkg_descr lbi suffixes
comp@(CLib lib) clbi distPref = do
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
info verbosity $ "Building library " ++ libName lib ++ "..."
let libbi = libBuildInfo lib
lib' = lib { libBuildInfo = addExtraCSources libbi extras }
buildLib verbosity numJobs pkg_descr lbi lib' clbi
-- Register the library in-place, so exes can depend
-- on internally defined libraries.
pwd <- getCurrentDirectory
let -- The in place registration uses the "-inplace" suffix, not an ABI hash
installedPkgInfo = inplaceInstalledPackageInfo pwd distPref pkg_descr
(AbiHash "") lib' lbi clbi
registerPackage verbosity (compiler lbi) (withPrograms lbi) HcPkg.MultiInstance
(withPackageDB lbi) installedPkgInfo
buildComponent verbosity numJobs pkg_descr lbi suffixes
comp@(CExe exe) clbi _ = do
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
info verbosity $ "Building executable " ++ exeName exe ++ "..."
let ebi = buildInfo exe
exe' = exe { buildInfo = addExtraCSources ebi extras }
buildExe verbosity numJobs pkg_descr lbi exe' clbi
buildComponent verbosity numJobs pkg_descr lbi suffixes
comp@(CTest test@TestSuite { testInterface = TestSuiteExeV10{} })
clbi _distPref = do
let exe = testSuiteExeV10AsExe test
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
info verbosity $ "Building test suite " ++ testName test ++ "..."
let ebi = buildInfo exe
exe' = exe { buildInfo = addExtraCSources ebi extras }
buildExe verbosity numJobs pkg_descr lbi exe' clbi
buildComponent verbosity numJobs pkg_descr lbi0 suffixes
comp@(CTest
test@TestSuite { testInterface = TestSuiteLibV09{} })
clbi -- This ComponentLocalBuildInfo corresponds to a detailed
-- test suite and not a real component. It should not
-- be used, except to construct the CLBIs for the
-- library and stub executable that will actually be
-- built.
distPref = do
pwd <- getCurrentDirectory
let (pkg, lib, libClbi, lbi, ipi, exe, exeClbi) =
testSuiteLibV09AsLibAndExe pkg_descr test clbi lbi0 distPref pwd
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
info verbosity $ "Building test suite " ++ testName test ++ "..."
buildLib verbosity numJobs pkg lbi lib libClbi
-- NB: need to enable multiple instances here, because on 7.10+
-- the package name is the same as the library, and we still
-- want the registration to go through.
registerPackage verbosity (compiler lbi) (withPrograms lbi) HcPkg.MultiInstance
(withPackageDB lbi) ipi
let ebi = buildInfo exe
exe' = exe { buildInfo = addExtraCSources ebi extras }
buildExe verbosity numJobs pkg_descr lbi exe' exeClbi
buildComponent _ _ _ _ _
(CTest TestSuite { testInterface = TestSuiteUnsupported tt })
_ _ =
die $ "No support for building test suite type " ++ display tt
buildComponent verbosity numJobs pkg_descr lbi suffixes
comp@(CBench bm@Benchmark { benchmarkInterface = BenchmarkExeV10 {} })
clbi _ = do
let (exe, exeClbi) = benchmarkExeV10asExe bm clbi
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
info verbosity $ "Building benchmark " ++ benchmarkName bm ++ "..."
let ebi = buildInfo exe
exe' = exe { buildInfo = addExtraCSources ebi extras }
buildExe verbosity numJobs pkg_descr lbi exe' exeClbi
buildComponent _ _ _ _ _
(CBench Benchmark { benchmarkInterface = BenchmarkUnsupported tt })
_ _ =
die $ "No support for building benchmark type " ++ display tt
-- | Add extra C sources generated by preprocessing to build
-- information.
addExtraCSources :: BuildInfo -> [FilePath] -> BuildInfo
addExtraCSources bi extras = bi { cSources = new }
where new = Set.toList $ old `Set.union` exs
old = Set.fromList $ cSources bi
exs = Set.fromList extras
replComponent :: Verbosity
-> PackageDescription
-> LocalBuildInfo
-> [PPSuffixHandler]
-> Component
-> ComponentLocalBuildInfo
-> FilePath
-> IO ()
replComponent verbosity pkg_descr lbi suffixes
comp@(CLib lib) clbi _ = do
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
let libbi = libBuildInfo lib
lib' = lib { libBuildInfo = libbi { cSources = cSources libbi ++ extras } }
replLib verbosity pkg_descr lbi lib' clbi
replComponent verbosity pkg_descr lbi suffixes
comp@(CExe exe) clbi _ = do
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
let ebi = buildInfo exe
exe' = exe { buildInfo = ebi { cSources = cSources ebi ++ extras } }
replExe verbosity pkg_descr lbi exe' clbi
replComponent verbosity pkg_descr lbi suffixes
comp@(CTest test@TestSuite { testInterface = TestSuiteExeV10{} })
clbi _distPref = do
let exe = testSuiteExeV10AsExe test
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
let ebi = buildInfo exe
exe' = exe { buildInfo = ebi { cSources = cSources ebi ++ extras } }
replExe verbosity pkg_descr lbi exe' clbi
replComponent verbosity pkg_descr lbi0 suffixes
comp@(CTest
test@TestSuite { testInterface = TestSuiteLibV09{} })
clbi distPref = do
pwd <- getCurrentDirectory
let (pkg, lib, libClbi, lbi, _, _, _) =
testSuiteLibV09AsLibAndExe pkg_descr test clbi lbi0 distPref pwd
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
let libbi = libBuildInfo lib
lib' = lib { libBuildInfo = libbi { cSources = cSources libbi ++ extras } }
replLib verbosity pkg lbi lib' libClbi
replComponent _ _ _ _
(CTest TestSuite { testInterface = TestSuiteUnsupported tt })
_ _ =
die $ "No support for building test suite type " ++ display tt
replComponent verbosity pkg_descr lbi suffixes
comp@(CBench bm@Benchmark { benchmarkInterface = BenchmarkExeV10 {} })
clbi _ = do
let (exe, exeClbi) = benchmarkExeV10asExe bm clbi
preprocessComponent pkg_descr comp lbi clbi False verbosity suffixes
extras <- preprocessExtras comp lbi
let ebi = buildInfo exe
exe' = exe { buildInfo = ebi { cSources = cSources ebi ++ extras } }
replExe verbosity pkg_descr lbi exe' exeClbi
replComponent _ _ _ _
(CBench Benchmark { benchmarkInterface = BenchmarkUnsupported tt })
_ _ =
die $ "No support for building benchmark type " ++ display tt
----------------------------------------------------
-- Shared code for buildComponent and replComponent
--
-- | Translate a exe-style 'TestSuite' component into an exe for building
testSuiteExeV10AsExe :: TestSuite -> Executable
testSuiteExeV10AsExe test@TestSuite { testInterface = TestSuiteExeV10 _ mainFile } =
Executable {
exeName = testName test,
modulePath = mainFile,
buildInfo = testBuildInfo test
}
testSuiteExeV10AsExe TestSuite{} = error "testSuiteExeV10AsExe: wrong kind"
-- | Translate a exe-style 'Benchmark' component into an exe for building
benchmarkExeV10asExe :: Benchmark -> ComponentLocalBuildInfo
-> (Executable, ComponentLocalBuildInfo)
benchmarkExeV10asExe bm@Benchmark { benchmarkInterface = BenchmarkExeV10 _ f }
clbi =
(exe, exeClbi)
where
exe = Executable {
exeName = benchmarkName bm,
modulePath = f,
buildInfo = benchmarkBuildInfo bm
}
exeClbi = ExeComponentLocalBuildInfo {
componentUnitId = componentUnitId clbi,
componentLocalName = CExeName (benchmarkName bm),
componentPackageDeps = componentPackageDeps clbi,
componentIncludes = componentIncludes clbi
}
benchmarkExeV10asExe Benchmark{} _ = error "benchmarkExeV10asExe: wrong kind"
addInternalBuildTools :: PackageDescription -> LocalBuildInfo -> BuildInfo
-> ProgramDb -> ProgramDb
addInternalBuildTools pkg lbi bi progs =
foldr updateProgram progs internalBuildTools
where
internalBuildTools =
[ simpleConfiguredProgram toolName (FoundOnSystem toolLocation)
| toolName <- toolNames
, let toolLocation = buildDir lbi </> toolName </> toolName <.> exeExtension ]
toolNames = intersect buildToolNames internalExeNames
internalExeNames = map exeName (executables pkg)
buildToolNames = map buildToolName (buildTools bi)
where
buildToolName (Dependency (PackageName name) _ ) = name
-- TODO: build separate libs in separate dirs so that we can build
-- multiple libs, e.g. for 'LibTest' library-style test suites
buildLib :: Verbosity -> Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity numJobs pkg_descr lbi lib clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.buildLib verbosity numJobs pkg_descr lbi lib clbi
GHCJS -> GHCJS.buildLib verbosity numJobs pkg_descr lbi lib clbi
JHC -> JHC.buildLib verbosity pkg_descr lbi lib clbi
LHC -> LHC.buildLib verbosity pkg_descr lbi lib clbi
UHC -> UHC.buildLib verbosity pkg_descr lbi lib clbi
HaskellSuite {} -> HaskellSuite.buildLib verbosity pkg_descr lbi lib clbi
_ -> die "Building is not supported with this compiler."
buildExe :: Verbosity -> Flag (Maybe Int)
-> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity numJobs pkg_descr lbi exe clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.buildExe verbosity numJobs pkg_descr lbi exe clbi
GHCJS -> GHCJS.buildExe verbosity numJobs pkg_descr lbi exe clbi
JHC -> JHC.buildExe verbosity pkg_descr lbi exe clbi
LHC -> LHC.buildExe verbosity pkg_descr lbi exe clbi
UHC -> UHC.buildExe verbosity pkg_descr lbi exe clbi
_ -> die "Building is not supported with this compiler."
replLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
replLib verbosity pkg_descr lbi lib clbi =
case compilerFlavor (compiler lbi) of
-- 'cabal repl' doesn't need to support 'ghc --make -j', so we just pass
-- NoFlag as the numJobs parameter.
GHC -> GHC.replLib verbosity NoFlag pkg_descr lbi lib clbi
GHCJS -> GHCJS.replLib verbosity NoFlag pkg_descr lbi lib clbi
_ -> die "A REPL is not supported for this compiler."
replExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
replExe verbosity pkg_descr lbi exe clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.replExe verbosity NoFlag pkg_descr lbi exe clbi
GHCJS -> GHCJS.replExe verbosity NoFlag pkg_descr lbi exe clbi
_ -> die "A REPL is not supported for this compiler."
initialBuildSteps :: FilePath -- ^"dist" prefix
-> PackageDescription -- ^mostly information from the .cabal file
-> LocalBuildInfo -- ^Configuration information
-> ComponentLocalBuildInfo
-> Verbosity -- ^The verbosity to use
-> IO ()
initialBuildSteps _distPref pkg_descr lbi clbi verbosity = do
-- check that there's something to build
unless (not . null $ allBuildInfo pkg_descr) $ do
let name = display (packageId pkg_descr)
die $ "No libraries, executables, tests, or benchmarks "
++ "are enabled for package " ++ name ++ "."
createDirectoryIfMissingVerbose verbosity True (componentBuildDir lbi clbi)
writeAutogenFiles verbosity pkg_descr lbi clbi
-- | Generate and write out the Paths_<pkg>.hs and cabal_macros.h files
--
writeAutogenFiles :: Verbosity
-> PackageDescription
-> LocalBuildInfo
-> ComponentLocalBuildInfo
-> IO ()
writeAutogenFiles verbosity pkg lbi clbi = do
createDirectoryIfMissingVerbose verbosity True (autogenModulesDir lbi clbi)
let pathsModulePath = autogenModulesDir lbi clbi
</> ModuleName.toFilePath (autogenModuleName pkg) <.> "hs"
rewriteFile pathsModulePath (Build.PathsModule.generate pkg lbi clbi)
let cppHeaderPath = autogenModulesDir lbi clbi </> cppHeaderName
rewriteFile cppHeaderPath (Build.Macros.generate pkg lbi clbi)
| thomie/cabal | Cabal/Distribution/Simple/Build.hs | bsd-3-clause | 21,870 | 0 | 18 | 5,620 | 4,762 | 2,411 | 2,351 | 368 | 7 |
{-# LANGUAGE PackageImports #-}
module GHC.Float.RealFracMethods (module M) where
import "base" GHC.Float.RealFracMethods as M
| silkapp/base-noprelude | src/GHC/Float/RealFracMethods.hs | bsd-3-clause | 132 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Monoid ((<>))
import Reflex.Dom
import qualified Reflex.Dom as Dom
import ReflexJsx (jsx)
main :: IO ()
main = return ()
-------------------------------------------------------------------------------
-- Some examples that should compile.
-------------------------------------------------------------------------------
-- These test basic html parsing
html1, html2, html3, html4 :: (MonadWidget t m) => m ()
html1 = [jsx|<div/>|]
html2 = [jsx|<div></div>|]
html3 = [jsx|<div>Hello</div>|]
html4 = [jsx|<h1>My <span style="color:red">Important</span> Heading</h1>|]
-- These test antiquotation (MonadWidget values + dynamic attributes)
anti1, anti2, anti3, anti4, anti5 :: (MonadWidget t m) => m ()
anti1 = [jsx|<div>{Dom.text "Hello"}</div>|]
anti2 = [jsx|<div>{Dom.text "Hello"}{Dom.text "World"}</div>|]
anti3 = let str = "Hello" in [jsx|<div>{Dom.text str}</div>|]
anti4 = [jsx|<div style={"color: " <> color <> ";width:10px;height:10px"}/>|]
where color = "blue"
anti5 = [jsx|<span {...attrs}/>|]
where attrs = constDyn $ "class" =: "my-class"
| dackerman/reflex-jsx | test/Main.hs | bsd-3-clause | 1,154 | 0 | 8 | 148 | 234 | 158 | 76 | 22 | 1 |
{-# LANGUAGE LambdaCase #-}
module Ppt.Decode where
import System.Directory
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Lens
import Ppt.Frame.ParsedRep hiding (FValue)
import Ppt.Frame.Types
import Ppt.Frame.Layout
import Numeric (showHex)
import Foreign.Ptr
import Foreign.Storable
import Data.Int (Int32)
import Data.Maybe
import GHC.Float
import Data.Vector.Storable ((!), (!?))
import Foreign.Storable
import qualified Data.List as L
import Data.Vector.Storable.ByteString
import Safe
import System.IO
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HM
import qualified Data.Vector.Storable as V
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as BSLC
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString as B
import qualified Data.Binary as DB
import qualified Data.Binary.Get as DBG
import Data.Word
import Data.Aeson (decode)
data FrameElementValue = FEValue { _primValue :: Prim
, _frameMember :: FrameMember
, _layoutMember :: LayoutMember }
| FESeqno { _seqNo :: Word32 }
deriving (Eq, Show)
data FrameValue = FValue { _frame :: Frame
, _values :: [FrameElementValue] }
deriving (Eq, Show)
data DecodedRow = DRow { _rElements :: [FrameElement]
, _rSeqno :: Int
, _rValues :: [Prim]
} deriving (Eq, Show)
data DecodedFrame = DFrame { _dFrame :: Frame
, _dLayout :: [LayoutMember]
, _dRows :: [DecodedRow]
} deriving (Eq, Show)
hexList [] = ""
hexList xs = (concatMap hex thisWord) ++ (' ':(hexList rest))
where hex n = if n < 16 then "0" ++ (showHex n " ") else showHex n " "
(thisWord, rest) = splitAt 4 xs
descValue :: FrameValue -> String
descValue (FValue (Frame n _) vals) =
let descElem (FEValue p _ l) = (l ^. lName) ++ " " ++ show p
descElem (FESeqno n) = "# " ++ show n
in n ++ ": " ++ (L.intercalate ", " $ map descElem vals)
findMember :: String -> FrameLayout -> Maybe FrameMember
findMember name layout =
if length mems > 0 then Just (head mems) else Nothing
where (Frame _ elements) = layout ^. flFrame
memberNamed s (FMemberElem mem@(FMember _ name _))
| (s == name) = Just mem
| otherwise = Nothing
memberNamed _ _ = Nothing
mems = mapMaybe (memberNamed name) elements
type MaybeIO = MaybeT IO
frMemName :: LayoutMember -> String
frMemName fl = case (fl ^. lKind) of
(LKMember (FMember _ nm _) _) -> nm
_ -> undefined
readMember :: [LayoutMember] -> ReadConfig -> FrameLayout -> (V.Vector Word8, ReadConfig, Int) -> MaybeIO ( [FrameElementValue])
readMember [] _ _ _ = do return []
readMember (lmem:lmems) rconf layout v@(vec, rinfo, startOffset) =
case lmem ^. lKind of
LKSeqno FrontSeq -> do
primValue <- MaybeT $ V.unsafeWith vec $ \ptr -> do
value <- peekElemOff (castPtr (plusPtr ptr startOffset) :: Ptr Word32) 0
return $ Just value
rest <- readMember lmems rconf layout v
MaybeT $ return $ (:) <$> (pure $ FESeqno primValue) <*> (pure rest)
LKMember elem _ -> do
let lIxOf mem = startOffset + (mem ^. lOffset)
mrequire :: Show a => Bool -> a -> MaybeIO a
mrequire True a = MaybeT $ return $ Just a
mrequire False msg = MaybeT $ do putStrLn $ show msg
return Nothing
primValue <- MaybeT $ liftM Just $ readValue (lmem ^. lType) rconf vec (lIxOf lmem)
let thisResult = FEValue <$> (pure primValue) <*> (findMember (frMemName lmem) layout) <*> pure lmem
rest <- readMember lmems rconf layout v
--MaybeT $ do putStrLn $ "Got member: " ++ show primValue ++ " for found member " ++ (
-- show $ findMember (frMemName lmem) layout) ++ " for layout mem " ++ show lmem
-- return $ Just ()
MaybeT $ return $ (:) <$> thisResult <*> (pure rest)
_ -> readMember lmems rconf layout v -- Either back seqno (already checked), padding, or type desc.
decodeFromBuffer :: ReadConfig -> V.Vector Word8 -> Int -> Int -> [FrameLayout] -> MaybeIO (FrameValue)
decodeFromBuffer rinfo vec startOffset sz layouts =
do let genSpec = layoutSpec $ head layouts
size = genSpec ^.lioSize
lIxOf mem = startOffset + (mem ^. lOffset)
firstMembers = (head layouts) ^. flLayout
memFrontSeq = head $ firstMembers ^.. folded.filtered (\m -> m ^. lKind == (LKSeqno FrontSeq))
memBackSeq = head $ firstMembers ^.. folded.filtered (\m -> m ^. lKind == (LKSeqno BackSeq))
-- memTypeDescs :: [LayoutMember]
memTypeDescs = firstMembers ^.. folded.filtered (\m -> has _LKTypeDescrim (m ^. lKind))
nrFrameTypes = headDef 1 (memTypeDescs ^.. folded.lKind._LKTypeDescrim)
showBytes :: IO ()
showBytes = do frameBytes <- V.unsafeWith vec (\ptr -> forM [0..sz-1] (\i -> peekByteOff ptr (startOffset + i))) :: IO [Word8]
putStrLn $ show (hexList frameBytes)
mrequire :: Show a => Bool -> a -> MaybeIO a
mrequire True a = MaybeT $ return $ Just a
mrequire False msg = MaybeT $ do putStrLn $ show msg
showBytes
return Nothing
mpred True _ a = MaybeT $ a
mpred False d _ = MaybeT $ return $ Just d
readVecInt :: V.Vector Word8 -> Int -> MaybeIO Int32
readVecInt vec i = MaybeT $ V.unsafeWith vec (\ptr -> do let p = castPtr ptr :: Ptr Int32
val <- peekElemOff p (i `div` 4)
return (Just val))
mlog s = MaybeT $ do putStrLn s
return (Just s)
mrequire (sz == size) "Frame sizes are equal"
mrequire (startOffset + sz <= V.length vec) ("Frame fits in vector (start offset + size, length of vec)",
startOffset + sz, V.length vec)
mrequire (lIxOf memFrontSeq == startOffset) "Frame seqno is first"
mrequire (size - tInt (rcTargetInfo rinfo) == memBackSeq ^. lOffset) "Back seqno is last"
startSeqno <- readVecInt vec (lIxOf memFrontSeq)
endSeqno <- readVecInt vec (lIxOf memBackSeq)
if startSeqno /= endSeqno
then MaybeT $ do putStrLn ( "* Failed synchronization. Starting offset is " ++ show startOffset ++ " and bytes are:")
showBytes
putStrLn $ "Got start = " ++ show startSeqno ++ ", and end = " ++ show endSeqno
return Nothing
else MaybeT $ return (Just 0)
mrequire (startSeqno == endSeqno) ("Sequence numbers match", startSeqno, endSeqno)
frameType <- if nrFrameTypes > 1
then do mlog $ "Reading " ++ show (head memTypeDescs) ++ " at loffset " ++ show startOffset
MaybeT $ do showBytes
return (Just 1)
rawFrameType <- readVecInt vec (lIxOf $ head memTypeDescs)
MaybeT $ return $ Just (fromIntegral rawFrameType :: Int)
else MaybeT $ return $ Just 0
mrequire (frameType /= 0 && frameType <= nrFrameTypes) ("Frame type discriminator in range (frame type, nr values)", frameType, nrFrameTypes)
let layout = layouts !! (frameType - 1)
members <- readMember (layout ^. flLayout) rinfo layout (vec, rinfo, startOffset)
return (FValue (layout ^. flFrame) members)
-- |Applies collection parameters (time stamp type, performance
-- counter names) to the member definitions.
configureLayouts :: FileRecord -> [FrameLayout]
configureLayouts frecord =
let json = frJson frecord
counterConfig = case frCounters frecord of
[] -> Just (PPCNone, 0)
xs -> Just (PPIntelCounter (x !! 0) (x !! 1) (x !! 2), 0)
where x = xs ++ repeat ""
timeConfig = Just ((jsBufferEmit (frJson frecord)) ^. eTimeRep, 0, 0)
convertMember :: LayoutMember -> LayoutMember
convertMember mem =
case mem ^. lKind of
LKMember fm@(FMember (PTime t) _ _) side ->
mem { _lKind = LKMember (fm { fmType = PTime timeConfig }) side }
LKMember fm@(FMember (PCounter e v) _ _) side ->
mem { _lKind = LKMember (fm { fmType = PCounter e counterConfig }) side }
_ -> mem
convertLayout :: FrameLayout -> FrameLayout
convertLayout layout =
layout { _flLayout = map convertMember (layout ^. flLayout) }
in map convertLayout (jsBufferFrames json)
-- TODO: Make this a lazy bytestring input, then use fromChunks to get
-- out strict ByteStrings, and combine the chunks (copying only the
-- bytes needed! as we cross boundaries.
decodeFromBytes :: FileRecord -> BSL.ByteString -> IO [FrameValue]
decodeFromBytes frecord bytes = do
let rinfo = readConfig frecord
json = frJson frecord
case frameSize json of
Nothing -> return []
Just frsize -> do
let frameLayouts = configureLayouts frecord
vec :: V.Vector Word8
vec = V.fromList $ BSL.unpack bytes
let numRecords = fromIntegral (BSL.length bytes `div` fromIntegral frsize)
res <- mapM (\idx -> runMaybeT $ decodeFromBuffer rinfo vec (idx * frsize) frsize frameLayouts) [0..numRecords]
let successful = catMaybes res
putStrLn $ " decoded " ++ show (length successful) ++ " records successfully out of "++ show (length res) ++ ":\n\t" ++ L.intercalate "\n\t" (map show res)
return $ catMaybes res
showBytesForFrame :: FileRecord -> BSL.ByteString -> Int -> IO ()
showBytesForFrame frecord bytes nr = do
let json = frJson frecord
case frameSize json of
Nothing -> putStrLn "Framesize is Nothing"
Just frsize -> do
let rawBytes :: [Word8]
rawBytes = BSL.unpack $ BSL.take (fromIntegral frsize) bytes
putStrLn ("Bytes for frame " ++ show nr ++ ": " ++ hexList rawBytes)
decodeOneFromBytes :: FileRecord -> BSL.ByteString -> Int -> IO (Maybe FrameValue)
decodeOneFromBytes frecord bytes nr = do
let rinfo = readConfig frecord
json = frJson frecord
case frameSize json of
Nothing -> do putStrLn "Framesize is Nothing"
return Nothing
Just frsize -> do
let frameLayouts = jsBufferFrames json
rawBytes :: [Word8]
rawBytes = BSL.unpack $ BSL.take (fromIntegral frsize) bytes
vec = V.fromList rawBytes
putStrLn ("Reading " ++ hexList rawBytes)
runMaybeT $ decodeFromBuffer rinfo vec (nr * frsize) frsize frameLayouts
deserialiseHeader :: DBG.Get (Maybe Word32)
deserialiseHeader = do
prefix <- DBG.getWord32be
if prefix /= 0x50505431
then return Nothing
else Just <$> DBG.getWord32be
-- split up the string into three sections:
-- (1) the 8 byte header we just read
-- (2) the json blob
-- (3) the binary frames
splitFileContents :: BSL.ByteString -> Maybe (FileRecord, BSL.ByteString, Int)
splitFileContents contents =
let length = DBG.runGet deserialiseHeader contents
in case length of
Nothing -> Nothing
Just len ->
let fileRecordBlob = BSL.take (fromIntegral len) $ BSL.drop 8 contents
binaryFrames = BSL.drop (fromIntegral len + 8) contents
mfileRecord = decode fileRecordBlob :: Maybe FileRecord
in (\v -> Just (v, binaryFrames, 8 + fromIntegral len)) =<< mfileRecord
readConfig :: FileRecord -> ReadConfig
readConfig fr =
let counterNames = frCounters fr
infCounterNames = counterNames ++ repeat ""
counters = if null counterNames
then PPCNone
else PPIntelCounter (infCounterNames !! 0) (infCounterNames !! 1) (infCounterNames !! 2)
json = frJson fr
in ReadConfig (jsTarget json) (jsBufferEmit json ^. eTimeRep) counters
decodeFile :: BSL.ByteString -> IO ([FrameValue])
decodeFile contents = do
let header = splitFileContents contents
case header of
Nothing -> do putStrLn "Invalid file format"
return []
Just (fileRecord, binaryFrames, headerLen) -> do
let length = DBG.runGet deserialiseHeader contents
json = frJson fileRecord
layoutSpecs = map (\f -> let (LayoutIO ss _) = layoutSpec f in ss) (jsBufferFrames json)
putStrLn $ "Frame record sizes are (and should all be equal): " ++ L.intercalate ", " (map show layoutSpecs)
putStrLn $ "Got remaining " ++ show (BSL.length binaryFrames) ++ " for file after header."
putStrLn $ "That should be " ++ show (fromIntegral (BSL.length binaryFrames) / fromIntegral (head layoutSpecs)) ++ " Frames."
putStrLn $ "File header was " ++ show headerLen ++ " bytes."
decodeFromBytes fileRecord binaryFrames
decodeFileToConsole :: String -> Int -> IO ()
decodeFileToConsole filename maxNr = do
contents <- BSL.readFile filename
values <- decodeFile contents
putStrLn $ ">> " ++ (L.intercalate "\n>> " $ map descValue (take maxNr values))
-- Always returns the sequence number *first*. Also assumes its first.
decodeValue :: FrameValue -> (Int, [Prim])
decodeValue (FValue fr ((FESeqno s):vals)) =
(fromIntegral s, map getPrim vals)
where getPrim (FEValue p _ _) = p
-- |Prototypical simple sorter. Sorts decodded FrameValues into a
-- list of DecocdedFrame values. Each element in the output list
-- contains a list of rows. Each input corresponds to a row.
sortValues :: [FrameValue] -> [DecodedFrame]
sortValues inputs =
map snd $ HM.toList $ foldr updateForFV HM.empty inputs
where
mergeEntry :: DecodedFrame -> DecodedFrame -> DecodedFrame
mergeEntry dfr (DFrame _ _ []) = dfr
mergeEntry (DFrame fr l rows) (DFrame _ _ r) = DFrame fr l (rows ++ r)
makeEntry fr lmem seq row = DFrame fr lmem [DRow (_frameElements fr) seq row]
updateForFV :: FrameValue -> HM.HashMap Frame DecodedFrame -> HM.HashMap Frame DecodedFrame
updateForFV fv@(FValue fr vals) mp =
let (seq, row) = decodeValue fv
layoutMems = mapMaybe (\case (FEValue _ _ m) -> Just m ; (FESeqno _) -> Nothing) vals
in HM.insertWith mergeEntry fr (makeEntry fr layoutMems seq row) mp
-- |Show a raw value given a time representation config.
showValue :: Prim -> String
showValue (PTime (Just (ETimeSpec _, a, b))) = show $ a * 1000000000 + b
showValue (PTime (Just (ETimeVal, a, b))) = show $ a * 1000000 + b
-- these two should probably truncate
showValue (PRational _ (Just d)) = show d
showValue (PIntegral _ (Just i)) = show i
showValue (PCounter (Expanded _) (Just (_, v))) = show v
memLayoutType :: GenLayoutMember FrameMember -> Maybe Prim
memLayoutType lm = case (lm ^. lKind) of
LKMember d _ -> Just (fmType d)
_ -> Nothing
-- |Currently does no processing. Opens 'filename' and writes out CSVs
-- - one per found frame type - to 'destDir'.
decodeFileToCSVs filename destDir = do
let writeCsv dir (DFrame fr lmem rows) = do
let fileName = _frameName fr ++ ".csv"
firstRow = head rows
nameOf :: LayoutMember -> String
nameOf lm =
case memLayoutType lm of
Just (PCounter (Expanded 0) (Just (PPIntelCounter a _ _, v))) -> (lm ^. lName) ++ ": " ++ a
Just (PCounter (Expanded 1) (Just (PPIntelCounter _ b _, v))) -> (lm ^. lName) ++ ": " ++ b
Just (PCounter (Expanded 2) (Just (PPIntelCounter _ _ c, v))) -> (lm ^. lName) ++ ": " ++ c
_ -> lm ^. lName
headers = "ppt_seqno, " ++ (L.intercalate ", " (map nameOf lmem))
saveRow (DRow _ n vs) = L.intercalate ", " $ show n:map showValue vs
h <- openFile (destDir ++ "/" ++ fileName) WriteMode
hPutStrLn h headers
mapM_ (hPutStrLn h . saveRow) rows
hClose h
-- This will fail quickly if we can't create the directory.
createDirectory destDir
contents <- BSL.readFile filename
values <- decodeFile contents
-- let csvs = F.foldl' (\hm fv -> HM.insertWith (++) (_frameName $ _frame fv) [fv] hm) HM.empty values
let csvs = sortValues values
mapM_ (writeCsv destDir) csvs
return $ map (_frameName . _dFrame) csvs
decodeCommand :: [String] -> IO ()
decodeCommand [] = do
putStrLn "usage: ppt decode input_filename [output_dir]"
putStrLn " where output_dir will be generated if unspecified."
decodeCommand (first:rest) = do
let (console, filename) = if (head first) == '-'
then (True, head rest)
else (False, first)
if console
then decodeFileToConsole filename 50
else do let outputDir = if length rest < 1
then filename ++ "_output"
else head rest
result <- decodeFileToCSVs filename outputDir
putStrLn $ "Decoded " ++ (L.intercalate ", " result ) ++ " into " ++ outputDir
return ()
| lally/libmet | src/Ppt/Decode.hs | bsd-3-clause | 17,260 | 0 | 24 | 4,777 | 5,399 | 2,732 | 2,667 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import Control.Applicative
import Control.Monad
import "monads-tf" Control.Monad.Trans
import Data.HandleLike
import System.Environment
import Network
import Network.PeyoTLS.ReadFile
import Network.PeyoTLS.Client
import "crypto-random" Crypto.Random
import qualified Data.ByteString.Char8 as BSC
main :: IO ()
main = do
d : _ <- getArgs
rk <- readKey $ d ++ "/yoshikuni.sample_key"
rc <- readCertificateChain [d ++ "/yoshikuni.sample_crt"]
ek <- readKey $ d ++ "/client_ecdsa.sample_key"
ec <- readCertificateChain [d ++ "/client_ecdsa.sample_crt"]
ca <- readCertificateStore [d ++ "/cacert.pem"]
h <- connectTo "localhost" $ PortNumber 443
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
(`run` g) $ do
p <- open' h "localhost"
["TLS_RSA_WITH_AES_128_CBC_SHA"] [(ek, ec), (rk, rc)] ca
hlPut p "GET / HTTP/1.1 \r\n"
hlPut p "Host: localhost\r\n\r\n"
doUntil BSC.null (hlGetLine p) >>= liftIO . mapM_ BSC.putStrLn
hlClose p
doUntil :: Monad m => (a -> Bool) -> m a -> m [a]
doUntil p rd = rd >>= \x ->
(if p x then return . (: []) else (`liftM` doUntil p rd) . (:)) x
| YoshikuniJujo/peyotls | peyotls/examples/clcertEcdsaClient.hs | bsd-3-clause | 1,151 | 4 | 14 | 190 | 406 | 212 | 194 | 31 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module Intake.Client where
import Data.Aeson
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Network.JSONClient (apiGet, apiPost)
import Intake.Core (WorkflowId(..), WorkflowIdPrefix(..), WorkflowName(..), WStatus(..))
-- | Execute a GET agains the specified URI (e.g. `/workflow`) using the
-- supplied parameters.
get :: FromJSON a => B.ByteString
-> [(B.ByteString, Maybe B.ByteString)] -> IO (Maybe a)
get = apiGet Nothing "http://127.0.0.1:7001"
post :: B.ByteString -> [(B.ByteString, Maybe B.ByteString)] -> LB.ByteString
-> IO (Maybe WorkflowId)
post = apiPost Nothing "http://127.0.0.1:7001"
-- | Return the list of defined workflows.
workflows :: IO [WorkflowName]
workflows = do
m <- get "/workflows" []
return $ maybe (error "GET /worklfows") id m
-- | Instanciate a workflow.
instanciate :: (Either String WorkflowName) -> IO WorkflowId
instanciate n =
case n of
Right (WorkflowName name) -> do
m <- post ("/workflows/" `B.append` B.pack name) [] ""
return $ maybe (error "POST /workflows") id m
Left command -> do -- TODO it is not yet implemented on the server.
m <- post ("/commands/" `B.append` B.pack command) [] ""
return $ maybe (error "POST /commands") id m
-- | Return the status of a workflow instance.
status :: WorkflowIdPrefix -> IO WStatus
status (WorkflowIdPrefix i) = do
m <- get ("/instances/" `B.append` B.pack i `B.append` "/status") []
return $ maybe (error "GET /instances") id m
| noteed/intake | Intake/Client.hs | bsd-3-clause | 1,619 | 0 | 15 | 281 | 494 | 264 | 230 | 32 | 2 |
{-# LANGUAGE PackageImports #-}
module Foreign.Marshal.Alloc (module M) where
import "base" Foreign.Marshal.Alloc as M
| silkapp/base-noprelude | src/Foreign/Marshal/Alloc.hs | bsd-3-clause | 124 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
{-# LANGUAGE TypeApplications #-}
module Database.PostgreSQL.PQTypes.Array (
-- * Array1
Array1(..)
, unArray1
-- * CompositeArray1
, CompositeArray1(..)
, unCompositeArray1
-- * Array2
, Array2(..)
, unArray2
-- * CompositeArray2
, CompositeArray2(..)
, unCompositeArray2
) where
import Control.Monad
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Foreign.Storable
import qualified Control.Exception as E
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Unsafe as BS
import qualified Data.Vector.Storable as V
import Database.PostgreSQL.PQTypes.Composite
import Database.PostgreSQL.PQTypes.Format
import Database.PostgreSQL.PQTypes.FromRow
import Database.PostgreSQL.PQTypes.FromSQL
import Database.PostgreSQL.PQTypes.Internal.C.Get
import Database.PostgreSQL.PQTypes.Internal.C.Interface
import Database.PostgreSQL.PQTypes.Internal.C.Put
import Database.PostgreSQL.PQTypes.Internal.C.Types
import Database.PostgreSQL.PQTypes.Internal.Error
import Database.PostgreSQL.PQTypes.Internal.Utils
import Database.PostgreSQL.PQTypes.ToSQL
-- | One dimensional array of non-composite elements.
newtype Array1 a = Array1 [a]
deriving (Eq, Functor, Ord, Show)
-- | Extract list of elements from 'Array1'.
unArray1 :: Array1 a -> [a]
unArray1 (Array1 a) = a
instance PQFormat t => PQFormat (Array1 t) where
pqFormat = pqFormat @t `BS.append` BS.pack "[]"
instance FromSQL t => FromSQL (Array1 t) where
type PQBase (Array1 t) = PGarray
fromSQL Nothing = unexpectedNULL
fromSQL (Just arr) = getArray1 Array1 arr getItem
where
getItem res err i ptr fmt = do
verifyPQTRes err "fromSQL (Array1)" =<< c_PQgetf1 res err i fmt 0 ptr
isNull <- c_PQgetisnull res i 0
mbase <- if isNull == 1 then return Nothing else Just <$> peek ptr
fromSQL mbase
instance ToSQL t => ToSQL (Array1 t) where
type PQDest (Array1 t) = PGarray
toSQL (Array1 arr) pa@(ParamAllocator allocParam) conv =
alloca $ \err -> allocParam $ \param ->
putArray1 arr param conv $ \fmt item ->
toSQL item pa (c_PQputf1 param err fmt)
>>= verifyPQTRes err "toSQL (Array1)"
----------------------------------------
-- | One dimensional array of composite elements.
newtype CompositeArray1 a = CompositeArray1 [a]
deriving (Eq, Functor, Ord, Show)
-- | Extract list of elements from 'CompositeArray1'.
unCompositeArray1 :: CompositeArray1 a -> [a]
unCompositeArray1 (CompositeArray1 a) = a
instance PQFormat t => PQFormat (CompositeArray1 t) where
pqFormat = pqFormat @(Array1 t)
instance CompositeFromSQL t => FromSQL (CompositeArray1 t) where
type PQBase (CompositeArray1 t) = PGarray
fromSQL Nothing = unexpectedNULL
fromSQL (Just arr) = getArray1 CompositeArray1 arr getItem
where
getItem res err i (_::Ptr CInt) _ = toComposite <$> fromRow res err 0 i
instance CompositeToSQL t => ToSQL (CompositeArray1 t) where
type PQDest (CompositeArray1 t) = PGarray
toSQL (CompositeArray1 arr) pa@(ParamAllocator allocParam) conv =
alloca $ \err -> allocParam $ \param ->
putArray1 arr param conv $ \fmt item ->
toSQL (Composite item) pa (c_PQputf1 param err fmt)
>>= verifyPQTRes err "toSQL (CompositeArray1)"
----------------------------------------
-- | Helper function for putting elements of
-- 'Array1' / 'CompositeArray1' into 'PGparam'.
putArray1 :: forall t r. PQFormat t
=> [t] -- ^ List of items to be put.
-> Ptr PGparam -- ^ Inner 'PGparam' to put items into.
-> (Ptr PGarray -> IO r) -- ^ Continuation that puts
-- 'PGarray' into outer 'PGparam'.
-> (CString -> t -> IO ()) -- ^ Function that takes item
-- along with its format and puts it into inner 'PGparam'.
-> IO r
putArray1 arr param conv putItem = do
pqFormat0 @t `BS.unsafeUseAsCString` (forM_ arr . putItem)
putAsPtr (PGarray {
pgArrayNDims = 0
, pgArrayLBound = V.empty
, pgArrayDims = V.empty
, pgArrayParam = param
, pgArrayRes = nullPtr
}) conv
-- | Helper function for getting elements of
-- 'Array1' / 'CompositeArray1' out of 'PGarray'.
getArray1 :: forall a array t. (PQFormat t, Storable a)
=> ([t] -> array) -- ^ Array constructor.
-> PGarray -- ^ Source 'PGarray'.
-> (Ptr PGresult -> Ptr PGerror -> CInt -> Ptr a -> CString -> IO t) -- ^
-- Function that takes an item with a given index
-- out of 'PGresult' and stores it in provided 'Ptr'.
-> IO array
getArray1 con PGarray{..} getItem = flip E.finally (c_PQclear pgArrayRes) $
if pgArrayNDims > 1
then E.throwIO ArrayDimensionMismatch {
arrDimExpected = 1
, arrDimDelivered = fromIntegral pgArrayNDims
}
else do
size <- c_PQntuples pgArrayRes
alloca $ \err -> alloca $ \ptr -> pqFormat0 @t
`BS.unsafeUseAsCString` loop [] (size - 1) err ptr
where
loop :: [t] -> CInt -> Ptr PGerror -> Ptr a -> CString -> IO array
loop acc !i err ptr fmt = case i of
-1 -> return . con $ acc
_ -> do
item <- getItem pgArrayRes err i ptr fmt `E.catch` rethrowWithArrayError i
loop (item : acc) (i - 1) err ptr fmt
----------------------------------------
-- | Two dimensional array of non-composite elements.
newtype Array2 a = Array2 [[a]]
deriving (Eq, Functor, Ord, Show)
-- | Extract list of elements from 'Array2'.
unArray2 :: Array2 a -> [[a]]
unArray2 (Array2 a) = a
instance PQFormat t => PQFormat (Array2 t) where
pqFormat = pqFormat @(Array1 t)
instance FromSQL t => FromSQL (Array2 t) where
type PQBase (Array2 t) = PGarray
fromSQL Nothing = unexpectedNULL
fromSQL (Just arr) = getArray2 Array2 arr getItem
where
getItem res err i ptr fmt = do
verifyPQTRes err "fromSQL (Array2)" =<< c_PQgetf1 res err i fmt 0 ptr
isNull <- c_PQgetisnull res i 0
mbase <- if isNull == 1 then return Nothing else Just <$> peek ptr
fromSQL mbase
instance ToSQL t => ToSQL (Array2 t) where
type PQDest (Array2 t) = PGarray
toSQL (Array2 arr) pa@(ParamAllocator allocParam) conv =
alloca $ \err -> allocParam $ \param ->
putArray2 arr param conv $ \fmt item ->
toSQL item pa (c_PQputf1 param err fmt)
>>= verifyPQTRes err "toSQL (Array2)"
----------------------------------------
-- | Two dimensional array of composite elements.
newtype CompositeArray2 a = CompositeArray2 [[a]]
deriving (Eq, Functor, Ord, Show)
-- | Extract list of elements from 'CompositeArray2'.
unCompositeArray2 :: CompositeArray2 a -> [[a]]
unCompositeArray2 (CompositeArray2 a) = a
instance PQFormat t => PQFormat (CompositeArray2 t) where
pqFormat = pqFormat @(Array2 t)
instance CompositeFromSQL t => FromSQL (CompositeArray2 t) where
type PQBase (CompositeArray2 t) = PGarray
fromSQL Nothing = unexpectedNULL
fromSQL (Just arr) = getArray2 CompositeArray2 arr getItem
where
getItem res err i (_::Ptr CInt) _ = toComposite <$> fromRow res err 0 i
instance CompositeToSQL t => ToSQL (CompositeArray2 t) where
type PQDest (CompositeArray2 t) = PGarray
toSQL (CompositeArray2 arr) pa@(ParamAllocator allocParam) conv =
alloca $ \err -> allocParam $ \param ->
putArray2 arr param conv $ \fmt item ->
toSQL (Composite item) pa (c_PQputf1 param err fmt)
>>= verifyPQTRes err "toSQL (CompositeArray2)"
----------------------------------------
-- | Helper function for putting elements of
-- 'Array2' / 'CompositeArray2' into 'PGparam'.
putArray2 :: forall t r. PQFormat t
=> [[t]] -- ^ List of items to be put.
-> Ptr PGparam -- ^ Inner 'PGparam' to put items into.
-> (Ptr PGarray -> IO r) -- ^ Continuation
-- that puts 'PGarray' into outer 'PGparam'.
-> (CString -> t -> IO ()) -- ^ Function that takes item
-- along with its format and puts it into inner 'PGparam'.
-> IO r
putArray2 arr param conv putItem = do
dims <- pqFormat0 @t `BS.unsafeUseAsCString` loop arr 0 0
putAsPtr (PGarray {
pgArrayNDims = 2
, pgArrayLBound = V.fromList [1, 1]
, pgArrayDims = dims
, pgArrayParam = param
, pgArrayRes = nullPtr
}) conv
where
loop :: [[t]] -> CInt -> CInt -> CString -> IO (V.Vector CInt)
loop rows !size !innerSize fmt = case rows of
[] -> return . V.fromList $ [size, innerSize]
(row : rest) -> do
nextInnerSize <- innLoop row 0 fmt
when (size > 0 && innerSize /= nextInnerSize) $
hpqTypesError $ "putArray2: inner rows have different sizes"
loop rest (size + 1) nextInnerSize fmt
innLoop :: [t] -> CInt -> CString -> IO CInt
innLoop items !size fmt = case items of
[] -> return size
(item : rest) -> do
putItem fmt item
innLoop rest (size + 1) fmt
-- | Helper function for getting elements of
-- 'Array2' / 'CompositeArray2' out of 'PGarray'.
getArray2 :: forall a array t. (PQFormat t, Storable a)
=> ([[t]] -> array) -- ^ Array constructor.
-> PGarray -- ^ Source 'PGarray'.
-> (Ptr PGresult -> Ptr PGerror -> CInt -> Ptr a -> CString -> IO t) -- ^
-- Function that takes an item with a given index
-- out of 'PGresult' and stores it in provided 'Ptr'.
-> IO array
getArray2 con PGarray{..} getItem = flip E.finally (c_PQclear pgArrayRes) $ do
if pgArrayNDims /= 0 && pgArrayNDims /= 2
then E.throwIO ArrayDimensionMismatch {
arrDimExpected = 2
, arrDimDelivered = fromIntegral pgArrayNDims
}
else do
let dim2 = pgArrayDims V.! 1
size <- c_PQntuples pgArrayRes
alloca $ \ptr -> alloca $ \err -> pqFormat0 @t
`BS.unsafeUseAsCString` loop [] dim2 size err ptr
where
loop :: [[t]] -> CInt -> CInt -> Ptr PGerror -> Ptr a -> CString -> IO array
loop acc dim2 !i err ptr fmt = case i of
0 -> return . con $ acc
_ -> do
let i' = i - dim2
arr <- innLoop [] (dim2 - 1) i' err ptr fmt
loop (arr : acc) dim2 i' err ptr fmt
innLoop :: [t] -> CInt -> CInt -> Ptr PGerror -> Ptr a -> CString -> IO [t]
innLoop acc !i baseIdx err ptr fmt = case i of
-1 -> return acc
_ -> do
let i' = baseIdx + i
item <- getItem pgArrayRes err i' ptr fmt `E.catch` rethrowWithArrayError i'
innLoop (item : acc) (i - 1) baseIdx err ptr fmt
| scrive/hpqtypes | src/Database/PostgreSQL/PQTypes/Array.hs | bsd-3-clause | 10,447 | 0 | 18 | 2,489 | 3,177 | 1,667 | 1,510 | -1 | -1 |
module TupleFunctions where
-- partern match on tuple
f :: (a, b) -> (c, d) -> ((b, d), (a, c))
f x y= ((snd x, snd y), (fst x, fst y))
f' :: (a, b) -> (c, d) -> ((b, d), (a, c))
f' (a, b) (c, d) = ((b, d), (a, c))
addEmUp2 :: Num a => (a, a) -> a
addEmUp2 (x, y) = x + y
fst3 :: (a, b, c) -> a
fst3 (x, _, _) = x
f'' :: (a, b, c) -> (d, e, f) -> ((a, d), (c, f))
f'' (a, _, c) (d, _, f) = ((a, d), (c, f))
| chengzh2008/hpffp | src/ch07-FunctionPattern/matchTuples1.hs | bsd-3-clause | 412 | 0 | 8 | 113 | 341 | 207 | 134 | 11 | 1 |
module Associativity where
data Fixity = Prefix
| Infix Precedence Associativity
type Precedence = Int
-- TODO make datatype for (Precedence,Associativity) and hide implementation
-- TODO at support for non Associativity
data Associativity
= AssoRight -- ^ Right Associative.
| AssoLeft -- ^ Left Associative.
deriving Eq
-- | Compare Precedence and returns true if the first argument bind tighter.
-- It expect that the order of its argument's to be the same as the corresponding functions
-- This is so it can take Associativity in to account
higherPrec :: (Precedence, Associativity) -> (Precedence, Associativity) -> Bool
higherPrec (p1, AssoLeft) (p2, _) = p1 >= p2
higherPrec (p1, AssoRight) (p2, _) = p1 > p2
-- | Highest possible Precedence and Associativity.
--
-- Is Right Associative.
highPrec :: (Precedence, Associativity)
highPrec = (100, AssoLeft)
-- |Lowest possible Precedence and Associativity.
--
-- Is Right Associative.
lowPrec :: (Precedence, Associativity)
lowPrec = (0, AssoRight)
| kwibus/myLang | src/Associativity.hs | bsd-3-clause | 1,034 | 0 | 7 | 183 | 171 | 109 | 62 | 15 | 1 |
-- This is the state data structure
module Queue where
import Command
import CommandParser (twitchUser)
import Control.Monad.State
import Data.Maybe
import Data.Time
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
data Queue
= Queue
{ queueOn :: Bool
, queueLastMessage :: UTCTime
, queueMode :: Mode
, queueAdmins :: Set.Set TwitchUser
, queueRestricted :: Set.Set String
, queueQueue :: Seq.Seq UserOrTeam
, queueSoftClosedList :: Set.Set UserOrTeam
, queueSoftClose :: Bool
, queueOpen :: Bool
, queueTeams :: Map.Map TwitchUser TeamName
, queueStreamer :: TwitchUser
, queueSetWins :: Int
, queueSetLosses :: Int
, queueCrewStockA :: Int
, queueCrewStockB :: Int
, queueFriendMes :: Set.Set TwitchUser
, queueIndex :: Map.Map TwitchUser (ConnectCode, Int, Int)
, queueRulesSingles :: String
, queueRulesDoubles :: String
, queueRulesCrew :: String
, queueStagelist :: String
, queueHereMap :: Map.Map TwitchUser UTCTime
, queueInvites :: Map.Map TwitchUser (Set.Set TeamName)
, queueDenyReply :: String
, queueWinBuffer :: Maybe Seconds
, queueListBuffer :: Maybe Seconds
, queueSinglesLimit :: Maybe Int
, queueDoublesLimit :: Maybe Int
, queueReenterWait :: Maybe Minutes
, queueHereAlert :: Maybe Seconds
, queueSinglesBestOf :: Int
, queueDoublesBestOf :: Int
} deriving (Show, Eq, Ord)
type Message = String
defaultQueue :: Queue
defaultQueue = Queue
{ queueOn = True
, queueLastMessage = UTCTime (fromGregorian 2016 1 1) 0
, queueMode = Singles
, queueAdmins = Set.fromList [twitchUser "josuf107"]
, queueRestricted = Set.empty
, queueQueue = Seq.empty
, queueOpen = False
, queueSoftClosedList = Set.empty
, queueSoftClose = False
, queueTeams = Map.empty
, queueStreamer = twitchUser "josuf107"
, queueSetWins = 0
, queueSetLosses = 0
, queueCrewStockA = 3
, queueCrewStockB = 3
, queueFriendMes = Set.empty
, queueIndex = Map.empty
, queueRulesSingles = "2 Stock, 6m Time, No Items, Legal Stages Only | Refer to !stagelist for legal stages."
, queueRulesDoubles = "3 Stock, 8m Time, No Items, Team Attack On, Legal Stages Only | Refer to !stagelist for legal stages."
, queueRulesCrew = "It's a crew battle."
, queueStagelist = "Battlefield, FD(Omega Palutena’s), Smashville, Town and City, Duck Hunt, Dreamland, and Lylat."
, queueHereMap = Map.empty
, queueInvites = Map.empty
, queueDenyReply = "You can't do that"
, queueWinBuffer = Nothing
, queueListBuffer = Nothing
, queueSinglesLimit = Nothing
, queueDoublesLimit = Nothing
, queueReenterWait = Nothing
, queueHereAlert = Nothing
, queueSinglesBestOf = 3
, queueDoublesBestOf = 3
}
type Modify a = a -> a
type QueueModify a = Modify a -> State Queue ()
type QueueSet a = a -> State Queue ()
setQueueOn :: QueueSet Bool
setQueueOn v = modify $ \q -> q { queueOn = v }
setQueueLastMessage :: QueueSet UTCTime
setQueueLastMessage v = modify $ \q -> q { queueLastMessage = v }
setQueueMode :: QueueSet Mode
setQueueMode v = modify $ \q -> q { queueMode = v }
withQueueAdmins :: QueueModify (Set.Set TwitchUser)
withQueueAdmins f = modify $ \q -> q { queueAdmins = f (queueAdmins q) }
withQueueRestricted :: QueueModify (Set.Set String)
withQueueRestricted f = modify $ \q -> q { queueRestricted = f (queueRestricted q) }
withQueueQueue :: QueueModify (Seq.Seq UserOrTeam)
withQueueQueue f = modify $ \q -> q { queueQueue = f (queueQueue q) }
withQueueSoftClosedList :: QueueModify (Set.Set UserOrTeam)
withQueueSoftClosedList f = modify $ \q -> q { queueSoftClosedList = f (queueSoftClosedList q) }
setQueueSoftClose :: QueueSet Bool
setQueueSoftClose v = modify $ \q -> q { queueSoftClose = v }
setQueueOpen :: QueueSet Bool
setQueueOpen v = modify $ \q -> q { queueOpen = v }
withQueueTeams :: QueueModify (Map.Map TwitchUser TeamName)
withQueueTeams f = modify $ \q -> q { queueTeams = f (queueTeams q) }
withQueueSetWins :: QueueModify Int
withQueueSetWins f = modify $ \q -> q { queueSetWins = f (queueSetWins q) }
withQueueSetLosses :: QueueModify Int
withQueueSetLosses f = modify $ \q -> q { queueSetLosses = f (queueSetLosses q) }
setQueueCrewStockA :: QueueSet Int
setQueueCrewStockA v = modify $ \q -> q { queueCrewStockA = v }
setQueueCrewStockB :: QueueSet Int
setQueueCrewStockB v = modify $ \q -> q { queueCrewStockB = v }
withQueueFriendMes :: QueueModify (Set.Set TwitchUser)
withQueueFriendMes f = modify $ \q -> q { queueFriendMes = f (queueFriendMes q) }
withQueueIndex :: QueueModify (Map.Map TwitchUser (ConnectCode, Int, Int))
withQueueIndex f = modify $ \q -> q { queueIndex = f (queueIndex q) }
setQueueRulesSingles :: QueueSet String
setQueueRulesSingles v = modify $ \q -> q { queueRulesSingles = v }
setQueueRulesDoubles :: QueueSet String
setQueueRulesDoubles v = modify $ \q -> q { queueRulesDoubles = v }
setQueueRulesCrew :: QueueSet String
setQueueRulesCrew v = modify $ \q -> q { queueRulesCrew = v }
setQueueStagelist :: QueueSet String
setQueueStagelist v = modify $ \q -> q { queueStagelist = v }
withQueueHereMap :: QueueModify (Map.Map TwitchUser UTCTime)
withQueueHereMap f = modify $ \q -> q { queueHereMap = f (queueHereMap q) }
withQueueInvites :: QueueModify (Map.Map TwitchUser (Set.Set TeamName))
withQueueInvites f = modify $ \q -> q { queueInvites = f (queueInvites q) }
setQueueStreamer :: QueueSet TwitchUser
setQueueStreamer v = modify $ \q -> q { queueStreamer = v }
setQueueDenyReply :: QueueSet String
setQueueDenyReply v = modify $ \q -> q { queueDenyReply = v }
setQueueWinBuffer :: QueueSet (Maybe Seconds)
setQueueWinBuffer v = modify $ \q -> q { queueWinBuffer = v }
setQueueListBuffer :: QueueSet (Maybe Seconds)
setQueueListBuffer v = modify $ \q -> q { queueListBuffer = v }
setQueueSinglesLimit :: QueueSet (Maybe Int)
setQueueSinglesLimit v = modify $ \q -> q { queueSinglesLimit = v }
setQueueDoublesLimit :: QueueSet (Maybe Int)
setQueueDoublesLimit v = modify $ \q -> q { queueDoublesLimit = v }
setQueueReenterWait :: QueueSet (Maybe Minutes)
setQueueReenterWait v = modify $ \q -> q { queueReenterWait = v }
setQueueHereAlert :: QueueSet (Maybe Seconds)
setQueueHereAlert v = modify $ \q -> q { queueHereAlert = v }
setQueueSinglesBestOf :: QueueSet Int
setQueueSinglesBestOf v = modify $ \q -> q { queueSinglesBestOf = v }
setQueueDoublesBestOf :: QueueSet Int
setQueueDoublesBestOf v = modify $ \q -> q { queueDoublesBestOf = v }
getQueue :: (Queue -> a) -> State Queue a
getQueue f = fmap f get
getFriendMesForMode :: State Queue (Map.Map UserOrTeam [TwitchUser])
getFriendMesForMode = do
teams <- getQueue queueTeams
mode <- getQueue queueMode
friendMeUsers <- getQueue (Set.toList . queueFriendMes)
return . Map.fromListWith (++) . catMaybes . fmap (\k -> case getFriendMe mode teams k of
Nothing -> Nothing
Just userOrTeam -> Just (userOrTeam, [k])) $ friendMeUsers
where
getFriendMe mode teams friendMeUser = case mode of
Singles -> Just . generalizeUser $ friendMeUser
Doubles -> fmap generalizeTeam . Map.lookup friendMeUser $ teams
Crew -> Nothing -- TODO: do we need this?
InvalidMode _ -> Nothing -- This should never happen
getConnectCodes :: UserOrTeam -> State Queue [ConnectCode]
getConnectCodes userOrTeam = do
mode <- getQueue queueMode
case mode of
Singles -> do
let user = twitchUser . getUserOrTeam $ userOrTeam
lookupConnectCode user
Doubles -> do
let team = TeamName . getUserOrTeam $ userOrTeam
users <- getQueue (Map.keys . Map.filter (==team) . queueTeams)
fmap concat (mapM lookupConnectCode users)
Crew -> return [] -- TODO: Crew
InvalidMode _ -> return [] -- Shrug
where
extractConnectCode (connectCode, _, _) = connectCode
lookupConnectCode user = getQueue (fmap extractConnectCode . maybeToList . Map.lookup user . queueIndex)
generalizeUser :: TwitchUser -> UserOrTeam
generalizeUser (TwitchUser user) = UserOrTeam user
generalizeTeam :: TeamName -> UserOrTeam
generalizeTeam (TeamName team) = UserOrTeam team
getCurrentTip :: State Queue (Maybe UserOrTeam)
getCurrentTip = get >>= \q -> case Seq.viewl (queueQueue q) of
(current Seq.:< _) -> return $ Just current
_ -> return Nothing
getNextUp :: State Queue (Maybe UserOrTeam)
getNextUp = get >>= \q -> case Seq.viewl (Seq.drop 1 $ queueQueue q) of
(next Seq.:< _) -> return $ Just next
_ -> return Nothing
getRequiredWins :: State Queue Int
getRequiredWins = do
mode <- getQueue queueMode
bestOf <- case mode of
Singles -> getQueue queueSinglesBestOf
Doubles -> getQueue queueDoublesBestOf
_ -> return 0 -- This doesn't really make sense
return (ceiling . (/(2::Double)) . fromIntegral $ bestOf)
userOrTeamBasedOnMode :: TwitchUser -> State Queue (Maybe UserOrTeam)
userOrTeamBasedOnMode user = get >>= \q -> case queueMode q of
Doubles -> return $ fmap generalizeTeam $ Map.lookup user (queueTeams q)
_ -> return $ Just (generalizeUser user)
| josuf107/xioqbot | src/Queue.hs | bsd-3-clause | 9,279 | 0 | 18 | 1,924 | 2,823 | 1,521 | 1,302 | 200 | 5 |
{- -*- mode: haskell; eval: (turn-on-haskell-unicode-input-method) -*- -}
{-# LANGUAGE UnicodeSyntax #-}
import Prelude.Unicode
main ∷ IO ()
main = putStrLn "Test suite not yet implemented"
| L3n41c/qrar | test/Spec.hs | bsd-3-clause | 194 | 0 | 6 | 28 | 26 | 14 | 12 | 4 | 1 |
module Game (Game(..)) where
import Common
-- ゲームに関する型クラスの宣言
class Game g where
-- ゲームは描画可能
renderGame :: g -> IO ()
-- ゲームはキー入力により更新可能
updateGame :: KeyInputs -> g -> g
| r-edamame/haskell-shooting | app/Game.hs | bsd-3-clause | 255 | 0 | 9 | 40 | 55 | 32 | 23 | 5 | 0 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
module QueryArrow.RPC.Service.FileSystem.TCP where
{-import Control.Monad.Trans.Resource
import Data.Time
import Control.Monad.Except
import System.Log.Logger
import Network
import QueryArrow.Control.Monad.Logger.HSLogger ()
import Control.Concurrent
import QueryArrow.RPC.Message (sendMsgPack, receiveMsgPack)
import System.IO (Handle)
import Data.Aeson
import Data.Maybe
import QueryArrow.RPC.Config
import QueryArrow.FileSystem.Serialization
import QueryArrow.FileSystem.Interpreter
import QueryArrow.RPC.Service
worker3 :: Handle -> Interpreter -> IO ()
worker3 handle i = do
t0 <- getCurrentTime
req0 <- receiveMsgPack handle
infoM "RPC_FS_SERVER" ("received message " ++ show req0)
case fromMaybe (error "message error") req0 of
LocalizedCommandWrapper req -> do
resp <- interpreter i req
sendMsgPack handle resp
t1 <- getCurrentTime
infoM "RPC_FS_SERVER" (show (diffUTCTime t1 t0))
worker3 handle i
Exit ->
return ()
data FileSystemRPCService = FileSystemRPCService
instance RPCService FileSystemRPCService where
startService _ _ ps0 = do
let ps = case fromJSON ps0 of
Error err -> error err
Success ps2 -> ps2
let addr = fs_server_addr ps
port = fs_server_port ps
root = fs_server_root ps
i = makeLocalInterpreter addr port root
infoM "RPC_FS_SERVER" ("listening at " ++ addr ++ ":" ++ show port)
let sockHandler sock = forever $ do
(handle, clientAddr, clientPort) <- accept sock
infoM "RPC_FS_SERVER" ("client connected from " ++ clientAddr ++ " " ++ show clientPort)
forkIO $ runResourceT $
lift $ worker3 handle i
sock <- listenOn (PortNumber (fromIntegral port))
sockHandler sock
-} | xu-hao/QueryArrow | QueryArrow-rpc-socket/src/QueryArrow/RPC/Service/FileSystem/TCP.hs | bsd-3-clause | 1,958 | 0 | 3 | 524 | 11 | 9 | 2 | 2 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Main
where
import GalFld.Core
import TestsCommon
--------------------------------------------------------------------------------
main :: IO ()
main = hspec $ do
describe "GalFld.Core.PrimeFields" $ do
it "modulus should give the modulus" $ do
modulus (2 ::F2) `shouldBe` 2
modulus (2 ::F3) `shouldBe` 3
modulus (2 ::F5) `shouldBe` 5
modulus (2 ::F101) `shouldBe` 101
it "test Eq" $ do
(2 ::F2) `shouldBe` (0 ::F2)
(2 ::F2) `shouldBe` (4 ::F2)
it "1^{-1} == 1" $
recip (1::F101) `shouldBe` (1 ::F101)
it "x/0 throws exception" $
evaluate ((3::F101) / (0::F101)) `shouldThrow` anyException
it "0/0 throws exception" $
evaluate ((0::F101) / (0::F101)) `shouldThrow` anyException
{-
it "test invMod (x/x=1) in F101" $ mapM_
(\ x -> x / x `shouldBe` (1 ::F101))
(units undefined ::[F101])
it "test invMod (x/x*x=x) in F101" $ mapM_
(\ x -> x / x * x `shouldBe` x)
(units undefined ::[F101])
-}
describe "GalFld.Core.PrimeFields @F2" $ do
testFieldSpec (1::F2)
it "charRootP should be inverse to ^p (full)" $
pMapM_ (\f -> charRootP (f ^ 2) `shouldBe` f)
(getAllP (elems (1::F2)) 4)
describe "GalFld.Core.PrimeFields @F3" $ do
testFieldSpec (1::F3)
it "charRootP should be inverse to ^p (full)" $
pMapM_ (\f -> charRootP (f ^ 3) `shouldBe` f)
(getAllP (elems (1::F3)) 4)
describe "GalFld.Core.PrimeFields @F5" $ do
testFieldSpec (1::F5)
it "charRootP should be inverse to ^p (full)" $
pMapM_ (\f -> charRootP (f ^ 5) `shouldBe` f)
(getAllP (elems (1::F5)) 4)
{-
describe "GalFld.Core.PrimeFields @F101" $ do
testFieldSpec (1::F101)
-}
{-
it "charRootP should be inverse to ^p (full)" $
pMapM_ (\f -> charRootP (f ^ 101) `shouldBe` f)
(getAllP (elems (1::F101)) 4)
-}
| maximilianhuber/softwareProjekt | test/PFTests.hs | bsd-3-clause | 2,021 | 0 | 18 | 582 | 530 | 283 | 247 | 36 | 1 |
{-# LANGUAGE CPP, OverloadedStrings, TemplateHaskell #-}
module AUVLog where
import Control.Concurrent
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import qualified Data.Time.Clock.POSIX as CL
import qualified Nanomsg as N
import PseudoMacros
newtype AUVLogConn = AUVLogConn { unAUVLogConn :: N.Socket N.Pub }
initialize ∷ IO AUVLogConn
initialize = do
sock <- N.socket N.Pub
_ <- N.connect sock "tcp://127.0.0.1:7654"
threadDelay 10000
return $ AUVLogConn sock
logRaw ∷ AUVLogConn → T.Text → T.Text → T.Text → Int → T.Text → T.Text → IO ()
logRaw (AUVLogConn sock) tree msg file line block linetxt = do
now <- CL.getPOSIXTime
let obj = A.Object $ M.fromList [
("tree", A.String tree),
("timestamp", A.Number $ fromRational $ toRational now),
("message", A.String msg),
("filename", A.String file),
("lineno", A.Number $ fromIntegral line),
("block", A.String block),
("linetxt", A.String linetxt)
]
N.send sock $ BL.toStrict $ A.encode obj
wlog ∷ AUVLogConn → T.Text → T.Text → IO ()
wlog c t m = logRaw c t m __FILE__ __LINE__ ($__PACKAGE__) ($__MODULE__)
| cuauv/software | auvlog/AUVLog.hs | bsd-3-clause | 1,382 | 0 | 16 | 364 | 437 | 237 | 200 | 31 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Noelm.Get.Server.Generate.Html where
import Control.Monad.Error
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.String (renderHtml)
import System.FilePath as FP
import System.Directory
import qualified Data.ByteString.Char8 as BSC
import qualified Noelm.Get.Utils.Commands as Cmd
generatePublic :: FilePath -> ErrorT String IO ()
generatePublic path =
do Cmd.run "noelm" ["--make","--runtime=/resources/noelm-runtime.js"
, "--build-dir=.", "--src-dir=src", path]
liftIO $ removeFile path
liftIO $ adjustHtmlFile $ FP.replaceExtension path "html"
generateSrc :: FilePath -> ErrorT String IO ()
generateSrc path =
do Cmd.run "noelm" ["--make","--runtime=/resources/noelm-runtime.js"
, "--build-dir=.", "--src-dir=src", path]
let old = FP.replaceExtension path "html"
new = FP.replaceDirectory old "public"
liftIO $ do
renameFile old new
adjustHtmlFile new
adjustHtmlFile :: FilePath -> IO ()
adjustHtmlFile file =
do src <- BSC.readFile file
let (before, after) = BSC.breakSubstring "<title>" src
BSC.writeFile file $ BSC.concat [before, style, after]
style :: BSC.ByteString
style =
"<style type=\"text/css\">\n\
\ a:link {text-decoration: none; color: rgb(15,102,230);}\n\
\ a:visited {text-decoration: none; color: rgb(15,102,230);}\n\
\ a:active {text-decoration: none}\n\
\ a:hover {text-decoration: underline; color: rgb(234,21,122);}\n\
\ body { font-family: \"Lucida Grande\",\"Trebuchet MS\",\"Bitstream Vera Sans\",Verdana,Helvetica,sans-serif !important; }\n\
\ p, li { font-size: 14px !important;\n\
\ line-height: 1.5em !important; }\n\
\</style>" | timthelion/noelm-get-server | src/Noelm/Get/Server/Generate/Html.hs | bsd-3-clause | 1,878 | 0 | 11 | 345 | 366 | 202 | 164 | 34 | 1 |
module Language.Expression
(
module Language.Expression.Expression,
module Language.Expression.Value,
module Language.Expression.Match,
module Language.Expression.Pattern,
module Language.Expression.Regular,
module Language.Expression.Mono,
) where
{
import Language.Expression.Expression;
import Language.Expression.Value;
import Language.Expression.Match;
import Language.Expression.Pattern;
import Language.Expression.Regular;
import Language.Expression.Mono;
}
| AshleyYakeley/expression | src/Language/Expression.hs | bsd-3-clause | 513 | 0 | 5 | 79 | 95 | 68 | 27 | 14 | 0 |
{-# LANGUAGE FlexibleContexts, GADTs, BangPatterns, MagicHash #-}
{-|
Module : Matrix.Mult
Description : Provides fucntions for matrix multiplication.
Provides fucntions for matrix multiplication.
-}
module Data.Matrix.Mult (matMult) where
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import Control.Loop
import Data.Matrix.Base
-- help from https://hackage.haskell.org/package/matrix-0.3.4.4/docs/src/Data-Matrix.html
-- |Multiplies two 'Matrix's using matrix multiplication
matMult, unsafeMatMult :: (Num a, MV.Unbox a) => Matrix a -> Matrix a -> Matrix a
matMult a b | cols a == rows b = unsafeMatMult a b
| otherwise = error "The number of columns of the first matrix must equal the number of rows of the second matrix"
unsafeMatMult a b = b { vector = newB }
where
newB = V.create $ do
out <- {-# SCC "alloc_new" #-} MV.new (len b)
let ra = rows a
rb = rows b
numLoop 0 (cols b - 1) $ \c ->
numLoop 0 3 $ \r -> do
let !a' = vector a
!b' = vector b
fa = ra + r
fb = c * rb
!a1 = a' `V.unsafeIndex` r
!b1 = b' `V.unsafeIndex` fb
!a2 = a' `V.unsafeIndex` fa
!b2 = b' `V.unsafeIndex` (fb + 1)
!a3 = a' `V.unsafeIndex` (fa + ra)
!b3 = b' `V.unsafeIndex` (fb + 2)
!a4 = a' `V.unsafeIndex` (fa + ra + ra)
!b4 = b' `V.unsafeIndex` (fb + 3)
MV.unsafeWrite out (fb + r) $ (a1 * b1) + (a2 * b2) + (a3 * b3) + (a4 * b4)
return out
{-# SPECIALIZE matMult :: Matrix Double -> Matrix Double -> Matrix Double #-}
{-# SPECIALIZE unsafeMatMult :: Matrix Double -> Matrix Double -> Matrix Double #-}
{-# SPECIALIZE matMult :: Matrix Int -> Matrix Int -> Matrix Int #-}
{-# SPECIALIZE unsafeMatMult :: Matrix Int -> Matrix Int -> Matrix Int #-}
| jbaum98/graphics | src/Data/Matrix/Mult.hs | bsd-3-clause | 1,939 | 0 | 22 | 561 | 513 | 271 | 242 | 34 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Writer.Lazy
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (multi-param classes, functional dependencies)
--
-- Lazy writer monads.
--
-- Inspired by the paper
-- /Functional Programming with Overloading and Higher-Order Polymorphism/,
-- Mark P Jones (<http://web.cecs.pdx.edu/~mpj/pubs/springschool.html>)
-- Advanced School of Functional Programming, 1995.
-----------------------------------------------------------------------------
module Control.Monad.Writer.Lazy (
-- * MonadWriter class
MonadWriter(..),
listens,
censor,
-- * The Writer monad
Writer,
runWriter,
execWriter,
mapWriter,
-- * The WriterT monad transformer
WriterT(..),
execWriterT,
mapWriterT,
module Control.Monad,
module Control.Monad.Fix,
module Control.Monad.Trans,
module Data.Monoid,
) where
import Control.Monad.Writer.Class
import Control.Monad.Trans
import Control.Monad.Trans.Writer.Lazy (
Writer, runWriter, execWriter, mapWriter,
WriterT(..), execWriterT, mapWriterT)
import Control.Monad
import Control.Monad.Fix
import Data.Monoid
| davnils/minijava-compiler | lib/mtl-2.1.3.1/Control/Monad/Writer/Lazy.hs | bsd-3-clause | 1,476 | 0 | 6 | 290 | 160 | 116 | 44 | 23 | 0 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE DeriveDataTypeable, BangPatterns #-}
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName' represents names as strings with just a little more information:
-- the \"namespace\" that the name came from, e.g. the namespace of value, type constructors or
-- data constructors
--
-- * 'RdrName.RdrName': see "RdrName#name_types"
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
-- * 'Var.Var': see "Var#name_types"
module OccName (
-- * The 'NameSpace' type
NameSpace, -- Abstract
nameSpacesRelated,
-- ** Construction
-- $real_vs_source_data_constructors
tcName, clsName, tcClsName, dataName, varName,
tvName, srcDataName,
-- ** Pretty Printing
pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief,
-- * The 'OccName' type
OccName, -- Abstract, instance of Outputable
pprOccName,
-- ** Construction
mkOccName, mkOccNameFS,
mkVarOcc, mkVarOccFS,
mkDataOcc, mkDataOccFS,
mkTyVarOcc, mkTyVarOccFS,
mkTcOcc, mkTcOccFS,
mkClsOcc, mkClsOccFS,
mkDFunOcc,
setOccNameSpace,
demoteOccName,
HasOccName(..),
-- ** Derived 'OccName's
isDerivedOccName,
mkDataConWrapperOcc, mkWorkerOcc,
mkMatcherOcc, mkBuilderOcc,
mkDefaultMethodOcc,
mkNewTyCoOcc, mkClassOpAuxOcc,
mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc,
mkClassDataConOcc, mkDictOcc, mkIPOcc,
mkSpecOcc, mkForeignExportOcc, mkRepEqOcc,
mkGenD, mkGenR, mkGen1R, mkGenRCo, mkGenC, mkGenS,
mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc,
mkSuperDictSelOcc, mkSuperDictAuxOcc,
mkLocalOcc, mkMethodOcc, mkInstTyTcOcc,
mkInstTyCoOcc, mkEqPredCoOcc,
mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
mkPDataTyConOcc, mkPDataDataConOcc,
mkPDatasTyConOcc, mkPDatasDataConOcc,
mkPReprTyConOcc,
mkPADFunOcc,
mkRecFldSelOcc,
mkTyConRepOcc,
-- ** Deconstruction
occNameFS, occNameString, occNameSpace,
isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc,
parenSymOcc, startsWithUnderscore,
isTcClsNameSpace, isTvNameSpace, isDataConNameSpace, isVarNameSpace, isValNameSpace,
-- * The 'OccEnv' type
OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv,
lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv,
occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C,
extendOccEnv_Acc, filterOccEnv, delListFromOccEnv, delFromOccEnv,
alterOccEnv, pprOccEnv,
-- * The 'OccSet' type
OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet,
extendOccSetList,
unionOccSets, unionManyOccSets, minusOccSet, elemOccSet, occSetElts,
foldOccSet, isEmptyOccSet, intersectOccSet, intersectsOccSet,
filterOccSet,
-- * Tidying up
TidyOccEnv, emptyTidyOccEnv, tidyOccName, initTidyOccEnv,
-- FsEnv
FastStringEnv, emptyFsEnv, lookupFsEnv, extendFsEnv, mkFsEnv
) where
import Util
import Unique
import DynFlags
import UniqFM
import UniqSet
import FastString
import FastStringEnv
import Outputable
import Lexeme
import Binary
import Module
import Data.Char
import Data.Data
{-
************************************************************************
* *
\subsection{Name space}
* *
************************************************************************
-}
data NameSpace = VarName -- Variables, including "real" data constructors
| DataName -- "Source" data constructors
| TvName -- Type variables
| TcClsName -- Type constructors and classes; Haskell has them
-- in the same name space for now.
deriving( Eq, Ord )
{-! derive: Binary !-}
-- Note [Data Constructors]
-- see also: Note [Data Constructor Naming] in DataCon.hs
--
-- $real_vs_source_data_constructors
-- There are two forms of data constructor:
--
-- [Source data constructors] The data constructors mentioned in Haskell source code
--
-- [Real data constructors] The data constructors of the representation type, which may not be the same as the source type
--
-- For example:
--
-- > data T = T !(Int, Int)
--
-- The source datacon has type @(Int, Int) -> T@
-- The real datacon has type @Int -> Int -> T@
--
-- GHC chooses a representation based on the strictness etc.
tcName, clsName, tcClsName :: NameSpace
dataName, srcDataName :: NameSpace
tvName, varName :: NameSpace
-- Though type constructors and classes are in the same name space now,
-- the NameSpace type is abstract, so we can easily separate them later
tcName = TcClsName -- Type constructors
clsName = TcClsName -- Classes
tcClsName = TcClsName -- Not sure which!
dataName = DataName
srcDataName = DataName -- Haskell-source data constructors should be
-- in the Data name space
tvName = TvName
varName = VarName
isDataConNameSpace :: NameSpace -> Bool
isDataConNameSpace DataName = True
isDataConNameSpace _ = False
isTcClsNameSpace :: NameSpace -> Bool
isTcClsNameSpace TcClsName = True
isTcClsNameSpace _ = False
isTvNameSpace :: NameSpace -> Bool
isTvNameSpace TvName = True
isTvNameSpace _ = False
isVarNameSpace :: NameSpace -> Bool -- Variables or type variables, but not constructors
isVarNameSpace TvName = True
isVarNameSpace VarName = True
isVarNameSpace _ = False
isValNameSpace :: NameSpace -> Bool
isValNameSpace DataName = True
isValNameSpace VarName = True
isValNameSpace _ = False
pprNameSpace :: NameSpace -> SDoc
pprNameSpace DataName = text "data constructor"
pprNameSpace VarName = text "variable"
pprNameSpace TvName = text "type variable"
pprNameSpace TcClsName = text "type constructor or class"
pprNonVarNameSpace :: NameSpace -> SDoc
pprNonVarNameSpace VarName = empty
pprNonVarNameSpace ns = pprNameSpace ns
pprNameSpaceBrief :: NameSpace -> SDoc
pprNameSpaceBrief DataName = char 'd'
pprNameSpaceBrief VarName = char 'v'
pprNameSpaceBrief TvName = text "tv"
pprNameSpaceBrief TcClsName = text "tc"
-- demoteNameSpace lowers the NameSpace if possible. We can not know
-- in advance, since a TvName can appear in an HsTyVar.
-- See Note [Demotion] in RnEnv
demoteNameSpace :: NameSpace -> Maybe NameSpace
demoteNameSpace VarName = Nothing
demoteNameSpace DataName = Nothing
demoteNameSpace TvName = Nothing
demoteNameSpace TcClsName = Just DataName
{-
************************************************************************
* *
\subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
* *
************************************************************************
-}
data OccName = OccName
{ occNameSpace :: !NameSpace
, occNameFS :: !FastString
}
deriving Typeable
instance Eq OccName where
(OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2
instance Ord OccName where
-- Compares lexicographically, *not* by Unique of the string
compare (OccName sp1 s1) (OccName sp2 s2)
= (s1 `compare` s2) `thenCmp` (sp1 `compare` sp2)
instance Data OccName where
-- don't traverse?
toConstr _ = abstractConstr "OccName"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "OccName"
instance HasOccName OccName where
occName = id
{-
************************************************************************
* *
\subsection{Printing}
* *
************************************************************************
-}
instance Outputable OccName where
ppr = pprOccName
instance OutputableBndr OccName where
pprBndr _ = ppr
pprInfixOcc n = pprInfixVar (isSymOcc n) (ppr n)
pprPrefixOcc n = pprPrefixVar (isSymOcc n) (ppr n)
pprOccName :: OccName -> SDoc
pprOccName (OccName sp occ)
= getPprStyle $ \ sty ->
if codeStyle sty
then ztext (zEncodeFS occ)
else pp_occ <> pp_debug sty
where
pp_debug sty | debugStyle sty = braces (pprNameSpaceBrief sp)
| otherwise = empty
pp_occ = sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressUniques dflags
then text (strip_th_unique (unpackFS occ))
else ftext occ
-- See Note [Suppressing uniques in OccNames]
strip_th_unique ('[' : c : _) | isAlphaNum c = []
strip_th_unique (c : cs) = c : strip_th_unique cs
strip_th_unique [] = []
{-
Note [Suppressing uniques in OccNames]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a hack to de-wobblify the OccNames that contain uniques from
Template Haskell that have been turned into a string in the OccName.
See Note [Unique OccNames from Template Haskell] in Convert.hs
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
mkOccName :: NameSpace -> String -> OccName
mkOccName occ_sp str = OccName occ_sp (mkFastString str)
mkOccNameFS :: NameSpace -> FastString -> OccName
mkOccNameFS occ_sp fs = OccName occ_sp fs
mkVarOcc :: String -> OccName
mkVarOcc s = mkOccName varName s
mkVarOccFS :: FastString -> OccName
mkVarOccFS fs = mkOccNameFS varName fs
mkDataOcc :: String -> OccName
mkDataOcc = mkOccName dataName
mkDataOccFS :: FastString -> OccName
mkDataOccFS = mkOccNameFS dataName
mkTyVarOcc :: String -> OccName
mkTyVarOcc = mkOccName tvName
mkTyVarOccFS :: FastString -> OccName
mkTyVarOccFS fs = mkOccNameFS tvName fs
mkTcOcc :: String -> OccName
mkTcOcc = mkOccName tcName
mkTcOccFS :: FastString -> OccName
mkTcOccFS = mkOccNameFS tcName
mkClsOcc :: String -> OccName
mkClsOcc = mkOccName clsName
mkClsOccFS :: FastString -> OccName
mkClsOccFS = mkOccNameFS clsName
-- demoteOccName lowers the Namespace of OccName.
-- see Note [Demotion]
demoteOccName :: OccName -> Maybe OccName
demoteOccName (OccName space name) = do
space' <- demoteNameSpace space
return $ OccName space' name
-- Name spaces are related if there is a chance to mean the one when one writes
-- the other, i.e. variables <-> data constructors and type variables <-> type constructors
nameSpacesRelated :: NameSpace -> NameSpace -> Bool
nameSpacesRelated ns1 ns2 = ns1 == ns2 || otherNameSpace ns1 == ns2
otherNameSpace :: NameSpace -> NameSpace
otherNameSpace VarName = DataName
otherNameSpace DataName = VarName
otherNameSpace TvName = TcClsName
otherNameSpace TcClsName = TvName
{- | Other names in the compiler add additional information to an OccName.
This class provides a consistent way to access the underlying OccName. -}
class HasOccName name where
occName :: name -> OccName
{-
************************************************************************
* *
Environments
* *
************************************************************************
OccEnvs are used mainly for the envts in ModIfaces.
Note [The Unique of an OccName]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
They are efficient, because FastStrings have unique Int# keys. We assume
this key is less than 2^24, and indeed FastStrings are allocated keys
sequentially starting at 0.
So we can make a Unique using
mkUnique ns key :: Unique
where 'ns' is a Char representing the name space. This in turn makes it
easy to build an OccEnv.
-}
instance Uniquable OccName where
-- See Note [The Unique of an OccName]
getUnique (OccName VarName fs) = mkVarOccUnique fs
getUnique (OccName DataName fs) = mkDataOccUnique fs
getUnique (OccName TvName fs) = mkTvOccUnique fs
getUnique (OccName TcClsName fs) = mkTcOccUnique fs
newtype OccEnv a = A (UniqFM a)
deriving (Data, Typeable)
emptyOccEnv :: OccEnv a
unitOccEnv :: OccName -> a -> OccEnv a
extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a
extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a
lookupOccEnv :: OccEnv a -> OccName -> Maybe a
mkOccEnv :: [(OccName,a)] -> OccEnv a
mkOccEnv_C :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a
elemOccEnv :: OccName -> OccEnv a -> Bool
foldOccEnv :: (a -> b -> b) -> b -> OccEnv a -> b
occEnvElts :: OccEnv a -> [a]
extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a
extendOccEnv_Acc :: (a->b->b) -> (a->b) -> OccEnv b -> OccName -> a -> OccEnv b
plusOccEnv :: OccEnv a -> OccEnv a -> OccEnv a
plusOccEnv_C :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a
mapOccEnv :: (a->b) -> OccEnv a -> OccEnv b
delFromOccEnv :: OccEnv a -> OccName -> OccEnv a
delListFromOccEnv :: OccEnv a -> [OccName] -> OccEnv a
filterOccEnv :: (elt -> Bool) -> OccEnv elt -> OccEnv elt
alterOccEnv :: (Maybe elt -> Maybe elt) -> OccEnv elt -> OccName -> OccEnv elt
emptyOccEnv = A emptyUFM
unitOccEnv x y = A $ unitUFM x y
extendOccEnv (A x) y z = A $ addToUFM x y z
extendOccEnvList (A x) l = A $ addListToUFM x l
lookupOccEnv (A x) y = lookupUFM x y
mkOccEnv l = A $ listToUFM l
elemOccEnv x (A y) = elemUFM x y
foldOccEnv a b (A c) = foldUFM a b c
occEnvElts (A x) = eltsUFM x
plusOccEnv (A x) (A y) = A $ plusUFM x y
plusOccEnv_C f (A x) (A y) = A $ plusUFM_C f x y
extendOccEnv_C f (A x) y z = A $ addToUFM_C f x y z
extendOccEnv_Acc f g (A x) y z = A $ addToUFM_Acc f g x y z
mapOccEnv f (A x) = A $ mapUFM f x
mkOccEnv_C comb l = A $ addListToUFM_C comb emptyUFM l
delFromOccEnv (A x) y = A $ delFromUFM x y
delListFromOccEnv (A x) y = A $ delListFromUFM x y
filterOccEnv x (A y) = A $ filterUFM x y
alterOccEnv fn (A y) k = A $ alterUFM fn y k
instance Outputable a => Outputable (OccEnv a) where
ppr x = pprOccEnv ppr x
pprOccEnv :: (a -> SDoc) -> OccEnv a -> SDoc
pprOccEnv ppr_elt (A env) = pprUniqFM ppr_elt env
type OccSet = UniqSet OccName
emptyOccSet :: OccSet
unitOccSet :: OccName -> OccSet
mkOccSet :: [OccName] -> OccSet
extendOccSet :: OccSet -> OccName -> OccSet
extendOccSetList :: OccSet -> [OccName] -> OccSet
unionOccSets :: OccSet -> OccSet -> OccSet
unionManyOccSets :: [OccSet] -> OccSet
minusOccSet :: OccSet -> OccSet -> OccSet
elemOccSet :: OccName -> OccSet -> Bool
occSetElts :: OccSet -> [OccName]
foldOccSet :: (OccName -> b -> b) -> b -> OccSet -> b
isEmptyOccSet :: OccSet -> Bool
intersectOccSet :: OccSet -> OccSet -> OccSet
intersectsOccSet :: OccSet -> OccSet -> Bool
filterOccSet :: (OccName -> Bool) -> OccSet -> OccSet
emptyOccSet = emptyUniqSet
unitOccSet = unitUniqSet
mkOccSet = mkUniqSet
extendOccSet = addOneToUniqSet
extendOccSetList = addListToUniqSet
unionOccSets = unionUniqSets
unionManyOccSets = unionManyUniqSets
minusOccSet = minusUniqSet
elemOccSet = elementOfUniqSet
occSetElts = uniqSetToList
foldOccSet = foldUniqSet
isEmptyOccSet = isEmptyUniqSet
intersectOccSet = intersectUniqSets
intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2))
filterOccSet = filterUniqSet
{-
************************************************************************
* *
\subsection{Predicates and taking them apart}
* *
************************************************************************
-}
occNameString :: OccName -> String
occNameString (OccName _ s) = unpackFS s
setOccNameSpace :: NameSpace -> OccName -> OccName
setOccNameSpace sp (OccName _ occ) = OccName sp occ
isVarOcc, isTvOcc, isTcOcc, isDataOcc :: OccName -> Bool
isVarOcc (OccName VarName _) = True
isVarOcc _ = False
isTvOcc (OccName TvName _) = True
isTvOcc _ = False
isTcOcc (OccName TcClsName _) = True
isTcOcc _ = False
-- | /Value/ 'OccNames's are those that are either in
-- the variable or data constructor namespaces
isValOcc :: OccName -> Bool
isValOcc (OccName VarName _) = True
isValOcc (OccName DataName _) = True
isValOcc _ = False
isDataOcc (OccName DataName _) = True
isDataOcc _ = False
-- | Test if the 'OccName' is a data constructor that starts with
-- a symbol (e.g. @:@, or @[]@)
isDataSymOcc :: OccName -> Bool
isDataSymOcc (OccName DataName s) = isLexConSym s
isDataSymOcc _ = False
-- Pretty inefficient!
-- | Test if the 'OccName' is that for any operator (whether
-- it is a data constructor or variable or whatever)
isSymOcc :: OccName -> Bool
isSymOcc (OccName DataName s) = isLexConSym s
isSymOcc (OccName TcClsName s) = isLexSym s
isSymOcc (OccName VarName s) = isLexSym s
isSymOcc (OccName TvName s) = isLexSym s
-- Pretty inefficient!
parenSymOcc :: OccName -> SDoc -> SDoc
-- ^ Wrap parens around an operator
parenSymOcc occ doc | isSymOcc occ = parens doc
| otherwise = doc
startsWithUnderscore :: OccName -> Bool
-- ^ Haskell 98 encourages compilers to suppress warnings about unsed
-- names in a pattern if they start with @_@: this implements that test
startsWithUnderscore occ = case occNameString occ of
('_' : _) -> True
_other -> False
{-
************************************************************************
* *
\subsection{Making system names}
* *
************************************************************************
Here's our convention for splitting up the interface file name space:
d... dictionary identifiers
(local variables, so no name-clash worries)
All of these other OccNames contain a mixture of alphabetic
and symbolic characters, and hence cannot possibly clash with
a user-written type or function name
$f... Dict-fun identifiers (from inst decls)
$dmop Default method for 'op'
$pnC n'th superclass selector for class C
$wf Worker for function 'f'
$sf.. Specialised version of f
D:C Data constructor for dictionary for class C
NTCo:T Coercion connecting newtype T with its representation type
TFCo:R Coercion connecting a data family to its representation type R
In encoded form these appear as Zdfxxx etc
:... keywords (export:, letrec: etc.)
--- I THINK THIS IS WRONG!
This knowledge is encoded in the following functions.
@mk_deriv@ generates an @OccName@ from the prefix and a string.
NB: The string must already be encoded!
-}
mk_deriv :: NameSpace
-> String -- Distinguishes one sort of derived name from another
-> String
-> OccName
mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str)
isDerivedOccName :: OccName -> Bool
-- ^ Test for definitions internally generated by GHC. This predicte
-- is used to suppress printing of internal definitions in some debug prints
isDerivedOccName occ =
case occNameString occ of
'$':c:_ | isAlphaNum c -> True -- E.g. $wfoo
c:':':_ | isAlphaNum c -> True -- E.g. N:blah newtype coercions
_other -> False
mkDataConWrapperOcc, mkWorkerOcc,
mkMatcherOcc, mkBuilderOcc,
mkDefaultMethodOcc,
mkClassDataConOcc, mkDictOcc,
mkIPOcc, mkSpecOcc, mkForeignExportOcc, mkRepEqOcc,
mkGenR, mkGen1R, mkGenRCo,
mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkNewTyCoOcc,
mkInstTyCoOcc, mkEqPredCoOcc, mkClassOpAuxOcc,
mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc,
mkTyConRepOcc
:: OccName -> OccName
-- These derived variables have a prefix that no Haskell value could have
mkDataConWrapperOcc = mk_simple_deriv varName "$W"
mkWorkerOcc = mk_simple_deriv varName "$w"
mkMatcherOcc = mk_simple_deriv varName "$m"
mkBuilderOcc = mk_simple_deriv varName "$b"
mkDefaultMethodOcc = mk_simple_deriv varName "$dm"
mkClassOpAuxOcc = mk_simple_deriv varName "$c"
mkDictOcc = mk_simple_deriv varName "$d"
mkIPOcc = mk_simple_deriv varName "$i"
mkSpecOcc = mk_simple_deriv varName "$s"
mkForeignExportOcc = mk_simple_deriv varName "$f"
mkRepEqOcc = mk_simple_deriv tvName "$r" -- In RULES involving Coercible
mkClassDataConOcc = mk_simple_deriv dataName "C:" -- Data con for a class
mkNewTyCoOcc = mk_simple_deriv tcName "N:" -- Coercion for newtypes
mkInstTyCoOcc = mk_simple_deriv tcName "D:" -- Coercion for type functions
mkEqPredCoOcc = mk_simple_deriv tcName "$co"
-- Used in derived instances
mkCon2TagOcc = mk_simple_deriv varName "$con2tag_"
mkTag2ConOcc = mk_simple_deriv varName "$tag2con_"
mkMaxTagOcc = mk_simple_deriv varName "$maxtag_"
-- TyConRepName stuff; see Note [Grand plan for Typeable] in TcTypeable
mkTyConRepOcc occ = mk_simple_deriv varName prefix occ
where
prefix | isDataOcc occ = "$tc'"
| otherwise = "$tc"
-- Generic deriving mechanism
-- | Generate a module-unique name, to be used e.g. while generating new names
-- for Generics types. We use module unit id to avoid name clashes when
-- package imports is used.
mkModPrefix :: Module -> String
mkModPrefix mod = pk ++ "_" ++ mn
where
pk = unitIdString (moduleUnitId mod)
mn = moduleNameString (moduleName mod)
mkGenD :: Module -> OccName -> OccName
mkGenD mod = mk_simple_deriv tcName ("D1_" ++ mkModPrefix mod ++ "_")
mkGenC :: Module -> OccName -> Int -> OccName
mkGenC mod occ m =
mk_deriv tcName ("C1_" ++ show m) $
mkModPrefix mod ++ "_" ++ occNameString occ
mkGenS :: Module -> OccName -> Int -> Int -> OccName
mkGenS mod occ m n =
mk_deriv tcName ("S1_" ++ show m ++ "_" ++ show n) $
mkModPrefix mod ++ "_" ++ occNameString occ
mkGenR = mk_simple_deriv tcName "Rep_"
mkGen1R = mk_simple_deriv tcName "Rep1_"
mkGenRCo = mk_simple_deriv tcName "CoRep_"
-- data T = MkT ... deriving( Data ) needs definitions for
-- $tT :: Data.Generics.Basics.DataType
-- $cMkT :: Data.Generics.Basics.Constr
mkDataTOcc = mk_simple_deriv varName "$t"
mkDataCOcc = mk_simple_deriv varName "$c"
-- Vectorisation
mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
mkPADFunOcc, mkPReprTyConOcc,
mkPDataTyConOcc, mkPDataDataConOcc,
mkPDatasTyConOcc, mkPDatasDataConOcc
:: Maybe String -> OccName -> OccName
mkVectOcc = mk_simple_deriv_with varName "$v"
mkVectTyConOcc = mk_simple_deriv_with tcName "V:"
mkVectDataConOcc = mk_simple_deriv_with dataName "VD:"
mkVectIsoOcc = mk_simple_deriv_with varName "$vi"
mkPADFunOcc = mk_simple_deriv_with varName "$pa"
mkPReprTyConOcc = mk_simple_deriv_with tcName "VR:"
mkPDataTyConOcc = mk_simple_deriv_with tcName "VP:"
mkPDatasTyConOcc = mk_simple_deriv_with tcName "VPs:"
mkPDataDataConOcc = mk_simple_deriv_with dataName "VPD:"
mkPDatasDataConOcc = mk_simple_deriv_with dataName "VPDs:"
-- Overloaded record field selectors
mkRecFldSelOcc :: String -> OccName
mkRecFldSelOcc = mk_deriv varName "$sel"
mk_simple_deriv :: NameSpace -> String -> OccName -> OccName
mk_simple_deriv sp px occ = mk_deriv sp px (occNameString occ)
mk_simple_deriv_with :: NameSpace -> String -> Maybe String -> OccName -> OccName
mk_simple_deriv_with sp px Nothing occ = mk_deriv sp px (occNameString occ)
mk_simple_deriv_with sp px (Just with) occ = mk_deriv sp (px ++ with ++ "_") (occNameString occ)
-- Data constructor workers are made by setting the name space
-- of the data constructor OccName (which should be a DataName)
-- to VarName
mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ
mkSuperDictAuxOcc :: Int -> OccName -> OccName
mkSuperDictAuxOcc index cls_tc_occ
= mk_deriv varName "$cp" (show index ++ occNameString cls_tc_occ)
mkSuperDictSelOcc :: Int -- ^ Index of superclass, e.g. 3
-> OccName -- ^ Class, e.g. @Ord@
-> OccName -- ^ Derived 'Occname', e.g. @$p3Ord@
mkSuperDictSelOcc index cls_tc_occ
= mk_deriv varName "$p" (show index ++ occNameString cls_tc_occ)
mkLocalOcc :: Unique -- ^ Unique to combine with the 'OccName'
-> OccName -- ^ Local name, e.g. @sat@
-> OccName -- ^ Nice unique version, e.g. @$L23sat@
mkLocalOcc uniq occ
= mk_deriv varName ("$L" ++ show uniq) (occNameString occ)
-- The Unique might print with characters
-- that need encoding (e.g. 'z'!)
-- | Derive a name for the representation type constructor of a
-- @data@\/@newtype@ instance.
mkInstTyTcOcc :: String -- ^ Family name, e.g. @Map@
-> OccSet -- ^ avoid these Occs
-> OccName -- ^ @R:Map@
mkInstTyTcOcc str set =
chooseUniqueOcc tcName ('R' : ':' : str) set
mkDFunOcc :: String -- ^ Typically the class and type glommed together e.g. @OrdMaybe@.
-- Only used in debug mode, for extra clarity
-> Bool -- ^ Is this a hs-boot instance DFun?
-> OccSet -- ^ avoid these Occs
-> OccName -- ^ E.g. @$f3OrdMaybe@
-- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real
-- thing when we compile the mother module. Reason: we don't know exactly
-- what the mother module will call it.
mkDFunOcc info_str is_boot set
= chooseUniqueOcc VarName (prefix ++ info_str) set
where
prefix | is_boot = "$fx"
| otherwise = "$f"
{-
Sometimes we need to pick an OccName that has not already been used,
given a set of in-use OccNames.
-}
chooseUniqueOcc :: NameSpace -> String -> OccSet -> OccName
chooseUniqueOcc ns str set = loop (mkOccName ns str) (0::Int)
where
loop occ n
| occ `elemOccSet` set = loop (mkOccName ns (str ++ show n)) (n+1)
| otherwise = occ
{-
We used to add a '$m' to indicate a method, but that gives rise to bad
error messages from the type checker when we print the function name or pattern
of an instance-decl binding. Why? Because the binding is zapped
to use the method name in place of the selector name.
(See TcClassDcl.tcMethodBind)
The way it is now, -ddump-xx output may look confusing, but
you can always say -dppr-debug to get the uniques.
However, we *do* have to zap the first character to be lower case,
because overloaded constructors (blarg) generate methods too.
And convert to VarName space
e.g. a call to constructor MkFoo where
data (Ord a) => Foo a = MkFoo a
If this is necessary, we do it by prefixing '$m'. These
guys never show up in error messages. What a hack.
-}
mkMethodOcc :: OccName -> OccName
mkMethodOcc occ@(OccName VarName _) = occ
mkMethodOcc occ = mk_simple_deriv varName "$m" occ
{-
************************************************************************
* *
\subsection{Tidying them up}
* *
************************************************************************
Before we print chunks of code we like to rename it so that
we don't have to print lots of silly uniques in it. But we mustn't
accidentally introduce name clashes! So the idea is that we leave the
OccName alone unless it accidentally clashes with one that is already
in scope; if so, we tack on '1' at the end and try again, then '2', and
so on till we find a unique one.
There's a wrinkle for operators. Consider '>>='. We can't use '>>=1'
because that isn't a single lexeme. So we encode it to 'lle' and *then*
tack on the '1', if necessary.
Note [TidyOccEnv]
~~~~~~~~~~~~~~~~~
type TidyOccEnv = UniqFM Int
* Domain = The OccName's FastString. These FastStrings are "taken";
make sure that we don't re-use
* Int, n = A plausible starting point for new guesses
There is no guarantee that "FSn" is available;
you must look that up in the TidyOccEnv. But
it's a good place to start looking.
* When looking for a renaming for "foo2" we strip off the "2" and start
with "foo". Otherwise if we tidy twice we get silly names like foo23.
However, if it started with digits at the end, we always make a name
with digits at the end, rather than shortening "foo2" to just "foo",
even if "foo" is unused. Reasons:
- Plain "foo" might be used later
- We use trailing digits to subtly indicate a unification variable
in typechecker error message; see TypeRep.tidyTyVarBndr
We have to take care though! Consider a machine-generated module (Trac #10370)
module Foo where
a1 = e1
a2 = e2
...
a2000 = e2000
Then "a1", "a2" etc are all marked taken. But now if we come across "a7" again,
we have to do a linear search to find a free one, "a2001". That might just be
acceptable once. But if we now come across "a8" again, we don't want to repeat
that search.
So we use the TidyOccEnv mapping for "a" (not "a7" or "a8") as our base for
starting the search; and we make sure to update the starting point for "a"
after we allocate a new one.
-}
type TidyOccEnv = UniqFM Int -- The in-scope OccNames
-- See Note [TidyOccEnv]
emptyTidyOccEnv :: TidyOccEnv
emptyTidyOccEnv = emptyUFM
initTidyOccEnv :: [OccName] -> TidyOccEnv -- Initialise with names to avoid!
initTidyOccEnv = foldl add emptyUFM
where
add env (OccName _ fs) = addToUFM env fs 1
tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName)
tidyOccName env occ@(OccName occ_sp fs)
= case lookupUFM env fs of
Nothing -> (addToUFM env fs 1, occ) -- Desired OccName is free
Just {} -> case lookupUFM env base1 of
Nothing -> (addToUFM env base1 2, OccName occ_sp base1)
Just n -> find 1 n
where
base :: String -- Drop trailing digits (see Note [TidyOccEnv])
base = dropWhileEndLE isDigit (unpackFS fs)
base1 = mkFastString (base ++ "1")
find !k !n
= case lookupUFM env new_fs of
Just {} -> find (k+1 :: Int) (n+k)
-- By using n+k, the n argument to find goes
-- 1, add 1, add 2, add 3, etc which
-- moves at quadratic speed through a dense patch
Nothing -> (new_env, OccName occ_sp new_fs)
where
new_fs = mkFastString (base ++ show n)
new_env = addToUFM (addToUFM env new_fs 1) base1 (n+1)
-- Update: base1, so that next time we'll start where we left off
-- new_fs, so that we know it is taken
-- If they are the same (n==1), the former wins
-- See Note [TidyOccEnv]
{-
************************************************************************
* *
Binary instance
Here rather than BinIface because OccName is abstract
* *
************************************************************************
-}
instance Binary NameSpace where
put_ bh VarName = do
putByte bh 0
put_ bh DataName = do
putByte bh 1
put_ bh TvName = do
putByte bh 2
put_ bh TcClsName = do
putByte bh 3
get bh = do
h <- getByte bh
case h of
0 -> do return VarName
1 -> do return DataName
2 -> do return TvName
_ -> do return TcClsName
instance Binary OccName where
put_ bh (OccName aa ab) = do
put_ bh aa
put_ bh ab
get bh = do
aa <- get bh
ab <- get bh
return (OccName aa ab)
| tjakway/ghcjvm | compiler/basicTypes/OccName.hs | bsd-3-clause | 32,995 | 0 | 14 | 8,789 | 5,739 | 3,066 | 2,673 | 472 | 5 |
module MasterSlave where
import Control.Monad
import Control.Distributed.Process
import Control.Distributed.Process.Closure
import PrimeFactors
{-
slave :: (ProcessId<p>, Integer)
-> Process me < me ▹ send(p, Integer) > ()
-}
slave :: (ProcessId, Integer) -> Process ()
slave (pid, n) = send pid (numPrimeFactors n)
remotable ['slave]
-- | Wait for n integers and sum them all up
{-
sumIntegers :: n:Int
-> Process me < me ▹ foreach (i ∈ [1..n]): recv(Integer); > Integer
-}
sumIntegers :: Int -> Process Integer
sumIntegers = go 0
where
go :: Integer -> Int -> Process Integer
go !acc 0 = return acc
go !acc n = do
m <- expect
go (acc + m) (n - 1)
{-
sumIntegers' :: n:Int
-> Process me < me ▹ foreach (i ∈ [1..n]): recv(Integer); > Integer
-}
sumIntegers' :: Int -> Process Integer
sumIntegers' = foldM go 0 [1..n]
where
{- go :: Integer -> Int -> Process me < me ▹ recv(Integer) > Integer -}
go :: Integer -> Int -> Process Integer
go !acc _ = do
m <- expect
return (acc + m)
data SpawnStrategy = SpawnSyncWithReconnect
| SpawnSyncNoReconnect
| SpawnAsync
deriving (Show, Read)
{-
G(n) = foreach (p ∈ p[n]):
p --> me <Integer>;
G(n) ↑ (p ∈ p[n]) = send(me, Integer)
G(n) ↑ me = foreach (p ∈ p[n]): recv(Integer)
-}
{-
master :: n:Integer
-> SpawnStrategy
-> NodeId
-> Process me < me ▹ foreach (i ∈ [1..n]):
recv(Integer);
p ∈ P ▹ send(me, Integer);
> Integer
-}
master :: Integer -> SpawnStrategy -> [NodeId] -> Process Integer
master n spawnStrategy slaves = do
{- us :: ProcessId <me> -}
us <- getSelfPid
-- Distribute 1 .. n amongst the slave processes
spawnLocal $ case spawnStrategy of
SpawnSyncWithReconnect ->
forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
them <- spawn there ($(mkClosure 'slave) (us, m))
reconnect them
SpawnSyncNoReconnect ->
forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
_them <- spawn there ($(mkClosure 'slave) (us, m))
return ()
SpawnAsync ->
forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
spawnAsync there ($(mkClosure 'slave) (us, m))
_ <- expectTimeout 0 :: Process (Maybe DidSpawn)
return ()
-- Wait for the result
sumIntegers (fromIntegral n)
| gokhankici/symmetry | background/examples/MasterSlave.hs | mit | 2,534 | 0 | 21 | 766 | 617 | 319 | 298 | -1 | -1 |
{- Copyright 2013 Gabriel Gonzalez
This file is part of the Suns Search Engine
The Suns Search Engine 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.
The Suns Search Engine 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
the Suns Search Engine. If not, see <http://www.gnu.org/licenses/>.
-}
module Structure (Structure(..), atomsToStructure, bonds, deleteBond) where
import Atom (Atom(name), distSqA)
import AtomName (AtomName)
import Control.Applicative ((<$>), (<*>))
import Control.DeepSeq (NFData(rnf))
import Control.Monad (guard)
import Data.Array ((//), (!))
import Data.Graph (Graph, Edge, buildG, edges)
import Data.List (delete, findIndices)
import qualified Data.Vector.Storable as VS
import HSerialize (HSerialize(get, put))
data Structure = Structure {
graph :: Graph ,
atoms :: VS.Vector AtomName}
deriving (Show)
instance HSerialize Structure where
put (Structure g as) = do
put g
put as
get = Structure <$> get <*> get
instance NFData Structure where
rnf (Structure gr as) = rnf gr `seq` rnf as `seq` ()
cutoff, cutoffSq :: Double
cutoff = 2 -- Angstroms
cutoffSq = cutoff * cutoff
atomsToEdges :: VS.Vector Atom -> [Edge]
atomsToEdges as = do
let as' = VS.toList as
(i1, a1) <- zip [0..] as'
i2 <- findIndices (\a2 -> distSqA a1 a2 < cutoffSq) as'
guard (i1 /= i2)
return (i1, i2)
atomsToStructure :: VS.Vector Atom -> Structure
atomsToStructure as
= let graph_ = buildG (0, VS.length as - 1) (atomsToEdges as)
names = VS.map name as
in Structure graph_ names
bonds :: Graph -> [Edge]
bonds = filter (uncurry (<=)) . edges
deleteBond :: Edge -> Graph -> Graph
deleteBond (i1, i2) g
= let i1adj = g ! i1
i2adj = g ! i2
i1adj' = delete i2 i1adj
i2adj' = delete i1 i2adj
in g // [(i1, i1adj'), (i2, i2adj')]
| Gabriel439/suns-search | src/Structure.hs | gpl-3.0 | 2,331 | 0 | 13 | 533 | 624 | 349 | 275 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.DeleteApp
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a specified app.
--
-- Required Permissions: To use this action, an IAM user must have a Manage
-- permissions level for the stack, or an attached policy that explicitly grants
-- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DeleteApp.html>
module Network.AWS.OpsWorks.DeleteApp
(
-- * Request
DeleteApp
-- ** Request constructor
, deleteApp
-- ** Request lenses
, daAppId
-- * Response
, DeleteAppResponse
-- ** Response constructor
, deleteAppResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype DeleteApp = DeleteApp
{ _daAppId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteApp' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'daAppId' @::@ 'Text'
--
deleteApp :: Text -- ^ 'daAppId'
-> DeleteApp
deleteApp p1 = DeleteApp
{ _daAppId = p1
}
-- | The app ID.
daAppId :: Lens' DeleteApp Text
daAppId = lens _daAppId (\s a -> s { _daAppId = a })
data DeleteAppResponse = DeleteAppResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteAppResponse' constructor.
deleteAppResponse :: DeleteAppResponse
deleteAppResponse = DeleteAppResponse
instance ToPath DeleteApp where
toPath = const "/"
instance ToQuery DeleteApp where
toQuery = const mempty
instance ToHeaders DeleteApp
instance ToJSON DeleteApp where
toJSON DeleteApp{..} = object
[ "AppId" .= _daAppId
]
instance AWSRequest DeleteApp where
type Sv DeleteApp = OpsWorks
type Rs DeleteApp = DeleteAppResponse
request = post "DeleteApp"
response = nullResponse DeleteAppResponse
| romanb/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/DeleteApp.hs | mpl-2.0 | 2,995 | 0 | 9 | 667 | 360 | 221 | 139 | 48 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- Module : Khan.CLI.Profile
-- Copyright : (c) 2013 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Khan.CLI.Profile (commands) where
import Khan.Internal
import Khan.Model.IAM.Role (Paths(..))
import qualified Khan.Model.IAM.Role as Role
import Khan.Prelude
import Network.AWS.IAM hiding (Role)
default (Text)
data Info = Info
{ iRole :: !Role
, iEnv :: !Env
} deriving (Show)
infoParser :: EnvMap -> Parser Info
infoParser env = Info
<$> roleOption
<*> envOption env
instance Options Info where
validate Info{..} =
check iEnv "--env must be specified."
instance Naming Info where
names Info{..} = unversioned iRole iEnv
data Update = Update
{ uRole :: !Role
, uEnv :: !Env
, uTrust :: !TrustPath
, uPolicy :: !PolicyPath
} deriving (Show)
updateParser :: EnvMap -> Parser Update
updateParser env = Update
<$> roleOption
<*> envOption env
<*> trustOption
<*> policyOption
instance Options Update where
discover _ Common{..} r@Update{..} = return $! r
{ uTrust = pTrustPath
, uPolicy = pPolicyPath
}
where
Paths{..} = Role.paths r cConfig uTrust uPolicy
validate Update{..} = do
check uEnv "--env must be specified."
checkFile (_trust uTrust) " specified by --trust must exist."
checkFile (_policy uPolicy) " specified by --policy must exist."
instance Naming Update where
names Update{..} = unversioned uRole uEnv
commands :: EnvMap -> Mod CommandFields Command
commands env = group "profile" "IAM Updates and Roles." $ mconcat
[ command "info" info (infoParser env)
"Display information about an IAM Role."
, command "update" update (updateParser env)
"Create or update IAM Role and associated Role."
]
info :: Common -> Info -> AWS ()
info _ i = do
ra <- async (Role.find i)
pa <- async (Role.findPolicy i)
r <- wait ra
p <- wait pa
pPrint (title r <-> body r <-> body p)
update :: Common -> Update -> AWS ()
update _ u = void $ Role.update u (uTrust u) (uPolicy u)
| zinfra/khan | khan-cli/src/Khan/CLI/Profile.hs | mpl-2.0 | 2,750 | 0 | 11 | 736 | 666 | 346 | 320 | 75 | 1 |
-- Copyright 2012-2013 Greg Horn
--
-- This file is part of rawesome.
--
-- rawesome is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- rawesome 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 Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with rawesome. If not, see <http://www.gnu.org/licenses/>.
{-# OPTIONS_GHC -Wall #-}
module Main ( main ) where
import Data.Foldable ( toList )
import Data.Packed ( fromLists )
import Text.ProtocolBuffers.Basic ( uToString )
import SpatialMath
import MultiCarousel ( State(..), NiceKite(..), runMultiCarousel )
import qualified Carousel.Trajectory as PT
import qualified Carousel.Dae as PD
import qualified Carousel.DifferentialStates as PX
toNice :: PD.Dae -> NiceKite
toNice dae = NiceKite { nk_xyz = xyz
, nk_q'n'b = q'n'b
, nk_r'n0'a0 = r'n0'a0
, nk_r'n0't0 = r'n0't0
, nk_lineAlpha = 0.2 -- realToFrac $ fromMaybe 1 (CS.lineTransparency cs)
, nk_kiteAlpha = 1 -- realToFrac $ fromMaybe 1 (CS.kiteTransparency cs)
, nk_visSpan = 3 -- fromMaybe 1 (CS.visSpan cs)
}
where
daeX = PD.differentialStates dae
-- daeZ = PD.algebraicVars dae
-- daeU = PD.controls dae
-- daeP = PD.parameters dae
x = PX.x daeX
y = PX.y daeX
z = PX.z daeX
e11 = PX.e11 daeX
e12 = PX.e12 daeX
e13 = PX.e13 daeX
e21 = PX.e21 daeX
e22 = PX.e22 daeX
e23 = PX.e23 daeX
e31 = PX.e31 daeX
e32 = PX.e32 daeX
e33 = PX.e33 daeX
delta = atan2 (PX.sin_delta daeX) (PX.cos_delta daeX)
q'n'a = Quat (cos(0.5*delta)) 0 0 (sin(0.5*delta))
q'a'b = quatOfDcm $ fromLists [ [e11, e12, e13]
, [e21, e22, e23]
, [e31, e32, e33]
]
q'n'b = q'n'a * q'a'b
rArm = Xyz 1.2 0 0 -- CS.rArm
xyzArm = rArm + Xyz x y z
xyz = rotVecByQuatB2A q'n'a xyzArm
zt = 0 --CS.zt cs
r'n0'a0 = rotVecByQuatB2A q'n'a rArm
r'n0't0 = xyz + (rotVecByQuatB2A q'n'b $ Xyz 0 0 zt)
toState :: PT.Trajectory -> State
toState ptTraj = State nicekites messages
where
messages = map uToString $ toList $ PT.messages ptTraj
nicekites = map toNice $ toList $ PT.traj ptTraj
main :: IO ()
main = runMultiCarousel "carousel" toState
| ghorn/rawesome | examples/carousel/viz/Multi.hs | lgpl-3.0 | 2,806 | 0 | 11 | 805 | 599 | 342 | 257 | 49 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Internal.Http.Server.Parser.Tests (tests) where
------------------------------------------------------------------------------
import Control.Monad (liftM)
import Control.Parallel.Strategies (rdeepseq, using)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.List (sort)
import qualified Data.Map as Map
import Data.Monoid (mconcat)
import Text.Printf (printf)
------------------------------------------------------------------------------
import Data.ByteString.Builder (byteString, toLazyByteString)
import Test.Framework (Test)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit (assertEqual)
import Test.QuickCheck (Arbitrary (arbitrary))
import Test.QuickCheck.Monadic (forAllM, monadicIO)
import qualified Test.QuickCheck.Monadic as QC
------------------------------------------------------------------------------
import Snap.Internal.Debug (debug)
import Snap.Internal.Http.Server.Parser (HttpParseException (..), IRequest (IRequest, iMethod, iRequestHeaders, iStdHeaders), getStdHost, parseCookie, parseRequest, parseUrlEncoded, readChunkedTransferEncoding, writeChunkedTransferEncoding)
import Snap.Internal.Http.Types (Cookie (Cookie), Method (CONNECT, DELETE, GET, HEAD, Method, OPTIONS, PATCH, POST, PUT, TRACE))
import Snap.Test.Common (coverEqInstance, coverShowInstance, coverTypeableInstance, expectException)
import qualified Snap.Types.Headers as H
import qualified System.IO.Streams as Streams
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testShow
, testCookie
, testChunked
, testNull
, testPartial
, testParseError
, testFormEncoded
, testTrivials
, testMethods
, testSimpleParse
, testSimpleParseErrors
, testWriteChunkedTransferEncoding
]
------------------------------------------------------------------------------
testShow :: Test
testShow = testCase "parser/show" $ do
let i = IRequest GET "/" (1, 1) H.empty undefined
let !b = show i `using` rdeepseq
return $ b `seq` ()
------------------------------------------------------------------------------
testNull :: Test
testNull = testCase "parser/shortParse" $
expectException (Streams.fromList [] >>= parseRequest)
------------------------------------------------------------------------------
testPartial :: Test
testPartial = testCase "parser/partial" $
expectException (Streams.fromList ["GET / "] >>= parseRequest)
------------------------------------------------------------------------------
testParseError :: Test
testParseError = testCase "parser/error" $ do
expectException (Streams.fromList ["ZZZZZZZZZ"] >>= parseRequest)
expectException (Streams.fromList ["GET / HTTP/1.1"] >>= parseRequest)
expectException (Streams.fromList ["GET / HTTP/x.z\r\n\r\n"] >>=
parseRequest)
------------------------------------------------------------------------------
-- | convert a bytestring to chunked transfer encoding
transferEncodingChunked :: L.ByteString -> L.ByteString
transferEncodingChunked = f . L.toChunks
where
toChunk s = L.concat [ len, "\r\n", L.fromChunks [s], "\r\n" ]
where
len = L.pack $ printf "%x" $ S.length s
f l = L.concat $ (map toChunk l ++ ["0\r\n\r\n"])
------------------------------------------------------------------------------
-- | ensure that running 'readChunkedTransferEncoding' against
-- 'transferEncodingChunked' returns the original string
testChunked :: Test
testChunked = testProperty "parser/chunkedTransferEncoding" $
monadicIO $ forAllM arbitrary prop_chunked
where
prop_chunked s = QC.run $ do
debug "=============================="
debug $ "input is " ++ show s
debug $ "chunked is " ++ show chunked
debug "------------------------------"
out <- Streams.fromList (L.toChunks chunked) >>=
readChunkedTransferEncoding >>=
Streams.toList >>=
return . L.fromChunks
assertEqual "chunked" s out
debug "==============================\n"
where
chunked = transferEncodingChunked s
------------------------------------------------------------------------------
testWriteChunkedTransferEncoding :: Test
testWriteChunkedTransferEncoding = testCase "parser/writeChunked" $ do
(os, getList) <- Streams.listOutputStream
os' <- writeChunkedTransferEncoding os
Streams.fromList [byteString "ok"] >>= Streams.connectTo os'
Streams.write Nothing os'
s <- liftM (toLazyByteString . mconcat) getList
assertEqual "chunked" "002\r\nok\r\n0\r\n\r\n" s
------------------------------------------------------------------------------
testCookie :: Test
testCookie =
testCase "parser/parseCookie" $ do
assertEqual "cookie parsing" (Just [cv]) cv2
where
cv = Cookie nm v Nothing Nothing Nothing False False
cv2 = parseCookie ct
nm = "foo"
v = "bar"
ct = S.concat [ nm , "=" , v ]
------------------------------------------------------------------------------
testFormEncoded :: Test
testFormEncoded = testCase "parser/formEncoded" $ do
let bs = "foo1=bar1&foo2=bar2+baz2;foo3=foo%20bar"
let mp = parseUrlEncoded bs
assertEqual "foo1" (Just ["bar1"] ) $ Map.lookup "foo1" mp
assertEqual "foo2" (Just ["bar2 baz2"]) $ Map.lookup "foo2" mp
assertEqual "foo3" (Just ["foo bar"] ) $ Map.lookup "foo3" mp
------------------------------------------------------------------------------
testTrivials :: Test
testTrivials = testCase "parser/trivials" $ do
coverTypeableInstance (undefined :: HttpParseException)
coverShowInstance (HttpParseException "ok")
coverEqInstance (IRequest GET "" (0, 0) H.empty undefined)
------------------------------------------------------------------------------
testMethods :: Test
testMethods = testCase "parser/methods" $ mapM_ testOne ms
where
ms = [ GET, POST, HEAD, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
, Method "ZZZ" ]
mToStr (Method m) = m
mToStr m = S.pack $ show m
restOfRequest = [ " / HTTP/1.1\r\nz:b\r\nq:\r\nw\r\n", "foo: ", "bar"
, "\r\n baz\r\n\r\n" ]
testOne m = let s = mToStr m
in Streams.fromList (s:restOfRequest) >>=
parseRequest >>=
checkMethod m
checkMethod m i = do
assertEqual "method" m $ iMethod i
let expected = sort [ ("z", "b")
, ("q", "")
, ("w", "")
, ("foo", "bar baz")
]
assertEqual "hdrs" expected $ sort $ H.toList $ iRequestHeaders i
------------------------------------------------------------------------------
testSimpleParse :: Test
testSimpleParse = testCase "parser/simpleParse" $ do
Streams.fromList ["GET / HTTP/1.1\r\n\r\n"] >>=
parseRequest >>=
assertEqual "simple0" (IRequest GET "/" (1, 1) H.empty undefined)
Streams.fromList ["GET http://foo.com/ HTTP/1.1\r\n\r\n"] >>=
parseRequest >>=
assertEqual "simple1" (IRequest GET "/" (1, 1) H.empty undefined)
z <- Streams.fromList ["GET http://foo.com HTTP/1.1\r\n\r\n"] >>=
parseRequest
assertEqual "simple2" z (IRequest GET "/" (1, 1) H.empty undefined)
assertEqual "simple2-host" (Just "foo.com") (getStdHost $ iStdHeaders z)
z2 <- Streams.fromList ["GET https://foo.com/ HTTP/1.1\r\n\r\n"] >>=
parseRequest
assertEqual "simpleHttps" (IRequest GET "/" (1, 1) H.empty undefined) z2
assertEqual "simpleHttps-2" (Just "foo.com") (getStdHost $ iStdHeaders z2)
Streams.fromList ["GET / HTTP/1.1\r\nz:b\r\n", "", "\r\n"] >>=
parseRequest >>=
assertEqual "simple4" (IRequest GET "/" (1, 1)
(H.fromList [("z", "b")]) undefined)
Streams.fromList [ "GET / HTTP/1.1\r\na:a\r", "\nz:b\r\n", ""
, "\r\n" ] >>=
parseRequest >>=
assertEqual "simple5" (IRequest GET "/" (1, 1)
(H.fromList [("a", "a"), ("z", "b")]) undefined)
Streams.fromList ["GET /\r\n\r\n"] >>=
parseRequest >>=
assertEqual "simple6" (IRequest GET "/" (1, 0) H.empty undefined)
Streams.fromList ["G", "ET", " /\r", "\n\r", "", "\n"] >>=
parseRequest >>=
assertEqual "simple7" (IRequest GET "/" (1, 0) H.empty undefined)
------------------------------------------------------------------------------
testSimpleParseErrors :: Test
testSimpleParseErrors = testCase "parser/simpleParseErrors" $ do
expectException (
Streams.fromList ["\r\nGET / HTTP/1.1\r\nz:b\r\n \r\n"] >>=
parseRequest)
expectException (
Streams.fromList ["\r\nGET / HTTP/1.1\r\nz:b\r "] >>=
parseRequest)
expectException (
Streams.fromList ["\r\nGET / HTTP/1.1\r"] >>=
parseRequest)
expectException (
Streams.fromList ["\r\nGET / HTTP/1.1\r", "", "foo\nz:b\r "] >>=
parseRequest)
| sopvop/snap-server | test/Snap/Internal/Http/Server/Parser/Tests.hs | bsd-3-clause | 9,912 | 0 | 18 | 2,454 | 2,157 | 1,166 | 991 | 169 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid
import Data.Prototype
import Lens.Micro.Platform ((.=))
import Yi.Boot (configMain, reload)
import Yi.Config
import Yi.Config.Default (defaultConfig)
import Yi.Config.Default.HaskellMode (configureHaskellMode)
import Yi.Config.Default.JavaScriptMode (configureJavaScriptMode)
import Yi.Config.Default.MiscModes (configureMiscModes)
import Yi.Config.Default.Vim
import Yi.Config.Default.Vty
import Yi.Config.Simple hiding (super)
import qualified Yi.Keymap.Vim as V
import qualified Yi.Keymap.Vim.Common as V
import qualified Yi.Keymap.Vim.Ex.Types as V
import qualified Yi.Keymap.Vim.Ex.Commands.Common as V
import qualified Yi.Keymap.Vim.Utils as V
import qualified Yi.Mode.Haskell as Haskell
import qualified Yi.Rope as R
main :: IO ()
main = configMain defaultConfig $ do
configureVty
myVimConfig
configureHaskellMode
configureJavaScriptMode
configureMiscModes
myVimConfig :: ConfigM ()
myVimConfig = do
configureVim
defaultKmA .= myKeymapSet
modeTableA .= myModes
configCheckExternalChangesObsessivelyA .= False
myKeymapSet :: KeymapSet
myKeymapSet = V.mkKeymapSet $ V.defVimConfig `override` \super this ->
let eval = V.pureEval this
in super {
-- Here we can add custom bindings.
-- See Yi.Keymap.Vim.Common for datatypes and
-- Yi.Keymap.Vim.Utils for useful functions like mkStringBindingE
-- In case of conflict, that is if there exist multiple bindings
-- whose prereq function returns WholeMatch,
-- the first such binding is used.
-- So it's important to have custom bindings first.
V.vimBindings = myBindings eval <> V.vimBindings super
, V.vimExCommandParsers = exReload : V.vimExCommandParsers super
}
myBindings :: (V.EventString -> EditorM ()) -> [V.VimBinding]
myBindings eval =
let nmap x y = V.mkStringBindingE V.Normal V.Drop (x, y, id)
imap x y = V.VimBindingE (\evs state -> case V.vsMode state of
V.Insert _ ->
fmap (const (y >> return V.Continue))
(evs `V.matchesString` x)
_ -> V.NoMatch)
in [ nmap "<C-h>" previousTabE
, nmap "<C-l>" nextTabE
-- Press space to clear incremental search highlight
, nmap " " (eval ":nohlsearch<CR>")
, nmap "<F3>" (withCurrentBuffer deleteTrailingSpaceB)
, nmap "<F4>" (withCurrentBuffer moveToSol)
, nmap "<F1>" (withCurrentBuffer readCurrentWordB >>= printMsg . R.toText)
, imap "<Home>" (withCurrentBuffer moveToSol)
, imap "<End>" (withCurrentBuffer moveToEol)
]
myModes :: [AnyMode]
myModes = [
AnyMode Haskell.fastMode {
-- Disable beautification
modePrettify = const $ return ()
}
]
exReload :: V.EventString -> Maybe V.ExCommand
exReload "reload" = Just $ V.impureExCommand {
V.cmdShow = "reload"
, V.cmdAction = YiA reload
}
exReload _ = Nothing
| noughtmare/yi | example-configs/yi-vim-vty-dynamic/yi.hs | gpl-2.0 | 3,319 | 0 | 21 | 992 | 724 | 408 | 316 | 64 | 2 |
{-
Copyright 2012, 2013, 2014 Colin Woodbury <colingw@gmail.com>
This file is part of Aura.
Aura 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 3 of the License, or
(at your option) any later version.
Aura 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 Aura. If not, see <http://www.gnu.org/licenses/>.
-}
module Aura.Settings.Enable
( getSettings
, debugOutput ) where
import System.Environment (getEnvironment)
import System.Directory (doesDirectoryExist)
import Data.Maybe (fromMaybe)
import Aura.Languages (Language,langFromEnv)
import Aura.MakePkg (makepkgConfFile)
import Aura.Settings.Base
import Aura.Pacman
import Aura.Flags
import Utilities (ifM2,nothing,readFileUTF8)
import Shell
---
getSettings :: Maybe Language -> ([Flag],[String],[String]) -> IO Settings
getSettings lang (auraFlags,input,pacOpts) = do
confFile <- getPacmanConf
environment <- getEnvironment
pmanCommand <- getPacmanCmd environment $ noPowerPillStatus auraFlags
makepkgConf <- readFileUTF8 makepkgConfFile
buildPath' <- checkBuildPath (buildPath auraFlags) (getCachePath confFile)
let language = checkLang lang environment
buildUser' = fromMaybe (getTrueUser environment) (buildUser auraFlags)
return Settings { inputOf = input
, pacOptsOf = pacOpts
, otherOptsOf = map show auraFlags
, environmentOf = environment
, buildUserOf = buildUser'
, langOf = language
, pacmanCmdOf = pmanCommand
, editorOf = getEditor environment
, carchOf = singleEntry makepkgConf "CARCH"
"COULDN'T READ $CARCH"
, ignoredPkgsOf = getIgnoredPkgs confFile ++
ignoredAuraPkgs auraFlags
, makepkgFlagsOf = makepkgFlags auraFlags
, buildPathOf = buildPath'
, cachePathOf = getCachePath confFile
, logFilePathOf = getLogFilePath confFile
, sortSchemeOf = sortSchemeStatus auraFlags
, truncationOf = truncationStatus auraFlags
, beQuiet = quietStatus auraFlags
, suppressMakepkg = suppressionStatus auraFlags
, delMakeDeps = delMakeDepsStatus auraFlags
, mustConfirm = confirmationStatus auraFlags
, neededOnly = neededStatus auraFlags
, mayHotEdit = hotEditStatus auraFlags
, diffPkgbuilds = pbDiffStatus auraFlags
, rebuildDevel = rebuildDevelStatus auraFlags
, useCustomizepkg = customizepkgStatus auraFlags
, noPowerPill = noPowerPillStatus auraFlags
, keepSource = keepSourceStatus auraFlags
, buildABSDeps = buildABSDepsStatus auraFlags
, dryRun = dryRunStatus auraFlags }
debugOutput :: Settings -> IO ()
debugOutput ss = do
let yn a = if a then "Yes!" else "No."
env = environmentOf ss
mapM_ putStrLn [ "User => " ++ getUser' env
, "True User => " ++ getTrueUser env
, "Build User => " ++ buildUserOf ss
, "Using Sudo? => " ++ yn (varExists "SUDO_USER" env)
, "Pacman Flags => " ++ unwords (pacOptsOf ss)
, "Other Flags => " ++ unwords (otherOptsOf ss)
, "Other Input => " ++ unwords (inputOf ss)
, "Language => " ++ show (langOf ss)
, "Pacman Command => " ++ pacmanCmdOf ss
, "Editor => " ++ editorOf ss
, "$CARCH => " ++ carchOf ss
, "Ignored Pkgs => " ++ unwords (ignoredPkgsOf ss)
, "Build Path => " ++ buildPathOf ss
, "Pkg Cache Path => " ++ cachePathOf ss
, "Log File Path => " ++ logFilePathOf ss
, "Quiet? => " ++ yn (beQuiet ss)
, "Silent Building? => " ++ yn (suppressMakepkg ss)
, "Must Confirm? => " ++ yn (mustConfirm ss)
, "Needed only? => " ++ yn (neededOnly ss)
, "PKGBUILD editing? => " ++ yn (mayHotEdit ss)
, "Diff PKGBUILDs? => " ++ yn (diffPkgbuilds ss)
, "Rebuild Devel? => " ++ yn (rebuildDevel ss)
, "Use Customizepkg? => " ++ yn (useCustomizepkg ss)
, "Forego PowerPill? => " ++ yn (noPowerPill ss)
, "Keep source? => " ++ yn (keepSource ss) ]
checkLang :: Maybe Language -> Environment -> Language
checkLang Nothing env = langFromEnv $ getLangVar env
checkLang (Just lang) _ = lang
-- | Defaults to the cache path if no (legal) build path was given.
checkBuildPath :: FilePath -> FilePath -> IO FilePath
checkBuildPath bp = ifM2 (doesDirectoryExist bp) return nothing bp
| joehillen/aura | src/Aura/Settings/Enable.hs | gpl-3.0 | 5,558 | 0 | 12 | 1,963 | 1,016 | 535 | 481 | 87 | 2 |
{-# LANGUAGE DataKinds, TypeOperators, OverloadedStrings #-}
module CoinBias50 where
import Prelude (print, length, IO)
import Language.Hakaru.Syntax.Prelude
import Language.Hakaru.Disintegrate
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Types.DataKind
import Language.Hakaru.Types.Sing
type Model a b = TrivialABT Term '[] ('HMeasure (HPair a b))
type Cond a b = TrivialABT Term '[] (a ':-> 'HMeasure b)
coinBias :: Model (HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
(HPair HBool
HBool)))))))))))))))))))))))))))))))))))))))))))))))))
'HProb
coinBias =
beta (prob_ 2) (prob_ 5) >>= \bias ->
bern bias >>= \tossResult0 ->
bern bias >>= \tossResult1 ->
bern bias >>= \tossResult2 ->
bern bias >>= \tossResult3 ->
bern bias >>= \tossResult4 ->
bern bias >>= \tossResult5 ->
bern bias >>= \tossResult6 ->
bern bias >>= \tossResult7 ->
bern bias >>= \tossResult8 ->
bern bias >>= \tossResult9 ->
bern bias >>= \tossResult10 ->
bern bias >>= \tossResult11 ->
bern bias >>= \tossResult12 ->
bern bias >>= \tossResult13 ->
bern bias >>= \tossResult14 ->
bern bias >>= \tossResult15 ->
bern bias >>= \tossResult16 ->
bern bias >>= \tossResult17 ->
bern bias >>= \tossResult18 ->
bern bias >>= \tossResult19 ->
bern bias >>= \tossResult20 ->
bern bias >>= \tossResult21 ->
bern bias >>= \tossResult22 ->
bern bias >>= \tossResult23 ->
bern bias >>= \tossResult24 ->
bern bias >>= \tossResult25 ->
bern bias >>= \tossResult26 ->
bern bias >>= \tossResult27 ->
bern bias >>= \tossResult28 ->
bern bias >>= \tossResult29 ->
bern bias >>= \tossResult30 ->
bern bias >>= \tossResult31 ->
bern bias >>= \tossResult32 ->
bern bias >>= \tossResult33 ->
bern bias >>= \tossResult34 ->
bern bias >>= \tossResult35 ->
bern bias >>= \tossResult36 ->
bern bias >>= \tossResult37 ->
bern bias >>= \tossResult38 ->
bern bias >>= \tossResult39 ->
bern bias >>= \tossResult40 ->
bern bias >>= \tossResult41 ->
bern bias >>= \tossResult42 ->
bern bias >>= \tossResult43 ->
bern bias >>= \tossResult44 ->
bern bias >>= \tossResult45 ->
bern bias >>= \tossResult46 ->
bern bias >>= \tossResult47 ->
bern bias >>= \tossResult48 ->
bern bias >>= \tossResult49 ->
dirac (pair (pair tossResult0
(pair tossResult1
(pair tossResult2
(pair tossResult3
(pair tossResult4
(pair tossResult5
(pair tossResult6
(pair tossResult7
(pair tossResult8
(pair tossResult9
(pair tossResult10
(pair tossResult11
(pair tossResult12
(pair tossResult13
(pair tossResult14
(pair tossResult15
(pair tossResult16
(pair tossResult17
(pair tossResult18
(pair tossResult19
(pair tossResult20
(pair tossResult21
(pair tossResult22
(pair tossResult23
(pair tossResult24
(pair tossResult25
(pair tossResult26
(pair tossResult27
(pair tossResult28
(pair tossResult29
(pair tossResult30
(pair tossResult31
(pair tossResult32
(pair tossResult33
(pair tossResult34
(pair tossResult35
(pair tossResult36
(pair tossResult37
(pair tossResult38
(pair tossResult39
(pair tossResult40
(pair tossResult41
(pair tossResult42
(pair tossResult43
(pair tossResult44
(pair tossResult45
(pair tossResult46
(pair tossResult47
(pair tossResult48
tossResult49)))))))))))))))))))))))))))))))))))))))))))))))))
bias)
main :: IO ()
main = print (length (disintegrate coinBias))
| zaxtax/hakaru | haskell/Tests/Unroll/CoinBias50.hs | bsd-3-clause | 8,270 | 0 | 207 | 4,976 | 1,596 | 813 | 783 | 167 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Pane.HLint
-- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
-- | The pane of ide where HLint results are displayed
--
-----------------------------------------------------------------------------
module IDE.Pane.HLint (
IDEHLint(..)
, refreshHLint
, HLintState(..)
, getHLint
) where
import Graphics.UI.Gtk hiding (get)
import qualified Graphics.UI.Gtk.Gdk.Events as Gdk
import Text.ParserCombinators.Parsec.Language
import Text.ParserCombinators.Parsec hiding(Parser)
import qualified Text.ParserCombinators.Parsec.Token as P
import Data.Maybe
import Data.Typeable
import IDE.Core.State hiding (SrcSpan(..))
import IDE.BufferMode
import IDE.LogRef (logOutput, defaultLineLogger)
import IDE.Pane.SourceBuffer
(goToSourceDefinition', maybeActiveBuf, IDEBuffer(..), replaceHLintSource)
import IDE.TextEditor (grabFocus)
import Control.Applicative ((<$>))
import System.FilePath ((</>), dropFileName)
import System.Exit (ExitCode(..))
import IDE.Pane.Log (getLog)
import Control.Monad (void, forM_, foldM, when)
import Control.Monad.Trans.Reader (ask)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.IO.Class (MonadIO(..))
import Language.Haskell.HLint (Suggestion(..), suggestionLocation)
import Language.Haskell.Exts (SrcLoc(..))
import Language.Haskell.Exts.SrcLoc (SrcSpan(..))
import qualified Language.Haskell.HLint2 as H
import IDE.Utils.GUIUtils (__, treeViewContextMenu)
import Data.List (isPrefixOf, findIndex)
import Debug.Trace (trace)
import Control.Exception (SomeException, catch)
import Distribution.ModuleName (ModuleName)
import IDE.Metainfo.Provider (getWorkspaceInfo)
import qualified Data.Map as Map (keys, lookup)
import Distribution.Package (PackageIdentifier(..))
import Data.Text (Text)
import qualified Data.Text as T
(replicate, unlines, init, lines, pack, unpack)
import Data.Monoid ((<>))
import qualified System.IO.Strict as S (readFile)
data HLintRecord = HLintRecord {
condPackage :: Maybe IDEPackage
, context :: Text
, condIdea :: Maybe H.Idea
, parDir :: Maybe FilePath
} deriving (Eq)
isDir HLintRecord{parDir = Nothing} = True
isDir otherwies = False
-- | A HLint pane description
--
data IDEHLint = IDEHLint {
scrolledView :: ScrolledWindow
, treeView :: TreeView
, hlintStore :: TreeStore HLintRecord
} deriving Typeable
data HLintState = HLintState
deriving(Eq,Ord,Read,Show,Typeable)
instance Pane IDEHLint IDEM
where
primPaneName _ = "HLint"
getAddedIndex _ = 0
getTopWidget = castToWidget . scrolledView
paneId b = "*HLint"
instance RecoverablePane IDEHLint HLintState IDEM where
saveState p = return (Just HLintState)
recoverState pp HLintState = do
nb <- getNotebook pp
buildPane pp nb builder
builder pp nb windows = reifyIDE $ \ ideR -> do
hlintStore <- treeStoreNew []
treeView <- treeViewNew
treeViewSetModel treeView hlintStore
renderer1 <- cellRendererTextNew
renderer10 <- cellRendererPixbufNew
col1 <- treeViewColumnNew
treeViewColumnSetTitle col1 (__ "Context")
treeViewColumnSetSizing col1 TreeViewColumnAutosize
treeViewColumnSetResizable col1 True
treeViewColumnSetReorderable col1 True
treeViewAppendColumn treeView col1
cellLayoutPackStart col1 renderer10 False
cellLayoutPackStart col1 renderer1 True
cellLayoutSetAttributes col1 renderer1 hlintStore
$ \row -> [ cellText := context row ]
treeViewSetHeadersVisible treeView False
sel <- treeViewGetSelection treeView
treeSelectionSetMode sel SelectionSingle
scrolledView <- scrolledWindowNew Nothing Nothing
scrolledWindowSetShadowType scrolledView ShadowIn
containerAdd scrolledView treeView
scrolledWindowSetPolicy scrolledView PolicyAutomatic PolicyAutomatic
let hlint = IDEHLint {..}
cid1 <- after treeView focusInEvent $ do
liftIO $ reflectIDE (makeActive hlint) ideR
return True
cid2 <- on treeView rowExpanded $ \ iter path -> do
record <- treeStoreGetValue hlintStore path
case record of
HLintRecord { condPackage = Just p, parDir = Nothing } ->
reflectIDE (refreshDir hlintStore iter p) ideR
_ -> reflectIDE (ideMessage Normal (__ "Unexpected Expansion in HLint Pane")) ideR
cid3 <- on treeView rowActivated $ \ path col -> do
record <- treeStoreGetValue hlintStore path
mbIter <- treeModelGetIter hlintStore path
case (mbIter, record) of
(Just iter, HLintRecord { condPackage = Just p, parDir = Nothing }) ->
reflectIDE (refreshDir hlintStore iter p) ideR
_ -> return ()
cid4 <- on treeView keyPressEvent $ do
name <- eventKeyName
liftIO $ case name of
"Return" -> reflectIDE (gotoSource True treeView hlintStore) ideR
"Escape" -> do
reflectIDE (do
lastActiveBufferPane ?>>= \paneName -> do
(PaneC pane) <- paneFromName paneName
makeActive pane
return ()
triggerEventIDE StartFindInitial) ideR
return True
-- gotoSource True
_ -> return False
treeViewContextMenu treeView
$ hlintContextMenu ideR hlintStore treeView
on sel treeSelectionSelectionChanged (reflectIDE (void $ gotoSource False treeView hlintStore) ideR)
return (Just hlint,map ConnectC [cid1])
getHLint :: Maybe PanePath -> IDEM IDEHLint
getHLint Nothing = forceGetPane (Right "*HLint")
getHLint (Just pp) = forceGetPane (Left pp)
data FindResult = WhereExpected TreeIter | Found TreeIter | NotFound
find :: Eq a => a -> TreeStore a -> Maybe TreeIter -> IO FindResult
find _ _ Nothing = return NotFound
find a store (Just iter) = do
row <- treeModelGetRow store iter
if row == a
then return $ WhereExpected iter
else treeModelIterNext store iter >>= find'
where
find' :: Maybe TreeIter -> IO FindResult
find' Nothing = return NotFound
find' (Just iter) = do
row <- treeModelGetRow store iter
if row == a
then return $ Found iter
else treeModelIterNext store iter >>= find'
removeUntil :: Eq a => a -> TreeStore a -> TreePath -> IO ()
removeUntil a store path = do
row <- treeStoreGetValue store path
when (row /= a) $ do
found <- treeStoreRemove store path
when found $ removeUntil a store path
removeRemaining :: TreeStore a -> TreePath -> IO ()
removeRemaining store path = do
found <- treeStoreRemove store path
when found $ removeRemaining store path
getSelectionHLintRecord :: TreeView
-> TreeStore HLintRecord
-> IO (Maybe HLintRecord)
getSelectionHLintRecord treeView hlintStore = do
treeSelection <- treeViewGetSelection treeView
paths <- treeSelectionGetSelectedRows treeSelection
case paths of
p:_ -> Just <$> treeStoreGetValue hlintStore p
_ -> return Nothing
refreshHLint :: WorkspaceAction
refreshHLint = do
ws <- ask
maybeActive <- lift $ readIDE activePack
let packages = case maybeActive of
Just active -> active : filter (/= active) (wsAllPackages ws)
Nothing -> wsAllPackages ws
lift $ hlintDirectories2 packages
--gotoSource :: Bool -> IDEM Bool
gotoSource focus treeView hlintStore = do
sel <- liftIO $ getSelectionHLintRecord treeView hlintStore
case sel of
Just record ->
case record of
HLintRecord {condIdea = Just idea} ->
goToSourceDefinition' (srcSpanFilename (H.ideaSpan idea))
(Location "" (srcSpanStartLine (H.ideaSpan idea))
(srcSpanStartColumn (H.ideaSpan idea))
(srcSpanEndLine (H.ideaSpan idea))
(srcSpanEndColumn (H.ideaSpan idea)))
?>>= (\(IDEBuffer {sourceView = sv}) -> when focus $ grabFocus sv)
_ -> return ()
Nothing -> return ()
return True
hlintDirectories2 :: [IDEPackage] -> IDEAction
hlintDirectories2 packages = do
hlint <- getHLint Nothing
let store = hlintStore hlint
liftIO $ do
treeStoreClear store
forM_ packages $ \ p -> do
nDir <- treeModelIterNChildren store Nothing
treeStoreInsert store [] nDir $ HLintRecord (Just p) (packageIdentifierToString (ipdPackageId p)) Nothing Nothing
treeStoreInsert store [nDir] 0 $ HLintRecord (Just p) (packageIdentifierToString (ipdPackageId p)) Nothing Nothing
refreshDir :: TreeStore HLintRecord -> TreeIter -> IDEPackage -> IDEM ()
refreshDir store iter package = do
mbHlintDir <- liftIO $ leksahSubDir "hlint"
(flags, classify, hint) <- liftIO $ case mbHlintDir of
Just d ->
#if MIN_VERSION_hlint(1, 9, 13)
H.autoSettings' d
#else
H.autoSettings
#endif
Nothing -> H.autoSettings
let modules = Map.keys (ipdModules package)
paths <- getSourcePaths (ipdPackageId package) modules
resL <- liftIO $ mapM (\ file -> do
str <- S.readFile file
H.parseModuleEx flags file (Just str)) paths
let resOk = mapMaybe (\ pr -> case pr of
Left e -> trace ("can't parse: " ++ H.parseErrorContents e ++
" location " ++ show H.parseErrorLocation) Nothing
Right r -> Just r) resL
let ideas = H.applyHints classify hint resOk
liftIO $ setHLint2Results store iter (T.unpack $ packageIdentifierToString (ipdPackageId package)) ideas
return ()
getSourcePaths :: PackageIdentifier -> [ModuleName] -> IDEM [FilePath]
getSourcePaths packId names = do
mbWorkspaceInfo <- getWorkspaceInfo
case mbWorkspaceInfo of
Nothing -> return []
Just (sc, _) -> return (mapMaybe (sourcePathFromScope sc) names)
where
sourcePathFromScope :: GenScope -> ModuleName -> Maybe FilePath
sourcePathFromScope (GenScopeC (PackScope l _)) mn =
case packId `Map.lookup` l of
Just pack ->
case filter (\md -> modu (mdModuleId md) == mn)
(pdModules pack) of
(mod : tl) -> mdMbSourcePath mod
[] -> Nothing
Nothing -> Nothing
hlint2Record dir idea = HLintRecord {
condPackage = Nothing,
context = T.pack $ show idea,
condIdea = Just idea,
parDir = Just dir}
setHLint2Results :: TreeStore HLintRecord -> TreeIter -> FilePath -> [H.Idea] -> IO Int
setHLint2Results store parent dir ideas = do
parentPath <- treeModelGetPath store parent
forM_ (zip [0..] records) $ \(n, record) -> do
mbChild <- treeModelIterNthChild store (Just parent) n
findResult <- find record store mbChild
case (mbChild, findResult) of
(_, WhereExpected _) -> return ()
(Just iter, Found _) -> do
path <- treeModelGetPath store iter
removeUntil record store path
_ -> treeStoreInsert store parentPath n record
removeRemaining store (parentPath++[nRecords])
return nRecords
where
records = map (hlint2Record dir) ideas
nRecords = length records
hlintContextMenu :: IDERef
-> TreeStore HLintRecord
-> TreeView
-> Menu
-> IO ()
hlintContextMenu ideR store treeView theMenu = do
mbSel <- getSelectionHLintRecord treeView store
item0 <- menuItemNewWithLabel (__ "Replace")
item0 `on` menuItemActivate $ reflectIDE (replaceHlint store treeView mbSel) ideR
menuShellAppend theMenu item0
where
replaceableSelection Nothing = False
replaceableSelection (Just s) | isNothing (parDir s) = True
| otherwise = False
replaceHlint store treeView (Just sel) =
case condIdea sel of
Just idea | isJust (H.ideaTo idea) ->
let lined = T.lines (T.pack $ fromJust (H.ideaTo idea))
startColumn = srcSpanStartColumn (H.ideaSpan idea)
source = T.init $ T.unlines (head lined :
map (\ s -> T.replicate startColumn " " <> s) (tail lined))
in
replaceHLintSource (srcSpanFilename (H.ideaSpan idea))
(srcSpanStartLine (H.ideaSpan idea))
startColumn
(srcSpanEndLine (H.ideaSpan idea))
(srcSpanEndColumn (H.ideaSpan idea))
source
otherwise -> return ()
replaceHlint _ _ Nothing = return ()
| 573/leksah | src/IDE/Pane/HLint.hs | gpl-2.0 | 14,436 | 0 | 30 | 4,687 | 3,740 | 1,882 | 1,858 | 285 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype Foo = Foo Int deriving Data | bitemyapp/apply-refact | tests/examples/Extensions24.hs | bsd-3-clause | 80 | 0 | 5 | 11 | 13 | 8 | 5 | 2 | 0 |
module Yi.Config.Default.Cua (configureCua) where
import Lens.Micro.Platform ((.=))
import Yi.Config.Simple (ConfigM)
import Yi.Config.Lens (defaultKmA)
import Yi.Keymap.Cua
configureCua :: ConfigM ()
configureCua = defaultKmA .= keymap | siddhanathan/yi | yi-keymap-cua/src/Yi/Config/Default/Cua.hs | gpl-2.0 | 246 | 0 | 6 | 33 | 73 | 46 | 27 | 7 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>Alert Filters | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>İçerikler</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Dizin</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Arama</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favoriler</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/alertFilters/src/main/javahelp/org/zaproxy/zap/extension/alertFilters/resources/help_tr_TR/helpset_tr_TR.hs | apache-2.0 | 976 | 83 | 52 | 159 | 399 | 210 | 189 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
module Test where
import QQ
f :: [pq| foo |] -- Expands to Int -> Int
[pq| blah |] -- Expands to f x = x
h [pq| foo |] = f [pq| blah |] * 8
-- Expands to h (Just x) = f (x+1) * 8
| ezyang/ghc | testsuite/tests/quasiquotation/qq008/Test.hs | bsd-3-clause | 224 | 0 | 6 | 68 | 50 | 36 | 14 | 6 | 1 |
module Main where
import Control.Monad
import qualified Data.Text.Lazy.IO as TL
import qualified Data.Text.Lazy.Builder as TL
import Records
import MustacheTemplates
htmlEscape :: String -> String
htmlEscape = concatMap escChar
where
escChar '&' = "&"
escChar '"' = """
escChar '<' = "<"
escChar '>' = ">"
escChar c = [c]
main :: IO ()
main = void $ sequence $ replicate 10000 $ TL.putStr $ TL.toLazyText $
toplevel htmlEscape (TopLevel {
thing = 12,
subs = [
SubLevel {
thing2 = False,
other = Just "w00t!"
},
SubLevel {
thing2 = True,
other = Nothing
}
]
})
| singpolyma/mustache2hs | benchmark/bench1.hs | isc | 623 | 26 | 13 | 145 | 224 | 128 | 96 | 24 | 5 |
--------------------------------------------------------------------------------
-- |
-- Module: Euler.Problem6
--
-- Sum square difference
-- Problem 6
--
-- The sum of the squares of the first ten natural numbers is,
--
-- > 1^2 + 2^2 + ... + 10^2 = 385
--
-- The square of the sum of the first ten natural numbers is,
--
-- > (1 + 2 + ... + 10)^2 = 55^2 = 3025
--
-- Hence the difference between the sum of the squares of the first ten natural
-- numbers and the square of the sum is 3025 − 385 = 2640.
--
-- Find the difference between the sum of the squares of the first one hundred
-- natural numbers and the square of the sum.
--------------------------------------------------------------------------------
module Euler.Problem6 where
sumSquareDiff :: Integral a => [a] -> a
sumSquareDiff nums =
sum'*sum' - sum squares
where
sum' = sum nums
squares = map (\x -> x*x) nums | slogsdon/haskell-exercises | pe/src/Euler/Problem6.hs | mit | 898 | 0 | 10 | 169 | 97 | 61 | 36 | 6 | 1 |
module Main (main) where
import Test.DocTest
main :: IO ()
main = doctest $ srcFiles ++ compFlags
srcFiles :: [String]
srcFiles =
[ "src/Refined.hs"
, "src/Refined/Unsafe/Type.hs"
, "src/Refined/Unsafe.hs"
]
compFlags :: [String]
compFlags =
[ "-XScopedTypeVariables"
]
| nikita-volkov/refined | test/Doctests.hs | mit | 286 | 0 | 6 | 53 | 75 | 45 | 30 | 12 | 1 |
module Web.Apiary.WebSockets (
webSockets, webSockets'
, actionWithWebSockets
, actionWithWebSockets'
, websocketsToAction
-- * Reexport
-- | PendingConnection,
-- pandingRequest, acceptRequest, rejectrequest
--
-- receiveData
--
-- sendTextData, sendBinaryData, sendClose, sendPing
, module Network.WebSockets
) where
import Control.Monad(mzero, mplus)
import Control.Monad.Apiary(ApiaryT, action)
import Control.Monad.Apiary.Action(ActionT, getRequest, getParams, stopWith)
import qualified Network.Routing.Dict as Dict
import qualified Network.Wai.Handler.WebSockets as WS
import qualified Network.WebSockets as WS
import Network.WebSockets
( PendingConnection
, pendingRequest, acceptRequest, rejectRequest
, receiveData
, sendTextData, sendBinaryData, sendClose, sendPing
)
websocketsToAction :: Monad m => WS.ConnectionOptions
-> (Dict.Dict prms -> WS.ServerApp) -> ActionT exts prms m ()
websocketsToAction conn srv = do
req <- getRequest
d <- getParams
case WS.websocketsApp conn (srv d) req of
Nothing -> mzero
Just r -> stopWith r
-- | websocket only action. since 0.8.0.0.
webSockets' :: (Monad m, Monad actM) => WS.ConnectionOptions
-> (Dict.Dict prms -> WS.ServerApp) -> ApiaryT exts prms actM m ()
webSockets' conn srv = action $ websocketsToAction conn srv
-- | websocket only action. since 0.8.0.0.
webSockets :: (Monad m, Monad n)
=> (Dict.Dict prms -> WS.ServerApp) -> ApiaryT exts prms n m ()
webSockets = webSockets' WS.defaultConnectionOptions
actionWithWebSockets' :: (Monad m, Monad actM)
=> WS.ConnectionOptions
-> (Dict.Dict prms -> WS.ServerApp)
-> ActionT exts prms actM ()
-> ApiaryT exts prms actM m ()
actionWithWebSockets' conn srv m =
action $ websocketsToAction conn srv `mplus` m
actionWithWebSockets :: (Monad m, Monad actM)
=> (Dict.Dict prms -> WS.ServerApp)
-> ActionT exts prms actM ()
-> ApiaryT exts prms actM m ()
actionWithWebSockets = actionWithWebSockets' WS.defaultConnectionOptions
| philopon/apiary | apiary-websockets/src/Web/Apiary/WebSockets.hs | mit | 2,240 | 0 | 11 | 562 | 571 | 312 | 259 | 43 | 2 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module supports pure logging.
module System.Wlog.PureLogging
(
-- * Pure logging manipulation
PureLogger (..)
, LogEvent (..)
, dispatchEvents
, logEvents
, runPureLog
, launchPureLog
, NamedPureLogger (..)
, runNamedPureLog
, launchNamedPureLog
, launchNamedPureLogWith
, usingNamedPureLogger
, logPureAction
) where
import Universum
import Control.Monad.Morph (MFunctor (..))
import Data.Sequence ((|>))
import System.Wlog.CanLog (CanLog (..), WithLogger)
import System.Wlog.HasLoggerName (HasLoggerName (..))
import System.Wlog.LoggerName (LoggerName (..))
import System.Wlog.LoggerNameBox (LoggerNameBox (..), usingLoggerName)
import System.Wlog.Severity (Severity (..))
-- | Holds all required information for 'dispatchLoggerName' function.
data LogEvent = LogEvent
{ leLoggerName :: !LoggerName
, leSeverity :: !Severity
, leMessage :: !Text
} deriving (Show)
-- | Pure implementation of 'CanLog' type class. Instead of writing log messages
-- into console it appends log messages into 'StateT' log. It uses 'DList' for
-- better performance, because messages can be added only at the end of log.
-- But it uses 'unsafePerformIO' so use with caution within IO.
--
-- TODO: Should we use some @Data.Tree@-like structure to observe message only
-- by chosen logger names?
newtype PureLogger m a = PureLogger
{ runPureLogger :: StateT (Seq LogEvent) m a
} deriving (Functor, Applicative, Monad, MonadTrans, MonadState (Seq LogEvent),
MonadThrow, HasLoggerName)
instance Monad m => CanLog (PureLogger m) where
dispatchMessage leLoggerName leSeverity leMessage = modify' (|> LogEvent{..})
instance MFunctor PureLogger where
hoist f = PureLogger . hoist f . runPureLogger
-- | Return log of pure logging action as list of 'LogEvent'.
runPureLog :: Functor m => PureLogger m a -> m (a, [LogEvent])
runPureLog = fmap (second toList) . usingStateT mempty . runPureLogger
-- | Logs all 'LogEvent'`s from given list. This function supposed to
-- be used after 'runPureLog'.
dispatchEvents :: CanLog m => [LogEvent] -> m ()
dispatchEvents = mapM_ dispatchLogEvent
where
dispatchLogEvent (LogEvent name sev t) = dispatchMessage name sev t
-- | Logs all 'LogEvent'`s from given list. Just like
-- 'dispatchEvents' but uses proper logger Name.
logEvents :: WithLogger m => [LogEvent] -> m ()
logEvents events = do
logName <- askLoggerName
mapM_ (dispatchLogEvent logName) events
where
dispatchLogEvent logName (LogEvent _ sev t) = dispatchMessage logName sev t
-- | Performs actual logging once given action completes.
launchPureLog
:: (CanLog n, Monad m)
=> (forall f. Functor f => m (f a) -> n (f b))
-> PureLogger m a
-> n b
launchPureLog hoist' action = do
(logs, res) <- hoist' $ swap <$> runPureLog action
res <$ dispatchEvents logs
newtype NamedPureLogger m a = NamedPureLogger
{ runNamedPureLogger :: PureLogger (LoggerNameBox m) a
} deriving (Functor, Applicative, Monad, MonadState (Seq LogEvent),
MonadThrow, HasLoggerName)
instance MonadTrans NamedPureLogger where
lift = NamedPureLogger . lift . lift
instance Monad m => CanLog (NamedPureLogger m) where
dispatchMessage name sev msg =
NamedPureLogger $ dispatchMessage name sev msg
instance MFunctor NamedPureLogger where
hoist f = NamedPureLogger . hoist (hoist f) . runNamedPureLogger
-- | Return log of pure logging action as list of 'LogEvent',
-- using logger name provided by context.
runNamedPureLog
:: (Monad m, HasLoggerName m)
=> NamedPureLogger m a -> m (a, [LogEvent])
runNamedPureLog (NamedPureLogger action) =
askLoggerName >>= (`usingLoggerName` runPureLog action)
{- | Similar to 'launchPureLog', but provides logger name from current context.
Running the 'NamedPureLogger' gives us the pair of target and the list of 'LogEvent's,
wrapped in 'Monad' from where using the fact that @(,)@ is 'Functor' logging can be triggered.
==== __Example__
@
newtype PureSmth a = ...
deriving (MonadSmth, ...)
instance MonadSmth m => MonadSmt (NamedLoggerName m)
evalPureSmth :: PureSmth a -> a
makeField :: MonadSmth m => Data -> m Field
run :: (MonadIO m, WithLogger m) => m ()
run = do
data <- getData
-- field :: Field
field <- launchNamedPureLog (pure . evalPureSmth) (makeField data)
-- ^ logging happens here
...
@
-}
launchNamedPureLog
:: (WithLogger n, Monad m)
=> (forall f. Functor f => m (f a) -> n (f b))
-> NamedPureLogger m a
-> n b
launchNamedPureLog hoist' namedPureLogger = do
name <- askLoggerName
(logs, res) <- hoist' $ swap <$> usingNamedPureLogger name namedPureLogger
res <$ dispatchEvents logs
{- | Similar to 'launchNamedPureLog', but calls 'pure' on passed function result.
==== __Example__
The example from 'launchNamedPureLog' with usage of this function will look like:
@
newtype PureSmth a = ...
deriving (MonadSmth, ...)
instance MonadSmth m => MonadSmt (NamedLoggerName m)
evalPureSmth :: PureSmth a -> a
makeField :: MonadSmth m => Data -> m Field
run :: (MonadIO m, WithLogger m) => m ()
run = do
data <- getData
-- field :: Field
field <- launchNamedPureLogWith evalPureSmth $ makeField data
-- ^ logging happens here
...
@
-}
launchNamedPureLogWith
:: (WithLogger n, Monad m)
=> (forall f. Functor f => m (f a) -> f b)
-> NamedPureLogger m a
-> n b
launchNamedPureLogWith hoist' = launchNamedPureLog (pure . hoist')
-- | Similar to 'runNamedPureLog', but using provided logger name.
usingNamedPureLogger :: Functor m
=> LoggerName
-> NamedPureLogger m a
-> m (a, [LogEvent])
usingNamedPureLogger name (NamedPureLogger action) =
usingLoggerName name $ runPureLog action
-- | Perform pure-logging computation, log its events
-- and return the result of the computation
logPureAction :: WithLogger m => NamedPureLogger m a -> m a
logPureAction namedPureLogger = do
loggerName <- askLoggerName
(a, events) <- usingNamedPureLogger loggerName namedPureLogger
a <$ dispatchEvents events
| serokell/log-warper | src/System/Wlog/PureLogging.hs | mit | 6,558 | 0 | 13 | 1,472 | 1,257 | 674 | 583 | -1 | -1 |
module Nodes.Root where
import Data.Tree (Tree (Node))
import Nodes
import Nodes.Statement (Stmt)
data Root = CompilationUnit { statements :: [Stmt] }
instance AstNode Root where
ast (CompilationUnit statements) = Node "<root>" (map ast statements)
| milankinen/cbhs | src/nodes/Root.hs | mit | 258 | 0 | 9 | 43 | 86 | 49 | 37 | 7 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Hpack.Syntax.Defaults (
Defaults(..)
, Github(..)
, Local(..)
#ifdef TEST
, isValidOwner
, isValidRepo
#endif
) where
import Imports
import Data.Aeson.Config.KeyMap (member)
import qualified Data.Text as T
import System.FilePath.Posix (splitDirectories)
import Data.Aeson.Config.FromValue
import Hpack.Syntax.Git
data ParseGithub = ParseGithub {
parseGithubGithub :: GithubRepo
, parseGithubRef :: Ref
, parseGithubPath :: Maybe Path
} deriving (Generic, FromValue)
data GithubRepo = GithubRepo {
githubRepoOwner :: String
, githubRepoName :: String
}
instance FromValue GithubRepo where
fromValue = withString parseGithub
parseGithub :: String -> Parser GithubRepo
parseGithub github
| not (isValidOwner owner) = fail ("invalid owner name " ++ show owner)
| not (isValidRepo repo) = fail ("invalid repository name " ++ show repo)
| otherwise = return (GithubRepo owner repo)
where
(owner, repo) = drop 1 <$> break (== '/') github
isValidOwner :: String -> Bool
isValidOwner owner =
not (null owner)
&& all isAlphaNumOrHyphen owner
&& doesNotHaveConsecutiveHyphens owner
&& doesNotBeginWithHyphen owner
&& doesNotEndWithHyphen owner
where
isAlphaNumOrHyphen = (`elem` '-' : alphaNum)
doesNotHaveConsecutiveHyphens = not . isInfixOf "--"
doesNotBeginWithHyphen = not . isPrefixOf "-"
doesNotEndWithHyphen = not . isSuffixOf "-"
isValidRepo :: String -> Bool
isValidRepo repo =
not (null repo)
&& repo `notElem` [".", ".."]
&& all isValid repo
where
isValid = (`elem` '_' : '.' : '-' : alphaNum)
alphaNum :: [Char]
alphaNum = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
data Ref = Ref {unRef :: String}
instance FromValue Ref where
fromValue = withString parseRef
parseRef :: String -> Parser Ref
parseRef ref
| isValidRef ref = return (Ref ref)
| otherwise = fail ("invalid Git reference " ++ show ref)
data Path = Path {unPath :: [FilePath]}
instance FromValue Path where
fromValue = withString parsePath
parsePath :: String -> Parser Path
parsePath path
| '\\' `elem` path = fail ("rejecting '\\' in " ++ show path ++ ", please use '/' to separate path components")
| ':' `elem` path = fail ("rejecting ':' in " ++ show path)
| "/" `elem` p = fail ("rejecting absolute path " ++ show path)
| ".." `elem` p = fail ("rejecting \"..\" in " ++ show path)
| otherwise = return (Path p)
where
p = splitDirectories path
data Github = Github {
githubOwner :: String
, githubRepo :: String
, githubRef :: String
, githubPath :: [FilePath]
} deriving (Eq, Show)
toDefaultsGithub :: ParseGithub -> Github
toDefaultsGithub ParseGithub{..} = Github {
githubOwner = githubRepoOwner parseGithubGithub
, githubRepo = githubRepoName parseGithubGithub
, githubRef = unRef parseGithubRef
, githubPath = maybe [".hpack", "defaults.yaml"] unPath parseGithubPath
}
parseDefaultsGithubFromString :: String -> Parser ParseGithub
parseDefaultsGithubFromString xs = case break (== '@') xs of
(github, '@' : ref) -> ParseGithub <$> parseGithub github <*> parseRef ref <*> pure Nothing
_ -> fail ("missing Git reference for " ++ show xs ++ ", the expected format is owner/repo@ref")
data Local = Local {
localLocal :: String
} deriving (Eq, Show, Generic, FromValue)
data Defaults = DefaultsLocal Local | DefaultsGithub Github
deriving (Eq, Show)
instance FromValue Defaults where
fromValue v = case v of
String s -> DefaultsGithub . toDefaultsGithub <$> parseDefaultsGithubFromString (T.unpack s)
Object o | "local" `member` o -> DefaultsLocal <$> fromValue v
Object o | "github" `member` o -> DefaultsGithub . toDefaultsGithub <$> fromValue v
Object _ -> fail "neither key \"github\" nor key \"local\" present"
_ -> typeMismatch "Object or String" v
| sol/hpack | src/Hpack/Syntax/Defaults.hs | mit | 3,985 | 0 | 13 | 772 | 1,205 | 638 | 567 | 96 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module System.Tianbar.Plugin.DBus.FromData () where
import Data.Aeson
import Data.ByteString.Lazy as LBS
import Data.Maybe
import DBus
import DBus.Client
import System.Tianbar.Plugin
import System.Tianbar.Plugin.DBus.JSON ()
instance FromData MatchRule where
fromData = do
objPath <- fromData
iface <- fromData
memberName <- fromData
return $ matchAny { matchSender = Nothing
, matchDestination = Nothing
, matchPath = objPath
, matchInterface = iface
, matchMember = memberName
}
instance FromData MethodCall where
fromData = do
callPath <- fromData
iface <- fromData
member <- fromData
callBody <- (fromJust . decode . LBS.fromStrict) <$> lookBS "body"
dest <- fromData
let setBodyDest mcall = mcall { methodCallBody = callBody
, methodCallDestination = dest
}
return $ setBodyDest $ methodCall callPath iface member
instance FromData ObjectPath where
fromData = fromJust . parseObjectPath <$> look "path"
instance FromData InterfaceName where
fromData = fromJust . parseInterfaceName <$> look "iface"
instance FromData MemberName where
fromData = fromJust . parseMemberName <$> look "member"
instance FromData BusName where
fromData = fromJust . parseBusName <$> look "destination"
| koterpillar/tianbar | src/System/Tianbar/Plugin/DBus/FromData.hs | mit | 1,550 | 0 | 12 | 491 | 337 | 181 | 156 | 37 | 0 |
-- Divisible Ints
-- http://www.codewars.com/kata/566859a83557837d9700001a/
module Codewars.G964.Divisiblint where
import Data.List (tails, inits)
getCount :: Int -> Int
getCount n = pred . length . filter ((==0) . (n `mod'`) . read) . concatMap (tail . inits) . init . tails . show $ n
where mod' _ 0 = 1
mod' m n = mod m n
| gafiatulin/codewars | src/6 kyu/Divisiblint.hs | mit | 342 | 0 | 15 | 74 | 128 | 71 | 57 | 6 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module FilePathUtil(makeRelative', canonicalizePath', safeRemoveDirectoryRecursive, safeCreateDirectoryRecursive,
removeDotDirs, escapeFilePath, unescapeFilePath, pathify, unpathify) where
import Control.Exception (catch, SomeException(..))
import System.FilePath (joinPath, splitDirectories, (</>), isPathSeparator, pathSeparator)
import System.Directory (makeAbsolute, removeDirectoryRecursive, createDirectoryIfMissing)
-- This module provides some basic file path handling for redo
---------------------------------------------------------------------
-- # Defines
---------------------------------------------------------------------
-- Some #defines used for creating escaped dependency filenames. We want to avoid /'s.
#define seperator_replacement '^'
#define seperator_replacement_escape '@'
---------------------------------------------------------------------
-- Functions escaping and unescaping path names
---------------------------------------------------------------------
-- Takes a file path and replaces all </> with @
escapeFilePath :: FilePath -> FilePath
escapeFilePath path = concatMap repl path'
where path' = path
repl seperator_replacement = seperator_replacement : [seperator_replacement_escape]
repl c = if isPathSeparator c then [seperator_replacement] else [c]
-- Reverses escapeFilePath
unescapeFilePath :: FilePath -> FilePath
unescapeFilePath "" = ""
unescapeFilePath string = first : unescapeFilePath rest
where
(first, rest) = repl string
repl [] = ('\0',"")
repl (x:xs) = if x == seperator_replacement
then if head xs == seperator_replacement_escape
then (seperator_replacement, tail xs)
else (pathSeparator, xs)
else (x, xs)
-- Removes ".." and "." directories when possible:
removeDotDirs :: FilePath -> FilePath
removeDotDirs filePath = joinPath $ removeParents' [] (splitDirectories filePath)
where removeParents' :: [String] -> [String] -> [String]
removeParents' [] [] = []
removeParents' path [] = path
removeParents' [] (h:hs) = removeParents' [h] hs
removeParents' path (h : hs)
| h == "." = removeParents' path hs
| (h == "..") && (last path /= "") = removeParents' (init path) hs
| otherwise = removeParents' (path ++ [h]) hs
-- Find the shared root between two paths:
findCommonRoot :: FilePath -> FilePath -> FilePath
findCommonRoot filePath1 filePath2 = joinPath $ findCommonRoot' (splitDirectories filePath1) (splitDirectories filePath2)
where findCommonRoot' [] [] = []
findCommonRoot' _ [] = []
findCommonRoot' [] _ = []
findCommonRoot' (h1:path1) (h2:path2) = if h1 == h2 then h1 : findCommonRoot' path1 path2
else []
-- My version of makeRelative which actually works and inserts proper ".." where it can:
makeRelative' :: FilePath -> FilePath -> FilePath
makeRelative' filePath1 filePath2 = if numParentDirs >= 0 then joinPath (replicate numParentDirs "..") </> path2NoRoot
else filePath2
where commonRoot = findCommonRoot filePath1 filePath2
rootSize = length $ splitDirectories commonRoot
path1Size = length $ splitDirectories filePath1
numParentDirs = path1Size - rootSize
path2NoRoot = joinPath $ drop rootSize $ splitDirectories filePath2
-- A faster version of canonicalizePath from System.Directory that doesn't care about resolving simlinks. This is
-- not a necessary feature for redo, and it just slows us down.
canonicalizePath' :: FilePath -> IO FilePath
canonicalizePath' path = removeDotDirs <$> makeAbsolute path
-- Remove a directory recursively without complaining if it exists or not:
safeRemoveDirectoryRecursive :: FilePath -> IO ()
safeRemoveDirectoryRecursive dir = catch (removeDirectoryRecursive dir) (\(_ :: SomeException) -> return ())
-- Create a directory recursively withoutc complaining if it already exists:
safeCreateDirectoryRecursive :: FilePath -> IO ()
safeCreateDirectoryRecursive dir = catch (createDirectoryIfMissing True dir) (\(_ :: SomeException) -> return ())
-- Take a flat path and split by path seperators n times
pathify :: Int -> FilePath -> FilePath
pathify _ "" = ""
pathify n string = x </> pathify (n+n) xs
where (x,xs) = splitAt n string
-- Take a path with path separators and remove the path separators:
unpathify :: FilePath -> FilePath
unpathify "" = ""
unpathify (x:xs) = if isPathSeparator x then unpathify xs else x:unpathify xs
| dinkelk/redo | src/FilePathUtil.hs | mit | 4,695 | 0 | 13 | 951 | 1,027 | 553 | 474 | 60 | 5 |
module Y2021.M03.D19.Solution where
{--
@AnecdotesMaths has been publishing a formula for pi, or to approximate pi,
every day this month. I've been retweeting those formulae, because I like pi.
I also like tau, and I also like cake, so there's that.
Take one of those formulae and compute pi to a 'reasonable' degree of accuracy.
Print pi.
I choose Beeler's method:
pi / 2 = 1/1 + 1/3 + 1x2/3x5 + 1x2x3/3x5x7 ...
--}
import Prelude hiding (pi)
pi :: Double -- or some other numerical representation that suits you.
pi = nthPi 100
{-- BONUS -------------------------------------------------------
The above formula is either inaccurate or does not terminate ... or both.
Have a formula that either stops after the nth iteration or stops within a
certain degree of accuracy.
--}
nthPi :: Int -> Double
nthPi n = 2 * quarterTau (pred n) 1 [1] [3]
quarterTau :: Int -> Double -> [Double] -> [Double] -> Double
quarterTau 0 pi _ _ = pi
quarterTau n pi' num@(nu:_) dem@(d:_) =
quarterTau (pred n) (pi' + (product num / product dem))
(succ nu:num) (d+2:dem)
piWithin :: Double -> Double
piWithin epsilon = undefined
-- n.b. Today, 3.19 is a 'kinda'-accurate representation of pi? maybe?
| geophf/1HaskellADay | exercises/HAD/Y2021/M03/D19/Solution.hs | mit | 1,212 | 0 | 10 | 234 | 224 | 123 | 101 | 13 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SourceBuffer
(js_appendBuffer, appendBuffer, js_appendBufferView,
appendBufferView, js_abort, abort, js_remove, remove, js_setMode,
setMode, js_getMode, getMode, js_getUpdating, getUpdating,
js_getBuffered, getBuffered, js_setTimestampOffset,
setTimestampOffset, js_getTimestampOffset, getTimestampOffset,
js_getAudioTracks, getAudioTracks, js_getVideoTracks,
getVideoTracks, js_getTextTracks, getTextTracks,
js_setAppendWindowStart, setAppendWindowStart,
js_getAppendWindowStart, getAppendWindowStart,
js_setAppendWindowEnd, setAppendWindowEnd, js_getAppendWindowEnd,
getAppendWindowEnd, SourceBuffer, castToSourceBuffer,
gTypeSourceBuffer)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"appendBuffer\"]($2)"
js_appendBuffer :: SourceBuffer -> Nullable ArrayBuffer -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendBuffer Mozilla SourceBuffer.appendBuffer documentation>
appendBuffer ::
(MonadIO m, IsArrayBuffer data') =>
SourceBuffer -> Maybe data' -> m ()
appendBuffer self data'
= liftIO
(js_appendBuffer (self)
(maybeToNullable (fmap toArrayBuffer data')))
foreign import javascript unsafe "$1[\"appendBuffer\"]($2)"
js_appendBufferView ::
SourceBuffer -> Nullable ArrayBufferView -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendBuffer Mozilla SourceBuffer.appendBuffer documentation>
appendBufferView ::
(MonadIO m, IsArrayBufferView data') =>
SourceBuffer -> Maybe data' -> m ()
appendBufferView self data'
= liftIO
(js_appendBufferView (self)
(maybeToNullable (fmap toArrayBufferView data')))
foreign import javascript unsafe "$1[\"abort\"]()" js_abort ::
SourceBuffer -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.abort Mozilla SourceBuffer.abort documentation>
abort :: (MonadIO m) => SourceBuffer -> m ()
abort self = liftIO (js_abort (self))
foreign import javascript unsafe "$1[\"remove\"]($2, $3)" js_remove
:: SourceBuffer -> Double -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.remove Mozilla SourceBuffer.remove documentation>
remove :: (MonadIO m) => SourceBuffer -> Double -> Double -> m ()
remove self start end = liftIO (js_remove (self) start end)
foreign import javascript unsafe "$1[\"mode\"] = $2;" js_setMode ::
SourceBuffer -> JSVal -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.mode Mozilla SourceBuffer.mode documentation>
setMode :: (MonadIO m) => SourceBuffer -> AppendMode -> m ()
setMode self val = liftIO (js_setMode (self) (pToJSVal val))
foreign import javascript unsafe "$1[\"mode\"]" js_getMode ::
SourceBuffer -> IO JSVal
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.mode Mozilla SourceBuffer.mode documentation>
getMode :: (MonadIO m) => SourceBuffer -> m AppendMode
getMode self = liftIO ((js_getMode (self)) >>= fromJSValUnchecked)
foreign import javascript unsafe "($1[\"updating\"] ? 1 : 0)"
js_getUpdating :: SourceBuffer -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.updating Mozilla SourceBuffer.updating documentation>
getUpdating :: (MonadIO m) => SourceBuffer -> m Bool
getUpdating self = liftIO (js_getUpdating (self))
foreign import javascript unsafe "$1[\"buffered\"]" js_getBuffered
:: SourceBuffer -> IO (Nullable TimeRanges)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.buffered Mozilla SourceBuffer.buffered documentation>
getBuffered :: (MonadIO m) => SourceBuffer -> m (Maybe TimeRanges)
getBuffered self
= liftIO (nullableToMaybe <$> (js_getBuffered (self)))
foreign import javascript unsafe "$1[\"timestampOffset\"] = $2;"
js_setTimestampOffset :: SourceBuffer -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.timestampOffset Mozilla SourceBuffer.timestampOffset documentation>
setTimestampOffset :: (MonadIO m) => SourceBuffer -> Double -> m ()
setTimestampOffset self val
= liftIO (js_setTimestampOffset (self) val)
foreign import javascript unsafe "$1[\"timestampOffset\"]"
js_getTimestampOffset :: SourceBuffer -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.timestampOffset Mozilla SourceBuffer.timestampOffset documentation>
getTimestampOffset :: (MonadIO m) => SourceBuffer -> m Double
getTimestampOffset self = liftIO (js_getTimestampOffset (self))
foreign import javascript unsafe "$1[\"audioTracks\"]"
js_getAudioTracks :: SourceBuffer -> IO (Nullable AudioTrackList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.audioTracks Mozilla SourceBuffer.audioTracks documentation>
getAudioTracks ::
(MonadIO m) => SourceBuffer -> m (Maybe AudioTrackList)
getAudioTracks self
= liftIO (nullableToMaybe <$> (js_getAudioTracks (self)))
foreign import javascript unsafe "$1[\"videoTracks\"]"
js_getVideoTracks :: SourceBuffer -> IO (Nullable VideoTrackList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.videoTracks Mozilla SourceBuffer.videoTracks documentation>
getVideoTracks ::
(MonadIO m) => SourceBuffer -> m (Maybe VideoTrackList)
getVideoTracks self
= liftIO (nullableToMaybe <$> (js_getVideoTracks (self)))
foreign import javascript unsafe "$1[\"textTracks\"]"
js_getTextTracks :: SourceBuffer -> IO (Nullable TextTrackList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.textTracks Mozilla SourceBuffer.textTracks documentation>
getTextTracks ::
(MonadIO m) => SourceBuffer -> m (Maybe TextTrackList)
getTextTracks self
= liftIO (nullableToMaybe <$> (js_getTextTracks (self)))
foreign import javascript unsafe "$1[\"appendWindowStart\"] = $2;"
js_setAppendWindowStart :: SourceBuffer -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowStart Mozilla SourceBuffer.appendWindowStart documentation>
setAppendWindowStart ::
(MonadIO m) => SourceBuffer -> Double -> m ()
setAppendWindowStart self val
= liftIO (js_setAppendWindowStart (self) val)
foreign import javascript unsafe "$1[\"appendWindowStart\"]"
js_getAppendWindowStart :: SourceBuffer -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowStart Mozilla SourceBuffer.appendWindowStart documentation>
getAppendWindowStart :: (MonadIO m) => SourceBuffer -> m Double
getAppendWindowStart self = liftIO (js_getAppendWindowStart (self))
foreign import javascript unsafe "$1[\"appendWindowEnd\"] = $2;"
js_setAppendWindowEnd :: SourceBuffer -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowEnd Mozilla SourceBuffer.appendWindowEnd documentation>
setAppendWindowEnd :: (MonadIO m) => SourceBuffer -> Double -> m ()
setAppendWindowEnd self val
= liftIO (js_setAppendWindowEnd (self) val)
foreign import javascript unsafe "$1[\"appendWindowEnd\"]"
js_getAppendWindowEnd :: SourceBuffer -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SourceBuffer.appendWindowEnd Mozilla SourceBuffer.appendWindowEnd documentation>
getAppendWindowEnd :: (MonadIO m) => SourceBuffer -> m Double
getAppendWindowEnd self = liftIO (js_getAppendWindowEnd (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SourceBuffer.hs | mit | 8,445 | 118 | 11 | 1,242 | 1,737 | 953 | 784 | 118 | 1 |
module Data.Bag where
{-- We "re"present the Bag data-type. The 'Bag' or 'MultiSet' data type. 'Bag'
is from anon. 'MultiSet' is a nonesensical word from more recent times from
those too embarrassed to used the word 'bag' in a sentence, so they say the word
'multiset,' which means a set of unique objects with a count for each unique
object that is ... repeated ... in the set.
You see the absurdity? A set contains unique objects, but a multi-set contains
multiple unique objects. So are these unique objects unique? No, of course not,
as there are multiples of them, so it's either not a set (because the objects
are not unique) or the objects are not unique in the set (which, by definition,
contains only unique objects).
... 'MultiSet.' Yeah.
Whatever.
But we CAN'T say the word 'bag' because that's derogatory somehow, so, instead,
we say an absurdity ('MultiSet') because we don't want to look like fools
saying the word 'bag.'
We just want to say absurdities, but give them multi-syllabic renderings, so we
look sophisticated saying these absurdities.
--}
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid
import Data.Ord
-- below import available via 1HaskellADay git repository
import Control.Logic.Frege ((<<-))
-- an implementation of the bag data type from http://lpaste.net/107881
{--
A bag is a collection of elements grouped and counted by isomorphism.
So if you had:
*Data.Bag> Bag.fromList [1,2,2,1,1,1,3]
The bag would have something like the following representation:
~> Bag { (1, 4), (2, 2), (3, 1) }
--}
type Bag a = Map a (Sum Int)
emptyBag :: Bag a
emptyBag = Map.empty
addn :: Ord a => a -> Int -> Bag a -> Bag a
addn elt = Map.insertWith mappend elt . Sum
add :: Ord a => a -> Bag a -> Bag a
add = flip addn 1 -- geddit? 'add a bag'? geddit?
-- ... I don't get it.
-- the above is from my blog entry on the bag data type in Idris at
-- http://logicaltypes.blogspot.com/2014/06/thats-totes-my-bag.html
-- since Bag IS(actually)A Map, all the instantiation follows.
-- This happens often enough; we want to rank by the frequency, most frequent
-- first
rank :: Ord a => Bag a -> [(a, Int)]
rank = sortOn (Down . snd) . toList
asMap :: Ord a => Bag a -> Map a Int
asMap = Map.map getSum
toList :: Ord a => Bag a -> [(a, Int)]
toList = Map.toList . asMap
-- we used to have a countOf, but now this reduces, simply, to Map.!
-- ... but we do need fromList still
fromList :: Ord a => [a] -> Bag a
fromList = foldr add emptyBag
size :: Bag a -> Int
size = getSum . sum . Map.elems
merge :: Ord a => Bag a -> Bag a -> Bag a
merge =
-- well, let's think about this merge a and b is
-- get all the elements in a that are not in b and vice versa:
-- now we need to sum the sums of the a /\ b
-- this is Map.mergeWithKey, yes?
Map.mergeWithKey (const (pure <<- (<>))) id id
| geophf/1HaskellADay | exercises/HAD/Data/Bag.hs | mit | 2,873 | 0 | 9 | 571 | 424 | 230 | 194 | 27 | 1 |
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
-- This was my first attempt, while this works, it's REALLY slow.
-- calc = take 1 $ [x | x <- [1..], all (\y -> x `rem` y == 0) [1..20]]
-- Second, and better: left fold using lcm (smallest possible integer that both x && y divide)
calc :: Int
calc = foldl (lcm) 1 [1..20]
main :: IO ()
main = do
print calc | daniel-beard/projecteulerhaskell | Problems/p5.hs | mit | 528 | 0 | 7 | 117 | 52 | 29 | 23 | 5 | 1 |
{-# htermination (reverse :: (List a) -> (List a)) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
flip :: (c -> b -> a) -> b -> c -> a;
flip f x y = f y x;
foldl :: (a -> b -> a) -> a -> (List b) -> a;
foldl f z Nil = z;
foldl f z (Cons x xs) = foldl f (f z x) xs;
reverse :: (List a) -> (List a);
reverse = foldl (flip Cons) Nil;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/reverse_1.hs | mit | 411 | 0 | 9 | 127 | 207 | 112 | 95 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html
module Stratosphere.ResourceProperties.OpsWorksAppSource where
import Stratosphere.ResourceImports
-- | Full data type definition for OpsWorksAppSource. See 'opsWorksAppSource'
-- for a more convenient constructor.
data OpsWorksAppSource =
OpsWorksAppSource
{ _opsWorksAppSourcePassword :: Maybe (Val Text)
, _opsWorksAppSourceRevision :: Maybe (Val Text)
, _opsWorksAppSourceSshKey :: Maybe (Val Text)
, _opsWorksAppSourceType :: Maybe (Val Text)
, _opsWorksAppSourceUrl :: Maybe (Val Text)
, _opsWorksAppSourceUsername :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON OpsWorksAppSource where
toJSON OpsWorksAppSource{..} =
object $
catMaybes
[ fmap (("Password",) . toJSON) _opsWorksAppSourcePassword
, fmap (("Revision",) . toJSON) _opsWorksAppSourceRevision
, fmap (("SshKey",) . toJSON) _opsWorksAppSourceSshKey
, fmap (("Type",) . toJSON) _opsWorksAppSourceType
, fmap (("Url",) . toJSON) _opsWorksAppSourceUrl
, fmap (("Username",) . toJSON) _opsWorksAppSourceUsername
]
-- | Constructor for 'OpsWorksAppSource' containing required fields as
-- arguments.
opsWorksAppSource
:: OpsWorksAppSource
opsWorksAppSource =
OpsWorksAppSource
{ _opsWorksAppSourcePassword = Nothing
, _opsWorksAppSourceRevision = Nothing
, _opsWorksAppSourceSshKey = Nothing
, _opsWorksAppSourceType = Nothing
, _opsWorksAppSourceUrl = Nothing
, _opsWorksAppSourceUsername = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-pw
owasPassword :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasPassword = lens _opsWorksAppSourcePassword (\s a -> s { _opsWorksAppSourcePassword = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-revision
owasRevision :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasRevision = lens _opsWorksAppSourceRevision (\s a -> s { _opsWorksAppSourceRevision = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-sshkey
owasSshKey :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasSshKey = lens _opsWorksAppSourceSshKey (\s a -> s { _opsWorksAppSourceSshKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-type
owasType :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasType = lens _opsWorksAppSourceType (\s a -> s { _opsWorksAppSourceType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-url
owasUrl :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasUrl = lens _opsWorksAppSourceUrl (\s a -> s { _opsWorksAppSourceUrl = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-username
owasUsername :: Lens' OpsWorksAppSource (Maybe (Val Text))
owasUsername = lens _opsWorksAppSourceUsername (\s a -> s { _opsWorksAppSourceUsername = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/OpsWorksAppSource.hs | mit | 3,453 | 0 | 12 | 397 | 628 | 355 | 273 | 47 | 1 |
import Control.Monad (guard)
let params = sortBy (compare `on` (\(fxtal, pllpre, plldiv, pllpost, fosc,
brgh, uxbrg, baud, bauderror,
dacfdiv, apostsclr, samplefreq) -> (fosc, 400-bauderror))) $ do
let kHz = 1000
let mHz = 1000000
let samplefreq = 24 * kHz :: Float
let dacclock = samplefreq * 256
guard $ dacclock <= 25.6 * mHz
dacfdiv <- [1..128]
let aclk = dacclock * dacfdiv
apostsclr <- [1,2,4,8,16,32,64,256]
let fosc = aclk * apostsclr
guard $ fosc >= 12.5 * mHz
guard $ fosc <= 80 * mHz
let fcy = fosc / 2
guard $ fcy > 36 * mHz
let fp = fosc / 2
pllpost <- [2,4,8]
let fvco = fosc * pllpost
guard $ fvco >= 100 * mHz
guard $ fvco <= 200 * mHz
plldiv <- [2..513]
let fxtaldiv = fvco / plldiv
guard $ fxtaldiv >= 0.8 * mHz
guard $ fxtaldiv <= 8.0 * mHz
pllpre <- [2..33]
let fxtal = fxtaldiv * pllpre
guard $ fxtal <= 30 * mHz -- suggested lower bound for XT OSC
guard $ fxtal >= 3.5 * mHz -- suggested upper bound for XT OSC
guard $ fxtal `elem` [7.3728 * mHz, 8 * mHz, 8.192 * mHz, 14.7456 * mHz] -- only include common crystals
brgh <- [0,1]
let brghdiv = if brgh == 0 then 16 else 4
let desired_baud = 31.25 * kHz
let uxbrg_desired = (fp / (brghdiv * desired_baud)) - 1
uxbrg <- [ fromIntegral (floor uxbrg_desired),
fromIntegral (ceiling uxbrg_desired) ]
guard $ uxbrg >= 0
guard $ uxbrg <= 65535
let baud = fp / ((brghdiv * uxbrg) + 1)
let bauderror = abs (desired_baud - baud)
guard $ bauderror <= (desired_baud/100.0)
spipostscale1 <- [1,4,16,64]
spipostscale2 <- [1..8]
sck1 = fcy / spipostscale1 / spipostscale2
guard $ sck1 < 25 * mHz
return (fxtal, pllpre, plldiv, pllpost, fosc,
brgh, uxbrg, baud, bauderror,
dacfdiv, apostsclr, samplefreq)
| jkoberg/dspic33f_synth | clocks.hs | gpl-2.0 | 1,974 | 2 | 18 | 628 | 800 | 412 | 388 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Isabelle instance of class Logic
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable (imports Logic)
Instance of class Logic for Isabelle (including Pure, HOL etc.).
-}
module Isabelle.Logic_Isabelle where
import Common.DefaultMorphism
import Common.Id
import Logic.Logic
import Isabelle.ATC_Isabelle ()
import Isabelle.IsaSign
import Isabelle.IsaPrint
import Isabelle.IsaProve
type IsabelleMorphism = DefaultMorphism Sign
{- a dummy datatype for the LogicGraph and for identifying the right
instances -}
data Isabelle = Isabelle deriving Show
instance Language Isabelle where
description _ =
"Isabelle - a generic theorem prover\n" ++
"This logic corresponds to the logic of Isabelle,\n" ++
"a weak intuitionistic type theory\n" ++
"Also, the logics encoded in Isabelle, like FOL, HOL, HOLCF, ZF " ++
"are made available\n" ++
"See http://www.cl.cam.ac.uk/Research/HVG/Isabelle/"
instance Logic.Logic.Syntax Isabelle () () () ()
-- default implementation is fine!
instance GetRange Sentence
instance Sentences Isabelle Sentence Sign IsabelleMorphism () where
map_sen Isabelle _ = return
print_named Isabelle = printNamedSen
-- other default implementations are fine
instance StaticAnalysis Isabelle () Sentence
() ()
Sign
IsabelleMorphism () () where
empty_signature Isabelle = emptySign
is_subsig Isabelle = isSubSign
subsig_inclusion Isabelle = defaultInclusion
instance Logic Isabelle () () Sentence () ()
Sign
IsabelleMorphism () () () where
stability _ = Testing
-- again default implementations are fine
empty_proof_tree _ = ()
provers Isabelle = [isabelleProver]
cons_checkers Isabelle = [isabelleConsChecker]
instance LogicalFramework Isabelle () () Sentence () () Sign IsabelleMorphism () () ()
| nevrenato/HetsAlloy | Isabelle/Logic_Isabelle.hs | gpl-2.0 | 2,168 | 0 | 10 | 468 | 355 | 187 | 168 | 39 | 0 |
{-# LANGUAGE TupleSections #-}
module Infernu.Builtins.Array
(arrayRowType)
where
import Control.Monad (foldM)
import Infernu.Builtins.Util
import Infernu.InferState (Infer)
import Infernu.Prelude
import Infernu.Types
import Infernu.Expr (EPropName(..))
arrayProps :: Type -> [(String, TypeScheme)]
arrayProps elemType = let aType = array elemType in
[ ("length", ty number)
, ("concat", ty $ func aType aType aType)
-- TODO support thisArg (requires type variables)
, ("every", ts [] $ func aType (funcN [tvar 1, elemType] boolean) boolean) -- missing thisArg
, ("filter", ts [] $ func aType (funcN [tvar 1, elemType] boolean) aType) -- missing thisArg
, ("forEach", ts [2] $ func aType (funcN [tvar 1, elemType] (tvar 2)) undef) -- missing thisArg
-- TODO support optional argument for fromIndex (last parameter)
, ("indexOf", ty $ funcN [aType, elemType, number] number)
, ("join", ty $ func aType string string)
, ("lastIndexOf", ty $ func aType number number)
, ("map", ts [2] $ func aType (funcN [tvar 1, elemType] (tvar 2)) (array $ tvar 2))
, ("pop", ty $ funcN [aType] elemType)
, ("push", ty $ funcN [aType, elemType] number)
, ("reduce", ts [1] $ funcN [aType, funcN [tvar 0, tvar 1, elemType] (tvar 1), (tvar 1)] (tvar 1))
, ("reverse", ty $ funcN [aType] aType)
, ("shift", ty $ funcN [aType] elemType)
, ("slice", ty $ funcN [aType, number, number] aType)
, ("some", ts [] $ func aType (funcN [tvar 0, elemType] boolean) aType) -- missing thisArg
, ("sort", ts [] $ func aType (funcN [tvar 0, elemType, elemType] number) aType)
, ("splice", ty $ funcN [aType, number, number] aType)
, ("unshift", ty $ funcN [aType] elemType)
]
-- TODO: when inserting builtin types, do fresh renaming of scheme qvars
arrayRowType :: Type -> Infer (TRowList Type)
arrayRowType elemType = TRowProp (TPropGetName EPropSetIndex) (ty $ funcN [aType, number, elemType] undef)
. TRowProp (TPropGetName EPropGetIndex) (ty $ func aType number elemType)
<$> foldM addProp (TRowEnd Nothing) (arrayProps elemType)
where aType = array elemType
| sinelaw/infernu | src/Infernu/Builtins/Array.hs | gpl-2.0 | 2,254 | 0 | 14 | 540 | 841 | 463 | 378 | 35 | 1 |
module Quenelle.Parse (
ParseResult(..),
parseRuleFromFile,
parseRuleFromString
) where
import Control.Applicative
import Text.ParserCombinators.Parsec.Char
import Text.ParserCombinators.Parsec.Combinator
import Text.ParserCombinators.Parsec.Error
import Text.ParserCombinators.Parsec.Prim
import Quenelle.Replace
import Quenelle.Rule
data ParseResult =
Success ExprRule ExprReplacement
| ParseError String
| RuleError String
| ReplacementError String
instance Show ParseResult where
show (Success _ _) = "success"
show (ParseError err) = "Error parsing rule: " ++ err
show (RuleError err) = "Error parsing matching: " ++ err
show (ReplacementError err) = "Error parsing replacement: " ++ err
pythonExpr :: GenParser Char st String
pythonExpr = many1 $ satisfy (/= '\n')
rule :: GenParser Char () (String, String)
rule = do
string "replace:"
rulestr <- between newline newline pythonExpr
string "with:"
replacementstr <- between newline newline pythonExpr
return (rulestr, replacementstr)
parseRuleFromString :: FilePath -> String -> ParseResult
parseRuleFromString filename contents =
case parse rule filename contents of
Left err -> ParseError $ show err
Right (rulestr, replacementstr) ->
case parseExprRule rulestr of
Left err -> RuleError $ show err
Right rule -> case parseExprReplacement replacementstr of
Left err -> ReplacementError $ show err
Right replacement -> Success rule replacement
parseRuleFromFile :: String -> IO ParseResult
parseRuleFromFile filename = parseRuleFromString filename <$> readFile filename
| philipturnbull/quenelle | src/Quenelle/Parse.hs | gpl-2.0 | 1,706 | 0 | 15 | 373 | 437 | 224 | 213 | 42 | 4 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RelaxedPolyRec #-}
{-# LANGUAGE FlexibleInstances #-}
module LexML.URN.Show where
import LexML.URN.Types
import Text.Printf
class URNShow a where
urnShow :: a -> String
instance URNShow Integer where
urnShow = show
instance URNShow Int where
urnShow = show
instance URNShow String where
urnShow = id
instance URNShow URNLexML where
urnShow (URNLexML local doc mversao mforma mfragmento) =
"urn:lex:" ++ urnShow local ++ ":" ++ urnShow doc ++ prefixJust "@" mversao
++ prefixJust "~" mforma ++ prefixJust "!" mfragmento
instance URNShow Local where
urnShow (Local pais mdetalhamento) = urnShow pais ++ prefixJust ";" mdetalhamento
instance URNShow Data where
urnShow (Data ano mes dia) = printf "%04u-%02u-%02u" ano mes dia
instance URNShow Datas where
urnShow (Datas (Left d)) = urnShow d
urnShow (Datas (Right (d1,d2))) = "[" ++ urnShow d1 ++ "," ++ urnShow d2 ++ "]"
instance URNShow Pais where
urnShow Brasil = "br"
instance URNShow DetalhamentoLocal where
urnShow (DLNormal uf mmunicipio) = urnShow uf ++ prefixJust ";" mmunicipio
urnShow (DLJudiciario muf localJudiciario) = suffixJust ";" muf ++ urnShow localJudiciario
instance URNShow LocalJudiciario where
urnShow (LocalJudiciario ramoJustica detalhes) =
urnShow ramoJustica ++ prefixAll ";" detalhes
instance URNShow RamoJustica where
urnShow RJ_Federal = "federal"
urnShow RJ_Trabalho = "trabalho"
urnShow RJ_Eleitoral = "eleitoral"
urnShow RJ_Militar = "militar"
urnShow RJ_Estadual = "estadual"
instance URNShow UnidadeFederacao where
urnShow (UnidadeFederacao nome) = urnShow nome
instance URNShow DetalheRamo where
urnShow (DR_Regiao n) = "regiao." ++ urnShow n
urnShow (DR_Zona n) = "zona." ++ urnShow n
urnShow DR_SecaoJudiciaria = "secao.judiciaria"
urnShow DR_Comarca = "comarca"
urnShow (DR_UnidadesFederacao unidades) = showBetween "," unidades
urnShow (DR_Municipio municipio) = urnShow municipio
instance URNShow Municipio where
urnShow (Municipio nome) = urnShow nome
instance URNShow Nome where
urnShow (Nome componentes) = between "." componentes
instance URNShow Documento where
urnShow (Documento autoridade tipoDocumento descritor) =
urnShow autoridade ++ ":" ++ urnShow tipoDocumento ++ ":" ++ urnShow descritor
instance URNShow Autoridade where
urnShow (A_Normal sujeitos) = showBetween "," sujeitos
urnShow (A_Convencionada ac) = urnShow ac
instance URNShow AutoridadeConvencionada where
urnShow AC_Federal = "federal"
urnShow AC_Estadual = "estadual"
urnShow AC_Municipal = "municipal"
urnShow AC_Distrital = "distrital"
instance URNShow Sujeito where
urnShow (SJ_Instituicao instituicao orgaos mfuncao) =
urnShow instituicao ++ prefixAll ";" orgaos ++ prefixJust ";" mfuncao
urnShow (SJ_Cargo cargo) = urnShow cargo
instance URNShow Instituicao where
urnShow (Instituicao nome) = urnShow nome
instance URNShow Orgao where
urnShow (Orgao nome) = urnShow nome
instance URNShow Funcao where
urnShow (Funcao nome) = urnShow nome
instance URNShow Cargo where
urnShow (Cargo nome) = urnShow nome
instance URNShow TipoDocumento where
urnShow (TipoDocumento1 subTipo mnomeSubtipoSequenciador) =
urnShow subTipo ++ prefixJust ";" mnomeSubtipoSequenciador
urnShow (TipoDocumento2 nomePeriodicoOficial mnomeSecaoPeriodicoOficial mdetalheExtraSuplemento) =
"publicacao.oficial;" ++ urnShow nomePeriodicoOficial ++ prefixJust ";" mnomeSecaoPeriodicoOficial ++
prefixJust ";" mdetalheExtraSuplemento
instance URNShow SubTipoDocumento where
urnShow (STD1_Norma tipoNorma) = urnShow tipoNorma
urnShow (STD1_Jurisprudencia jurisprudencia) = urnShow jurisprudencia
urnShow (STD1_ProjetoNorma projetoNorma) = urnShow projetoNorma
instance URNShow TipoProjetoNorma where
urnShow (TipoProjetoNorma nome) = urnShow nome
instance URNShow TipoNorma where
urnShow (TipoNorma nome) = urnShow nome
instance URNShow TipoJurisprudencia where
urnShow (TipoJurisprudencia nome) = urnShow nome
instance URNShow NomeSubtipoSequenciador where
urnShow (NomeSubtipoSequenciador nome) = urnShow nome
instance URNShow NomePeriodicoOficial where
urnShow (NomePeriodicoOficial nome) = urnShow nome
instance URNShow NomeSecaoPeriodicoOficial where
urnShow (NomeSecaoPeriodicoOficial nome) = urnShow nome
instance URNShow DetalheExtraSuplemento where
urnShow (DetalheExtraSuplemento tipoDetalhe mnumero) =
urnShow tipoDetalhe ++ prefixJust "." mnumero
instance URNShow TipoDetalheExtraSuplemento where
urnShow TDES_EdicaoExtra = "edicao.extra"
urnShow TDES_Suplemento = "suplemento"
instance URNShow Descritor where
urnShow (Descritor tipoDescritor comps mseqRetificacao) =
urnShow tipoDescritor ++ prefixAll ";" comps ++ prefixJust ";retificacao." mseqRetificacao
instance URNShow TipoDescritor where
urnShow (TD_Datas datas midentificadores) = urnShow datas ++ prefixJust ";" midentificadores
urnShow (TD_Ano ano identificadores) = urnShow ano ++ ";" ++ urnShow identificadores
urnShow (TD_Apelido mdataOuAno apelido) = suffixJust ";" mdataOuAno ++ urnShow apelido
instance URNShow DatasOuAno where
urnShow (DatasOuAno e) = either urnShow urnShow e
instance URNShow ComponenteDescritor where
urnShow (ComponenteDescritor idcomp mtitulo) =
urnShow idcomp ++ prefixJust "," mtitulo
instance URNShow ApelidoDocumento where
urnShow (ApelidoDocumento nome) = urnShow nome
instance URNShow IdComponente where
urnShow (IdComponente nome) = urnShow nome
instance URNShow TituloComponente where
urnShow (TituloComponente nome) = urnShow nome
instance URNShow Identificadores where
urnShow (ID_Ids ids) = showBetween "," ids
urnShow (ID_NumeroLex n) = "lex-" ++ urnShow n
urnShow (ID_NumeroSeq n) = urnShow n
instance URNShow NumeroSeq where
urnShow (NumeroSeq sigla n) = "seq-" ++ urnShow sigla ++ "-" ++ urnShow n
instance URNShow SiglaOrgao where
urnShow (SiglaOrgao n) = urnShow n
instance URNShow IdDocumento where
urnShow (IdDocumento idd) = urnShow idd
instance URNShow NormalID where
urnShow (NormalID n) = n
instance URNShow Fragmento where
urnShow (Fragmento comps) = showBetween "_" comps
instance URNShow CompFragmento where
urnShow (CompFragmento tipoComponente UI_Unico) =
urnShow tipoComponente ++ "1u"
urnShow (CompFragmento tipoComponente (UI_Indices indices)) =
urnShow tipoComponente ++ showBetween "-" indices
instance URNShow TipoComponenteFragmento where
urnShow TCF_Parte = "prt"
urnShow TCF_Livro = "liv"
urnShow TCF_Titulo = "tit"
urnShow TCF_Capitulo = "cap"
urnShow TCF_Secao = "sec"
urnShow TCF_SubSecao = "sub"
urnShow TCF_AgrupamentoHierarquico = "agh"
urnShow TCF_Artigo = "art"
urnShow TCF_Caput = "cpt"
urnShow TCF_Paragrafo = "par"
urnShow TCF_Inciso = "inc"
urnShow TCF_Alinea = "ali"
urnShow TCF_Item = "ite"
urnShow TCF_DispositivoGenerico = "dpg"
urnShow TCF_Aspas = "asp"
instance URNShow Versao where
urnShow (Versao tipoVersao mdetalhe) =
urnShow tipoVersao ++ prefixJust ";" mdetalhe
instance URNShow TipoVersao where
urnShow (TV_Datas datas) = urnShow datas
urnShow TV_VersaoOriginal = "versao.original"
urnShow TV_InicioVigencia = "inicio.vigencia"
urnShow TV_MultiVigente = "multivigente"
urnShow (TV_VersaoVigenteEm d) = "versao.vigente.em;" ++ urnShow d
urnShow (TV_VersaoEficazEm d) = "versao.eficaz.em;" ++ urnShow d
urnShow (TV_VersaoConsultadaEm d) = "versao.consultada.em;" ++ urnShow d
instance URNShow DetalheVersao where
urnShow (DetalheVersao evento mvisao) = urnShow evento ++ prefixJust ";" mvisao
instance URNShow Evento where
urnShow (Evento nome) = urnShow nome
instance URNShow Visao where
urnShow (Visao datas) = urnShow datas
instance URNShow Forma where
urnShow (Forma tipoForma linguas) =
urnShow tipoForma ++ (if null linguas then "" else ";") ++ showBetween "," linguas
instance URNShow TipoForma where
urnShow (TipoForma nome) = urnShow nome
instance URNShow Lingua where
urnShow (Lingua linguaCodigo mlinguaScript mlinguaRegiao) =
urnShow linguaCodigo ++ prefixJust "-" mlinguaScript ++ prefixJust "-" mlinguaRegiao
instance URNShow LinguaCodigo where
urnShow (LinguaCodigo nome) = nome
instance URNShow LinguaScript where
urnShow (LinguaScript nome) = nome
instance URNShow LinguaRegiao where
urnShow (LinguaRegiao nome) = nome
prefixJust :: URNShow a => String -> Maybe a -> String
prefixJust _ Nothing = ""
prefixJust prefix (Just x) = prefix ++ urnShow x
suffixJust :: URNShow a => String -> Maybe a -> String
suffixJust _ Nothing = ""
suffixJust suffix (Just x) = urnShow x ++ suffix
prefixAll :: URNShow a => String -> [a] -> String
prefixAll prefix l = concat [ prefix ++ urnShow el | el <- l ]
between :: String -> [String] -> String
between sep [] = ""
between sep [x] = x
between sep (x:xs) = x ++ sep ++ showBetween sep xs
showBetween :: URNShow a => String -> [a] -> String
showBetween sep = between sep . map urnShow
| lexml/lexml-linker | src/main/haskell/LexML/URN/Show.hs | gpl-2.0 | 9,250 | 0 | 12 | 1,700 | 2,677 | 1,298 | 1,379 | 201 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Tester where
import Control.Applicative ((<$>), (<*>), (*>), (<*), (<$), pure)
import qualified Control.Applicative as CA ((<|>))
import Control.Arrow
import Control.Monad hiding (sequence)
import Data.Function
import Data.Functor
import Data.Maybe
import Data.Map hiding (filter, map, null)
import Data.Text.Lazy hiding (empty, filter, map)
import Data.Text.Lazy.IO (readFile, putStr)
import Data.Traversable
import Data.Traversable.Instances
import Prelude hiding (concat, drop, length, lex, lines, lookup, null, putStr, readFile, sequence, traverse)
import System.Directory
import System.Environment
import System.FilePath
import System.IO.Error
import Text.Parsec hiding (parse)
import Text.Parsec.Prim hiding (parse)
import Text.Parsec.Pos
import Text.Parsec.Text.Lazy
import Extensions
import Formatter
-- import Interpreter
import Lexer
import Parser
import Data hiding (ParseError)
main :: IO ()
main = getArgs >>= mapM_ (testAll 0)
help :: IO ()
help = do s <- getProgName
putStrLn ("Usage: " ++ s ++ " [file] [...]")
testAll :: Nat -> FilePath -> IO ()
testAll l fp = do f <- doesFileExist fp
d <- doesDirectoryExist fp
case (f, d) of
(True, False) -> when (takeExtension fp == ".case") (test fp)
(False, True) -> do fps <- filter (not . isDot) <$> getDirectoryContents fp
let l' = if l > 0 then pred l else l
when (l /= 0) (mapM_ (testAll l' . (fp </>)) fps)
_ -> error (show (f, d))
isDot :: FilePath -> Bool
isDot (x : _) = x == '.'
isDot _ = False
test :: FilePath -> IO ()
test fp = do t <- readFile fp
case caseFromEntries (parseEntries t) of
Just c -> testCase fp c
_ -> do putStrLn ("\"" ++ fp ++ "\":")
putStrLn "mangled case file"
putStrLn ""
testCase :: FilePath -> TestCase -> IO ()
testCase fp tc = do putStrLn (name tc ++ ":")
-- Remove CA.<|> to dispatch properly.
case parsed tc CA.<|> Just (Right (TElement (PLineComment "missing"))) of
-- Handle missing file later.
Just p -> do x <- (snd <$>) . rawParse <$> readFile (takeDirectory fp </> file tc)
let r = left (const ()) x
if r == p then
putStrLn "parsed and matched" else
do putStrLn "failed to match these"
print p
print x
_ -> putStrLn "nothing to do"
-- | A test description, file and expected values for various actions.
data TestCase = TC {name :: String,
file :: FilePath,
parsed :: Maybe (Either () (Tree Parse)), -- () -> ParseError...
compiled :: Maybe (Tree Expression), -- CompilationError...
evaluated :: Maybe Expression,
performed :: Maybe Text}
deriving (Show)
-- | A poorly written function.
-- Converts key-value pairs into a test case.
caseFromEntries :: Map Text Text -> Maybe TestCase
caseFromEntries m = TC <$> (unpack <$> lookup "name" m)
<*> (unpack <$> lookup "file" m)
<*> pure (readMaybeText =<< lookup "parsed" m)
<*> pure (const Nothing =<< lookup "compiled" m)
<*> pure (const Nothing =<< lookup "evaluated" m)
<*> pure (lookup "performed" m)
-- | A poorly written function.
-- Parses colon-separated key-value pairs.
parseEntries :: Text -> Map Text Text
parseEntries = fromList . filter (not . null . fst)
. fmap (first strip . second strip)
. catMaybes
. fmap (breakAround ":")
. lines
| Tuplanolla/eigenlanguage | haskell/Tester.hs | gpl-3.0 | 4,128 | 0 | 18 | 1,501 | 1,177 | 626 | 551 | 83 | 4 |
-- adopted from https://github.com/laughedelic/sparse-lin-alg
module Vector
where
import Data.Array.Unboxed
import Data.Array.Base as A ((!))
import Data.Foldable as F
import Data.List as L
type VKey = Int
type Vec a = Array VKey a
data Vector a = VV
{ vec :: Vec a } deriving Eq
instance Functor Vector where
fmap f v = v { vec = amap f (vec v) }
instance Foldable Vector where
foldr f d v = F.foldr f d (vec v)
instance (Eq a, Num a) => Num (Vector a) where
(+) = Vector.zipWith (+)
-- (*) = Vector.zipWith (*)
(*) = undefined
negate = fmap negate
-- fromInt 0 = emptyVec
-- fromInt x = singVec (fromInt x)
fromInteger = undefined
abs = fmap abs
signum = fmap signum
instance (Show a, Eq a) => Show (Vector a) where
show = show . fillVec
vecLength :: Vector a -> VKey
vecLength = snd . bounds . vec
setLength :: (Num a) => VKey -> Vector a -> Vector a
setLength n v = v { vec = newvec }
where newvec = listArray (1,n) arr
arr = elems (vec v) ++ repeat 0
emptyVec :: Vector a
emptyVec = VV $ array (1,0) []
zeroVec :: Num a => VKey -> Vector a
zeroVec n = VV $ listArray (1,n) $ repeat 0
isZeroVec, isNotZeroVec :: (Eq a,Num a) => Vector a -> Bool
isZeroVec = L.all (==0) . elems . vec
isNotZeroVec = not . isZeroVec
singVec :: (Eq a, Num a) => a -> Vector a
singVec x = VV $ listArray (1,1) [x]
-- TODO: partitionVec
(!) :: Vector a -> VKey -> a
v ! i = (A.!) (vec v) i
-- TODO: eraseInVec, vecIns
zipWith :: (a -> a -> a) -> Vector a -> Vector a -> Vector a
zipWith f vv@(VV v) wv@(VV w)
| vecLength wv /= n = error "zipWith: dimension error"
| otherwise = VV $ listArray (1,n) arr
where n = vecLength vv
va = elems v
wa = elems w
arr = L.zipWith f va wa
fillVec :: Vector a -> [a]
fillVec = elems . vec
vecList :: [a] -> Vector a
vecList l = VV $ listArray (1,n) l
where n = length l
dot :: Num a => Vector a -> Vector a -> a
v `dot` w = L.sum $ L.zipWith (*) (fillVec v) (fillVec w)
(·) :: Num a => Vector a -> Vector a -> a
(·) = dot
mulSV :: Num a => a -> Vector a -> Vector a
mulSV s = fmap (*s)
(.*) :: Num a => a -> Vector a -> Vector a
(.*) = mulSV
mulVS :: Num a => Vector a -> a -> Vector a
v `mulVS` s = s `mulSV` v
(*.) :: Num a => Vector a -> a -> Vector a
(*.) = mulVS
| KiNaudiz/bachelor | CN/Vector.hs | gpl-3.0 | 2,413 | 0 | 10 | 705 | 1,096 | 582 | 514 | 64 | 1 |
module Math.Structure.Instances
where
import Math.Structure.Instances.Standard.Num ()
import Math.Structure.Instances.Standard.Vector ()
| martinra/algebraic-structures | src/Math/Structure/Instances.hs | gpl-3.0 | 138 | 0 | 4 | 10 | 29 | 21 | 8 | 3 | 0 |
module STH.Lib.Text.Format.ASACarriageControl (
CCLine(..), fromCCLine, renderCCLine, toCCLine, readCCLines
) where
import Control.Arrow ((>>>))
import Data.List (intercalate, sortBy, isPrefixOf)
import STH.Lib.List (maxMonoSubseqsBy, fromSparseList, unfoldrMaybe)
import STH.Lib.Text.Format.Line (getLines)
--CCLine.S
data CCLine
= CCLine [String]
deriving (Show)
fromCCLine :: CCLine -> [String]
fromCCLine (CCLine xs) = xs
renderCCLine :: CCLine -> String
renderCCLine (CCLine xs)
= intercalate "\n" $ zipWith (:) (' ' : (repeat '+')) xs
--CCLine.E
toCCLines :: String -> [CCLine]
toCCLines = map toCCLine . getLines
{-|
'toCCLine' takes a string which may include
some backspace characters (but no newlines!)
and returns a CCLine; that is, a list of lines
which reproduce the effect of this sequence of
typewriter keypresses when fed to a line printer
by overstriking.
-}
--toCCLine.S
toCCLine :: String -> CCLine
toCCLine "" = CCLine [""]
toCCLine xs =
(columnIndices
>>> filter (\(c,_) -> c /= ' ') -- try omitting
>>> sortBy (\(_,a) (_,b) -> compare a b) -- these lines
>>> maxMonoSubseqsBy p
>>> map (fromSparseList ' ')
>>> CCLine) xs
where
p u v = if snd u < snd v
then True else False
-- Assign a column index
columnIndices :: String -> [(Char,Int)]
columnIndices = accum [] 1
where
accum zs _ "" = reverse zs
accum zs k (c:cs) = case c of
'\b' -> accum zs (max 1 (k-1)) cs
otherwise -> accum ((c,k):zs) (k+1) cs
--toCCLine.E
--readCCLines.S
readCCLines :: String -> Maybe [CCLine]
readCCLines = unfoldrMaybe readFirstCCLine . getLines
where
readFirstCCLine :: [String] -> Maybe (Maybe (CCLine, [String]))
readFirstCCLine [] = Just Nothing
readFirstCCLine ((' ':cs):ds) = do
let
(us,vs) = span (isPrefixOf "+") ds
stripPlus xs = case xs of
'+':ys -> Just ys
otherwise -> Nothing
case sequence $ map stripPlus us of
Just ws -> Just (Just (CCLine $ cs:ws, vs))
Nothing -> Nothing
readFirstCCLine _ = Nothing
--readCCLines.E
| nbloomf/st-haskell | src/STH/Lib/Text/Format/ASACarriageControl.hs | gpl-3.0 | 2,167 | 0 | 17 | 538 | 714 | 389 | 325 | 47 | 5 |
{-# 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.Ml.Projects.Locations.Studies.Trials.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a trial.
--
-- /See:/ <https://cloud.google.com/ml/ AI Platform Training & Prediction API Reference> for @ml.projects.locations.studies.trials.get@.
module Network.Google.Resource.Ml.Projects.Locations.Studies.Trials.Get
(
-- * REST Resource
ProjectsLocationsStudiesTrialsGetResource
-- * Creating a Request
, projectsLocationsStudiesTrialsGet
, ProjectsLocationsStudiesTrialsGet
-- * Request Lenses
, plstgXgafv
, plstgUploadProtocol
, plstgAccessToken
, plstgUploadType
, plstgName
, plstgCallback
) where
import Network.Google.MachineLearning.Types
import Network.Google.Prelude
-- | A resource alias for @ml.projects.locations.studies.trials.get@ method which the
-- 'ProjectsLocationsStudiesTrialsGet' request conforms to.
type ProjectsLocationsStudiesTrialsGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GoogleCloudMlV1__Trial
-- | Gets a trial.
--
-- /See:/ 'projectsLocationsStudiesTrialsGet' smart constructor.
data ProjectsLocationsStudiesTrialsGet =
ProjectsLocationsStudiesTrialsGet'
{ _plstgXgafv :: !(Maybe Xgafv)
, _plstgUploadProtocol :: !(Maybe Text)
, _plstgAccessToken :: !(Maybe Text)
, _plstgUploadType :: !(Maybe Text)
, _plstgName :: !Text
, _plstgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsStudiesTrialsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plstgXgafv'
--
-- * 'plstgUploadProtocol'
--
-- * 'plstgAccessToken'
--
-- * 'plstgUploadType'
--
-- * 'plstgName'
--
-- * 'plstgCallback'
projectsLocationsStudiesTrialsGet
:: Text -- ^ 'plstgName'
-> ProjectsLocationsStudiesTrialsGet
projectsLocationsStudiesTrialsGet pPlstgName_ =
ProjectsLocationsStudiesTrialsGet'
{ _plstgXgafv = Nothing
, _plstgUploadProtocol = Nothing
, _plstgAccessToken = Nothing
, _plstgUploadType = Nothing
, _plstgName = pPlstgName_
, _plstgCallback = Nothing
}
-- | V1 error format.
plstgXgafv :: Lens' ProjectsLocationsStudiesTrialsGet (Maybe Xgafv)
plstgXgafv
= lens _plstgXgafv (\ s a -> s{_plstgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plstgUploadProtocol :: Lens' ProjectsLocationsStudiesTrialsGet (Maybe Text)
plstgUploadProtocol
= lens _plstgUploadProtocol
(\ s a -> s{_plstgUploadProtocol = a})
-- | OAuth access token.
plstgAccessToken :: Lens' ProjectsLocationsStudiesTrialsGet (Maybe Text)
plstgAccessToken
= lens _plstgAccessToken
(\ s a -> s{_plstgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plstgUploadType :: Lens' ProjectsLocationsStudiesTrialsGet (Maybe Text)
plstgUploadType
= lens _plstgUploadType
(\ s a -> s{_plstgUploadType = a})
-- | Required. The trial name.
plstgName :: Lens' ProjectsLocationsStudiesTrialsGet Text
plstgName
= lens _plstgName (\ s a -> s{_plstgName = a})
-- | JSONP
plstgCallback :: Lens' ProjectsLocationsStudiesTrialsGet (Maybe Text)
plstgCallback
= lens _plstgCallback
(\ s a -> s{_plstgCallback = a})
instance GoogleRequest
ProjectsLocationsStudiesTrialsGet
where
type Rs ProjectsLocationsStudiesTrialsGet =
GoogleCloudMlV1__Trial
type Scopes ProjectsLocationsStudiesTrialsGet =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsStudiesTrialsGet'{..}
= go _plstgName _plstgXgafv _plstgUploadProtocol
_plstgAccessToken
_plstgUploadType
_plstgCallback
(Just AltJSON)
machineLearningService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsStudiesTrialsGetResource)
mempty
| brendanhay/gogol | gogol-ml/gen/Network/Google/Resource/Ml/Projects/Locations/Studies/Trials/Get.hs | mpl-2.0 | 5,040 | 0 | 15 | 1,108 | 697 | 408 | 289 | 107 | 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.Healthcare.Projects.Locations.DataSets.DicomStores.Studies.SearchForSeries
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- SearchForSeries returns a list of matching series. See [Search
-- Transaction]
-- (http:\/\/dicom.nema.org\/medical\/dicom\/current\/output\/html\/part18.html#sect_10.6).
-- For details on the implementation of SearchForSeries, see [Search
-- transaction](https:\/\/cloud.google.com\/healthcare\/docs\/dicom#search_transaction)
-- in the Cloud Healthcare API conformance statement. For samples that show
-- how to call SearchForSeries, see [Searching for studies, series,
-- instances, and
-- frames](https:\/\/cloud.google.com\/healthcare\/docs\/how-tos\/dicomweb#searching_for_studies_series_instances_and_frames).
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.studies.searchForSeries@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.Studies.SearchForSeries
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeriesResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresStudiesSearchForSeries
, ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries
-- * Request Lenses
, pldsdsssfsParent
, pldsdsssfsXgafv
, pldsdsssfsUploadProtocol
, pldsdsssfsAccessToken
, pldsdsssfsUploadType
, pldsdsssfsCallback
, pldsdsssfsDicomWebPath
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.studies.searchForSeries@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries' request conforms to.
type ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeriesResource
=
"v1" :>
Capture "parent" Text :>
"dicomWeb" :>
Capture "dicomWebPath" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] HTTPBody
-- | SearchForSeries returns a list of matching series. See [Search
-- Transaction]
-- (http:\/\/dicom.nema.org\/medical\/dicom\/current\/output\/html\/part18.html#sect_10.6).
-- For details on the implementation of SearchForSeries, see [Search
-- transaction](https:\/\/cloud.google.com\/healthcare\/docs\/dicom#search_transaction)
-- in the Cloud Healthcare API conformance statement. For samples that show
-- how to call SearchForSeries, see [Searching for studies, series,
-- instances, and
-- frames](https:\/\/cloud.google.com\/healthcare\/docs\/how-tos\/dicomweb#searching_for_studies_series_instances_and_frames).
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresStudiesSearchForSeries' smart constructor.
data ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries =
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries'
{ _pldsdsssfsParent :: !Text
, _pldsdsssfsXgafv :: !(Maybe Xgafv)
, _pldsdsssfsUploadProtocol :: !(Maybe Text)
, _pldsdsssfsAccessToken :: !(Maybe Text)
, _pldsdsssfsUploadType :: !(Maybe Text)
, _pldsdsssfsCallback :: !(Maybe Text)
, _pldsdsssfsDicomWebPath :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldsdsssfsParent'
--
-- * 'pldsdsssfsXgafv'
--
-- * 'pldsdsssfsUploadProtocol'
--
-- * 'pldsdsssfsAccessToken'
--
-- * 'pldsdsssfsUploadType'
--
-- * 'pldsdsssfsCallback'
--
-- * 'pldsdsssfsDicomWebPath'
projectsLocationsDataSetsDicomStoresStudiesSearchForSeries
:: Text -- ^ 'pldsdsssfsParent'
-> Text -- ^ 'pldsdsssfsDicomWebPath'
-> ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries
projectsLocationsDataSetsDicomStoresStudiesSearchForSeries pPldsdsssfsParent_ pPldsdsssfsDicomWebPath_ =
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries'
{ _pldsdsssfsParent = pPldsdsssfsParent_
, _pldsdsssfsXgafv = Nothing
, _pldsdsssfsUploadProtocol = Nothing
, _pldsdsssfsAccessToken = Nothing
, _pldsdsssfsUploadType = Nothing
, _pldsdsssfsCallback = Nothing
, _pldsdsssfsDicomWebPath = pPldsdsssfsDicomWebPath_
}
-- | The name of the DICOM store that is being accessed. For example,
-- \`projects\/{project_id}\/locations\/{location_id}\/datasets\/{dataset_id}\/dicomStores\/{dicom_store_id}\`.
pldsdsssfsParent :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries Text
pldsdsssfsParent
= lens _pldsdsssfsParent
(\ s a -> s{_pldsdsssfsParent = a})
-- | V1 error format.
pldsdsssfsXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries (Maybe Xgafv)
pldsdsssfsXgafv
= lens _pldsdsssfsXgafv
(\ s a -> s{_pldsdsssfsXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldsdsssfsUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries (Maybe Text)
pldsdsssfsUploadProtocol
= lens _pldsdsssfsUploadProtocol
(\ s a -> s{_pldsdsssfsUploadProtocol = a})
-- | OAuth access token.
pldsdsssfsAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries (Maybe Text)
pldsdsssfsAccessToken
= lens _pldsdsssfsAccessToken
(\ s a -> s{_pldsdsssfsAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldsdsssfsUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries (Maybe Text)
pldsdsssfsUploadType
= lens _pldsdsssfsUploadType
(\ s a -> s{_pldsdsssfsUploadType = a})
-- | JSONP
pldsdsssfsCallback :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries (Maybe Text)
pldsdsssfsCallback
= lens _pldsdsssfsCallback
(\ s a -> s{_pldsdsssfsCallback = a})
-- | The path of the SearchForSeries DICOMweb request. For example,
-- \`series\` or \`studies\/{study_uid}\/series\`.
pldsdsssfsDicomWebPath :: Lens' ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries Text
pldsdsssfsDicomWebPath
= lens _pldsdsssfsDicomWebPath
(\ s a -> s{_pldsdsssfsDicomWebPath = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries
where
type Rs
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries
= HTTPBody
type Scopes
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeries'{..}
= go _pldsdsssfsParent _pldsdsssfsDicomWebPath
_pldsdsssfsXgafv
_pldsdsssfsUploadProtocol
_pldsdsssfsAccessToken
_pldsdsssfsUploadType
_pldsdsssfsCallback
(Just AltJSON)
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresStudiesSearchForSeriesResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/Studies/SearchForSeries.hs | mpl-2.0 | 8,145 | 0 | 17 | 1,431 | 795 | 472 | 323 | 126 | 1 |
-- | Send notifications by e-mail.
module THIS.Notify
(sendNotifications
) where
import Control.Monad
import Control.Monad.Trans
import Data.Object
import System.Process
import System.IO
import Text.Printf
import qualified Data.Text as Text
import Database.Persist
import THIS.Types
import THIS.Util
import THIS.Templates.Text
import THIS.Database
-- | Compose text to pass to sendmail command.
composeMail :: String -- ^ From:
-> String -- ^ To:
-> String -- ^ Subject:
-> String -- ^ Message body
-> String
composeMail from to subj body =
printf "From: %s\n\
\To: %s\n\
\Subject: %s\n\n\
\%s\n" from to subj body
-- | Send one notification.
notify :: GlobalConfig
-> String -- ^ E-mail to send notification to
-> String -- ^ Message subject template
-> String -- ^ Message body template
-> StringObject
-> Variables
-> THIS ()
notify gc address subjtpl bodytpl object vars = do
let vars' = [("to", address), ("from", gcMailFrom gc)] ++ vars
sendmail <- liftEither $
evalTemplate "<sendmail template>" object vars' (gcSendmail gc)
subject <- liftEither $
evalTemplate "<subject template>" object vars' subjtpl
body <- liftEither $
evalTemplate "<body template>" object vars' bodytpl
let mail = composeMail (gcMailFrom gc) address subject body
liftIO $ putStrLn $ "> " ++ sendmail
liftIO $ putStrLn $ mail
(stdin, stdout, stderr, pid) <- liftIO $ runInteractiveCommand sendmail
liftIO $ do
hPutStrLn stdin mail
hClose stdin
waitForProcess pid
return ()
-- | Send notifications to all interested people
sendNotifications :: GlobalConfig
-> ProjectId
-> ProjectConfig
-> StringObject
-> Variables
-> String -- ^ Phase name
-> String -- ^ Phase result
-> THIS ()
sendNotifications gc pid pc object vars phase result = do
ts <- runDB (gcDatabase gc) $ do
rs <- selectList [NotifySetProject <-. [Just pid, Nothing],
NotifySetPhase <-. [Just phase, Nothing],
NotifySetResult <-. [Just result, Nothing] ] []
liftIO $ print rs
forM rs $ \set -> do
us <- selectList [UserGroup ==. notifySetGroup (entityVal set)] []
let tplId = notifySetTemplate (entityVal set)
mb <- get tplId
case mb of
Just tpl -> return (map entityVal us, templateSubject tpl, templateBody tpl)
Nothing -> fail $ "No template with ID " ++ show tplId
liftIO $ print ts
forM_ ts $ \(users, subject, body) ->
forM users $ \user -> do
let vars' = [("to", userEmail user),
("from", gcMailFrom gc),
("user", Text.unpack $ userFullName user)] ++ vars
notify gc (userEmail user) (Text.unpack subject) (Text.unpack body) object vars'
| portnov/integration-server | THIS/Notify.hs | lgpl-3.0 | 3,019 | 0 | 21 | 921 | 816 | 414 | 402 | 74 | 2 |
-- Compute letter distribution in a text file
-- Examples:
-- runhaskell haskell/text_analysis.hs letter-counts --filepath /path/to/doc.txt
-- runhaskell haskell/text_analysis.hs letter-frequency --filepath /path/to/doc.txt
import qualified Data.Map as Map
import System.IO
import Data.Char (toLower)
import Options.Applicative
import Data.Semigroup ((<>))
import Numeric (showFFloat)
stringToLower = map toLower
keepLetters = filter (`elem` ['a'..'z'])
toCharIntPairs :: String -> [(Char, Int)]
toCharIntPairs = map (\c -> (c, 1))
-- Given a string, return a map from character to the number of times it appears in the string
letter_counts :: String -> Map.Map Char Int
letter_counts string = Map.fromListWith (+) ((toCharIntPairs . keepLetters . stringToLower) string)
pad :: (Show a) => Int -> a -> String
pad n x = replicate (n-l) ' ' ++ (show x)
where l = (length . show) x
-- Format a map for output
format_counts :: Map.Map Char Int -> [String]
format_counts m = Map.foldrWithKey (\ k v ss -> ([k] ++ ": " ++ (pad w v)):ss) [] m
where w = Map.foldr (\ x acc -> max acc ((length . show) x)) 0 m
letter_frequencies :: String -> Map.Map Char Double
letter_frequencies string = Map.map (\x -> fromIntegral(x)/fromIntegral(total)) counts
where counts = letter_counts string
total = (Map.foldr (+) 0 counts)
format_float x = showFFloat (Just 3) x ""
format_frequencies :: Map.Map Char Double -> [String]
format_frequencies m = Map.foldrWithKey (\ k v ss -> ([k] ++ ": " ++ (format_float v)):ss) [] m
-- Command line options via the Options.Applicative module
data Command =
LetterCount FilePath
| LetterFrequency FilePath
deriving (Eq, Show)
letterCountOptions :: Parser Command
letterCountOptions = LetterCount
<$> strOption
( long "filepath"
<> short 'f'
<> metavar "FILEPATH"
<> help "Path to text file" )
letterFrequencyOptions :: Parser Command
letterFrequencyOptions = LetterFrequency
<$> strOption
( long "filepath"
<> short 'f'
<> metavar "FILEPATH"
<> help "Path to text file" )
cmds :: Parser Command
cmds = subparser (
command "letter-counts" (info (letterCountOptions <**> helper) (progDesc "Count occurences of letters" ))
<> command "letter-frequency" (info (letterFrequencyOptions <**> helper) (progDesc "Compute letter frequencies" )))
opts :: ParserInfo Command
opts = info (cmds <**> helper)
( fullDesc
<> progDesc "Analyze a piece of text."
<> header "Text Analyzer - get statistics on text." )
main = do
cmd <- execParser opts
case cmd of
LetterCount filepath -> do
text <- readFile filepath
let x = letter_counts text
mapM_ putStrLn (format_counts x)
LetterFrequency filepath -> do
text <- readFile filepath
let x = letter_frequencies text
mapM_ putStrLn (format_frequencies x)
-- text <- readFile filepath
-- let x = f text
-- mapM_ putStrLn (format_map x)
| cbare/Etudes | haskell/text_analysis.hs | apache-2.0 | 3,271 | 0 | 15 | 915 | 894 | 465 | 429 | 63 | 2 |
{-# START_FILE main.hs #-}
import Foo
main = print $ (foo undefined) + 1
| egaburov/funstuff | Haskell/BartoszBofH/3_PureFunctions/main.hs | apache-2.0 | 73 | 0 | 8 | 14 | 24 | 13 | 11 | 2 | 1 |
{-# LANGUAGE TemplateHaskell, TypeSynonymInstances, FlexibleInstances,
OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
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 Test.Ganeti.Objects
( testObjects
, Node(..)
, genConfigDataWithNetworks
, genDisk
, genDiskWithChildren
, genEmptyCluster
, genInst
, genInstWithNets
, genValidNetwork
, genBitStringMaxLen
) where
import Test.QuickCheck
import qualified Test.HUnit as HUnit
import Control.Applicative
import Control.Monad
import Data.Char
import qualified Data.List as List
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import GHC.Exts (IsString(..))
import qualified Text.JSON as J
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.Types ()
import qualified Ganeti.Constants as C
import Ganeti.Network
import Ganeti.Objects as Objects
import Ganeti.JSON
import Ganeti.Types
import Ganeti.Utils (bitStringToB64String)
-- * Arbitrary instances
$(genArbitrary ''PartialNDParams)
instance Arbitrary Node where
arbitrary = Node <$> genFQDN <*> genFQDN <*> genFQDN
<*> arbitrary <*> arbitrary <*> arbitrary <*> genFQDN
<*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
<*> arbitrary <*> arbitrary <*> genFQDN <*> arbitrary
<*> (Set.fromList <$> genTags)
$(genArbitrary ''BlockDriver)
$(genArbitrary ''DiskMode)
instance Arbitrary DiskLogicalId where
arbitrary = oneof [ LIDPlain <$> arbitrary <*> arbitrary
, LIDDrbd8 <$> genFQDN <*> genFQDN <*> arbitrary
<*> arbitrary <*> arbitrary <*> arbitrary
, LIDFile <$> arbitrary <*> arbitrary
, LIDBlockDev <$> arbitrary <*> arbitrary
, LIDRados <$> arbitrary <*> arbitrary
]
-- | 'Disk' 'arbitrary' instance. Since we don't test disk hierarchy
-- properties, we only generate disks with no children (FIXME), as
-- generating recursive datastructures is a bit more work.
instance Arbitrary Disk where
arbitrary = Disk <$> arbitrary <*> pure [] <*> arbitrary
<*> arbitrary <*> arbitrary <*> arbitrary
<*> arbitrary <*> arbitrary <*> arbitrary
-- FIXME: we should generate proper values, >=0, etc., but this is
-- hard for partial ones, where all must be wrapped in a 'Maybe'
$(genArbitrary ''PartialBeParams)
$(genArbitrary ''AdminState)
$(genArbitrary ''PartialNicParams)
$(genArbitrary ''PartialNic)
instance Arbitrary Instance where
arbitrary =
Instance
-- name
<$> genFQDN
-- primary node
<*> genFQDN
-- OS
<*> genFQDN
-- hypervisor
<*> arbitrary
-- hvparams
-- FIXME: add non-empty hvparams when they're a proper type
<*> pure (GenericContainer Map.empty)
-- beparams
<*> arbitrary
-- osparams
<*> pure (GenericContainer Map.empty)
-- admin_state
<*> arbitrary
-- nics
<*> arbitrary
-- disks
<*> vectorOf 5 genDisk
-- disk template
<*> arbitrary
-- disks active
<*> arbitrary
-- network port
<*> arbitrary
-- ts
<*> arbitrary <*> arbitrary
-- uuid
<*> arbitrary
-- serial
<*> arbitrary
-- tags
<*> (Set.fromList <$> genTags)
-- | Generates an instance that is connected to the given networks
-- and possibly some other networks
genInstWithNets :: [String] -> Gen Instance
genInstWithNets nets = do
plain_inst <- arbitrary
enhanceInstWithNets plain_inst nets
-- | Generates an instance that is connected to some networks
genInst :: Gen Instance
genInst = genInstWithNets []
-- | Enhances a given instance with network information, by connecting it to the
-- given networks and possibly some other networks
enhanceInstWithNets :: Instance -> [String] -> Gen Instance
enhanceInstWithNets inst nets = do
mac <- arbitrary
ip <- arbitrary
nicparams <- arbitrary
name <- arbitrary
uuid <- arbitrary
-- generate some more networks than the given ones
num_more_nets <- choose (0,3)
more_nets <- vectorOf num_more_nets genUUID
let genNic net = PartialNic mac ip nicparams net name uuid
partial_nics = map (genNic . Just)
(List.nub (nets ++ more_nets))
new_inst = inst { instNics = partial_nics }
return new_inst
genDiskWithChildren :: Int -> Gen Disk
genDiskWithChildren num_children = do
logicalid <- arbitrary
children <- vectorOf num_children (genDiskWithChildren 0)
ivname <- genName
size <- arbitrary
mode <- arbitrary
name <- genMaybe genName
spindles <- arbitrary
params <- arbitrary
uuid <- genName
let disk = Disk logicalid children ivname size mode name spindles params uuid
return disk
genDisk :: Gen Disk
genDisk = genDiskWithChildren 3
-- | FIXME: This generates completely random data, without normal
-- validation rules.
$(genArbitrary ''PartialISpecParams)
-- | FIXME: This generates completely random data, without normal
-- validation rules.
$(genArbitrary ''PartialIPolicy)
$(genArbitrary ''FilledISpecParams)
$(genArbitrary ''MinMaxISpecs)
$(genArbitrary ''FilledIPolicy)
$(genArbitrary ''IpFamily)
$(genArbitrary ''FilledNDParams)
$(genArbitrary ''FilledNicParams)
$(genArbitrary ''FilledBeParams)
instance Arbitrary DiskParams where
arbitrary = return $ GenericContainer Map.empty
-- | No real arbitrary instance for 'ClusterHvParams' yet.
instance Arbitrary ClusterHvParams where
arbitrary = return $ GenericContainer Map.empty
-- | No real arbitrary instance for 'OsHvParams' yet.
instance Arbitrary OsHvParams where
arbitrary = return $ GenericContainer Map.empty
instance Arbitrary ClusterNicParams where
arbitrary = (GenericContainer . Map.singleton C.ppDefault) <$> arbitrary
instance Arbitrary OsParams where
arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
instance Arbitrary ClusterOsParams where
arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
instance Arbitrary ClusterBeParams where
arbitrary = (GenericContainer . Map.fromList) <$> arbitrary
instance Arbitrary TagSet where
arbitrary = Set.fromList <$> genTags
$(genArbitrary ''Cluster)
instance Arbitrary Network where
arbitrary = genValidNetwork
-- | Generates a network instance with minimum netmasks of /24. Generating
-- bigger networks slows down the tests, because long bit strings are generated
-- for the reservations.
genValidNetwork :: Gen Objects.Network
genValidNetwork = do
-- generate netmask for the IPv4 network
netmask <- fromIntegral <$> choose (24::Int, 29)
name <- genName >>= mkNonEmpty
mac_prefix <- genMaybe genName
net <- arbitrary
net6 <- genMaybe genIp6Net
gateway <- genMaybe arbitrary
gateway6 <- genMaybe genIp6Addr
res <- liftM (Just . bitStringToB64String)
(genBitString $ netmask2NumHosts netmask)
ext_res <- liftM (Just . bitStringToB64String)
(genBitString $ netmask2NumHosts netmask)
uuid <- arbitrary
ctime <- arbitrary
mtime <- arbitrary
let n = Network name mac_prefix (Ip4Network net netmask) net6 gateway
gateway6 res ext_res uuid ctime mtime 0 Set.empty
return n
-- | Generate an arbitrary string consisting of '0' and '1' of the given length.
genBitString :: Int -> Gen String
genBitString len = vectorOf len (elements "01")
-- | Generate an arbitrary string consisting of '0' and '1' of the maximum given
-- length.
genBitStringMaxLen :: Int -> Gen String
genBitStringMaxLen maxLen = choose (0, maxLen) >>= genBitString
-- | Generator for config data with an empty cluster (no instances),
-- with N defined nodes.
genEmptyCluster :: Int -> Gen ConfigData
genEmptyCluster ncount = do
nodes <- vector ncount
version <- arbitrary
grp <- arbitrary
let guuid = groupUuid grp
nodes' = zipWith (\n idx ->
let newname = nodeName n ++ "-" ++ show idx
in (newname, n { nodeGroup = guuid,
nodeName = newname}))
nodes [(1::Int)..]
nodemap = Map.fromList nodes'
contnodes = if Map.size nodemap /= ncount
then error ("Inconsistent node map, duplicates in" ++
" node name list? Names: " ++
show (map fst nodes'))
else GenericContainer nodemap
continsts = GenericContainer Map.empty
networks = GenericContainer Map.empty
let contgroups = GenericContainer $ Map.singleton guuid grp
serial <- arbitrary
cluster <- resize 8 arbitrary
let c = ConfigData version cluster contnodes contgroups continsts networks
serial
return c
-- | FIXME: make an even simpler base version of creating a cluster.
-- | Generates config data with a couple of networks.
genConfigDataWithNetworks :: ConfigData -> Gen ConfigData
genConfigDataWithNetworks old_cfg = do
num_nets <- choose (0, 3)
-- generate a list of network names (no duplicates)
net_names <- genUniquesList num_nets genName >>= mapM mkNonEmpty
-- generate a random list of networks (possibly with duplicate names)
nets <- vectorOf num_nets genValidNetwork
-- use unique names for the networks
let nets_unique = map ( \(name, net) -> net { networkName = name } )
(zip net_names nets)
net_map = GenericContainer $ Map.fromList
(map (\n -> (networkUuid n, n)) nets_unique)
new_cfg = old_cfg { configNetworks = net_map }
return new_cfg
-- * Test properties
-- | Tests that fillDict behaves correctly
prop_fillDict :: [(Int, Int)] -> [(Int, Int)] -> Property
prop_fillDict defaults custom =
let d_map = Map.fromList defaults
d_keys = map fst defaults
c_map = Map.fromList custom
c_keys = map fst custom
in conjoin [ printTestCase "Empty custom filling"
(fillDict d_map Map.empty [] == d_map)
, printTestCase "Empty defaults filling"
(fillDict Map.empty c_map [] == c_map)
, printTestCase "Delete all keys"
(fillDict d_map c_map (d_keys++c_keys) == Map.empty)
]
-- | Test that the serialisation of 'DiskLogicalId', which is
-- implemented manually, is idempotent. Since we don't have a
-- standalone JSON instance for DiskLogicalId (it's a data type that
-- expands over two fields in a JSObject), we test this by actially
-- testing entire Disk serialisations. So this tests two things at
-- once, basically.
prop_Disk_serialisation :: Disk -> Property
prop_Disk_serialisation = testSerialisation
-- | Check that node serialisation is idempotent.
prop_Node_serialisation :: Node -> Property
prop_Node_serialisation = testSerialisation
-- | Check that instance serialisation is idempotent.
prop_Inst_serialisation :: Instance -> Property
prop_Inst_serialisation = testSerialisation
-- | Check that network serialisation is idempotent.
prop_Network_serialisation :: Network -> Property
prop_Network_serialisation = testSerialisation
-- | Check config serialisation.
prop_Config_serialisation :: Property
prop_Config_serialisation =
forAll (choose (0, maxNodes `div` 4) >>= genEmptyCluster) testSerialisation
-- | Custom HUnit test to check the correspondence between Haskell-generated
-- networks and their Python decoded, validated and re-encoded version.
-- For the technical background of this unit test, check the documentation
-- of "case_py_compat_types" of test/hs/Test/Ganeti/Opcodes.hs
casePyCompatNetworks :: HUnit.Assertion
casePyCompatNetworks = do
let num_networks = 500::Int
networks <- genSample (vectorOf num_networks genValidNetwork)
let networks_with_properties = map getNetworkProperties networks
serialized = J.encode networks
-- check for non-ASCII fields, usually due to 'arbitrary :: String'
mapM_ (\net -> when (any (not . isAscii) (J.encode net)) .
HUnit.assertFailure $
"Network has non-ASCII fields: " ++ show net
) networks
py_stdout <-
runPython "from ganeti import network\n\
\from ganeti import objects\n\
\from ganeti import serializer\n\
\import sys\n\
\net_data = serializer.Load(sys.stdin.read())\n\
\decoded = [objects.Network.FromDict(n) for n in net_data]\n\
\encoded = []\n\
\for net in decoded:\n\
\ a = network.AddressPool(net)\n\
\ encoded.append((a.GetFreeCount(), a.GetReservedCount(), \\\n\
\ net.ToDict()))\n\
\print serializer.Dump(encoded)" serialized
>>= checkPythonResult
let deserialised = J.decode py_stdout::J.Result [(Int, Int, Network)]
decoded <- case deserialised of
J.Ok ops -> return ops
J.Error msg ->
HUnit.assertFailure ("Unable to decode networks: " ++ msg)
-- this already raised an expection, but we need it
-- for proper types
>> fail "Unable to decode networks"
HUnit.assertEqual "Mismatch in number of returned networks"
(length decoded) (length networks_with_properties)
mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
) $ zip decoded networks_with_properties
-- | Creates a tuple of the given network combined with some of its properties
-- to be compared against the same properties generated by the python code.
getNetworkProperties :: Network -> (Int, Int, Network)
getNetworkProperties net =
let maybePool = createAddressPool net
in case maybePool of
(Just pool) -> (getFreeCount pool, getReservedCount pool, net)
Nothing -> (-1, -1, net)
-- | Tests the compatibility between Haskell-serialized node groups and their
-- python-decoded and encoded version.
casePyCompatNodegroups :: HUnit.Assertion
casePyCompatNodegroups = do
let num_groups = 500::Int
groups <- genSample (vectorOf num_groups genNodeGroup)
let serialized = J.encode groups
-- check for non-ASCII fields, usually due to 'arbitrary :: String'
mapM_ (\group -> when (any (not . isAscii) (J.encode group)) .
HUnit.assertFailure $
"Node group has non-ASCII fields: " ++ show group
) groups
py_stdout <-
runPython "from ganeti import objects\n\
\from ganeti import serializer\n\
\import sys\n\
\group_data = serializer.Load(sys.stdin.read())\n\
\decoded = [objects.NodeGroup.FromDict(g) for g in group_data]\n\
\encoded = [g.ToDict() for g in decoded]\n\
\print serializer.Dump(encoded)" serialized
>>= checkPythonResult
let deserialised = J.decode py_stdout::J.Result [NodeGroup]
decoded <- case deserialised of
J.Ok ops -> return ops
J.Error msg ->
HUnit.assertFailure ("Unable to decode node groups: " ++ msg)
-- this already raised an expection, but we need it
-- for proper types
>> fail "Unable to decode node groups"
HUnit.assertEqual "Mismatch in number of returned node groups"
(length decoded) (length groups)
mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
) $ zip decoded groups
-- | Generates a node group with up to 3 networks.
-- | FIXME: This generates still somewhat completely random data, without normal
-- validation rules.
genNodeGroup :: Gen NodeGroup
genNodeGroup = do
name <- genFQDN
members <- pure []
ndparams <- arbitrary
alloc_policy <- arbitrary
ipolicy <- arbitrary
diskparams <- pure (GenericContainer Map.empty)
num_networks <- choose (0, 3)
net_uuid_list <- vectorOf num_networks (arbitrary::Gen String)
nic_param_list <- vectorOf num_networks (arbitrary::Gen PartialNicParams)
net_map <- pure (GenericContainer . Map.fromList $
zip net_uuid_list nic_param_list)
-- timestamp fields
ctime <- arbitrary
mtime <- arbitrary
uuid <- genFQDN `suchThat` (/= name)
serial <- arbitrary
tags <- Set.fromList <$> genTags
let group = NodeGroup name members ndparams alloc_policy ipolicy diskparams
net_map ctime mtime uuid serial tags
return group
instance Arbitrary NodeGroup where
arbitrary = genNodeGroup
$(genArbitrary ''Ip4Address)
$(genArbitrary ''Ip4Network)
-- | Helper to compute absolute value of an IPv4 address.
ip4AddrValue :: Ip4Address -> Integer
ip4AddrValue (Ip4Address a b c d) =
fromIntegral a * (2^(24::Integer)) +
fromIntegral b * (2^(16::Integer)) +
fromIntegral c * (2^(8::Integer)) + fromIntegral d
-- | Tests that any difference between IPv4 consecutive addresses is 1.
prop_nextIp4Address :: Ip4Address -> Property
prop_nextIp4Address ip4 =
ip4AddrValue (nextIp4Address ip4) ==? ip4AddrValue ip4 + 1
-- | IsString instance for 'Ip4Address', to help write the tests.
instance IsString Ip4Address where
fromString s =
fromMaybe (error $ "Failed to parse address from " ++ s) (readIp4Address s)
-- | Tests a few simple cases of IPv4 next address.
caseNextIp4Address :: HUnit.Assertion
caseNextIp4Address = do
HUnit.assertEqual "" "0.0.0.1" $ nextIp4Address "0.0.0.0"
HUnit.assertEqual "" "0.0.0.0" $ nextIp4Address "255.255.255.255"
HUnit.assertEqual "" "1.2.3.5" $ nextIp4Address "1.2.3.4"
HUnit.assertEqual "" "1.3.0.0" $ nextIp4Address "1.2.255.255"
HUnit.assertEqual "" "1.2.255.63" $ nextIp4Address "1.2.255.62"
-- | Tests the compatibility between Haskell-serialized instances and their
-- python-decoded and encoded version.
-- Note: this can be enhanced with logical validations on the decoded objects
casePyCompatInstances :: HUnit.Assertion
casePyCompatInstances = do
let num_inst = 500::Int
instances <- genSample (vectorOf num_inst genInst)
let serialized = J.encode instances
-- check for non-ASCII fields, usually due to 'arbitrary :: String'
mapM_ (\inst -> when (any (not . isAscii) (J.encode inst)) .
HUnit.assertFailure $
"Instance has non-ASCII fields: " ++ show inst
) instances
py_stdout <-
runPython "from ganeti import objects\n\
\from ganeti import serializer\n\
\import sys\n\
\inst_data = serializer.Load(sys.stdin.read())\n\
\decoded = [objects.Instance.FromDict(i) for i in inst_data]\n\
\encoded = [i.ToDict() for i in decoded]\n\
\print serializer.Dump(encoded)" serialized
>>= checkPythonResult
let deserialised = J.decode py_stdout::J.Result [Instance]
decoded <- case deserialised of
J.Ok ops -> return ops
J.Error msg ->
HUnit.assertFailure ("Unable to decode instance: " ++ msg)
-- this already raised an expection, but we need it
-- for proper types
>> fail "Unable to decode instances"
HUnit.assertEqual "Mismatch in number of returned instances"
(length decoded) (length instances)
mapM_ (uncurry (HUnit.assertEqual "Different result after encoding/decoding")
) $ zip decoded instances
-- | Tests that the logical ID is correctly found in a plain disk
caseIncludeLogicalIdPlain :: HUnit.Assertion
caseIncludeLogicalIdPlain =
let vg_name = "xenvg" :: String
lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
d =
Disk (LIDPlain vg_name lv_name) [] "diskname" 1000 DiskRdWr
Nothing Nothing Nothing "asdfgr-1234-5123-daf3-sdfw-134f43"
in
HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
includesLogicalId vg_name lv_name d
-- | Tests that the logical ID is correctly found in a DRBD disk
caseIncludeLogicalIdDrbd :: HUnit.Assertion
caseIncludeLogicalIdDrbd =
let vg_name = "xenvg" :: String
lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
d =
Disk
(LIDDrbd8 "node1.example.com" "node2.example.com" 2000 1 5 "secret")
[ Disk (LIDPlain "onevg" "onelv") [] "disk1" 1000 DiskRdWr Nothing
Nothing Nothing "145145-asdf-sdf2-2134-asfd-534g2x"
, Disk (LIDPlain vg_name lv_name) [] "disk2" 1000 DiskRdWr Nothing
Nothing Nothing "6gd3sd-423f-ag2j-563b-dg34-gj3fse"
] "diskname" 1000 DiskRdWr Nothing Nothing Nothing
"asdfgr-1234-5123-daf3-sdfw-134f43"
in
HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
includesLogicalId vg_name lv_name d
-- | Tests that the logical ID is correctly NOT found in a plain disk
caseNotIncludeLogicalIdPlain :: HUnit.Assertion
caseNotIncludeLogicalIdPlain =
let vg_name = "xenvg" :: String
lv_name = "1234sdf-qwef-2134-asff-asd2-23145d.data" :: String
d =
Disk (LIDPlain "othervg" "otherlv") [] "diskname" 1000 DiskRdWr
Nothing Nothing Nothing "asdfgr-1234-5123-daf3-sdfw-134f43"
in
HUnit.assertBool "Unable to detect that plain Disk includes logical ID" $
not (includesLogicalId vg_name lv_name d)
testSuite "Objects"
[ 'prop_fillDict
, 'prop_Disk_serialisation
, 'prop_Inst_serialisation
, 'prop_Network_serialisation
, 'prop_Node_serialisation
, 'prop_Config_serialisation
, 'casePyCompatNetworks
, 'casePyCompatNodegroups
, 'casePyCompatInstances
, 'prop_nextIp4Address
, 'caseNextIp4Address
, 'caseIncludeLogicalIdPlain
, 'caseIncludeLogicalIdDrbd
, 'caseNotIncludeLogicalIdPlain
]
| apyrgio/snf-ganeti | test/hs/Test/Ganeti/Objects.hs | bsd-2-clause | 22,863 | 0 | 23 | 5,127 | 4,276 | 2,179 | 2,097 | 390 | 2 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Database.HyperDex.Internal.Options
-- Copyright : (c) Aaron Friel 2013-2014
-- License : BSD-style
-- Maintainer : mayreply@aaronfriel.com
-- Stability : unstable
-- Portability : portable
--
module Database.HyperDex.Internal.Options
( ConnectInfo (..)
, defaultConnectInfo
)
where
import Data.ByteString
import Data.Default
import Data.Word
-- | Parameters for connecting to a HyperDex cluster.
data ConnectInfo =
ConnectInfo
{ connectHost :: {-# UNPACK #-} !ByteString
, connectPort :: {-# UNPACK #-} !Word16
}
deriving (Eq, Read, Show)
instance Default ConnectInfo where
def =
ConnectInfo
{ connectHost = "127.0.0.1"
, connectPort = 1982
}
defaultConnectInfo :: ConnectInfo
defaultConnectInfo = def
| AaronFriel/hyhac | src/Database/HyperDex/Internal/Options.hs | bsd-3-clause | 854 | 8 | 9 | 203 | 130 | 82 | 48 | 19 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Sound.OpenAL.AL.Doppler
-- Copyright : (c) Sven Panne 2005
-- License : BSD-style (see the file libraries/OpenAL/LICENSE)
--
-- Maintainer : sven.panne@aedion.de
-- Stability : provisional
-- Portability : portable
--
-- This module corresponds to section 3.5.2. (Velocity Dependent Doppler Effect)
-- of the OpenAL Specification and Reference (version 1.1).
--
--------------------------------------------------------------------------------
module Sound.OpenAL.AL.Doppler (
-- * Introduction
-- $Introduction
dopplerFactor, speedOfSound
) where
import Foreign.Ptr ( FunPtr )
import Graphics.Rendering.OpenGL.GL.StateVar (
HasGetter(get), StateVar, makeStateVar )
import Sound.OpenAL.AL.BasicTypes ( ALenum, ALfloat )
import Sound.OpenAL.AL.Extensions ( alProcAddress )
import Sound.OpenAL.AL.QueryUtils (
GetPName(GetDopplerFactor,GetSpeedOfSound), marshalGetPName )
#ifdef __HADDOCK__
import Sound.OpenAL.AL.Errors ( ALError(ALInvalidValue) )
#endif
--------------------------------------------------------------------------------
-- | 'dopplerFactor' is a simple scaling of source and listener velocities to
-- exaggerate or deemphasize the Doppler (pitch) shift resulting from the
-- calculation. Setting 'dopplerFactor' to a negative value will result in an
-- 'ALInvalidValue' error, the command is then ignored. The default value is 1.
-- The implementation is free to optimize the case of 'dopplerFactor' containing
-- zero, as this effectively disables the effect.
dopplerFactor :: StateVar ALfloat
dopplerFactor = makeDopplerVar GetDopplerFactor "alDopplerFactor"
--------------------------------------------------------------------------------
-- | 'speedOfSound' allows the application to change the reference (propagation)
-- speed used in the Doppler calculation. The source and listener velocities
-- should be expressed in the same units as the speed of sound. Setting
-- 'speedOfSound' to a negative or zero value will result in an 'ALInvalidValue'
-- error, the command is ignored then. The default value is 343.3 (appropriate
-- for velocity units of meters and air as the propagation medium).
speedOfSound :: StateVar ALfloat
speedOfSound = makeDopplerVar GetSpeedOfSound "alSpeedOfSound"
--------------------------------------------------------------------------------
makeDopplerVar :: GetPName -> String -> StateVar ALfloat
makeDopplerVar p apiEntryName =
makeStateVar
(alGetFloat (marshalGetPName p))
(\value -> do
-- ToDo: Should we check alcVersion or alIsExtensionPresent here?
funPtr <- get (alProcAddress apiEntryName)
invokeWithFloat funPtr value)
foreign import CALLCONV unsafe "alGetFloat"
alGetFloat :: ALenum -> IO ALfloat
type Invoker a = FunPtr a -> a
foreign import CALLCONV unsafe "dynamic"
invokeWithFloat :: Invoker (ALfloat -> IO ())
--------------------------------------------------------------------------------
-- $Introduction
-- The Doppler Effect depends on the velocities of source and listener relative
-- to the medium, and the propagation speed of sound in that medium. The
-- application might want to emphasize or de-emphasize the Doppler Effect as
-- physically accurate calculation might not give the desired results.
-- The amount of frequency shift (pitch change) is proportional to the speed of
-- listener and source along their line of sight.
--
-- The Doppler Effect as implemented by OpenAL is described in detail in section
-- 3.5.2 of the OpenAL 1.1 specification. Note that effects of the medium (air,
-- water) moving with respect to listener and source are ignored. There are two
-- API calls global to the current context that provide control of the Doppler
-- factor and the speed of sound. Distance and velocity units are completely
-- independent of one another (so you could use different units for each if
-- desired).
| FranklinChen/hugs98-plus-Sep2006 | packages/OpenAL/Sound/OpenAL/AL/Doppler.hs | bsd-3-clause | 3,995 | 4 | 14 | 603 | 345 | 215 | 130 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
-- | read/write Scream Tracker 3 Instruments
module Codec.Tracker.S3M.Instrument (
Instrument (..)
, getInstrument
, putInstrument
) where
import Control.Monad
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Maybe
import Codec.Tracker.S3M.Instrument.Adlib
import Codec.Tracker.S3M.Instrument.PCM
-- | Scream Tracker 3 instrument
data Instrument = Instrument { instrumentType :: Word8 -- ^ 0: empty, 1: PCM, 2: adlib melody instrument, 3-7: adlib percussion instrument
, fileName :: [Word8] -- ^ 12 bytes
, pcmSample :: Maybe PCMSample -- ^ if instrumentType == 1
, adlibSample :: Maybe AdlibSample
}
deriving (Show, Eq)
-- | Read an `Instrument` from the monad state.
getInstrument :: Get Instrument
getInstrument = label "S3M.Instrument" $ do
instrumentType <- getWord8
fileName <- replicateM 12 getWord8
pcmSample <- sequence $ if instrumentType == 1 then Just getPCMSample else Nothing
adlibSample <- sequence $ if instrumentType `elem` [2..7] then Just getAdlibSample else Nothing
return Instrument{..}
-- | Write an `Instrument` to the buffer.
putInstrument :: Int -> Instrument -> Put
putInstrument ptr Instrument{..} = do
putWord8 instrumentType
mapM_ putWord8 fileName
_ <- if isNothing pcmSample && isNothing adlibSample then do
mapM_ putWord8 $ replicate 63 0 -- padding because of reasons
putWord32le 0x53524353
else return ()
forM_ pcmSample $ putPCMSample ptr
forM_ adlibSample putAdlibSample
| riottracker/modfile | src/Codec/Tracker/S3M/Instrument.hs | bsd-3-clause | 1,811 | 0 | 12 | 549 | 352 | 189 | 163 | 34 | 3 |
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE OverloadedStrings #-}
module Twilio.Applications
( -- * Resource
Applications(..)
, Twilio.Applications.get
) where
import Control.Applicative
import Control.Monad.Catch
import Data.Aeson
import Data.Maybe
import Control.Monad.Twilio
import Twilio.Application
import Twilio.Internal.Request
import Twilio.Internal.Resource as Resource
import Twilio.Types
{- Resource -}
data Applications = Applications
{ applicationsPagingInformation :: PagingInformation
, applicationList :: [Application]
} deriving (Show, Eq)
instance List Applications Application where
getListWrapper = wrap (Applications . fromJust)
getList = applicationList
getPlural = Const "applications"
instance FromJSON Applications where
parseJSON = parseJSONToList
instance Get0 Applications where
get0 = request parseJSONFromResponse =<< makeTwilioRequest "/Applications.json"
{- | Get the 'Applications' for your account.
For example, you can fetch the 'Applications' resource in the 'IO' monad as follows:
>module Main where
>
>import Control.Monad.IO.Class (liftIO)
>import System.Environment (getEnv)
>import Twilio.Applications as Applications
>import Twilio.Types
>
>-- | Print applications.
>main :: IO ()
>main = runTwilio' (getEnv "ACCOUNT_SID")
> (getEnv "AUTH_TOKEN")
> $ Applications.get >>= liftIO . print
-}
get :: MonadThrow m => TwilioT m Applications
get = Resource.get
| seagreen/twilio-haskell | src/Twilio/Applications.hs | bsd-3-clause | 1,461 | 0 | 9 | 224 | 210 | 123 | 87 | 29 | 1 |
{-# LANGUAGE TypeFamilies, FlexibleInstances, TypeSynonymInstances #-}
module Language.Quasi.Convenience
( toExp, toPat, toType, toDec, toBody, toStmt, toMatch, toGuard, toTyVarBndr
, fromExp, fromPat, fromType, fromDec, fromBody, fromStmt, fromMatch, fromGuard, fromTyVarBndr
)
where
import Control.Applicative ((<$>), (<*>))
import Data.Char (isUpper)
import Language.Haskell.TH
class ToExp a where toExp :: a -> Exp
class ToPat a where toPat :: a -> Pat
class ToType a where toType :: a -> Type
class ToDec a where toDec :: a -> Dec
class ToBody a where toBody :: a -> Body
class ToStmt a where toStmt :: a -> Stmt
class ToMatch a where toMatch :: a -> Match
class ToGuard a where toGuard :: a -> Guard
class ToTyVarBndr a where toTyVarBndr :: a -> TyVarBndr
instance ToExp Exp where toExp = id
instance ToPat Pat where toPat = id
instance ToType Type where toType = id
instance ToDec Dec where toDec = id
instance ToBody Body where toBody = id
instance ToStmt Stmt where toStmt = id
instance ToMatch Match where toMatch = id
instance ToGuard Guard where toGuard = id
ifCap :: (Name -> a) -> (Name -> a) -> Name -> a
ifCap f g n = if isUpper . head $ nameBase n then f n else g n
instance ToExp Name where toExp = ifCap ConE VarE
instance ToPat Name where toPat = ifCap (`ConP` []) VarP
instance ToType Name where toType = ifCap ConT VarT
instance ToBody Name where toBody = toBody . toExp
instance ToStmt Name where toStmt = toStmt . toExp
instance ToTyVarBndr Name where toTyVarBndr = PlainTV
instance ToExp String where toExp = toExp . mkName
instance ToPat String where toPat = toPat . mkName
instance ToType String where toType = toType . mkName
instance ToBody String where toBody = toBody . mkName
instance ToStmt String where toStmt = toStmt . mkName
instance ToTyVarBndr String where toTyVarBndr = toTyVarBndr . mkName
instance ToBody Exp where toBody = NormalB
--TODO: good idea?
instance ToBody [(Guard, Exp)] where toBody = GuardedB
instance ToGuard Exp where toGuard = NormalG
instance ToGuard Stmt where toGuard = PatG . (:[])
instance ToGuard [Stmt] where toGuard = PatG
instance ToStmt Exp where toStmt = NoBindS
--TODO: good ideas?
instance ToTyVarBndr (Name, Kind) where toTyVarBndr = uncurry KindedTV
-- instance ToPred (Name, [Type])
-- instance ToPred (Type, Type)
instance (ToPat p, ToBody b, ToDec d) => ToMatch (p, b, [d]) where toMatch (p, b, ds) = Match (toPat p) (toBody b) (map toDec ds)
instance (ToPat p, ToBody b) => ToMatch (p, b ) where toMatch (p, b ) = Match (toPat p) (toBody b) []
class FromExp a where fromExp :: Exp -> a
class FromPat a where fromPat :: Pat -> a
class FromType a where fromType :: Type -> a
class FromDec a where fromDec :: Dec -> a
class FromBody a where fromBody :: Body -> a
class FromStmt a where fromStmt :: Stmt -> a
class FromMatch a where fromMatch :: Match -> a
class FromGuard a where fromGuard :: Guard -> a
class FromTyVarBndr a where fromTyVarBndr :: TyVarBndr -> a
instance FromExp Exp where fromExp = id
instance FromPat Pat where fromPat = id
instance FromType Type where fromType = id
instance FromDec Dec where fromDec = id
instance FromBody Body where fromBody = id
instance FromStmt Stmt where fromStmt = id
instance FromMatch Match where fromMatch = id
instance FromGuard Guard where fromGuard = id
-- TODO
{-
instance FromExp Name where fromExp = name_of
instance FromPat Name where fromPat = name_of
instance FromType Name where fromType = name_of
instance FromBody Name where fromBody = name_of
instance FromStmt Name where fromStmt = name_of
instance FromTyVarBndr Name where fromTyVarBndr = name_of
-}
{-
instance FromExp String where fromExp = toExp . mkName
instance FromPat String where fromPat = toPat . mkName
instance FromType String where fromType = toType . mkName
instance FromBody String where fromBody = toBody . mkName
instance FromStmt String where fromStmt = toStmt . mkName
instance FromTyVarBndr String where fromTyVarBndr = toTyVarBndr . mkName
instance FromBody Exp where fromBody = normalB . return
instance FromBody Exp where fromBody = normalB
--TODO: good idea?
instance FromBody [ (Guard, Exp)] where fromBody = guardedB . map return
instance FromBody [ (Guard, Exp)] where fromBody = guardedB
instance FromBody [(Guard, Expeval)] where fromBody = toBody . map (\(g, e) -> (,) <$> g <*> e)
instance FromGuard Exp where fromGuard = normalG . return
instance FromGuard Exp where fromGuard = normalG
instance FromGuard Stmt where fromGuard = patG . (:[]) . return
instance FromGuard Stmt where fromGuard = patG . (:[])
instance FromGuard [Stmt ] where fromGuard = patG . map return
instance FromGuard [Stmt] where fromGuard = patG
instance FromStmt Exp where fromStmt = noBindS . return
instance FromStmt Exp where fromStmt = noBindS
-}
--TODO: good ideas?
--instance FromTyVarBndr (Name, Kind) where fromTyVarBndr = uncurry KindedTV
-- instance ToPred (Name, [Type])
-- instance ToPred (Type, Type)
--instance (FromPat p, FromBody b, FromDec d) => FromMatch (p, b, [d]) where toMatch (p, b, ds) = match (toPat p) (toBody b) (map toDec ds)
--instance (FromPat p, FromBody b) => FromMatch (p, b ) where toMatch (p, b ) = match (toPat p) (toBody b) [] | mgsloan/quasi-extras | src/Language/Quasi/Convenience.hs | bsd-3-clause | 5,848 | 0 | 8 | 1,562 | 1,192 | 647 | 545 | 64 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.