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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module BuiltInFunctions where
myOr :: [Bool] -> Bool
myOr = foldr (||) False
myAny :: (a -> Bool) -> [a] -> Bool
myAny f list = myOr $ map f list
myElem :: Eq a => a -> [a] -> Bool
-- myElem item = myAny (== item)
myElem item list = foldr (||) False $ map (== item) list
myReverse :: [a] -> [a]
myReverse list = foldl (flip (:)) [] list
myMap :: (a -> b) -> [a] -> [b]
myMap f list = foldr ((:) . f) [] list
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f list = foldr (\item acc -> if (f item) then item : acc else acc) [] list
| mikegehard/haskellBookExercises | chapter10/BuiltInFunctions.hs | mit | 588 | 0 | 10 | 178 | 291 | 160 | 131 | 13 | 2 |
module Handler.GamesJsonSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getGamesJsonR" $ do
error "Spec not implemented: getGamesJsonR"
| jabaraster/minibas-web | test/Handler/GamesJsonSpec.hs | mit | 183 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
import Prelude hiding (lookup)
import Control.Monad.ST
import Data.HashTable.ST.Basic
-- Hashtable parameterized by ST "thread"
type HT s = HashTable s String String
example1 :: ST s (HT s)
example1 = do
ht <- new
insert ht "key" "value1"
return ht
example2 :: HT s -> ST s (Maybe String)
example2 ht = do
val <- lookup ht "key"
return val
example3 :: Maybe String
example3 = runST (example1 >>= example2)
| riwsky/wiwinwlh | src/hashtables.hs | mit | 421 | 0 | 8 | 85 | 154 | 78 | 76 | 15 | 1 |
module Maskell.Stats where
import Control.Monad
import Data.List
import Data.Maybe
test_mcmath = do
putStrLn "hello from Mcmath"
{-|
The `prank' function calculates percentile ranks of a list of floats.
prank [23.0, 20.0, 20.0, 57.0, 46.0]
-}
prank :: [Float] -> [Float]
prank arr =
map score arr
where
len p v = fromIntegral $ length $ filter (p v) arr
n = fromIntegral $ length arr
score v = ((len (>) v) + 0.5 * (len (==) v))/n
data1 = [23.0, 20.0, 20.0, 57.0, 46.0]
testPrank = prank data1
prankM :: [Maybe Float] -> [Maybe Float]
prankM arrM =
rebuild [] pranks arrM
where
pranks = prank $ catMaybes arrM
rebuild acc _ [] = acc
rebuild acc (p:ps) (m:ms) =
if isJust m
then rebuild (acc ++ [Just p]) ps ms
else rebuild (acc ++ [Nothing]) (p:ps) ms
testPrankM = prankM [Just 23.0, Just 20.0, Just 20.0, Nothing, Just 57.0, Just 46.0]
-- | on a sorted list
median' xs | null xs = Nothing
| odd len = Just $ xs !! mid
| even len = Just $ meanMedian
where len = length xs
mid = len `div` 2
meanMedian = (xs !! mid + xs !! (mid-1)) / 2
median' :: Fractional a => [a] -> Maybe a
-- | on an unsorted list
median xs = median' $ sort xs
mmedian xs = median $ catMaybes xs
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs
mmean xs = mean $ catMaybes xs
| blippy/maskell | src/Maskell/Stats.hs | mit | 1,454 | 0 | 12 | 421 | 589 | 306 | 283 | 37 | 3 |
module Nameless.Conversion where
import Named.Data
import Nameless.Data
import Data.List
type NamingContext = [Name] -- Naming context for DeBrujin, head = 0
getFree :: Expression -> NamingContext
getFree (Func b ex) = filter (b /=) (getFree ex)
getFree (Call e1 e2) = union (getFree e1) (getFree e2)
getFree (Var x) = [x]
toNameless :: NamingContext -> Expression -> NamelessExp
toNameless ctx (Var x) = case elemIndex x ctx of
Just i -> NlVar i
Nothing -> NlVar (-1) -- Dodgyyyyy!
toNameless ctx (Call e1 e2) = NlCall (toNameless ctx e1) (toNameless ctx e2)
toNameless ctx (Func n e) = NlFunc (toNameless (n : ctx) e)
| mcapodici/haskelllearn | firstlang/simple/src/Nameless/Conversion.hs | mit | 632 | 0 | 10 | 116 | 261 | 135 | 126 | 15 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK prune #-}
module System.Console.Docopt.QQ
(
-- * QuasiQuoter usage parsers
docopt
, docoptFile
) where
import qualified Data.Map as M
import System.Console.Docopt.Types
import System.Console.Docopt.QQ.Instances ()
import System.Console.Docopt.ApplicativeParsec
import System.Console.Docopt.UsageParse
import Language.Haskell.TH
import Language.Haskell.TH.Quote
parseFmt :: FilePath -> String -> Either ParseError OptFormat
parseFmt = runParser pDocopt M.empty
docoptExp :: String -> Q Exp
docoptExp rawUsg = do
let usg = trimEmptyLines rawUsg
let mkDocopt fmt = Docopt { usage = usg, optFormat = fmt }
loc <- loc_filename <$> location
case mkDocopt <$> parseFmt loc usg of
Left err -> fail $ show err
Right parser -> [| parser |]
-- | A 'QuasiQuoter' which parses a usage string and returns a
-- 'Docopt'.
--
-- Example usage:
--
-- @
-- patterns :: Docopt
-- patterns = [docopt|
-- docopt-sample version 0.1.0
--
-- Usage:
-- docopt-sample cat \<file\>
-- docopt-sample echo [--caps] \<string\>
--
-- Options:
-- -c, --caps Caps-lock the echoed argument
-- |]
-- @
--
-- For help with the docopt usage format, see
-- <https://github.com/docopt/docopt.hs/blob/master/README.md#help-text-format the readme on github>.
docopt :: QuasiQuoter
docopt = QuasiQuoter { quoteExp = docoptExp
, quoteDec = unsupported "Declaration"
, quotePat = unsupported "Pattern"
, quoteType = unsupported "Type"
}
where unsupported :: String -> String -> Q a
unsupported qqType _ = do
fail $ (qqType ++ " context unsupported")
-- | Same as 'docopt', but parses the given file instead of a literal
-- string.
--
-- Example:
--
-- @
-- patterns :: Docopt
-- patterns = [docoptFile|USAGE|]
-- @
--
-- where @USAGE@ is the name of a file which contains the usage
-- string (relative to the directory from which ghc is invoked).
docoptFile :: QuasiQuoter
docoptFile = quoteFile docopt
| docopt/docopt.hs | System/Console/Docopt/QQ.hs | mit | 2,082 | 0 | 11 | 463 | 348 | 209 | 139 | 33 | 2 |
{-# LANGUAGE RankNTypes, OverloadedStrings, DeriveDataTypeable,
ForeignFunctionInterface, JavaScriptFFI, EmptyDataDecls,
TypeFamilies, DataKinds, ScopedTypeVariables,
FlexibleContexts, FlexibleInstances, TypeSynonymInstances,
LambdaCase, MultiParamTypeClasses, DeriveGeneric #-}
module JavaScript.Web.XMLHttpRequest ( xhr
, xhrByteString
, xhrText
, xhrString
, Method(..)
, Request(..)
, RequestData(..)
, Response(..)
, ResponseType(..)
, FormDataVal(..)
, XHRError(..)
) where
import Control.Applicative
import Control.Exception
import Control.Monad
import GHCJS.Types
import GHCJS.Prim
import GHCJS.Marshal
import GHCJS.Marshal.Pure
import GHCJS.Internal.Types
import qualified GHCJS.Buffer as Buffer
import GHC.Generics
import Data.ByteString
import Data.Data
import Data.JSString
import Data.JSString.Internal.Type ( JSString(..) )
import Data.Typeable
import Data.Proxy
import Data.Text (Text)
import Data.JSString.Text (textFromJSString)
import qualified Data.JSString as JSS
import JavaScript.JSON.Types.Internal ( SomeValue(..) )
import JavaScript.TypedArray.Internal.Types ( SomeTypedArray(..) )
import JavaScript.TypedArray.ArrayBuffer ( ArrayBuffer(..) )
import JavaScript.TypedArray.ArrayBuffer.Internal ( SomeArrayBuffer(..) )
import JavaScript.Web.Blob
import JavaScript.Web.Blob.Internal
import JavaScript.Web.File
data Method = GET | POST | PUT | DELETE
deriving (Show, Eq, Ord, Enum)
data XHRError = XHRError String
| XHRAborted
deriving (Generic, Data, Typeable, Show, Eq)
instance Exception XHRError
methodJSString :: Method -> JSString
methodJSString GET = "GET"
methodJSString POST = "POST"
methodJSString PUT = "PUT"
methodJSString DELETE = "DELETE"
type Header = (JSString, JSString)
data FormDataVal = StringVal JSString
| BlobVal Blob (Maybe JSString)
| FileVal File (Maybe JSString)
deriving (Typeable)
data Request = Request { reqMethod :: Method
, reqURI :: JSString
, reqLogin :: Maybe (JSString, JSString)
, reqHeaders :: [Header]
, reqWithCredentials :: Bool
, reqData :: RequestData
}
deriving (Typeable)
data RequestData = NoData
| StringData JSString
| TypedArrayData (forall e. SomeTypedArray e Immutable)
| FormData [(JSString, FormDataVal)]
deriving (Typeable)
data Response a = Response { contents :: Maybe a
, status :: Int
, getAllResponseHeaders :: IO JSString
, getResponseHeader :: JSString -> IO (Maybe JSString)
}
instance Functor Response where fmap f r = r { contents = fmap f (contents r) }
class ResponseType a where
getResponseTypeString :: Proxy a -> JSString
wrapResponseType :: JSVal -> a
instance ResponseType ArrayBuffer where
getResponseTypeString _ = "arraybuffer"
wrapResponseType = SomeArrayBuffer
instance m ~ Immutable => ResponseType JSString where
getResponseTypeString _ = "text"
wrapResponseType = JSString
instance ResponseType Blob where
getResponseTypeString _ = "blob"
wrapResponseType = SomeBlob
instance m ~ Immutable => ResponseType (SomeValue m) where
getResponseTypeString _ = "json"
wrapResponseType = SomeValue
newtype JSFormData = JSFormData JSVal deriving (Typeable)
newtype XHR = XHR JSVal deriving (Typeable)
-- -----------------------------------------------------------------------------
-- main entry point
xhr :: forall a. ResponseType a => Request -> IO (Response a)
xhr req = js_createXHR >>= \x ->
let doRequest = do
case reqLogin req of
Nothing ->
js_open2 (methodJSString (reqMethod req)) (reqURI req) x
Just (user, pass) ->
js_open4 (methodJSString (reqMethod req)) (reqURI req) user pass x
js_setResponseType
(getResponseTypeString (Proxy :: Proxy a)) x
forM_ (reqHeaders req) (\(n,v) -> js_setRequestHeader n v x)
r <- case reqData req of
NoData ->
js_send0 x
StringData str ->
js_send1 (pToJSVal str) x
TypedArrayData (SomeTypedArray t) ->
js_send1 t x
FormData xs -> do
fd@(JSFormData fd') <- js_createFormData
forM_ xs $ \(name, val) -> case val of
StringVal str ->
js_appendFormData2 name (pToJSVal str) fd
BlobVal (SomeBlob b) mbFile ->
appendFormData name b mbFile fd
FileVal (SomeBlob b) mbFile ->
appendFormData name b mbFile fd
js_send1 fd' x
case r of
0 -> do
status <- js_getStatus x
r <- do
hr <- js_hasResponse x
if hr then Just . wrapResponseType <$> js_getResponse x
else pure Nothing
return $ Response r
status
(js_getAllResponseHeaders x)
(\h -> getResponseHeader' h x)
1 -> throwIO XHRAborted
2 -> throwIO (XHRError "some error")
in doRequest `onException` js_abort x
appendFormData :: JSString -> JSVal
-> Maybe JSString -> JSFormData -> IO ()
appendFormData name val Nothing fd =
js_appendFormData2 name val fd
appendFormData name val (Just fileName) fd =
js_appendFormData3 name val fileName fd
getResponseHeader' :: JSString -> XHR -> IO (Maybe JSString)
getResponseHeader' name x = do
h <- js_getResponseHeader name x
return $ if isNull h then Nothing else Just (JSString h)
-- -----------------------------------------------------------------------------
-- utilities
xhrString :: Request -> IO (Response String)
xhrString = fmap (fmap JSS.unpack) . xhr
xhrText :: Request -> IO (Response Text)
xhrText = fmap (fmap textFromJSString) . xhr
xhrByteString :: Request -> IO (Response ByteString)
xhrByteString = fmap
(fmap (Buffer.toByteString 0 Nothing . Buffer.createFromArrayBuffer)) . xhr
-- -----------------------------------------------------------------------------
foreign import javascript unsafe
"new XMLHttpRequest()"
js_createXHR :: IO XHR
foreign import javascript unsafe
"$2.responseType = $1;"
js_setResponseType :: JSString -> XHR -> IO ()
foreign import javascript unsafe
"$1.abort();"
js_abort :: XHR -> IO ()
foreign import javascript unsafe
"$3.setRequestHeader($1,$2);"
js_setRequestHeader :: JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"$3.open($1,$2)"
js_open2 :: JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"$5.open($1,$2,true,$4,$5);"
js_open4 :: JSString -> JSString -> JSString -> JSString -> XHR -> IO ()
foreign import javascript unsafe
"new FormData()"
js_createFormData :: IO JSFormData
foreign import javascript unsafe
"$3.append($1,$2)"
js_appendFormData2 :: JSString -> JSVal -> JSFormData -> IO ()
foreign import javascript unsafe
"$4.append($1,$2,$3)"
js_appendFormData3 :: JSString -> JSVal -> JSString -> JSFormData -> IO ()
foreign import javascript unsafe
"$1.status"
js_getStatus :: XHR -> IO Int
foreign import javascript unsafe
"$1.response"
js_getResponse :: XHR -> IO JSVal
foreign import javascript unsafe
"$1.response ? true : false"
js_hasResponse :: XHR -> IO Bool
foreign import javascript unsafe
"$1.getAllResponseHeaders()"
js_getAllResponseHeaders :: XHR -> IO JSString
foreign import javascript unsafe
"$2.getResponseHeader($1)"
js_getResponseHeader :: JSString -> XHR -> IO JSVal
-- -----------------------------------------------------------------------------
foreign import javascript interruptible
"h$sendXHR($1, null, $c);"
js_send0 :: XHR -> IO Int
foreign import javascript interruptible
"h$sendXHR($2, $1, $c);"
js_send1 :: JSVal -> XHR -> IO Int
| NewByteOrder/ghcjs-base | JavaScript/Web/XMLHttpRequest.hs | mit | 8,721 | 48 | 27 | 2,651 | 2,054 | 1,090 | 964 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Domain.StatText (wordCount) where
import qualified Data.Text.Lazy as T
import Data.Function(on)
import Data.List(sortBy)
import Data.Map.Lazy (Map, empty, insertWith, assocs)
import Debug.Trace
wordCount :: T.Text -> [(T.Text, Integer)]
wordCount = count . filter specialWord . filter (\w -> T.length w > 3) . T.split wordSeparator . T.toCaseFold
where
wordSeparator :: Char -> Bool
wordSeparator = flip elem ".,;`()-_=></\"\\#%' \n\r\t" -- Todo use regexp
specialWord :: T.Text -> Bool
specialWord = not . flip elem ["the", "be", "to", "of", "and", "a", "in", "that", "have", "I", "it", "for", "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "we", "say", "her", "she", "or", "an", "will", "my", "one", "all", "would", "there", "their", "what", "so", "up", "out", "if", "about", "who", "get", "which", "go", "me", "when", "make", "can", "like", "time", "no", "just", "him", "know", "take", "people", "into", "year", "your", "good", "some", "could", "them", "see", "other", "than", "then", "now", "look", "only", "come", "its", "over", "think", "also", "back", "us", "after", "use", "two", "how", "our", "work", "first", "well", "way", "even", "new", "want", "because", "any", "these", "give", "day", "most"]
count :: Ord a => [a] -> [(a, Integer)]
count = sortBy (flip $ on compare snd) . assocs . foldr f empty
where f a = insertWith (+) a 1 | johangirod/statext | src/server/Domain/StatText.hs | mit | 1,445 | 0 | 13 | 220 | 566 | 348 | 218 | 16 | 1 |
module Main where
import TralaParser
import TralaLexer
import TralaLexerInternal
import Conduit
import System.Environment
main :: IO ()
main = do
filename <- head <$> getArgs
runResult <- runResourceT $ runLexerConduitFromStart $ alexInputsFromFile filename .| tralaTokens .| mapM_C (liftIO . putStrLn . show)
either (putStrLn . show) (return) runResult
| tilgalas/trala-lala | app/Main.hs | mit | 365 | 0 | 12 | 59 | 107 | 56 | 51 | 11 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module ZipperGalaxy
where
import Control.Monad
import qualified Data.Map as M
import Data.Maybe
import Libaddutil.Named
import Galaxy
import Utils
import qualified Data.Edison.Assoc.StandardMap as E
type GalaxyZipper a = (Galaxy a, Maybe (StarSystem a, Maybe (Star a, [Planet a])))
galaxyZipper :: Galaxy a -> GalaxyZipper a
galaxyZipper g = (g, Nothing)
starsystemZipper :: Galaxy a -> StarSystem a -> GalaxyZipper a
starsystemZipper g s = (g, Just (s, Nothing))
starZipper :: GalaxyZipper a -> Star a -> GalaxyZipper a
starZipper (g, Just (ss, _)) s = (g, Just (ss, Just (s, [])))
starZipper _ _ = error "Invalid zipper"
expandStarsystemZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandStarsystemZipper (g, Just (ss, _)) = map (\s -> (g, Just (ss, Just (s, [])))) (M.elems (stars ss))
expandStarsystemZipper _ = []
expandStarZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandStarZipper (g, Just (ss, Just (s, _))) = map (\p -> (g, Just (ss, Just (s, [p])))) (M.elems (planets s))
expandStarZipper _ = []
expandPlanetZipper :: GalaxyZipper a -> [GalaxyZipper a]
expandPlanetZipper z@(g, Just (ss, Just (s, [p1]))) = z:map (\p2 -> (g, Just (ss, Just (s, p2:[p1])))) (M.elems (satellites p1))
expandPlanetZipper _ = []
addPlanetToZipper :: GalaxyZipper a -> Planet a -> GalaxyZipper a
addPlanetToZipper (g, Just (ss, Just (s, ps))) p = (g, Just (ss, Just (s, p:ps)))
addPlanetToZipper _ _ = error "Invalid zipper"
galaxyInZipper :: GalaxyZipper a -> Galaxy a
galaxyInZipper (g, _) = g
starsystemInZipper :: GalaxyZipper a -> Maybe (StarSystem a)
starsystemInZipper (_, Nothing) = Nothing
starsystemInZipper (_, Just (s, _)) = Just s
starInZipper :: GalaxyZipper a -> Maybe (Star a)
starInZipper (_, Nothing) = Nothing
starInZipper (_, Just (ss, Nothing)) = Nothing
starInZipper (_, Just (ss, Just (s, _))) = Just s
satelliteThreadInZipper :: GalaxyZipper a -> [Planet a]
satelliteThreadInZipper (_, Nothing) = []
satelliteThreadInZipper (_, Just (ss, Nothing)) = []
satelliteThreadInZipper (_, Just (ss, Just (s, sats))) = sats
satelliteInZipper :: GalaxyZipper a -> Maybe (Planet a)
satelliteInZipper z = safeHead (satelliteThreadInZipper z)
tryDown :: Name -> GalaxyZipper a -> Maybe (GalaxyZipper a)
tryDown i (g, Nothing) =
let mss = M.lookup i (starsystems g)
in case mss of
Nothing -> Nothing
Just x -> Just $ (g, Just (x, Nothing))
tryDown i (g, Just (ss, Nothing)) =
let ms = M.lookup i (stars ss)
in case ms of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (x, []))))
tryDown i (g, Just (ss, Just (s, []))) =
let msat = M.lookup i (planets s)
in case msat of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (s, [x]))))
tryDown i (g, Just (ss, Just (s, allsats@(sat:sats)))) =
let msat = M.lookup i (satellites sat)
in case msat of
Nothing -> Nothing
Just x -> Just $ (g, Just (ss, (Just (s, x:allsats))))
tryDownNum :: Int -> GalaxyZipper a -> Maybe (GalaxyZipper a)
tryDownNum i z@(g, Nothing) =
case safeIndex (E.keys $ starsystems g) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Nothing)) =
case safeIndex (E.keys $ stars ss) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Just (s, []))) =
case safeIndex (E.keys $ planets s) i of
Nothing -> Nothing
Just x -> tryDown x z
tryDownNum i z@(g, Just (ss, Just (s, (p:ps)))) =
case safeIndex (E.keys $ satellites p) i of
Nothing -> Nothing
Just x -> tryDown x z
up :: GalaxyZipper a -> GalaxyZipper a
up z@(g, Nothing) = z
up (g, Just (ss, Nothing)) = (g, Nothing)
up (g, Just (ss, Just (s, []))) = (g, Just (ss, Nothing))
up (g, Just (ss, Just (s, (sat:sats)))) = (g, Just (ss, Just (s, sats)))
type GalaxyLocation = [Name]
findLocation :: GalaxyLocation -> Galaxy a -> Maybe (Planet a)
findLocation l g = do
let z = galaxyZipper g
nz <- foldM (flip tryDown) z l
satelliteInZipper nz
zipperToNames :: GalaxyZipper a -> [String]
zipperToNames z =
let g = galaxyInZipper z
ss = starsystemInZipper z
s = starInZipper z
ps = reverse $ satelliteThreadInZipper z
ns = [name g, getName ss, getName s] ++ map name ps
getName :: (Named a) => Maybe a -> String
getName m = case m of
Nothing -> ""
Just x -> name x
in filter (not . null) ns
| anttisalonen/starrover | src/ZipperGalaxy.hs | mit | 4,557 | 0 | 17 | 1,080 | 2,180 | 1,152 | 1,028 | 105 | 5 |
-- | This transforms the output from ReadRawSpecFile for consumption into the
-- generator.
module Gen.Specifications
( CloudFormationSpec (..)
, specFromRaw
, PropertyType (..)
, Property (..)
, SpecType (..)
, subPropertyTypeNames
, customTypeNames
, AtomicType (..)
, ResourceType (..)
) where
import Control.Lens
import Data.List (sortOn)
import Data.Maybe (catMaybes)
import Data.Map (Map, toList)
import Data.Text
import GHC.Generics hiding (to)
import Gen.ReadRawSpecFile
data CloudFormationSpec
= CloudFormationSpec
{ cloudFormationSpecPropertyTypes :: [PropertyType]
, clousFormationSpecResourceSpecificationVersion :: Text
, cloudFormationSpecResourceTypes :: [ResourceType]
}
deriving (Show, Eq)
specFromRaw :: RawCloudFormationSpec -> CloudFormationSpec
specFromRaw spec = CloudFormationSpec props version resources
where
(RawCloudFormationSpec rawProps version rawResources) = fixSpecBugs spec
props = uncurry propertyTypeFromRaw <$> sortOn fst (toList rawProps)
resources = uncurry resourceTypeFromRaw <$> sortOn fst (toList rawResources)
-- | There are a few missing properties and resources in the official spec
-- document, as well as inconsistent or incorrect naming. There is an open
-- support ticket with AWS support to fix these things, but for now we are
-- patching things up manually.
fixSpecBugs :: RawCloudFormationSpec -> RawCloudFormationSpec
fixSpecBugs spec =
spec
-- There are a few naming conflicts with security group types. For example,
-- there is a resource named AWS::RDS::DBSecurityGroupIngress, and a property
-- named AWS::RDS::DBSecurityGroup.Ingress. There is a corresponding fix in
-- the function to render the full type name for
-- AWS::RDS::DBSecurityGroup.Ingress.
& propertyTypesLens
. at "AWS::RDS::DBSecurityGroup.IngressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::RDS::DBSecurityGroup.Ingress")
& propertyTypesLens
. at "AWS::RDS::DBSecurityGroup.Ingress"
.~ Nothing
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.IngressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::EC2::SecurityGroup.Ingress")
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.Ingress"
.~ Nothing
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.EgressProperty"
.~ (spec ^. propertyTypesLens . at "AWS::EC2::SecurityGroup.Egress")
& propertyTypesLens
. at "AWS::EC2::SecurityGroup.Egress"
.~ Nothing
-- Rename AWS::IoT::TopicRule.DynamoDBv2Action to capitalize the "v" so it is
-- different from AWS::IoT::TopicRule.DynamoDBAction
& propertyTypesLens
. at "AWS::IoT::TopicRule.DynamoDBV2Action"
.~ (spec ^. propertyTypesLens . at "AWS::IoT::TopicRule.DynamoDBv2Action")
& propertyTypesLens
. at "AWS::IoT::TopicRule.DynamoDBv2Action"
.~ Nothing
-- AWS::ECS::TaskDefinition.ContainerDefinition has two properties that are
-- required, but the doc says they aren't.
& propertyTypesLens
. ix "AWS::ECS::TaskDefinition.ContainerDefinition"
. propertyPropsLens
. at "Image"
%~ (\(Just rawProp) -> Just rawProp { rawPropertyRequired = True })
& propertyTypesLens
. ix "AWS::ECS::TaskDefinition.ContainerDefinition"
. propertyPropsLens
. at "Name"
%~ (\(Just rawProp) -> Just rawProp { rawPropertyRequired = True })
where
propertyTypesLens :: Lens' RawCloudFormationSpec (Map Text RawPropertyType)
propertyTypesLens = lens rawCloudFormationSpecPropertyTypes (\s a -> s { rawCloudFormationSpecPropertyTypes = a })
propertyPropsLens :: Lens' RawPropertyType (Map Text RawProperty)
propertyPropsLens = lens rawPropertyTypeProperties (\s a -> s { rawPropertyTypeProperties = a })
-- resourceTypesLens :: Lens' RawCloudFormationSpec (Map Text RawResourceType)
-- resourceTypesLens = lens rawCloudFormationSpecResourceTypes (\s a -> s { rawCloudFormationSpecResourceTypes = a })
-- resourcePropsLens :: Lens' RawResourceType (Map Text RawProperty)
-- resourcePropsLens = lens rawResourceTypeProperties (\s a -> s { rawResourceTypeProperties = a })
data PropertyType
= PropertyType
{ propertyTypeName :: Text
, propertyTypeDocumentation :: Text
, propertyTypeProperties :: [Property]
}
deriving (Show, Eq)
propertyTypeFromRaw :: Text -> RawPropertyType -> PropertyType
propertyTypeFromRaw fullName (RawPropertyType doc props) =
PropertyType fullName doc (uncurry (propertyFromRaw fullName) <$> sortOn fst (toList props))
data Property
= Property
{ propertyName :: Text
, propertyDocumentation :: Text
--, propertyDuplicatesAllowed :: Maybe Bool -- Don't care about this
, propertySpecType :: SpecType
, propertyRequired :: Bool
--, propertyUpdateType :: Maybe Text -- Don't care about this
}
deriving (Show, Eq)
propertyFromRaw :: Text -> Text -> RawProperty -> Property
propertyFromRaw fullTypeName name (RawProperty doc _ itemType primItemType primType required type' _) =
Property name doc (rawToSpecType fullTypeName name primType type' primItemType itemType) required
data SpecType
= AtomicType AtomicType
| ListType AtomicType
| MapType AtomicType
deriving (Show, Eq)
rawToSpecType :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> SpecType
-- Overrides for our custom types
rawToSpecType "AWS::ApiGateway::Authorizer" "Type" _ _ _ _ = AtomicType $ CustomType "AuthorizerType"
rawToSpecType "AWS::ApiGateway::Method" "AuthorizationType" _ _ _ _ = AtomicType $ CustomType "AuthorizationType"
rawToSpecType "AWS::ApiGateway::Method.Integration" "IntegrationHttpMethod" _ _ _ _ = AtomicType $ CustomType "HttpMethod"
rawToSpecType "AWS::ApiGateway::Method.Integration" "PassthroughBehavior" _ _ _ _ = AtomicType $ CustomType "PassthroughBehavior"
rawToSpecType "AWS::ApiGateway::Method.Integration" "Type" _ _ _ _ = AtomicType $ CustomType "ApiBackendType"
rawToSpecType "AWS::ApiGateway::UsagePlan.QuotaSettings" "Period" _ _ _ _ = AtomicType $ CustomType "Period"
rawToSpecType "AWS::DynamoDB::Table.AttributeDefinition" "AttributeType" _ _ _ _ = AtomicType $ CustomType "AttributeType"
rawToSpecType "AWS::DynamoDB::Table.KeySchema" "KeyType" _ _ _ _ = AtomicType $ CustomType "KeyType"
rawToSpecType "AWS::DynamoDB::Table.Projection" "ProjectionType" _ _ _ _ = AtomicType $ CustomType "ProjectionType"
rawToSpecType "AWS::DynamoDB::Table.StreamSpecification" "StreamViewType" _ _ _ _ = AtomicType $ CustomType "StreamViewType"
rawToSpecType "AWS::Events::Rule" "State" _ _ _ _ = AtomicType $ CustomType "EnabledState"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" "CompressionFormat" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseS3CompressionFormat"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration" "S3BackupMode" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseElasticsearchS3BackupMode"
rawToSpecType "AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration" "NoEncryptionConfig" _ _ _ _ = AtomicType $ CustomType "KinesisFirehoseNoEncryptionConfig"
rawToSpecType "AWS::Lambda::Function" "Runtime" _ _ _ _ = AtomicType $ CustomType "Runtime"
rawToSpecType "AWS::S3::Bucket" "AccessControl" _ _ _ _ = AtomicType $ CustomType "CannedACL"
rawToSpecType "AWS::SNS::Subscription" "Protocol" _ _ _ _ = AtomicType $ CustomType "SNSProtocol"
rawToSpecType "AWS::SNS::Topic.Subscription" "Protocol" _ _ _ _ = AtomicType $ CustomType "SNSProtocol"
rawToSpecType _ "HttpMethod" _ _ _ _ = AtomicType $ CustomType "HttpMethod"
rawToSpecType _ "LoggingLevel" _ _ _ _ = AtomicType $ CustomType "LoggingLevel"
-- Default
rawToSpecType _ _ primType type' primItemType itemType = rawToSpecType' primType type' primItemType itemType
rawToSpecType'
:: Maybe Text -- PrimitiveType
-> Maybe Text -- Type
-> Maybe Text -- PrimitiveItemType
-> Maybe Text -- ItemType
-> SpecType
-- Just primitive type, nothing else
rawToSpecType' (Just prim) Nothing Nothing Nothing = AtomicType $ textToPrimitiveType prim
-- A list of primitives
rawToSpecType' Nothing (Just "List") (Just prim) Nothing = ListType $ textToPrimitiveType prim
-- A list of non-primitives
rawToSpecType' Nothing (Just "List") Nothing (Just item) = ListType $ SubPropertyType item
-- A map of primitives
rawToSpecType' Nothing (Just "Map") (Just prim) Nothing = MapType $ textToPrimitiveType prim
-- A map of non-primitives
rawToSpecType' Nothing (Just "Map") Nothing (Just item) = MapType $ SubPropertyType item
-- A non-primitive type
rawToSpecType' Nothing (Just prop) Nothing Nothing = AtomicType $ SubPropertyType prop
rawToSpecType' prim type' primItem item = error $ "Unknown raw type: " ++ show (prim, type', primItem, item)
data AtomicType
= StringPrimitive
| IntegerPrimitive
| DoublePrimitive
| BoolPrimitive
| JsonPrimitive
| SubPropertyType Text
| CustomType Text
deriving (Show, Eq)
textToPrimitiveType :: Text -> AtomicType
textToPrimitiveType "String" = StringPrimitive
textToPrimitiveType "Long" = IntegerPrimitive
textToPrimitiveType "Integer" = IntegerPrimitive
textToPrimitiveType "Double" = DoublePrimitive
textToPrimitiveType "Boolean" = BoolPrimitive
textToPrimitiveType "Timestamp" = StringPrimitive
textToPrimitiveType "Json" = JsonPrimitive
textToPrimitiveType t = error $ "Unknown primitive type: " ++ unpack t
subPropertyTypeName :: SpecType -> Maybe Text
subPropertyTypeName (AtomicType (SubPropertyType name)) = Just name
subPropertyTypeName (ListType (SubPropertyType name)) = Just name
subPropertyTypeName (MapType (SubPropertyType name)) = Just name
subPropertyTypeName _ = Nothing
customTypeName :: SpecType -> Maybe Text
customTypeName (AtomicType (CustomType name)) = Just name
customTypeName (ListType (CustomType name)) = Just name
customTypeName (MapType (CustomType name)) = Just name
customTypeName _ = Nothing
subPropertyTypeNames :: [Property] -> [Text]
subPropertyTypeNames = catMaybes . fmap (subPropertyTypeName . propertySpecType)
customTypeNames :: [Property] -> [Text]
customTypeNames = catMaybes . fmap (customTypeName . propertySpecType)
data ResourceType
= ResourceType
{ resourceTypeFullName :: Text
--, resourceTypeAttributes :: [ResourceAttribute] -- Don't care about this yet, could be useful
, resourceTypeDocumentation :: Text
, resourceTypeProperties :: [Property]
}
deriving (Show, Eq, Generic)
resourceTypeFromRaw :: Text -> RawResourceType -> ResourceType
resourceTypeFromRaw fullName (RawResourceType _ doc props) =
ResourceType fullName doc (uncurry (propertyFromRaw fullName) <$> sortOn fst (toList props))
| frontrowed/stratosphere | gen/src/Gen/Specifications.hs | mit | 10,530 | 0 | 39 | 1,494 | 2,236 | 1,163 | 1,073 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
module DBacc where
-- try optimization: cut, accu
import Context
import System.Process (callCommand)
import Data.Char (isUpper)
------------------------------------------------------
-- Sample complex program: graph matching, query and transformation
------------------------------------------------------
-- graph database = set of edges/triples, see "db.png"
type Edge = (String,String,String)
type Graph = [Edge]
-- generate Graphviz view
view file db = writeFile (file++".dot") ("digraph G {\nnode[shape=plaintext]; edge[arrowhead=vee];\n"++(concat (map (\(a,b,c)-> (show a)++"->"++(show c)++"[label="++(show b)++"];\n") db))++"}")
display file db = do
view file db
callCommand ("dot -Tpng "++file++".dot -o "++file++".png")
-- matching
--isVariable p = isUpper (p!!0)
isVariable p = (p!!0)=='?'
--isVariable p = (p!!0)=='_'
match1 :: String -> String -> Context -> (Bool,Context)
match1 p v ctx =
if (isVariable p) then
if (has p ctx) then ((get p ctx)==v,ctx)
else (True,put p v ctx)
else (p==v,ctx)
match3 :: Edge -> Edge -> Context -> (Bool,Context)
match3 (p,q,r) (v,w,x) ctx =
let (r1,ctx1) = match1 p v ctx in
if r1 then
let (r2,ctx2) = match1 q w ctx1 in
if r2 then
match1 r x ctx2
else (False,ctx)
else (False,ctx)
--matchn :: Edge -> Graph -> Context -> [(Bool,Context)]
--matchn p vs ctx = filter fst (map (\v -> match3 p v ctx) vs)
--matchn p [] ctx = []
--matchn p (v:vs) ctx =
--let (r1,r2) = match3 p v ctx
--rs = matchn p vs ctx
--in if r1 then (r1,r2):rs else rs
matchn :: Edge -> [Edge] -> Context -> [Context]
matchn p vs ctx = matchnacc p vs ctx []
matchnacc p [] ctx acc = acc
matchnacc p (v:vs) ctx acc =
let (r1,r2) = match3 p v ctx
in if r1 then matchnacc p vs ctx $! (r2:acc) else matchnacc p vs ctx acc
--answer :: Graph -> Graph -> Context -> [(Bool,Context)]
--answer [] vs ctx = [(True,ctx)]
--answer (p:[]) vs ctx = matchn p vs ctx
--answer (p:ps) vs ctx = concat (map (answer ps vs) (matchn p vs ctx))
answer ps vs ctx = answerAcc ps vs ctx []
answerAcc (p:[]) vs ctx acc = matchn p vs ctx
answerAcc (p:ps) vs ctx acc = answerAcc ps vs ctx $! (uniMap' (matchn p vs) acc)
uniMap f [] = []
uniMap f (x:xs) = (f x)++(uniMap f xs)
uniMap' f xs = uniMapAcc f xs []
uniMapAcc f [] r = r
uniMapAcc f (x:xs) r = uniMapAcc f xs $! ((f x)++r)
| thiry/DComp | src/DBacc.hs | gpl-2.0 | 2,396 | 0 | 21 | 495 | 847 | 458 | 389 | 41 | 3 |
predecessor = predecessor
-- |comment 0
-- |comment 1
successor :: a
successor = successor
| evolutics/haskell-formatter | testsuite/resources/source/comments/depends_on_displacement/single_annotation/line_pair/before_before/Input.hs | gpl-3.0 | 91 | 0 | 4 | 15 | 18 | 11 | 7 | 3 | 1 |
module NaiveBayes.NaiveBayes where
import Data.List
import Data.Char
data Classifier = Classifier {
wordCategoryStore :: [(String,[(String,Int)])]
}
stopwords = ["a",
"about",
"above",
"after",
"again",
"against",
"all",
"am",
"an",
"and",
"any",
"are",
"arent",
"aren't",
"as",
"at",
"be",
"because",
"been",
"before",
"being",
"below",
"between",
"both",
"but",
"by",
"cant",
"can't",
"cannot",
"could",
"couldnt",
"couldn't",
"did",
"didnt",
"didn't",
"do",
"does",
"doesnt",
"doesn't",
"doing",
"dont",
"don't",
"down",
"during",
"each",
"few",
"for",
"from",
"further",
"had",
"hadnt",
"hadn't",
"has",
"hasnt",
"hasn't",
"have",
"havent",
"haven't",
"having",
"he",
"hed",
"he'd",
"he'll",
"hes",
"he's",
"her",
"here",
"heres",
"here's",
"hers",
"herself",
"him",
"himself",
"his",
"how",
"hows",
"how's",
"i",
"i'd",
"i'll",
"im",
"i'm",
"ive",
"i've",
"if",
"in",
"into",
"is",
"isnt",
"isn't",
"it",
"it's",
"its",
"itself",
"lets",
"let's",
"me",
"more",
"most",
"mustnt",
"mustn't",
"my",
"myself",
"no",
"nor",
"not",
"of",
"off",
"on",
"once",
"only",
"or",
"other",
"ought",
"our",
"ours ",
"ourselves",
"out",
"over",
"own",
"same",
"shant",
"shan't",
"she",
"she'd",
"she'll",
"shes",
"she's",
"should",
"shouldnt",
"shouldn't",
"so",
"some",
"such",
"than",
"that",
"thats",
"that's",
"the",
"their",
"theirs",
"them",
"themselves",
"then",
"there",
"theres",
"there's",
"these",
"they",
"theyd",
"they'd",
"theyll",
"they'll",
"theyre",
"they're",
"theyve",
"they've",
"this",
"those",
"through",
"to",
"too",
"under",
"until",
"up",
"very",
"was",
"wasnt",
"wasn't",
"we",
"we'd",
"we'll",
"we're",
"weve",
"we've",
"were",
"werent",
"weren't",
"what",
"whats",
"what's",
"when",
"whens",
"when's",
"where",
"wheres",
"where's",
"which",
"while",
"who",
"whos",
"who's",
"whom",
"why",
"whys",
"why's",
"with",
"wont",
"won't",
"would",
"wouldnt",
"wouldn't",
"you",
"youd",
"you'd",
"youll",
"you'll",
"youre",
"you're",
"youve",
"you've",
"your",
"yours",
"yourself",
"yourselves"]
--removeStopWords from doc
removeStopwords ::String-> [String]
removeStopwords doc = filter g $ words doc
where
g x = notElem x stopwords
--returns total number of words of the category
categoryCount :: [(String,[(String,Int)])] -> String -> Int
categoryCount ws category =
let
f (a,b) = a==category
l = filter f ws
g (p,q) =q
h = map g l
i = concat h
j = map snd i
in
sum j
--returns number of occurances of word in the category
wordCategoryCount :: [(String,[(String,Int)])] -> String -> String -> Int
wordCategoryCount ws category word = sum $ map f ws
where
f (x,y) = if (x==category) then (g y) else 0
g [] = 0
g ((a,b):xs) = if (a==word) then b else g xs
--trains the classifier by adding doc with respective category
train :: Classifier -> String -> String -> Classifier
train (Classifier ws) category doc = Classifier cs
where
cs= (category, pairs) : ws
pairs = map (\x-> (head x, length x)) $ group $ sort $ words doc
--total number of words in classifier
totalCount :: [(String,[(String,Int)])] -> Int
totalCount cs =
let
f (a,b)= b
g = map f cs
h = concat g
i (a,b) = b
j = map i h
in
sum j
--returns all categories
categories :: [(String,[(String,Int)])] -> [String]
categories cs = nub $ map f cs
where
f (a,b)=a
--return the probability of the word being in a particular category
probWordCategory :: [(String,[(String,Int)])] -> String -> String -> Double
probWordCategory cs category word =
let
allWords = fromIntegral $ categoryCount cs category
wordCount = fromIntegral $ wordCategoryCount cs category word
in
wordCount / allWords
--return the probability of categry
probCategory :: [(String,[(String,Int)])] -> String -> Double
probCategory cs category = (fromIntegral $ categoryCount cs category) / ( fromIntegral $ totalCount cs )
--probability of each cateogry
probAllCategories :: [(String,[(String,Int)])] -> [Double]
probAllCategories cs = map (probCategory cs) $ map fst cs
--probability of document to be in a catgory
probDocCategory :: [(String,[(String,Int)])] -> String -> String -> Double
probDocCategory cs doc category =probCategory cs category * ( foldl (*) 1.0 $ map (probWordCategory cs category) $ words doc )
--probability of document in all categories
probDocAllCategories :: [(String,[(String,Int)])] -> String -> [(String,Double)]
probDocAllCategories cs doc = map (\cat -> (cat,probDocCategory cs doc cat)) $ categories cs
--classify document
classify :: Classifier -> String -> (String,Double)
classify cls doc =
let
l = probDocAllCategories (wordCategoryStore cls ) doc
f (a,b) (p,q) = q `compare` b
h = sortBy f l
i = head h
in
i
| rahulaaj/ML-Library | src/NaiveBayes/NaiveBayes.hs | gpl-3.0 | 6,044 | 448 | 14 | 2,124 | 2,203 | 1,265 | 938 | -1 | -1 |
yes :: a -> Bool
yes _ = True | hmemcpy/milewski-ctfp-pdf | src/content/1.5/code/haskell/snippet03.hs | gpl-3.0 | 29 | 0 | 5 | 8 | 18 | 9 | 9 | 2 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
-- | This module is completely exposed by 'Network.Gopher'
module Network.Gopher.Log
( GopherLogStr ()
, makeSensitive
, hideSensitive
, GopherLogLevel (..)
, ToGopherLogStr (..)
, FromGopherLogStr (..)
) where
import Network.Gopher.Util (uEncode, uDecode)
import Data.ByteString.Builder (Builder ())
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Builder as BB
import qualified Data.Sequence as S
import Data.String (IsString (..))
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import System.Socket.Family.Inet6
-- | Indicates the log level of a 'GopherLogStr' to a
-- 'Network.Gopher.GopherLogHandler'. If you want to
-- filter by log level you can use either the 'Ord'
-- or 'Enum' instance of 'GopherLogLevel' as the following
-- holds:
--
-- @
-- 'GopherLogLevelError' < 'GopherLogLevelWarn' < 'GopherLogLevelInfo'
-- @
data GopherLogLevel
= GopherLogLevelError
| GopherLogLevelWarn
| GopherLogLevelInfo
deriving (Show, Eq, Ord, Enum)
-- | UTF-8 encoded string which may have parts of it marked as
-- sensitive (see 'makeSensitive'). Use its 'ToGopherLogStr',
-- 'Semigroup' and 'IsString' instances to construct
-- 'GopherLogStr's and 'FromGopherLogStr' to convert to the
-- commonly used Haskell string types.
newtype GopherLogStr
= GopherLogStr { unGopherLogStr :: S.Seq GopherLogStrChunk }
instance Show GopherLogStr where
show = show . (fromGopherLogStr :: GopherLogStr -> String)
instance Semigroup GopherLogStr where
GopherLogStr s1 <> GopherLogStr s2 = GopherLogStr (s1 <> s2)
instance Monoid GopherLogStr where
mempty = GopherLogStr mempty
instance IsString GopherLogStr where
fromString = toGopherLogStr
data GopherLogStrChunk
= GopherLogStrChunk
{ glscSensitive :: Bool
, glscBuilder :: Builder
}
-- | Mark a 'GopherLogStr' as sensitive. This is used by this
-- library mostly to mark IP addresses of connecting clients.
-- By using 'hideSensitive' on a 'GopherLogStr' sensitive
-- parts will be hidden from the string — even if the sensitive
-- string was concatenated to other strings.
makeSensitive :: GopherLogStr -> GopherLogStr
makeSensitive = GopherLogStr
. fmap (\c -> c { glscSensitive = True })
. unGopherLogStr
-- | Replaces all chunks of the 'GopherLogStr' that have been
-- marked as sensitive by 'makeSensitive' with @[redacted]@.
-- Note that the chunking is dependent on the way the string
-- was assembled by the user and the internal implementation
-- of 'GopherLogStr' which can lead to multiple consecutive
-- @[redacted]@ being returned unexpectedly. This may be
-- improved in the future.
hideSensitive :: GopherLogStr -> GopherLogStr
hideSensitive = GopherLogStr
. fmap (\c -> GopherLogStrChunk False $
if glscSensitive c
then BB.byteString "[redacted]"
else glscBuilder c)
. unGopherLogStr
-- | Convert 'GopherLogStr's to other string types. Since it is used
-- internally by 'GopherLogStr', it is best to use the 'Builder'
-- instance for performance if possible.
class FromGopherLogStr a where
fromGopherLogStr :: GopherLogStr -> a
instance FromGopherLogStr GopherLogStr where
fromGopherLogStr = id
instance FromGopherLogStr Builder where
fromGopherLogStr = foldMap glscBuilder . unGopherLogStr
instance FromGopherLogStr BL.ByteString where
fromGopherLogStr = BB.toLazyByteString . fromGopherLogStr
instance FromGopherLogStr B.ByteString where
fromGopherLogStr = BL.toStrict . fromGopherLogStr
instance FromGopherLogStr T.Text where
fromGopherLogStr = T.decodeUtf8 . fromGopherLogStr
instance FromGopherLogStr TL.Text where
fromGopherLogStr = TL.decodeUtf8 . fromGopherLogStr
instance FromGopherLogStr [Char] where
fromGopherLogStr = uDecode . fromGopherLogStr
-- | Convert something to a 'GopherLogStr'. In terms of
-- performance it is best to implement a 'Builder' for
-- the type you are trying to render to 'GopherLogStr'
-- and then reuse its 'ToGopherLogStr' instance.
class ToGopherLogStr a where
toGopherLogStr :: a -> GopherLogStr
instance ToGopherLogStr GopherLogStr where
toGopherLogStr = id
instance ToGopherLogStr Builder where
toGopherLogStr b = GopherLogStr
. S.singleton
$ GopherLogStrChunk
{ glscSensitive = False
, glscBuilder = b
}
instance ToGopherLogStr B.ByteString where
toGopherLogStr = toGopherLogStr . BB.byteString
instance ToGopherLogStr BL.ByteString where
toGopherLogStr = toGopherLogStr . BB.lazyByteString
instance ToGopherLogStr [Char] where
toGopherLogStr = toGopherLogStr . uEncode
instance ToGopherLogStr GopherLogLevel where
toGopherLogStr l =
case l of
GopherLogLevelInfo -> toGopherLogStr ("info" :: B.ByteString)
GopherLogLevelWarn -> toGopherLogStr ("warn" :: B.ByteString)
GopherLogLevelError -> toGopherLogStr ("error" :: B.ByteString)
instance ToGopherLogStr (SocketAddress Inet6) where
-- TODO shorten address if possible
toGopherLogStr (SocketAddressInet6 addr port _ _) =
let (b1, b2, b3, b4, b5, b6, b7, b8) = inet6AddressToTuple addr
in toGopherLogStr $
BB.charUtf8 '[' <>
BB.word16HexFixed b1 <> BB.charUtf8 ':' <>
BB.word16HexFixed b2 <> BB.charUtf8 ':' <>
BB.word16HexFixed b3 <> BB.charUtf8 ':' <>
BB.word16HexFixed b4 <> BB.charUtf8 ':' <>
BB.word16HexFixed b5 <> BB.charUtf8 ':' <>
BB.word16HexFixed b6 <> BB.charUtf8 ':' <>
BB.word16HexFixed b7 <> BB.charUtf8 ':' <>
BB.word16HexFixed b8 <> BB.charUtf8 ']' <>
BB.charUtf8 ':' <> BB.intDec (fromIntegral port)
| sternenseemann/spacecookie | src/Network/Gopher/Log.hs | gpl-3.0 | 5,825 | 0 | 28 | 1,053 | 1,069 | 600 | 469 | 106 | 2 |
{-# LANGUAGE NoImplicitPrelude, TemplateHaskell #-}
module Lamdu.Sugar.Names.NameGen
( NameGen, initial
, VarInfo(..), existingName, newName
) where
import Prelude.Compat
import Control.Arrow ((&&&))
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Monad.Trans.State (State, state)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
data VarInfo = Function | NormalVar
data NameGen g = NameGen
{ _ngUnusedNames :: [String]
, _ngUnusedFuncNames :: [String]
, _ngUsedNames :: Map g String
}
Lens.makeLenses ''NameGen
initial :: Ord g => NameGen g
initial =
NameGen indepNames indepFuncNames Map.empty
where
indepFuncNames = numberCycle ["f", "g", "h"]
indepNames = numberCycle ["x", "y", "z", "w", "u", "v"]
numberCycle s = (s ++) . concat . zipWith appendAll [0::Int ..] $ repeat s
appendAll num = map (++ show num)
existingName :: (Ord g, Show g) => g -> State (NameGen g) String
existingName g =
fromMaybe ("TodoError:" ++ show g) <$>
Lens.uses ngUsedNames (Map.lookup g)
newName :: Ord g => (String -> Bool) -> VarInfo -> g -> State (NameGen g) String
newName acceptName isFunc g =
do
name <- Lens.zoom names loop
ngUsedNames %= Map.insert g name
return name
where
loop =
do
name <- state (head &&& tail)
if acceptName name
then return name
else loop
names =
case isFunc of
NormalVar -> ngUnusedNames
Function -> ngUnusedFuncNames
| da-x/lamdu | Lamdu/Sugar/Names/NameGen.hs | gpl-3.0 | 1,712 | 0 | 12 | 523 | 519 | 284 | 235 | 45 | 3 |
module Main where
import Idme.Config (defaultConfig)
import Idme.Server (runServer)
-- | Startup as blocking process
main :: IO ()
main = runServer defaultConfig
| awagner83/IdMe | src/Idme.hs | gpl-3.0 | 165 | 0 | 6 | 26 | 43 | 25 | 18 | 5 | 1 |
module Language.Nautilus.Bytecode.Interpreter where
import Control.Applicative
import Control.Monad
import Data.Word
import Language.Nautilus.Bytecode.Abstract
import Language.Nautilus.Bytecode.FromNBC
import Language.Nautilus.Bytecode.Machine
fetch :: NBCI Instr
fetch = do
instr <- peekIP
moveIP 1
return instr
execute :: Instr -> NBCI ()
execute Nop = return ()
execute Halt = halt =<< fromNBC1 <$> popData 1
execute (Push x) = pushData x
execute (Peek ix) = peekData (fromIntegral ix) >>= pushData
execute (JumpRel condition offset) = do
doJump <- cond condition
when doJump $ moveIP offset
execute it = error $ "unimplemented: " ++ show it
cond :: Condition -> NBCI Bool
cond Always = return True
cond EqZ = do
[test] <- popData 1
return $ fromNBC test == (0 :: Integer)
cond it = error $ "unimplemented condition: " ++ show it
cycles :: NBCI ()
cycles = fetch >>= execute >> cycles
debugCycles :: NBCI ()
debugCycles = do
instr <- fetch
system $ print instr
execute instr
debugCycles
| Zankoku-Okuno/nautilus-bytecode | src/Language/Nautilus/Bytecode/Interpreter.hs | gpl-3.0 | 1,044 | 0 | 9 | 209 | 371 | 183 | 188 | 35 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import SequenceFormats.FreqSum (FreqSumHeader(..), FreqSumEntry(..), readFreqSumStdIn,
printFreqSumStdOut)
import Control.Error (runScript, tryAssert, scriptIO, Script, tryJust)
import Data.Monoid ((<>))
import Data.Text (pack)
import Data.Version (showVersion)
import qualified Options.Applicative as OP
import Pipes ((>->), runEffect)
import qualified Pipes.Prelude as P
import System.Random (randomIO)
import Paths_rarecoal_tools (version)
data MyOpts = MyOpts String Int
main :: IO ()
main = OP.execParser opts >>= runWithOptions
where
opts = OP.info (OP.helper <*> parser) (OP.progDesc ("downSampleFreqSum version " ++
showVersion version ++ ": A tool for downsampling a freqSum file. If \
\a column is -1, the downsampled column will also have -1. \
\Reads from stdin"))
parser :: OP.Parser MyOpts
parser = MyOpts <$> OP.strArgument (OP.metavar "<NAME>" <> OP.help "the name of the population \
\to sample from")
<*> OP.argument OP.auto (OP.metavar "<N_AFTER>" <>
OP.help "the new number of haplotypes to downsample to")
runWithOptions :: MyOpts -> IO ()
runWithOptions (MyOpts name nAfter) = runScript $ do
(FreqSumHeader names counts, entries) <- readFreqSumStdIn
index <- tryJust "did not find name" $ (pack name) `lookup` zip names [0..]
let nBefore = counts !! index
tryAssert "nBefore has to be >= nAfter" $ nBefore >= nAfter
let newEntries = entries >-> P.mapM (downSample index nBefore nAfter)
newCounts = take index counts ++ [nAfter] ++ drop (index + 1) counts
runEffect $ newEntries >-> printFreqSumStdOut (FreqSumHeader names newCounts)
downSample :: Int -> Int -> Int -> FreqSumEntry -> Script FreqSumEntry
downSample pos nBefore nAfter fs = do
tryAssert "position outside bounds" $ pos < length (fsCounts fs)
newFS <- case fsCounts fs !! pos of
Nothing -> return fs
Just c -> do
newK <- scriptIO $ sampleWithoutReplacement nBefore c nAfter
let newCounts = take pos (fsCounts fs) ++ [Just newK] ++ drop (pos + 1) (fsCounts fs)
return fs {fsCounts = newCounts}
return newFS
sampleWithoutReplacement :: Int -> Int -> Int -> IO Int
sampleWithoutReplacement n k howMany = go n k howMany 0
where
go _ _ 0 ret = return ret
go _ 0 _ ret = return ret
go n' k' howMany' ret = do
val <- bernoulli $ fromIntegral k' / fromIntegral n'
if val
then go (n' - 1) (k' - 1) (howMany' - 1) (ret + 1)
else go (n' - 1) k' (howMany' - 1) ret
bernoulli :: Double -> IO Bool
bernoulli p = (<p) <$> randomIO
| stschiff/rarecoal-tools | src-downSampleFreqSum/downSampleFreqSum.hs | gpl-3.0 | 2,708 | 0 | 20 | 660 | 875 | 448 | 427 | 51 | 4 |
import Test.Framework.Providers.API
import Test.Framework.Runners.Console
import qualified Math.Test as Math
tests :: [Test]
tests = [
testGroup "Math" Math.tests
]
main :: IO ()
main = defaultMain tests
| sykora/zeta | test/Test.hs | gpl-3.0 | 219 | 0 | 7 | 42 | 64 | 38 | 26 | 8 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Glacier.UploadArchive
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation adds an archive to a vault. This is a synchronous
-- operation, and for a successful upload, your data is durably persisted.
-- Amazon Glacier returns the archive ID in the 'x-amz-archive-id' header
-- of the response.
--
-- You must use the archive ID to access your data in Amazon Glacier. After
-- you upload an archive, you should save the archive ID returned so that
-- you can retrieve or delete the archive later. Besides saving the archive
-- ID, you can also index it and give it a friendly name to allow for
-- better searching. You can also use the optional archive description
-- field to specify how the archive is referred to in an external index of
-- archives, such as you might create in Amazon DynamoDB. You can also get
-- the vault inventory to obtain a list of archive IDs in a vault. For more
-- information, see InitiateJob.
--
-- You must provide a SHA256 tree hash of the data you are uploading. For
-- information about computing a SHA256 tree hash, see
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html Computing Checksums>.
--
-- You can optionally specify an archive description of up to 1,024
-- printable ASCII characters. You can get the archive description when you
-- either retrieve the archive or get the vault inventory. For more
-- information, see InitiateJob. Amazon Glacier does not interpret the
-- description in any way. An archive description does not need to be
-- unique. You cannot use the description to retrieve or sort the archive
-- list.
--
-- Archives are immutable. After you upload an archive, you cannot edit the
-- archive or its description.
--
-- An AWS account has full permission to perform all operations (actions).
-- However, AWS Identity and Access Management (IAM) users don\'t have any
-- permissions by default. You must grant them explicit permission to
-- perform specific actions. For more information, see
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>.
--
-- For conceptual information and underlying REST API, go to
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/uploading-an-archive.html Uploading an Archive in Amazon Glacier>
-- and
-- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-archive-post.html Upload Archive>
-- in the /Amazon Glacier Developer Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-UploadArchive.html AWS API Reference> for UploadArchive.
module Network.AWS.Glacier.UploadArchive
(
-- * Creating a Request
uploadArchive
, UploadArchive
-- * Request Lenses
, uaChecksum
, uaArchiveDescription
, uaVaultName
, uaAccountId
, uaBody
-- * Destructuring the Response
, archiveCreationOutput
, ArchiveCreationOutput
-- * Response Lenses
, acoArchiveId
, acoChecksum
, acoLocation
) where
import Network.AWS.Glacier.Types
import Network.AWS.Glacier.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Provides options to add an archive to a vault.
--
-- /See:/ 'uploadArchive' smart constructor.
data UploadArchive = UploadArchive'
{ _uaChecksum :: !(Maybe Text)
, _uaArchiveDescription :: !(Maybe Text)
, _uaVaultName :: !Text
, _uaAccountId :: !Text
, _uaBody :: !RqBody
} deriving (Show,Generic)
-- | Creates a value of 'UploadArchive' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uaChecksum'
--
-- * 'uaArchiveDescription'
--
-- * 'uaVaultName'
--
-- * 'uaAccountId'
--
-- * 'uaBody'
uploadArchive
:: Text -- ^ 'uaVaultName'
-> Text -- ^ 'uaAccountId'
-> RqBody -- ^ 'uaBody'
-> UploadArchive
uploadArchive pVaultName_ pAccountId_ pBody_ =
UploadArchive'
{ _uaChecksum = Nothing
, _uaArchiveDescription = Nothing
, _uaVaultName = pVaultName_
, _uaAccountId = pAccountId_
, _uaBody = pBody_
}
-- | The SHA256 tree hash of the data being uploaded.
uaChecksum :: Lens' UploadArchive (Maybe Text)
uaChecksum = lens _uaChecksum (\ s a -> s{_uaChecksum = a});
-- | The optional description of the archive you are uploading.
uaArchiveDescription :: Lens' UploadArchive (Maybe Text)
uaArchiveDescription = lens _uaArchiveDescription (\ s a -> s{_uaArchiveDescription = a});
-- | The name of the vault.
uaVaultName :: Lens' UploadArchive Text
uaVaultName = lens _uaVaultName (\ s a -> s{_uaVaultName = a});
-- | The 'AccountId' value is the AWS account ID of the account that owns the
-- vault. You can either specify an AWS account ID or optionally a single
-- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account
-- ID associated with the credentials used to sign the request. If you use
-- an account ID, do not include any hyphens (apos-apos) in the ID.
uaAccountId :: Lens' UploadArchive Text
uaAccountId = lens _uaAccountId (\ s a -> s{_uaAccountId = a});
-- | The data to upload.
uaBody :: Lens' UploadArchive RqBody
uaBody = lens _uaBody (\ s a -> s{_uaBody = a});
instance AWSRequest UploadArchive where
type Rs UploadArchive = ArchiveCreationOutput
request = postBody glacier
response
= receiveEmpty
(\ s h x ->
ArchiveCreationOutput' <$>
(h .#? "x-amz-archive-id") <*>
(h .#? "x-amz-sha256-tree-hash")
<*> (h .#? "Location"))
instance ToBody UploadArchive where
toBody = _uaBody
instance ToHeaders UploadArchive where
toHeaders UploadArchive'{..}
= mconcat
["x-amz-sha256-tree-hash" =# _uaChecksum,
"x-amz-archive-description" =# _uaArchiveDescription]
instance ToPath UploadArchive where
toPath UploadArchive'{..}
= mconcat
["/", toBS _uaAccountId, "/vaults/",
toBS _uaVaultName, "/archives"]
instance ToQuery UploadArchive where
toQuery = const mempty
| fmapfmapfmap/amazonka | amazonka-glacier/gen/Network/AWS/Glacier/UploadArchive.hs | mpl-2.0 | 6,869 | 0 | 13 | 1,437 | 698 | 436 | 262 | 90 | 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.MapsEngine.Maps.Permissions.BatchDelete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Remove permission entries from an already existing asset.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.maps.permissions.batchDelete@.
module Network.Google.Resource.MapsEngine.Maps.Permissions.BatchDelete
(
-- * REST Resource
MapsPermissionsBatchDeleteResource
-- * Creating a Request
, mapsPermissionsBatchDelete
, MapsPermissionsBatchDelete
-- * Request Lenses
, mpbdPayload
, mpbdId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.maps.permissions.batchDelete@ method which the
-- 'MapsPermissionsBatchDelete' request conforms to.
type MapsPermissionsBatchDeleteResource =
"mapsengine" :>
"v1" :>
"maps" :>
Capture "id" Text :>
"permissions" :>
"batchDelete" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PermissionsBatchDeleteRequest :>
Post '[JSON] PermissionsBatchDeleteResponse
-- | Remove permission entries from an already existing asset.
--
-- /See:/ 'mapsPermissionsBatchDelete' smart constructor.
data MapsPermissionsBatchDelete = MapsPermissionsBatchDelete'
{ _mpbdPayload :: !PermissionsBatchDeleteRequest
, _mpbdId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'MapsPermissionsBatchDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mpbdPayload'
--
-- * 'mpbdId'
mapsPermissionsBatchDelete
:: PermissionsBatchDeleteRequest -- ^ 'mpbdPayload'
-> Text -- ^ 'mpbdId'
-> MapsPermissionsBatchDelete
mapsPermissionsBatchDelete pMpbdPayload_ pMpbdId_ =
MapsPermissionsBatchDelete'
{ _mpbdPayload = pMpbdPayload_
, _mpbdId = pMpbdId_
}
-- | Multipart request metadata.
mpbdPayload :: Lens' MapsPermissionsBatchDelete PermissionsBatchDeleteRequest
mpbdPayload
= lens _mpbdPayload (\ s a -> s{_mpbdPayload = a})
-- | The ID of the asset from which permissions will be removed.
mpbdId :: Lens' MapsPermissionsBatchDelete Text
mpbdId = lens _mpbdId (\ s a -> s{_mpbdId = a})
instance GoogleRequest MapsPermissionsBatchDelete
where
type Rs MapsPermissionsBatchDelete =
PermissionsBatchDeleteResponse
type Scopes MapsPermissionsBatchDelete =
'["https://www.googleapis.com/auth/mapsengine"]
requestClient MapsPermissionsBatchDelete'{..}
= go _mpbdId (Just AltJSON) _mpbdPayload
mapsEngineService
where go
= buildClient
(Proxy :: Proxy MapsPermissionsBatchDeleteResource)
mempty
| rueshyna/gogol | gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Maps/Permissions/BatchDelete.hs | mpl-2.0 | 3,607 | 0 | 15 | 803 | 391 | 235 | 156 | 64 | 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.Content.Accounts.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a Merchant Center sub-account. This method can only be called
-- for multi-client accounts.
--
-- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.accounts.delete@.
module Network.Google.Resource.Content.Accounts.Delete
(
-- * REST Resource
AccountsDeleteResource
-- * Creating a Request
, accountsDelete
, AccountsDelete
-- * Request Lenses
, adMerchantId
, adAccountId
, adDryRun
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.accounts.delete@ method which the
-- 'AccountsDelete' request conforms to.
type AccountsDeleteResource =
"content" :>
"v2" :>
Capture "merchantId" (Textual Word64) :>
"accounts" :>
Capture "accountId" (Textual Word64) :>
QueryParam "dryRun" Bool :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a Merchant Center sub-account. This method can only be called
-- for multi-client accounts.
--
-- /See:/ 'accountsDelete' smart constructor.
data AccountsDelete = AccountsDelete'
{ _adMerchantId :: !(Textual Word64)
, _adAccountId :: !(Textual Word64)
, _adDryRun :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AccountsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'adMerchantId'
--
-- * 'adAccountId'
--
-- * 'adDryRun'
accountsDelete
:: Word64 -- ^ 'adMerchantId'
-> Word64 -- ^ 'adAccountId'
-> AccountsDelete
accountsDelete pAdMerchantId_ pAdAccountId_ =
AccountsDelete'
{ _adMerchantId = _Coerce # pAdMerchantId_
, _adAccountId = _Coerce # pAdAccountId_
, _adDryRun = Nothing
}
-- | The ID of the managing account.
adMerchantId :: Lens' AccountsDelete Word64
adMerchantId
= lens _adMerchantId (\ s a -> s{_adMerchantId = a})
. _Coerce
-- | The ID of the account.
adAccountId :: Lens' AccountsDelete Word64
adAccountId
= lens _adAccountId (\ s a -> s{_adAccountId = a}) .
_Coerce
-- | Flag to run the request in dry-run mode.
adDryRun :: Lens' AccountsDelete (Maybe Bool)
adDryRun = lens _adDryRun (\ s a -> s{_adDryRun = a})
instance GoogleRequest AccountsDelete where
type Rs AccountsDelete = ()
type Scopes AccountsDelete =
'["https://www.googleapis.com/auth/content"]
requestClient AccountsDelete'{..}
= go _adMerchantId _adAccountId _adDryRun
(Just AltJSON)
shoppingContentService
where go
= buildClient (Proxy :: Proxy AccountsDeleteResource)
mempty
| rueshyna/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Accounts/Delete.hs | mpl-2.0 | 3,582 | 0 | 14 | 826 | 503 | 296 | 207 | 71 | 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.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified DICOM store and removes all images that are
-- contained within it.
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.delete@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.Delete
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresDeleteResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresDelete
, ProjectsLocationsDataSetsDicomStoresDelete
-- * Request Lenses
, pXgafv
, pUploadProtocol
, pAccessToken
, pUploadType
, pName
, pCallback
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.delete@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresDelete' request conforms to.
type ProjectsLocationsDataSetsDicomStoresDeleteResource
=
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes the specified DICOM store and removes all images that are
-- contained within it.
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresDelete' smart constructor.
data ProjectsLocationsDataSetsDicomStoresDelete =
ProjectsLocationsDataSetsDicomStoresDelete'
{ _pXgafv :: !(Maybe Xgafv)
, _pUploadProtocol :: !(Maybe Text)
, _pAccessToken :: !(Maybe Text)
, _pUploadType :: !(Maybe Text)
, _pName :: !Text
, _pCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pXgafv'
--
-- * 'pUploadProtocol'
--
-- * 'pAccessToken'
--
-- * 'pUploadType'
--
-- * 'pName'
--
-- * 'pCallback'
projectsLocationsDataSetsDicomStoresDelete
:: Text -- ^ 'pName'
-> ProjectsLocationsDataSetsDicomStoresDelete
projectsLocationsDataSetsDicomStoresDelete pPName_ =
ProjectsLocationsDataSetsDicomStoresDelete'
{ _pXgafv = Nothing
, _pUploadProtocol = Nothing
, _pAccessToken = Nothing
, _pUploadType = Nothing
, _pName = pPName_
, _pCallback = Nothing
}
-- | V1 error format.
pXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresDelete (Maybe Xgafv)
pXgafv = lens _pXgafv (\ s a -> s{_pXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresDelete (Maybe Text)
pUploadProtocol
= lens _pUploadProtocol
(\ s a -> s{_pUploadProtocol = a})
-- | OAuth access token.
pAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresDelete (Maybe Text)
pAccessToken
= lens _pAccessToken (\ s a -> s{_pAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresDelete (Maybe Text)
pUploadType
= lens _pUploadType (\ s a -> s{_pUploadType = a})
-- | The resource name of the DICOM store to delete.
pName :: Lens' ProjectsLocationsDataSetsDicomStoresDelete Text
pName = lens _pName (\ s a -> s{_pName = a})
-- | JSONP
pCallback :: Lens' ProjectsLocationsDataSetsDicomStoresDelete (Maybe Text)
pCallback
= lens _pCallback (\ s a -> s{_pCallback = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresDelete
where
type Rs ProjectsLocationsDataSetsDicomStoresDelete =
Empty
type Scopes
ProjectsLocationsDataSetsDicomStoresDelete
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresDelete'{..}
= go _pName _pXgafv _pUploadProtocol _pAccessToken
_pUploadType
_pCallback
(Just AltJSON)
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresDeleteResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/Delete.hs | mpl-2.0 | 5,219 | 0 | 15 | 1,134 | 699 | 410 | 289 | 103 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : Turtle
-- Copyright : (c) 2003, Graham Klyne, 2009 Vasili I Galchin, 2011, 2012, 2013, 2014, 2018 Douglas Burke
-- License : GPL V2
--
-- Maintainer : Douglas Burke
-- Stability : experimental
-- Portability : CPP, OverloadedStrings
--
-- This Module implements a Turtle parser, returning a
-- new 'RDFGraph' consisting of triples and namespace information parsed from
-- the supplied input string, or an error indication.
--
-- REFERENCES:
--
-- - \"Turtle, Terse RDF Triple Language\",
-- W3C Candidate Recommendation 19 February 2013 (<http://www.w3.org/TR/2013/CR-turtle-20130219/L),
-- <http://www.w3.org/TR/turtle/>
--
-- NOTES:
--
-- - Prior to version @0.9.0.4@, the parser followed the
-- W3C Working Draft 09 August 2011 (<http://www.w3.org/TR/2011/WD-turtle-20110809/>)
--
-- - Strings with no language tag are converted to a 'LitTag' not a
-- 'TypedLitTag' with a type of @xsd:string@ (e.g. see
-- <http://www.w3.org/TR/2011/WD-turtle-20110809/#terms>).
--
-- - If the URI is actually an IRI (Internationalized Resource Identifiers)
-- then the parser will fail since 'Network.URI.parseURI' fails.
--
-- - The current (August 2013) Turtle test suite from
-- <http://www.w3.org/2013/TurtleTests/> passes except for the four
-- tests with non-ASCII local names, namely:
-- @localName_with_assigned_nfc_bmp_PN_CHARS_BASE_character_boundaries@,
-- @localName_with_assigned_nfc_PN_CHARS_BASE_character_boundaries@,
-- @localName_with_nfc_PN_CHARS_BASE_character_boundaries@,
-- and
-- @localName_with_non_leading_extras@.
--
--------------------------------------------------------------------------------
-- TODO:
-- - should the productions moved to an Internal module for use by
-- others - e.g. Sparql or the N3 parser?
module Swish.RDF.Parser.Turtle
( ParseResult
, parseTurtle
, parseTurtlefromText
)
where
import Swish.GraphClass (arc)
import Swish.Namespace (Namespace, ScopedName)
import Swish.Namespace (makeNamespace, getNamespaceTuple
, getScopeNamespace, getScopedNameURI
, getScopeNamespace, makeURIScopedName, makeNSScopedName)
import Swish.QName (newLName, emptyLName)
import Swish.RDF.Graph
( RDFGraph, RDFLabel(..)
, NamespaceMap
, addArc
, setNamespaces
, emptyRDFGraph
)
import Swish.RDF.Vocabulary
( LanguageTag
, toLangTag
, rdfType
, rdfFirst, rdfRest, rdfNil
, xsdBoolean, xsdInteger, xsdDecimal, xsdDouble
, defaultBase
)
import Swish.RDF.Datatype (makeDatatypedLiteral)
import Swish.RDF.Parser.Utils
( ParseResult
, runParserWithError
, ignore
, noneOf
, char
, ichar
, string
, stringT
, sepEndBy1
, isymbol
, lexeme
, whiteSpace
, hex4
, hex8
, appendURIs
)
import Control.Applicative
import Control.Monad (foldM)
import Data.Char (chr, isAsciiLower, isAsciiUpper, isDigit, isHexDigit, ord, toLower)
#if MIN_VERSION_base(4, 7, 0)
import Data.Functor (($>))
#endif
import Data.Maybe (fromMaybe)
import Data.Word (Word32)
import Network.URI (URI(..), parseURIReference)
import Text.ParserCombinators.Poly.StateText
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
#if !MIN_VERSION_base(4, 7, 0)
($>) :: Functor f => f a -> b -> f b
($>) = flip (<$)
#endif
----------------------------------------------------------------------
-- Define parser state and helper functions
----------------------------------------------------------------------
-- | Turtle parser state
data TurtleState = TurtleState
{ graphState :: RDFGraph -- Graph under construction
, prefixUris :: NamespaceMap -- namespace prefix mapping table
, baseUri :: URI -- base URI
, nodeGen :: Word32 -- blank node id generator
} deriving Show
-- | Functions to update TurtleState vector (use with stUpdate)
setPrefix :: Maybe T.Text -> URI -> TurtleState -> TurtleState
setPrefix pre uri st = st { prefixUris=p' }
where
p' = M.insert pre uri (prefixUris st)
-- | Change the base
setBase :: URI -> TurtleState -> TurtleState
setBase buri st = st { baseUri = buri }
-- Functions to access state:
-- | Return the default prefix
getDefaultPrefix :: TurtleParser Namespace
getDefaultPrefix = do
s <- stGet
case getPrefixURI s Nothing of
Just uri -> return $ makeNamespace Nothing uri
_ -> failBad "No default prefix defined; how unexpected (probably a programming error)!"
-- Map prefix to URI (naming needs a scrub here)
getPrefixURI :: TurtleState -> Maybe T.Text -> Maybe URI
getPrefixURI st pre = M.lookup pre (prefixUris st)
findPrefixNamespace :: Maybe L.Text -> TurtleParser Namespace
findPrefixNamespace (Just p) = findPrefix (L.toStrict p)
findPrefixNamespace Nothing = getDefaultPrefix
-- Return function to update graph in Turtle parser state,
-- using the supplied function of a graph
--
updateGraph :: (RDFGraph -> RDFGraph) -> TurtleState -> TurtleState
updateGraph f s = s { graphState = f (graphState s) }
----------------------------------------------------------------------
-- Define top-level parser function:
-- accepts a string and returns a graph or error
----------------------------------------------------------------------
type TurtleParser a = Parser TurtleState a
-- | Parse as Turtle (with no real base URI).
--
-- See 'parseTurtle' if you need to provide a base URI.
--
parseTurtlefromText ::
L.Text -- ^ input in N3 format.
-> ParseResult
parseTurtlefromText = flip parseTurtle Nothing
-- | Parse a string with an optional base URI.
--
-- Unlike 'parseN3' we treat the base URI as a URI and not
-- a QName.
--
parseTurtle ::
L.Text -- ^ input in N3 format.
-> Maybe URI -- ^ optional base URI
-> ParseResult
parseTurtle txt mbase = parseAnyfromText turtleDoc mbase txt
{-
hashURI :: URI
hashURI = fromJust $ parseURIReference "#"
-}
-- | The W3C turtle tests - e.g. <http://www.w3.org/2013/TurtleTests/turtle-syntax-bad-prefix-01.ttl> -
-- point out there's no default prefix mapping.
--
emptyState ::
Maybe URI -- ^ starting base for the graph
-> TurtleState
emptyState mbase =
let pmap = M.empty -- M.singleton Nothing hashURI
buri = fromMaybe (getScopedNameURI defaultBase) mbase
in TurtleState
{ graphState = emptyRDFGraph
, prefixUris = pmap
, baseUri = buri
, nodeGen = 0
}
-- | Function to supply initial context and parse supplied term.
--
parseAnyfromText ::
TurtleParser a -- ^ parser to apply
-> Maybe URI -- ^ base URI of the input, or @Nothing@ to use default base value
-> L.Text -- ^ input to be parsed
-> Either String a
parseAnyfromText parser mbase = runParserWithError parser (emptyState mbase)
newBlankNode :: TurtleParser RDFLabel
newBlankNode = do
n <- stQuery (succ . nodeGen)
stUpdate $ \s -> s { nodeGen = n }
return $ Blank (show n)
{-
This has been made tricky by the attempt to remove the default list
of prefixes from the starting point of a parse and the subsequent
attempt to add every new namespace we come across to the parser state.
So we add in the original default namespaces for testing, since
this routine is really for testing.
addTestPrefixes :: TurtleParser ()
addTestPrefixes = stUpdate $ \st -> st { prefixUris = LookupMap prefixTable } -- should append to existing map
-}
-- helper routines
comma, semiColon , fullStop :: TurtleParser ()
comma = isymbol ","
semiColon = isymbol ";"
fullStop = isymbol "."
sQuot, dQuot, sQuot3, dQuot3 :: TurtleParser ()
sQuot = ichar '\''
dQuot = ichar '"'
sQuot3 = ignore $ string "'''"
dQuot3 = ignore $ string "\"\"\""
match :: (Ord a) => a -> [(a,a)] -> Bool
match v = any (\(l,h) -> v >= l && v <= h)
-- a specialization of bracket that ensures white space after
-- the bracket symbol is parsed.
br :: Char -> Char -> TurtleParser a -> TurtleParser a
br lsym rsym =
let f = lexeme . char
in bracket (f lsym) (f rsym)
-- this is a lot simpler than N3
atWord :: T.Text -> TurtleParser ()
atWord s = (char '@' *> lexeme (stringT s)) $> ()
-- | Case insensitive match.
charI ::
Char -- ^ must be upper case
-> TurtleParser Char
charI c = satisfy (`elem` c : [ toLower c ])
-- | Case insensitive match.
stringI ::
String -- ^ must be upper case
-> TurtleParser String
stringI = mapM charI
{-
Add statement to graph in the parser state; there is a special case
for the special-case literals in the grammar since we need to ensure
the necessary namespaces (in other words xsd) are added to the
namespace store.
-}
addStatement :: RDFLabel -> RDFLabel -> RDFLabel -> TurtleParser ()
addStatement s p o@(TypedLit _ dtype) | dtype `elem` [xsdBoolean, xsdInteger, xsdDecimal, xsdDouble] = do
ost <- stGet
let stmt = arc s p o
oldp = prefixUris ost
ogs = graphState ost
(nspre, nsuri) = getNamespaceTuple $ getScopeNamespace dtype
newp = M.insert nspre nsuri oldp
stUpdate $ \st -> st { prefixUris = newp, graphState = addArc stmt ogs }
addStatement s p o = stUpdate (updateGraph (addArc (arc s p o) ))
isaz, isAZ, isaZ, is09, isaZ09 :: Char -> Bool
isaz = isAsciiLower
isAZ = isAsciiUpper
isaZ c = isaz c || isAZ c
is09 = isDigit
isaZ09 c = isaZ c || is09 c
{-
Since operatorLabel can be used to add a label with an
unknown namespace, we need to ensure that the namespace
is added if not known. If the namespace prefix is already
in use then it is over-written (rather than add a new
prefix for the label).
TODO:
- could we use the reverse lookupmap functionality to
find if the given namespace URI is in the namespace
list? If it is, use it's key otherwise do a
mapReplace for the input namespace (updated to use the
Data.Map.Map representation).
-}
operatorLabel :: ScopedName -> TurtleParser RDFLabel
operatorLabel snam = do
st <- stGet
let (pkey, pval) = getNamespaceTuple $ getScopeNamespace snam
opmap = prefixUris st
rval = Res snam
-- TODO: the lookup and the replacement could be fused; it may not
-- even make sense to separate now using a Map
case M.lookup pkey opmap of
Just val | val == pval -> return rval
| otherwise -> do
stUpdate $ \s -> s { prefixUris = M.insert pkey pval opmap }
return rval
_ -> do
stUpdate $ \s -> s { prefixUris = M.insert pkey pval opmap }
return rval
findPrefix :: T.Text -> TurtleParser Namespace
findPrefix pre = do
st <- stGet
case M.lookup (Just pre) (prefixUris st) of
Just uri -> return $ makeNamespace (Just pre) uri
Nothing -> failBad $ "Undefined prefix '" ++ T.unpack pre ++ ":'."
-- | Add the message to the start of the error message if the
-- parser fails (a minor specialization of 'adjustErr').
{-
addErr :: Parser s a -> String -> Parser s a
addErr p m = adjustErr p (m++)
-}
(<?) ::
Parser s a
-> String -- ^ Error message to add (a new line is added after the message)
-> Parser s a
(<?) p m = adjustErr p ((m++"\n")++)
-- Applicative's <* et al are infixl 4, with <|> infixl 3
infixl 4 <?
{-
Syntax productions; the Turtle ENBF grammar elements are from
http://www.w3.org/TR/2013/CR-turtle-20130219/#sec-grammar-grammar
The element names are converted to match Haskell syntax
and idioms where possible:
- camel Case rather than underscores and all upper case
- upper-case identifiers prepended by _ after above form
-}
{-
[1] turtleDoc ::= statement*
-}
turtleDoc :: TurtleParser RDFGraph
turtleDoc = mkGr <$> (whiteSpace *> many statement *> eof *> stGet)
where
mkGr s = setNamespaces (prefixUris s) (graphState s)
{-
[2] statement ::= directive | triples '.'
-}
statement :: TurtleParser ()
statement = directive <|> (triples *> commit fullStop <? "Missing '.' after a statement.")
{-
[3] directive ::= prefixID | base | sparqlPrefix | sparqlBase
With the addition of sparqlPrefix/sparqlBase (so '.' handling moved
into prefixID/base) may need to adjust use of lexeme.
-}
directive :: TurtleParser ()
directive =
lexeme
(prefixID <? "Unable to parse @prefix statement."
<|> base <? "Unable to parse @base statement."
<|> sparqlPrefix <? "Unable to parse Sparql PREFIX statement."
<|> sparqlBase <? "Unable to parse Sparql BASE statement.")
{-
[4] prefixID ::= '@prefix' PNAME_NS IRIREF '.'
-}
prefixID :: TurtleParser ()
prefixID = do
atWord "prefix"
p <- commit $ lexeme _pnameNS
u <- lexeme _iriRef
fullStop
stUpdate $ setPrefix (fmap L.toStrict p) u
{-
[5] base ::= '@base' IRIREF '.'
-}
base :: TurtleParser ()
base = do
atWord "base"
b <- commit $ lexeme _iriRef
fullStop
stUpdate $ setBase b
{-
[5s] sparqlBase ::= "BASE" IRIREF
-}
sparqlBase :: TurtleParser ()
sparqlBase = lexeme (stringI "BASE") >> commit _iriRef >>= stUpdate . setBase
{-
[6s] sparqlPrefix ::= "PREFIX" PNAME_NS IRIREF
-}
sparqlPrefix :: TurtleParser ()
sparqlPrefix = do
ignore $ lexeme $ stringI "PREFIX"
p <- commit $ lexeme _pnameNS
u <- lexeme _iriRef
stUpdate $ setPrefix (fmap L.toStrict p) u
{-
[6] triples ::= subject predicateObjectList | blankNodePropertyList predicateObjectList?
-}
triples :: TurtleParser ()
triples =
(subject >>= predicateObjectList)
<|>
(blankNodePropertyList >>= ignore . optional . predicateObjectList)
{-
[7] predicateObjectList ::= verb objectList (';' (verb objectList)?)*
-}
predicateObjectList :: RDFLabel -> TurtleParser ()
predicateObjectList subj =
let term = verb >>= objectList subj
in ignore $ sepEndBy1 term (many1 semiColon)
{-
[8] objectList ::= object (',' object)*
-}
objectList :: RDFLabel -> RDFLabel -> TurtleParser ()
objectList subj prd = sepBy1 object comma >>= mapM_ (addStatement subj prd)
{-
[9] verb ::= predicate | 'a'
-}
verb :: TurtleParser RDFLabel
verb = predicate <|> (lexeme (char 'a') *> operatorLabel rdfType)
{-
[10] subject ::= iri | BlankNode | collection
-}
subject :: TurtleParser RDFLabel
subject = (Res <$> iri) <|> blankNode <|> collection
{-
[11] predicate ::= iri
-}
predicate :: TurtleParser RDFLabel
predicate = Res <$> iri
{-
[12] object ::= iri | BlankNode | collection | blankNodePropertyList | literal
-}
object :: TurtleParser RDFLabel
object = (Res <$> iri) <|> blankNode <|> collection <|>
blankNodePropertyList <|> literal
{-
[13] literal ::= RDFLiteral | NumericLiteral | BooleanLiteral
-}
literal :: TurtleParser RDFLabel
literal = lexeme $ rdfLiteral <|> numericLiteral <|> booleanLiteral
{-
[14] blankNodePropertyList ::= '[' predicateObjectList ']'
-}
blankNodePropertyList :: TurtleParser RDFLabel
blankNodePropertyList = do
bNode <- newBlankNode
br '[' ']' $ lexeme (predicateObjectList bNode)
return bNode
{-
[15] collection ::= '(' object* ')'
-}
collection :: TurtleParser RDFLabel
collection = do
os <- br '(' ')' $ many object
eNode <- operatorLabel rdfNil
case os of
[] -> return eNode
(x:xs) -> do
sNode <- newBlankNode
first <- operatorLabel rdfFirst
addStatement sNode first x
lNode <- foldM addElem sNode xs
rest <- operatorLabel rdfRest
addStatement lNode rest eNode
return sNode
where
addElem prevNode curElem = do
bNode <- newBlankNode
first <- operatorLabel rdfFirst
rest <- operatorLabel rdfRest
addStatement prevNode rest bNode
addStatement bNode first curElem
return bNode
{-
[16] NumericLiteral ::= INTEGER | DECIMAL | DOUBLE
NOTE: We swap the order from this production
I have removed the conversion to a canonical form for
the double production, since it makes running the W3C
tests for Turtle harder (since it assumes that "1E0"
is passed through as is). It is also funny to
create a "canonical" form for only certain data types.
-}
numericLiteral :: TurtleParser RDFLabel
numericLiteral =
let f t v = makeDatatypedLiteral t (L.toStrict v)
in (f xsdDouble <$> _double)
<|>
(f xsdDecimal <$> _decimal)
<|>
(f xsdInteger <$> _integer)
{-
[128s] RDFLiteral ::= String (LANGTAG | '^^' iri)?
TODO: remove 'Lit lbl' form, since dtype=xsd:string in this case.
-}
rdfLiteral :: TurtleParser RDFLabel
rdfLiteral = do
lbl <- L.toStrict <$> turtleString
opt <- optional ((Left <$> (_langTag <? "Unable to parse the language tag"))
<|>
(string "^^" *> (Right <$> (commit iri <? "Unable to parse the datatype of the literal"))))
ignore $ optional whiteSpace
return $ case opt of
Just (Left lcode) -> LangLit lbl lcode
Just (Right dtype) -> TypedLit lbl dtype
_ -> Lit lbl
{-
[133s] BooleanLiteral ::= 'true' | 'false'
-}
booleanLiteral :: TurtleParser RDFLabel
booleanLiteral = makeDatatypedLiteral xsdBoolean . T.pack <$> lexeme (string "true" <|> string "false")
{-
[17] String ::= STRING_LITERAL_QUOTE | STRING_LITERAL_SINGLE_QUOTE | STRING_LITERAL_LONG_SINGLE_QUOTE | STRING_LITERAL_LONG_QUOTE
-}
turtleString :: TurtleParser L.Text
turtleString =
lexeme (
_stringLiteralLongQuote <|> _stringLiteralQuote <|>
_stringLiteralLongSingleQuote <|> _stringLiteralSingleQuote
) <? "Unable to parse a string literal"
{-
[135s] iri ::= IRIREF | PrefixedName
-}
iri :: TurtleParser ScopedName
iri = lexeme (
(makeURIScopedName <$> _iriRef)
<|>
prefixedName)
{-
[136s] PrefixedName ::= PNAME_LN | PNAME_NS
-}
prefixedName :: TurtleParser ScopedName
prefixedName =
_pnameLN <|>
flip makeNSScopedName emptyLName <$> (_pnameNS >>= findPrefixNamespace)
{-
[137s] BlankNode ::= BLANK_NODE_LABEL | ANON
-}
blankNode :: TurtleParser RDFLabel
blankNode = lexeme (_blankNodeLabel <|> _anon)
{--- Productions for terminals ---}
{-
[18] IRIREF ::= '<' ([^#x00-#x20<>\"{}|^`\] | UCHAR)* '>'
-}
_iriRef :: TurtleParser URI
_iriRef = do
-- ignore $ char '<'
-- why a, I using manyFinally' here? '>' shouldn't overlap
-- with iriRefChar.
-- ustr <- manyFinally' iriRefChar (char '>')
ustr <- bracket (char '<') (commit (char '>')) (many iriRefChar)
case parseURIReference ustr of
Nothing -> failBad $ "Invalid URI: <" ++ ustr ++ ">"
Just uref -> do
s <- stGet
either fail return $ appendURIs (baseUri s) uref
iriRefChar :: TurtleParser Char
iriRefChar = satisfy isIRIChar <|> _uchar
isIRIChar :: Char -> Bool
isIRIChar c =
c > chr 0x20
&&
c `notElem` ("<>\"{}|^`\\"::String)
{-
[139s] PNAME_NS ::= PN_PREFIX? ':'
-}
_pnameNS :: TurtleParser (Maybe L.Text)
_pnameNS = optional _pnPrefix <* char ':'
{-
[140s] PNAME_LN ::= PNAME_NS PN_LOCAL
-}
_pnameLN :: TurtleParser ScopedName
_pnameLN = do
ns <- _pnameNS >>= findPrefixNamespace
l <- fmap L.toStrict _pnLocal
case newLName l of
Just lname -> return $ makeNSScopedName ns lname
_ -> fail $ "Invalid local name: '" ++ T.unpack l ++ "'"
{-
[141s] BLANK_NODE_LABEL ::= '_:' (PN_CHARS_U | [0-9]) ((PN_CHARS | '.')* PN_CHARS)?
-}
_blankNodeLabel :: TurtleParser RDFLabel
_blankNodeLabel = do
ignore $ string "_:"
fChar <- _pnCharsU <|> satisfy is09
rest <- _pnRest
return $ Blank $ fChar : L.unpack rest
{-
Extracted from BLANK_NODE_LABEL and PN_PREFIX
<PN_REST> :== ( ( PN_CHARS | '.' )* PN_CHARS )?
We assume below that the match is only ever done for small strings, so
the cost isn't likely to be large. Let's see how well this assumption
holds up.
-}
_pnRest :: TurtleParser L.Text
_pnRest = noTrailingDot _pnChars
{-
There are two productions which look like
( (parser | '.')* parser )?
Unfortunately one of them has parser returning a Char and the
other has the parser returning multiple characters, so separate
out for now; hopefully can combine
Have decided to try replacing this with sepEndBy1, treating the '.'
as a separator, since this is closer to the EBNF. However, this
then eats up multiple '.' characters.
noTrailingDot ::
TurtleParser Char -- ^ This *should not* match '.'
-> TurtleParser L.Text
noTrailingDot p = do
terms <- sepEndBy1 (many p) (char '.')
return $ L.pack $ intercalate "." terms
noTrailingDotM ::
TurtleParser L.Text -- ^ This *should not* match '.'
-> TurtleParser L.Text
noTrailingDotM p = do
terms <- sepEndBy1 (many p) (char '.')
return $ L.intercalate "." $ map L.concat terms
-}
noTrailing ::
TurtleParser a -- ^ parser for '.'
-> ([a] -> String) -- ^ Collect fragments into a string
-> TurtleParser a -- ^ This *should not* match '.'
-> TurtleParser L.Text
noTrailing dotParser conv parser = do
lbl <- many (parser <|> dotParser)
let (nret, lclean) = clean $ conv lbl
-- a simple difference list implementation
edl = id
snocdl x xs = xs . (x:)
appenddl = (.)
replicatedl n x = (replicate n x ++)
-- this started out as a simple automaton/transducer from
-- http://www.haskell.org/pipermail/haskell-cafe/2011-September/095347.html
-- but then I decided to complicate it
--
clean :: String -> (Int, String)
clean = go 0 edl
where
go n acc [] = (n, acc [])
go n acc ('.':xs) = go (n+1) acc xs
go 0 acc (x:xs) = go 0 (snocdl x acc) xs
go n acc (x:xs) = go 0 (appenddl acc (snocdl x (replicatedl n '.'))) xs
reparse $ L.replicate (fromIntegral nret) "."
return $ L.pack lclean
noTrailingDot ::
TurtleParser Char -- ^ This *should not* match '.'
-> TurtleParser L.Text
noTrailingDot = noTrailing (char '.') id
noTrailingDotM ::
TurtleParser L.Text -- ^ This *should not* match '.'
-> TurtleParser L.Text
noTrailingDotM = noTrailing (char '.' $> ".") (L.unpack . L.concat)
{-
[144s] LANGTAG ::= '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)*
Note that toLangTag may fail since it does some extra
validation not done by the parser (mainly on the length of the
primary and secondary tags).
NOTE: This parser does not accept multiple secondary tags which RFC3066
does.
-}
_langTag :: TurtleParser LanguageTag
_langTag = do
ichar '@'
h <- commit $ many1Satisfy isaZ
mt <- optional (L.cons <$> char '-' <*> many1Satisfy isaZ09)
let lbl = L.toStrict $ L.append h $ fromMaybe L.empty mt
case toLangTag lbl of
Just lt -> return lt
_ -> fail ("Invalid language tag: " ++ T.unpack lbl) -- should this be failBad?
-- Returns True for + and False for -.
_leadingSign :: TurtleParser (Maybe Bool)
_leadingSign = do
ms <- optional (satisfy (`elem` ("+-"::String)))
return $ (=='+') `fmap` ms
{-
For when we tried to create a canonical representation.
addSign :: Maybe Bool -> L.Text -> L.Text
addSign (Just False) t = L.cons '-' t
addSign _ t = t
-}
addSign :: Maybe Bool -> L.Text -> L.Text
addSign (Just True) t = L.cons '+' t
addSign (Just _) t = L.cons '-' t
addSign _ t = t
{-
[19] INTEGER ::= [+-]? [0-9]+
We try to produce a canonical form for the
numbers.
-}
_integer :: TurtleParser L.Text
_integer = do
ms <- _leadingSign
rest <- many1Satisfy is09
return $ addSign ms rest
{-
[20] DECIMAL ::= [+-]? [0-9]* '.' [0-9]+
-}
_decimal :: TurtleParser L.Text
_decimal = do
ms <- _leadingSign
leading <- manySatisfy is09
ichar '.'
trailing <- many1Satisfy is09
let ans2 = L.cons '.' trailing
ans = if L.null leading
-- then L.cons '0' ans2 -- create a 'canonical' version
then ans2
else L.append leading ans2
return $ addSign ms ans
{-
[21] DOUBLE ::= [+-]? ([0-9]+ '.' [0-9]* EXPONENT | '.' [0-9]+ EXPONENT | [0-9]+ EXPONENT)
-}
_d1 :: TurtleParser L.Text
_d1 = do
a <- many1Satisfy is09
ichar '.'
b <- manySatisfy is09
return $ a `L.append` ('.' `L.cons` b)
_d2 :: TurtleParser L.Text
_d2 = do
ichar '.'
b <- many1Satisfy is09
return $ '.' `L.cons` b
_d3 :: TurtleParser L.Text
_d3 = many1Satisfy is09
_double :: TurtleParser L.Text
_double = do
ms <- _leadingSign
leading <- _d1 <|> _d2 <|> _d3
e <- _exponent
return $ addSign ms $ leading `L.append` e
{-
[154s] EXPONENT ::= [eE] [+-]? [0-9]+
-}
_exponent :: TurtleParser L.Text
_exponent = do
e <- char 'e' <|> char 'E'
ms <- _leadingSign
ep <- _integer
return $ L.cons e $ addSign ms ep
{-
[22] STRING_LITERAL_QUOTE ::= '"' ([^#x22#x5C#xA#xD] | ECHAR | UCHAR)* '"'
[23] STRING_LITERAL_SINGLE_QUOTE ::= "'" ([^#x27#x5C#xA#xD] | ECHAR | UCHAR)* "'"
[24] STRING_LITERAL_LONG_SINGLE_QUOTE ::= "'''" (("'" | "''")? [^'\] | ECHAR | UCHAR)* "'''"
[25] STRING_LITERAL_LONG_QUOTE ::= '"""' (('"' | '""')? [^"\] | ECHAR | UCHAR)* '"""'
Since ECHAR | UCHAR is common to all these we pull it out to
create the _protChar parser.
-}
_protChar :: TurtleParser Char
_protChar = char '\\' *> (_echar' <|> _uchar')
_exclSLQ, _exclSLSQ :: String
_exclSLQ = map chr [0x22, 0x5c, 0x0a, 0x0d]
_exclSLSQ = map chr [0x27, 0x5c, 0x0a, 0x0d]
_stringLiteralQuote, _stringLiteralSingleQuote :: TurtleParser L.Text
_stringLiteralQuote = _stringIt dQuot (_tChars _exclSLQ)
_stringLiteralSingleQuote = _stringIt sQuot (_tChars _exclSLSQ)
_stringLiteralLongQuote, _stringLiteralLongSingleQuote :: TurtleParser L.Text
_stringLiteralLongQuote = _stringItLong dQuot3 (_tCharsLong '"')
_stringLiteralLongSingleQuote = _stringItLong sQuot3 (_tCharsLong '\'')
_stringIt :: TurtleParser a -> TurtleParser Char -> TurtleParser L.Text
_stringIt sep chars = L.pack <$> bracket sep sep (many chars)
_stringItLong :: TurtleParser a -> TurtleParser L.Text -> TurtleParser L.Text
_stringItLong sep chars = L.concat <$> bracket sep sep (many chars)
_tChars :: String -> TurtleParser Char
_tChars excl = _protChar <|> noneOf excl
oneOrTwo :: Char -> TurtleParser L.Text
oneOrTwo c = do
ignore $ char c
mb <- optional (char c)
case mb of
Just _ -> return $ L.pack [c,c]
_ -> return $ L.singleton c
_multiQuote :: Char -> TurtleParser L.Text
_multiQuote c = do
mq <- optional (oneOrTwo c)
r <- noneOf (c : "\\")
return $ fromMaybe L.empty mq `L.snoc` r
_tCharsLong :: Char -> TurtleParser L.Text
_tCharsLong c =
L.singleton <$> _protChar
<|> _multiQuote c
{-
[26] UCHAR ::= '\u' HEX HEX HEX HEX | '\U' HEX HEX HEX HEX HEX HEX HEX HEX
-}
_uchar :: TurtleParser Char
_uchar = char '\\' >> _uchar'
_uchar' :: TurtleParser Char
_uchar' =
(char 'u' *> (commit hex4 <? "Expected 4 hex characters after \\u"))
<|>
(char 'U' *> (commit hex8 <? "Expected 8 hex characters after \\U"))
{-
[159s] ECHAR ::= '\' [tbnrf\"']
Since ECHAR is only used by the string productions
in the form ECHAR | UCHAR, the check for the leading
\ has been moved out (see _protChar)
_echar :: TurtleParser Char
_echar = char '\\' *> _echar'
-}
_echar' :: TurtleParser Char
_echar' =
(char 't' $> '\t') <|>
(char 'b' $> '\b') <|>
(char 'n' $> '\n') <|>
(char 'r' $> '\r') <|>
(char 'f' $> '\f') <|>
(char '\\' $> '\\') <|>
(char '"' $> '"') <|>
(char '\'' $> '\'')
{-
[161s] WS ::= #x20 | #x9 | #xD | #xA
-}
_ws :: TurtleParser ()
_ws = ignore $ satisfy (`elem` _wsChars)
_wsChars :: String
_wsChars = map chr [0x20, 0x09, 0x0d, 0x0a]
{-
[162s] ANON ::= '[' WS* ']'
-}
_anon :: TurtleParser RDFLabel
_anon =
br '[' ']' (many _ws) >> newBlankNode
{-
[163s] PN_CHARS_BASE ::= [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
TODO: may want to make this a Char -> Bool selector for
use with manySatisfy rather than a combinator.
-}
_pnCharsBase :: TurtleParser Char
_pnCharsBase =
let f c = let i = ord c
in isaZ c ||
match i [(0xc0, 0xd6), (0xd8, 0xf6), (0xf8, 0x2ff),
(0x370, 0x37d), (0x37f, 0x1fff), (0x200c, 0x200d),
(0x2070, 0x218f), (0x2c00, 0x2fef), (0x3001, 0xd7ff),
(0xf900, 0xfdcf), (0xfdf0, 0xfffd), (0x10000, 0xeffff)]
in satisfy f
{-
[164s] PN_CHARS_U ::= PN_CHARS_BASE | '_'
[166s] PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040]
-}
_pnCharsU, _pnChars :: TurtleParser Char
_pnCharsU = _pnCharsBase <|> char '_'
_pnChars =
let f c = let i = ord c
in match i [(0x300, 0x36f), (0x203f, 0x2040)]
in _pnCharsU <|> char '-' <|> satisfy is09 <|>
char (chr 0xb7) <|> satisfy f
{-
[167s] PN_PREFIX ::= PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)?
[168s] PN_LOCAL ::= (PN_CHARS_U | ':' | [0-9] | PLX) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX))?
-}
_pnPrefix :: TurtleParser L.Text
_pnPrefix = L.cons <$> _pnCharsBase <*> _pnRest
_pnLocal :: TurtleParser L.Text
_pnLocal = do
s <- L.singleton <$> (_pnCharsU <|> char ':' <|> satisfy is09)
<|> _plx
e <- noTrailingDotM (L.singleton <$> (_pnChars <|> char ':') <|> _plx)
return $ s `L.append` e
{-
[169s] PLX ::= PERCENT | PN_LOCAL_ESC
[170s] PERCENT ::= '%' HEX HEX
[171s] HEX ::= [0-9] | [A-F] | [a-f]
[172s] PN_LOCAL_ESC ::= '\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%')
We do not convert hex-encoded values into the characters, which
means we have to deal with Text rather than Char for these
parsers, which is annoying.
-}
_plx, _percent :: TurtleParser L.Text
_plx = _percent <|> (L.singleton <$> _pnLocalEsc)
_percent = do
ichar '%'
a <- _hex
b <- _hex
return $ L.cons '%' $ L.cons a $ L.singleton b
_hex, _pnLocalEsc :: TurtleParser Char
_hex = satisfy isHexDigit
_pnLocalEsc = char '\\' *> satisfy (`elem` _pnLocalEscChars)
_pnLocalEscChars :: String
_pnLocalEscChars = "_~.-!$&'()*+,;=/?#@%"
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, Graham Klyne, 2009 Vasili I Galchin,
-- 2011, 2012, 2013, 2014, 2018 Douglas Burke
-- All rights reserved.
--
-- This file is part of Swish.
--
-- Swish 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.
--
-- Swish 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 Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
| DougBurke/swish | src/Swish/RDF/Parser/Turtle.hs | lgpl-2.1 | 31,071 | 0 | 18 | 6,585 | 6,258 | 3,274 | 2,984 | 507 | 4 |
-- file: ch14/Maybe.hs
data Maybe a = Nothing | Just a
instance Monad Maybe where
-- chain
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Just x >>= fn = fn x
Nothing >>= fn = Nothing
-- inject
return :: a -> Maybe a
return a = Just a
---
(>>) :: Maybe a -> Maybe b -> Maybe b
Just _ >> mb = mb
Nothing >> mb = Nothing
fail _ = Nothing
{- Function that executes the Maybe monad. If the computation
fails the third parameter is Nothing it returns the value n,
on the other hand if the computation succeeds the third
parameter is (Just x) it applies the function (a -> b) to the
value x wrapped in the monad.
-}
maybe :: b -> (a -> b ) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x
| caiorss/Functional-Programming | haskell/rwh/ch14/Maybe.hs | unlicense | 755 | 0 | 10 | 216 | 226 | 113 | 113 | -1 | -1 |
#!/usr/bin/env stack
{-
stack
--resolver lts-11.10
--install-ghc
runghc
--package base
--
-hide-all-packages
-}
-- Copyright 2018 Google LLC. All Rights Reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
import qualified Data.Map as M
data Op2 = Minus | Times | Eq
deriving Show
data Term
= Var String
| Lam String Term
| Rec String Term
| App Term Term
| Op2 Op2 Term Term
| Lit Int
| If Term Term Term
deriving Show
type Env = M.Map String Val
data Val
= VInt Int
| VBool Bool
| VClosure Term Env
| VRClosure String Term Env
deriving Show
data Frame
= EvalOp2SecondArg Op2 Term Env
| EvalOp2 Op2 Val
| EvalArg Term Env
| EvalBody String Term Env
| EvalRecBody Val
| Branch Term Term Env
deriving Show
vOp2 Minus (VInt i) (VInt j) = VInt (i - j)
vOp2 Times (VInt i) (VInt j) = VInt (i * j)
vOp2 Eq (VInt i) (VInt j) = VBool (i == j)
apply [] v = v
apply (EvalOp2 op v2 : k) v1 = apply k (vOp2 op v2 v1)
apply (EvalOp2SecondArg op e env : k) v = eval e env (EvalOp2 op v : k)
apply (EvalBody x e env : k) v = eval e (M.insert x v env) k
apply (EvalRecBody vf@(VRClosure f (Lam x e) env) : k) v = eval e (M.insert x v (M.insert f vf env)) k
apply (EvalArg e1 env : k) (VClosure (Lam x e2) env') = eval e1 env (EvalBody x e2 env' : k)
apply (EvalArg e1 env : k) vf@(VRClosure _ _ _) = eval e1 env (EvalRecBody vf : k)
apply (Branch e1 e2 env : k) (VBool True) = eval e1 env k
apply (Branch e1 e2 env : k) (VBool False) = eval e2 env k
eval e env k = eval' e
where
eval' (Lit i) = apply k (VInt i)
eval' (Op2 op e1 e2) = eval e1 env (EvalOp2SecondArg op e2 env : k)
eval' (App f e) = eval f env (EvalArg e env : k)
eval' (Lam x e) = apply k (VClosure (Lam x e) env)
eval' (Rec f (Lam x e)) = apply k (VRClosure f (Lam x e) env)
eval' (Var x) = apply k (env M.! x)
eval' (If e1 e2 e3) = eval e1 env (Branch e2 e3 env : k)
fact = Rec
"fact"
(Lam
"n"
(If (Op2 Eq (Var "n") (Lit 0))
(Lit 1)
(Op2 Times (Var "n") (App (Var "fact") (Op2 Minus (Var "n") (Lit 1))))
)
)
main = print $ eval (App fact (Lit 20)) M.empty []
| polux/snippets | cps_defunc_evaluator.hs | apache-2.0 | 2,645 | 0 | 17 | 645 | 1,098 | 564 | 534 | 55 | 7 |
sq x = x * x
main = print $ sq 12
| egaburov/funstuff | Haskell/BartoszBofH/2_MyFirstProgram/a.hs | apache-2.0 | 35 | 0 | 6 | 13 | 25 | 12 | 13 | 2 | 1 |
module Main (main) where
import qualified System.Exit as Exit
import Hecate (configure, run)
main :: IO ()
main = configure >>= run >>= Exit.exitWith
| henrytill/hecate | executables/Main.hs | apache-2.0 | 169 | 0 | 6 | 43 | 53 | 32 | 21 | 5 | 1 |
import Data.List
tab = [("black", 0, 0, 0),
("blue", 0, 0,255),
("lime", 0,255, 0),
("aqua", 0,255,255),
("red", 255, 0, 0),
("fuchsia",255, 0,255),
("yellow", 255,255, 0),
("white", 255,255,255)]
h2d x = read ("0x"++x) :: Int
ans x =
let r = h2d $ take 2 $ drop 1 x
g = h2d $ take 2 $ drop 3 x
b = h2d $ take 2 $ drop 5 x
d = map (\ (c,r1,g1,b1) -> (c, (r1-r)^2+(g1-g)^2+(b1-b)^2 ) ) tab
s = sortBy (\ (c0,d0) (c1,d1) -> compare d0 d1 ) d
in
fst $ head s
main = do
c <- getContents
let i = takeWhile (/= "0") $ lines c
o = map ans i
mapM_ putStrLn o
| a143753/AOJ | 0176.hs | apache-2.0 | 681 | 0 | 19 | 249 | 403 | 226 | 177 | 22 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Text as T
import Data.RDF
import Data.RDF.Namespace
globalPrefix :: PrefixMappings
globalPrefix = ns_mappings []
baseURL :: Maybe BaseUrl
baseURL = Just $ BaseUrl "file://"
testURL = "file:///this/is/not/a/palindrome"
tris :: [Triple]
tris = [Triple
(unode testURL)
(unode testURL)
(LNode . PlainL . T.pack $ "literal string")]
testRdf :: TriplesGraph
testRdf = mkRdf tris baseURL globalPrefix
main :: IO ()
main = print testRdf
| bergey/metastic | src/TestCase.hs | bsd-2-clause | 506 | 0 | 10 | 97 | 147 | 80 | 67 | 18 | 1 |
{-| Implementation of the RAPI client interface.
-}
{-
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.
-}
{-# LANGUAGE BangPatterns, CPP #-}
module Ganeti.HTools.Backend.Rapi
( loadData
, parseData
) where
import Control.Exception
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.Curl
import Network.Curl.Types ()
import Control.Monad
import Text.JSON (JSObject, fromJSObject, decodeStrict)
import Text.JSON.Types (JSValue(..))
import Text.Printf (printf)
import System.FilePath
import Ganeti.BasicTypes
import Ganeti.Types (Hypervisor(..))
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.JSON (loadJSArray, JSRecord, tryFromObj, fromJVal, maybeFromObj,
fromJResult, tryArrayMaybeFromObj, readEitherString,
fromObjWithDefault, asJSObject)
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.Constants as C
{-# ANN module "HLint: ignore Eta reduce" #-}
-- | File method prefix.
filePrefix :: String
filePrefix = "file://"
-- | Read an URL via curl and return the body if successful.
getUrl :: (Monad m) => String -> IO (m String)
-- | Connection timeout (when using non-file methods).
connTimeout :: Long
connTimeout = 15
-- | The default timeout for queries (when using non-file methods).
queryTimeout :: Long
queryTimeout = 60
-- | The curl options we use.
curlOpts :: [CurlOption]
curlOpts = [ CurlSSLVerifyPeer False
, CurlSSLVerifyHost 0
, CurlTimeout queryTimeout
, CurlConnectTimeout connTimeout
]
getUrl url = do
(code, !body) <- curlGetString url curlOpts
return (case code of
CurlOK -> return body
_ -> fail $ printf "Curl error for '%s', error %s"
url (show code))
-- | Helper to convert I/O errors in 'Bad' values.
ioErrToResult :: IO a -> IO (Result a)
ioErrToResult ioaction =
Control.Exception.catch (liftM Ok ioaction)
(\e -> return . Bad . show $ (e::IOException))
-- | Append the default port if not passed in.
formatHost :: String -> String
formatHost master =
if ':' `elem` master
then master
else "https://" ++ master ++ ":" ++ show C.defaultRapiPort
-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
-> String
-> Result [(String, Instance.Instance)]
getInstances ktn body =
loadJSArray "Parsing instance data" body >>=
mapM (parseInstance ktn . fromJSObject)
-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> String -> Result [(String, Node.Node)]
getNodes ktg body = loadJSArray "Parsing node data" body >>=
mapM (parseNode ktg . fromJSObject)
-- | Parse a group list in JSON format.
getGroups :: String -> Result [(String, Group.Group)]
getGroups body = loadJSArray "Parsing group data" body >>=
mapM (parseGroup . fromJSObject)
-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
-> JSRecord
-> Result (String, Instance.Instance)
parseInstance ktn a = do
name <- tryFromObj "Parsing new instance" a "name"
let owner_name = "Instance '" ++ name ++ "', error while parsing data"
let extract s x = tryFromObj owner_name x s
disk <- extract "disk_usage" a
dsizes <- extract "disk.sizes" a
dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles"
beparams <- liftM fromJSObject (extract "beparams" a)
omem <- extract "oper_ram" a
mem <- case omem of
JSRational _ _ -> annotateResult owner_name (fromJVal omem)
_ -> extract "memory" beparams `mplus` extract "maxmem" beparams
vcpus <- extract "vcpus" beparams
pnode <- extract "pnode" a >>= lookupNode ktn name
snodes <- extract "snodes" a
snode <- case snodes of
[] -> return Node.noSecondary
x:_ -> readEitherString x >>= lookupNode ktn name
running <- extract "status" a
tags <- extract "tags" a
auto_balance <- extract "auto_balance" beparams
dt <- extract "disk_template" a
su <- extract "spindle_use" beparams
-- Not forthcoming by default.
forthcoming <- extract "forthcoming" a `orElse` Ok False
let disks = zipWith Instance.Disk dsizes dspindles
let inst = Instance.create name mem disk disks vcpus running tags
auto_balance pnode snode dt su [] forthcoming
return (name, inst)
-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node)
parseNode ktg a = do
name <- tryFromObj "Parsing new node" a "name"
let desc = "Node '" ++ name ++ "', error while parsing data"
extract key = tryFromObj desc a key
extractDef def key = fromObjWithDefault a key def
offline <- extract "offline"
drained <- extract "drained"
vm_cap <- annotateResult desc $ maybeFromObj a "vm_capable"
let vm_cap' = fromMaybe True vm_cap
ndparams <- extract "ndparams" >>= asJSObject
excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage"
guuid <- annotateResult desc $ maybeFromObj a "group.uuid"
guuid' <- lookupGroup ktg name (fromMaybe defaultGroupID guuid)
let live = not offline && vm_cap'
lvextract def = eitherLive live def . extract
lvextractDef def = eitherLive live def . extractDef def
sptotal <- if excl_stor
then lvextract 0 "sptotal"
else tryFromObj desc (fromJSObject ndparams) "spindle_count"
spfree <- lvextractDef 0 "spfree"
mtotal <- lvextract 0.0 "mtotal"
mnode <- lvextract 0 "mnode"
mfree <- lvextract 0 "mfree"
dtotal <- lvextractDef 0.0 "dtotal"
dfree <- lvextractDef 0 "dfree"
ctotal <- lvextract 0.0 "ctotal"
cnos <- lvextract 0 "cnos"
tags <- extract "tags"
let node = flip Node.setNodeTags tags $
Node.create name mtotal mnode mfree dtotal dfree ctotal cnos
(not live || drained) sptotal spfree guuid' excl_stor
return (name, node)
-- | Construct a group from a JSON object.
parseGroup :: JSRecord -> Result (String, Group.Group)
parseGroup a = do
name <- tryFromObj "Parsing new group" a "name"
let extract s = tryFromObj ("Group '" ++ name ++ "'") a s
uuid <- extract "uuid"
apol <- extract "alloc_policy"
ipol <- extract "ipolicy"
tags <- extract "tags"
-- TODO: parse networks to which this group is connected
return (uuid, Group.create name uuid apol [] ipol tags)
-- | Parse cluster data from the info resource.
parseCluster :: JSObject JSValue -> Result ([String], IPolicy,
String, Hypervisor)
parseCluster obj = do
let obj' = fromJSObject obj
extract s = tryFromObj "Parsing cluster data" obj' s
master <- extract "master"
tags <- extract "tags"
ipolicy <- extract "ipolicy"
hypervisor <- extract "default_hypervisor"
return (tags, ipolicy, master, hypervisor)
-- | Loads the raw cluster data from an URL.
readDataHttp :: String -- ^ Cluster or URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readDataHttp master = do
let url = formatHost master
group_body <- getUrl $ printf "%s/2/groups?bulk=1" url
node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url
inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url
info_body <- getUrl $ printf "%s/2/info" url
return (group_body, node_body, inst_body, info_body)
-- | Loads the raw cluster data from the filesystem.
readDataFile:: String -- ^ Path to the directory containing the files
-> IO (Result String, Result String, Result String, Result String)
readDataFile path = do
group_body <- ioErrToResult . readFile $ path </> "groups.json"
node_body <- ioErrToResult . readFile $ path </> "nodes.json"
inst_body <- ioErrToResult . readFile $ path </> "instances.json"
info_body <- ioErrToResult . readFile $ path </> "info.json"
return (group_body, node_body, inst_body, info_body)
-- | Loads data via either 'readDataFile' or 'readDataHttp'.
readData :: String -- ^ URL to use as source
-> IO (Result String, Result String, Result String, Result String)
readData url =
if filePrefix `isPrefixOf` url
then readDataFile (drop (length filePrefix) url)
else readDataHttp url
-- | Builds the cluster data from the raw Rapi content.
parseData :: (Result String, Result String, Result String, Result String)
-> Result ClusterData
parseData (group_body, node_body, inst_body, info_body) = do
group_data <- group_body >>= getGroups
let (group_names, group_idx) = assignIndices group_data
node_data <- node_body >>= getNodes group_names
let (node_names, node_idx) = assignIndices node_data
inst_data <- inst_body >>= getInstances node_names
let (_, inst_idx) = assignIndices inst_data
(tags, ipolicy, master, hypervisor) <-
info_body >>=
(fromJResult "Parsing cluster info" . decodeStrict) >>=
parseCluster
node_idx' <- setMaster node_names node_idx master
let node_idx'' = Container.map (`Node.setHypervisor` hypervisor) node_idx'
return (ClusterData group_idx node_idx'' inst_idx tags ipolicy)
-- | Top level function for data loading.
loadData :: String -- ^ Cluster or URL to use as source
-> IO (Result ClusterData)
loadData = fmap parseData . readData
| mbakke/ganeti | src/Ganeti/HTools/Backend/Rapi.hs | bsd-2-clause | 10,629 | 0 | 15 | 2,179 | 2,538 | 1,269 | 1,269 | 191 | 3 |
module Cube where
import Shader
import Data.Foldable
import Foreign
import Graphics.GL
import Linear
import Mesh
import Shader
data Cube = Cube
{ cubeVAO :: VertexArrayObject
, cubeShader :: GLProgram
, cubeIndexCount :: GLsizei
, cubeUniformMVP :: UniformLocation
}
----------------------------------------------------------
-- Make Cube
----------------------------------------------------------
renderCube :: Cube -> M44 GLfloat -> IO ()
renderCube cube mvp = do
useProgram (cubeShader cube)
uniformM44 (cubeUniformMVP cube) mvp
glBindVertexArray (unVertexArrayObject (cubeVAO cube))
glDrawElements GL_TRIANGLES (cubeIndexCount cube) GL_UNSIGNED_INT nullPtr
glBindVertexArray 0
makeCube :: GLProgram -> IO Cube
makeCube program = do
aPosition <- getShaderAttribute program "aPosition"
aColor <- getShaderAttribute program "aColor"
aID <- getShaderAttribute program "aID"
uMVP <- getShaderUniform program "uMVP"
-- Setup a VAO
vaoCube <- overPtr (glGenVertexArrays 1)
glBindVertexArray vaoCube
-----------------
-- Cube Positions
-----------------
-- Buffer the cube vertices
let cubeVertices =
--- front
[ -1.0 , -1.0 , 1.0
, 1.0 , -1.0 , 1.0
, 1.0 , 1.0 , 1.0
, -1.0 , 1.0 , 1.0
--- back
, -1.0 , -1.0 , -1.0
, 1.0 , -1.0 , -1.0
, 1.0 , 1.0 , -1.0
, -1.0 , 1.0 , -1.0 ] :: [GLfloat]
vaoCubeVertices <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vaoCubeVertices
let cubeVerticesSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeVertices)
withArray cubeVertices $
\cubeVerticesPtr ->
glBufferData GL_ARRAY_BUFFER cubeVerticesSize (castPtr cubeVerticesPtr) GL_STATIC_DRAW
-- Describe our vertices array to OpenGL
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aPosition))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aPosition)) -- attribute
3 -- number of elements per vertex, here (x,y,z)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
--------------
-- Cube Colors
--------------
-- Buffer the cube colors
let cubeColors =
-- front colors
[ 1.0, 0.0, 0.0
, 0.0, 1.0, 0.0
, 0.0, 0.0, 1.0
, 1.0, 1.0, 1.0
-- back colors
, 1.0, 0.0, 0.0
, 0.0, 1.0, 0.0
, 0.0, 0.0, 1.0
, 1.0, 1.0, 1.0 ] :: [GLfloat]
vboCubeColors <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vboCubeColors
let cubeColorsSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeColors)
withArray cubeColors $
\cubeColorsPtr ->
glBufferData GL_ARRAY_BUFFER cubeColorsSize (castPtr cubeColorsPtr) GL_STATIC_DRAW
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aColor))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aColor)) -- attribute
3 -- number of elements per vertex, here (R,G,B)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
-----------
-- Cube IDs
-----------
-- Buffer the cube ids
let cubeIDs =
[ 0
, 1
, 2
, 3
, 4
, 5 ] :: [GLfloat]
vboCubeIDs <- overPtr (glGenBuffers 1)
glBindBuffer GL_ARRAY_BUFFER vboCubeIDs
let cubeIDsSize = fromIntegral (sizeOf (undefined :: GLfloat) * length cubeIDs)
withArray cubeIDs $
\cubeIDsPtr ->
glBufferData GL_ARRAY_BUFFER cubeIDsSize (castPtr cubeIDsPtr) GL_STATIC_DRAW
glEnableVertexAttribArray (fromIntegral (unAttributeLocation aID))
glVertexAttribPointer
(fromIntegral (unAttributeLocation aID)) -- attribute
1 -- number of elements per vertex, here (R,G,B)
GL_FLOAT -- the type of each element
GL_FALSE -- don't normalize
0 -- no extra data between each position
nullPtr -- offset of first element
----------------
-- Cube Indicies
----------------
-- Buffer the cube indices
let cubeIndices =
-- front
[ 0, 1, 2
, 2, 3, 0
-- top
, 1, 5, 6
, 6, 2, 1
-- back
, 7, 6, 5
, 5, 4, 7
-- bottom
, 4, 0, 3
, 3, 7, 4
-- left
, 4, 5, 1
, 1, 0, 4
-- right
, 3, 2, 6
, 6, 7, 3 ] :: [GLuint]
iboCubeElements <- overPtr (glGenBuffers 1)
glBindBuffer GL_ELEMENT_ARRAY_BUFFER iboCubeElements
let cubeElementsSize = fromIntegral (sizeOf (undefined :: GLuint) * length cubeIndices)
withArray cubeIndices $
\cubeIndicesPtr ->
glBufferData GL_ELEMENT_ARRAY_BUFFER cubeElementsSize (castPtr cubeIndicesPtr) GL_STATIC_DRAW
glBindVertexArray 0
return $ Cube
{ cubeVAO = VertexArrayObject vaoCube
, cubeShader = program
, cubeIndexCount = fromIntegral (length cubeIndices)
, cubeUniformMVP = uMVP
}
| lukexi/wboit | test/Cube.hs | bsd-2-clause | 5,793 | 0 | 14 | 2,047 | 1,183 | 642 | 541 | 120 | 1 |
{-# OPTIONS -XUndecidableInstances #-}
{-# OPTIONS -XTypeOperators #-}
{-# OPTIONS -XMultiParamTypeClasses #-}
{-# OPTIONS -XFunctionalDependencies #-}
{-# OPTIONS -XFlexibleInstances #-}
module Data.Real.CReal
(CReal, inject, around,
approx, approxRange, integerInterval,
BoundedCReal, compact, choke,
proveNonZeroFrom, proveNonZero,
realNegate, realTranslate, realPlus,
realScale, realMultBound,
realAbs,
realRecipWitness,
realPowerIntBound, realPowerInt,
realBasePolynomialBound, realBasePolynomial2Bound,
rationalExp, realExpBound,
rationalSin, realSin, rationalCos, realCos,
rationalLn, realLnWitness, rationalArcTan, realArcTan,
scalePi, real2Pi, realPi, realPi2, realPi4,
rationalSqrt, realSqrt,
rationalErrorFunction, realErrorFunction,
sumRealList, unsafeMkCReal,
radius, answer) where
import Data.Real.Base
import Data.Real.Complete
import Data.Maybe
import Data.Multinomial
import Data.Interval
import Combinatorics
import Control.Exception
{- Thoughts: Polynomails should always return a Complete Base. Fractions grow to large othewise.
Separate interval aritmetic and (R+Q) optimisations into another file that implements the same interface. -}
radius = 2^^(-51)
newtype CReal = CReal {approx :: Complete Base}
unsafeMkCReal = CReal
inject :: Base -> CReal
inject x = CReal (unit x)
{- The real number is assumed to lie within the closed interval -}
type BoundedCReal = (CReal,Interval Base)
around :: CReal -> Integer
around (CReal f) = round (f (1/2))
integerInterval f = Interval (i-1, i+1)
where
i = fromInteger $ around f
compact :: CReal -> BoundedCReal
compact x = (x,integerInterval x)
choke :: BoundedCReal -> CReal
choke (CReal x, (Interval (lb,ub))) = CReal f
where
f eps | y < lb = lb
| ub < y = ub
| otherwise = y
where
y = x eps
{- produces a regular function whose resulting approximations are
small in memory size -}
compress :: Complete Base -> Complete Base
compress x eps = approxBase (x (eps/2)) (eps/2)
compress' (CReal x) = CReal (compress x)
mapCR f (CReal x) = CReal $ compress $ mapC f x
mapCR2 f (CReal x) (CReal y) = CReal $ compress $ mapC2 f x y
bindR f (CReal x) = CReal $ compress $ bind f x
instance Show CReal where
show x = error "Cannot show a CReal"
{- show x = show $ map (\n -> squish x ((1/2)^n)) [0..] -}
approxRange :: CReal -> Gauge -> Interval Base
approxRange x eps = Interval (r-eps, r+eps)
where
r = approx x eps
{- proveNonZeroFrom will not terminate if the input is 0 -}
{- Finds some y st 0 < (abs y) <= (abs x) -}
proveNonZeroFrom :: Gauge -> CReal -> Base
proveNonZeroFrom g r | high < 0 = high
| 0 < low = low
| otherwise = proveNonZeroFrom (g / (2 ^ 32)) r
where
Interval (low, high) = approxRange r g
proveNonZero x = proveNonZeroFrom 1 x
negateCts = mkUniformCts id negate
realNegate :: CReal -> CReal
realNegate = mapCR negateCts
plusBaseCts :: Base -> Base :=> Base
plusBaseCts a = mkUniformCts id (a+)
realTranslate :: Base -> CReal -> CReal
realTranslate a = mapCR (plusBaseCts a)
plusCts :: Base :=> Base :=> Base
plusCts = mkUniformCts id plusBaseCts
realPlus :: CReal -> CReal -> CReal
realPlus = mapCR2 plusCts
-- (==) never returns True.
instance Eq CReal where
a==b = 0==proveNonZero (realPlus a (realNegate b))
multBaseCts :: Base -> Base :=> Base
multBaseCts 0 = constCts 0
multBaseCts a = mkUniformCts mu (a*)
where
mu eps = eps/(abs a)
realScale :: Base -> CReal -> CReal
realScale a = mapCR (multBaseCts a)
{- \x -> (\y -> (x*y)) is uniformly continuous on the domain (abs y) <= maxy -}
multUniformCts :: Base -> Base :=> Base :=> Base
multUniformCts maxy = mkUniformCts mu multBaseCts
where
mu eps = assert (maxy>0) (eps/maxy)
{- We need to bound the value of x or y. I think it is better to bound
x so I actually compute y*x -}
realMultBound :: BoundedCReal -> CReal -> CReal
realMultBound (x,i) y = mapCR2 (multUniformCts b) y (choke (x,i))
where
b = bound i
absCts = mkUniformCts id abs
realAbs :: CReal -> CReal
realAbs = mapCR absCts
instance Num CReal where
(+) = realPlus
x * y = realMultBound (compact x) y
negate = realNegate
abs = realAbs
signum = inject . signum . proveNonZero
fromInteger = inject . fromInteger
{- domain is (-inf, nonZero] if nonZero < 0
domain is [nonZero, inf) if nonZero > 0 -}
recipUniformCts :: Base -> Base :=> Base
recipUniformCts nonZero = mkUniformCts mu f
where
f a | 0 <= nonZero = recip (max nonZero a)
| otherwise = recip (min a nonZero)
mu eps = eps*(nonZero^2)
realRecipWitness :: Base -> CReal -> CReal
realRecipWitness nonZero = mapCR (recipUniformCts nonZero)
instance Fractional CReal where
recip x = realRecipWitness (proveNonZero x) x
fromRational = inject . fromRational
intPowerCts _ 0 = constCts 1
intPowerCts maxx n = mkUniformCts mu (^n)
where
mu eps = assert (maxx > 0) $ eps/((fromIntegral n)*(maxx^(n-1)))
realPowerIntBound :: (Integral b) => BoundedCReal -> b -> CReal
realPowerIntBound (x,i) n = mapCR (intPowerCts b n) (choke (x,i))
where
b = bound i
realPowerInt :: (Integral b) => CReal -> b -> CReal
realPowerInt = realPowerIntBound . compact
polynomialUniformCts :: Interval Base ->
Polynomial Base -> Base :=> Base
polynomialUniformCts i p |maxSlope == 0 = constCts (evalP p 0)
|otherwise = mkUniformCts mu (evalP p)
where
maxSlope = bound $ boundPolynomial i (dx p)
mu eps = assert (maxSlope > 0) $ eps/maxSlope
realBasePolynomialBound :: Polynomial Base -> BoundedCReal -> CReal
realBasePolynomialBound p (x,i) = mapCR (polynomialUniformCts i p) (choke (x,i))
class MultinomialUniformCts i p r | i p -> r where
multinomialUniformCts :: i -> p -> r
instance MultinomialUniformCts (Interval Base) (Polynomial Base) (Base :=> Base)
where
multinomialUniformCts = polynomialUniformCts
instance (MultinomialUniformCts i p r, VectorQ p, Num p,
BoundPolynomial i p) =>
MultinomialUniformCts (Interval Base,i) (Polynomial p) (Base :=> r)
where
multinomialUniformCts i p | maxSlope == 0 = constCts $
multinomialUniformCts (snd i) (evalP p 0)
| otherwise = mkUniformCts mu $
\x -> multinomialUniformCts (snd i) (evalP p (x<*>1))
where
maxSlope = bound $ boundPolynomial i (dx p)
mu eps = assert (maxSlope > 0) $ eps/maxSlope
realBasePolynomial2Bound ::
Polynomial (Polynomial Base) -> BoundedCReal -> BoundedCReal -> CReal
realBasePolynomial2Bound p (x,i) (y,j) =
mapCR2 (multinomialUniformCts (i,j) p)
(choke (x,i)) (choke (y,j))
{- only valid for x <= ln(2). Works best for |x| <= 1/2 -}
rationalSmallExp :: Base -> CReal
rationalSmallExp x = assert ((abs x)<=(1/2)) $
CReal $ expTaylorApprox
where
m | x <= 0 = 1
| otherwise = 2
expTaylorApprox eps =
sumBase terms
where
terms = takeWhile highError $ zipWith (\x y -> x/(fromInteger y)) (powers x) factorials
highError t = m*(abs t) >= eps
rationalExp :: Base -> Base -> CReal
rationalExp tol x | (abs x) <= tol = rationalSmallExp x
| otherwise = realPowerInt (rationalExp tol (x/2)) 2
expUniformCts :: Integer -> Base :=> (Complete Base)
expUniformCts upperBound = mkUniformCts mu (approx . rationalExp radius)
where
mu eps | upperBound <= 0 = eps*(2^(-upperBound))
| otherwise = eps/(3^upperBound)
realExpBound :: BoundedCReal -> CReal
realExpBound a@(x,(Interval (_,ub))) =
bindR (expUniformCts (ceiling ub)) (choke a)
{-Requires that abs(a!!i+1) < abs(a!!i) and the sign of the terms alternate -}
alternatingSeries :: [Base] -> Complete Base
alternatingSeries a eps = sumBase partSeries
where
partSeries = (takeWhile (\x -> (abs x) > eps) a)
rationalSin :: Base -> Base -> CReal
rationalSin tol x | tol <= (abs x) =
realBasePolynomialBound (3*xP - 4*xP^3)
((rationalSin tol (x/3)),Interval (-1,1))
| otherwise = CReal (alternatingSeries series)
where
series = fst $ unzip $ iterate (\(t,n) -> (-t*(x^2)/(n^2+n),n+2)) (x, 2)
sinCts :: Base :=> (Complete Base)
sinCts = mkUniformCts id (approx . rationalSin radius)
realSin :: CReal -> CReal
realSin = bindR sinCts
{-
realSin :: CReal -> CReal
realSin x | 0==m = realSlowSin x'
| 1==m = realSlowCos x'
| 2==m = negate $ realSlowSin x'
| 3==m = negate $ realSlowCos x'
where
n = around (x / realPi2)
m = n `mod` 4
x' = x - (realScale (fromInteger n) realPi2)
-}
rationalCos :: Base -> Base -> CReal
rationalCos tol x = realBasePolynomialBound (1-2*xP^2)
((rationalSin tol (x/2)),Interval (-1,1))
cosCts :: Base :=> (Complete Base)
cosCts = mkUniformCts id (approx . rationalCos radius)
realCos :: CReal -> CReal
realCos = bindR cosCts
{-
realCos :: CReal -> CReal
realCos x | 3==m = realSlowSin x'
| 0==m = realSlowCos x'
| 1==m = negate $ realSlowSin x'
| 2==m = negate $ realSlowCos x'
where
n = around (x / realPi2)
m = n `mod` 4
x' = x - (realScale (fromInteger n) realPi2)
-}
{- computes ln(x). only valid for 1<=x<2 -}
rationalSmallLn :: Base -> CReal
rationalSmallLn x = assert (1<=x && x<=(3/2)) $
CReal $ alternatingSeries (zipWith (*) (poly 1) (tail (powers (x-1))))
where
poly n = (1/n):(-1/(n+1)):(poly (n+2))
{- requires that 0<=x -}
rationalLn :: Base -> CReal
rationalLn x | x<1 = negate (posLn (recip x))
| otherwise = posLn x
where
ln43 = rationalSmallLn (4/3)
ln2 = wideLn 2
{- good for 1<=x<=2 -}
wideLn x | x < (3/2) = rationalSmallLn x
| otherwise = (rationalSmallLn ((3/4)*x)) + ln43
{- requires that 1<=x -}
posLn x | n==0 = wideLn x
| otherwise = (wideLn x') + (realScale n ln2)
where
(x',n) = until (\(x,n) -> (x<=2)) (\(x,n) -> (x/2,n+1)) (x,0)
{- domain is [nonZero, inf) -}
lnUniformCts :: Base -> Base :=> (Complete Base)
lnUniformCts nonZero = mkUniformCts mu f
where
f x = approx $ rationalLn (max x nonZero)
mu eps = assert (nonZero > 0) $ eps*nonZero
realLnWitness :: Base -> CReal -> CReal
realLnWitness nonZero = bindR (lnUniformCts nonZero)
{- only valid for (abs x) < 1 -}
rationalSmallArcTan :: Base -> CReal
rationalSmallArcTan x = assert ((abs x)<(1/2)) $ CReal $
alternatingSeries (zipWith (\x y->x*(y^2)) (series 0) (powers x))
where
series n = (x/(n+1)):(-x/(n+3)):(series (n+4))
rationalArcTan :: Base -> CReal
rationalArcTan x | x <= (-1/2) = negate $ posArcTan $ negate x
| otherwise = posArcTan x
where
{-requires (-1/2) < x-}
posArcTan x | 2 < x = realPi2 - rationalSmallArcTan (recip x)
| (1/2) <= x = realPi4 + rationalSmallArcTan y
| otherwise = rationalSmallArcTan x
where
y = (x-1)/(x+1)
arcTanCts :: Base :=> (Complete Base)
arcTanCts = mkUniformCts id (approx . rationalArcTan)
realArcTan :: CReal -> CReal
realArcTan = bindR arcTanCts
{- Computes x * Pi -}
{- http://aemes.mae.ufl.edu/~uhk/PI.html -}
scalePi :: Base -> CReal
scalePi x =
((realScale (x*48) (rationalSmallArcTan (1/38))) +
(realScale (x*80) (rationalSmallArcTan (1/57)))) +
((realScale (x*28) (rationalSmallArcTan (1/239))) +
(realScale (x*96) (rationalSmallArcTan (1/268))))
real2Pi = scalePi 2
realPi = scalePi 1
realPi2 = scalePi (1/2)
realPi4 = scalePi (1/4)
{- Wolfram's algorithm -}
rationalSqrt :: Base -> CReal
rationalSqrt n | n < 1 = realScale (1/2) (rationalSqrt (4*n))
| 4 <= n = realScale 2 (rationalSqrt (n/4))
| otherwise = CReal f
where
f eps = vf*ef/8
where
(_,vf,ef) = until (\(u,v,e) -> e <= eps) wolfram (n, 0, 4)
wolfram (u,v,e) | u >= v + 1 = (4*(u-v-1), 2*(v+2), e/2)
| otherwise = (4*u, 2*v, e/2)
sqrtCts :: Base :=> (Complete Base)
sqrtCts = mkUniformCts (^2) (approx . rationalSqrt)
realSqrt :: CReal -> CReal
realSqrt = bindR sqrtCts
instance Floating CReal where
exp x = realExpBound (compact x)
log x = realLnWitness (proveNonZero x) x
pi = realPi
sin = realSin
cos = realCos
atan = realArcTan
sqrt = realSqrt
sinh x = realScale (1/2) (exp x - (exp (-x)))
cosh x = realScale (1/2) (exp x + (exp (-x)))
asin x = atan (x/sqrt(realTranslate 1 (negate (realPowerInt x 2))))
acos x = realPi2 - asin x
acosh x = log (x+sqrt(realTranslate (-1) (realPowerInt x 2)))
asinh x = log (x+sqrt(realTranslate 1 (realPowerInt x 2)))
atanh x = realScale (1/2)
(log ((realTranslate 1 x) / (realTranslate 1 (negate x))))
{- best for (abs x) < 1 -}
rationalErrorFunction :: Base -> CReal
rationalErrorFunction x = (2/(sqrt pi)*) . CReal $
alternatingSeries (zipWith (\x y->x*(y^2)) (series 0) (powers x))
where
series n = (x/((2*n'+1)*facts!!n)):(-x/((2*n'+3)*(facts!!(n+1)))):
(series (n+2))
where
facts = map (fromIntegral) factorials
n' = fromIntegral n
erfCts :: Base :=> (Complete Base)
erfCts = mkUniformCts mu (approx . rationalErrorFunction)
where
mu eps = eps*(4/5)
realErrorFunction :: CReal -> CReal
realErrorFunction = bindR erfCts
sumRealList :: [CReal] -> CReal
sumRealList [] = inject 0
sumRealList l = CReal (\eps -> sum (map (\x -> approx x (eps/n)) l))
where
n = fromIntegral $ length l
{- testing stuff is below -}
test0 = CReal id
answer n x = shows (around (realScale (10^n) x))
"x10^-"++(show n)
| robbertkrebbers/fewdigits | Data/Real/CReal.hs | bsd-2-clause | 13,570 | 0 | 16 | 3,127 | 5,192 | 2,710 | 2,482 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Applicative.Singletons
-- Copyright : (C) 2018 Ryan Scott
-- License : BSD-style (see LICENSE)
-- Maintainer : Ryan Scott
-- Stability : experimental
-- Portability : non-portable
--
-- Defines the promoted and singled versions of the 'Applicative' type class.
--
----------------------------------------------------------------------------
module Control.Applicative.Singletons (
PApplicative(..), SApplicative(..),
PAlternative(..), SAlternative(..),
Sing, SConst(..), Const, GetConst, sGetConst,
type (<$>), (%<$>), type (<$), (%<$), type (<**>), (%<**>),
LiftA, sLiftA, LiftA3, sLiftA3, Optional, sOptional,
-- * Defunctionalization symbols
PureSym0, PureSym1,
type (<*>@#@$), type (<*>@#@$$), type (<*>@#@$$$),
type (*>@#@$), type (*>@#@$$), type (*>@#@$$$),
type (<*@#@$), type (<*@#@$$), type (<*@#@$$$),
EmptySym0, type (<|>@#@$), type (<|>@#@$$), type (<|>@#@$$$),
ConstSym0, ConstSym1, GetConstSym0, GetConstSym1,
type (<$>@#@$), type (<$>@#@$$), type (<$>@#@$$$),
type (<$@#@$), type (<$@#@$$), type (<$@#@$$$),
type (<**>@#@$), type (<**>@#@$$), type (<**>@#@$$$),
LiftASym0, LiftASym1, LiftASym2,
LiftA2Sym0, LiftA2Sym1, LiftA2Sym2, LiftA2Sym3,
LiftA3Sym0, LiftA3Sym1, LiftA3Sym2, LiftA3Sym3,
OptionalSym0, OptionalSym1
) where
import Control.Applicative
import Control.Monad.Singletons.Internal
import Data.Functor.Const.Singletons
import Data.Functor.Singletons
import Data.Monoid.Singletons
import Data.Ord (Down(..))
import Data.Ord.Singletons
import Data.Singletons.Base.Instances
import Data.Singletons.TH
$(singletonsOnly [d|
-- -| One or none.
optional :: Alternative f => f a -> f (Maybe a)
optional v = Just <$> v <|> pure Nothing
instance Monoid a => Applicative ((,) a) where
pure x = (mempty, x)
(u, f) <*> (v, x) = (u `mappend` v, f x)
liftA2 f (u, x) (v, y) = (u `mappend` v, f x y)
instance Applicative Down where
pure = Down
Down f <*> Down x = Down (f x)
|])
| goldfirere/singletons | singletons-base/src/Control/Applicative/Singletons.hs | bsd-3-clause | 2,271 | 0 | 7 | 380 | 413 | 292 | 121 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-- | Hides away distracting bookkeeping while lambda lifting into a 'LiftM'
-- monad.
module GHC.Stg.Lift.Monad (
decomposeStgBinding, mkStgBinding,
Env (..),
-- * #floats# Handling floats
-- $floats
FloatLang (..), collectFloats, -- Exported just for the docs
-- * Transformation monad
LiftM, runLiftM,
-- ** Adding bindings
startBindingGroup, endBindingGroup, addTopStringLit, addLiftedBinding,
-- ** Substitution and binders
withSubstBndr, withSubstBndrs, withLiftedBndr, withLiftedBndrs,
-- ** Occurrences
substOcc, isLifted, formerFreeVars, liftedIdsExpander
) where
#include "HsVersions.h"
import GhcPrelude
import BasicTypes
import CostCentre ( isCurrentCCS, dontCareCCS )
import DynFlags
import FastString
import Id
import Name
import Outputable
import OrdList
import GHC.Stg.Subst
import GHC.Stg.Syntax
import Type
import UniqSupply
import Util
import VarEnv
import VarSet
import Control.Arrow ( second )
import Control.Monad.Trans.Class
import Control.Monad.Trans.RWS.Strict ( RWST, runRWST )
import qualified Control.Monad.Trans.RWS.Strict as RWS
import Control.Monad.Trans.Cont ( ContT (..) )
import Data.ByteString ( ByteString )
-- | @uncurry 'mkStgBinding' . 'decomposeStgBinding' = id@
decomposeStgBinding :: GenStgBinding pass -> (RecFlag, [(BinderP pass, GenStgRhs pass)])
decomposeStgBinding (StgRec pairs) = (Recursive, pairs)
decomposeStgBinding (StgNonRec bndr rhs) = (NonRecursive, [(bndr, rhs)])
mkStgBinding :: RecFlag -> [(BinderP pass, GenStgRhs pass)] -> GenStgBinding pass
mkStgBinding Recursive = StgRec
mkStgBinding NonRecursive = uncurry StgNonRec . head
-- | Environment threaded around in a scoped, @Reader@-like fashion.
data Env
= Env
{ e_dflags :: !DynFlags
-- ^ Read-only.
, e_subst :: !Subst
-- ^ We need to track the renamings of local 'InId's to their lifted 'OutId',
-- because shadowing might make a closure's free variables unavailable at its
-- call sites. Consider:
-- @
-- let f y = x + y in let x = 4 in f x
-- @
-- Here, @f@ can't be lifted to top-level, because its free variable @x@ isn't
-- available at its call site.
, e_expansions :: !(IdEnv DIdSet)
-- ^ Lifted 'Id's don't occur as free variables in any closure anymore, because
-- they are bound at the top-level. Every occurrence must supply the formerly
-- free variables of the lifted 'Id', so they in turn become free variables of
-- the call sites. This environment tracks this expansion from lifted 'Id's to
-- their free variables.
--
-- 'InId's to 'OutId's.
--
-- Invariant: 'Id's not present in this map won't be substituted.
}
emptyEnv :: DynFlags -> Env
emptyEnv dflags = Env dflags emptySubst emptyVarEnv
-- Note [Handling floats]
-- ~~~~~~~~~~~~~~~~~~~~~~
-- $floats
-- Consider the following expression:
--
-- @
-- f x =
-- let g y = ... f y ...
-- in g x
-- @
--
-- What happens when we want to lift @g@? Normally, we'd put the lifted @l_g@
-- binding above the binding for @f@:
--
-- @
-- g f y = ... f y ...
-- f x = g f x
-- @
--
-- But this very unnecessarily turns a known call to @f@ into an unknown one, in
-- addition to complicating matters for the analysis.
-- Instead, we'd really like to put both functions in the same recursive group,
-- thereby preserving the known call:
--
-- @
-- Rec {
-- g y = ... f y ...
-- f x = g x
-- }
-- @
--
-- But we don't want this to happen for just /any/ binding. That would create
-- possibly huge recursive groups in the process, calling for an occurrence
-- analyser on STG.
-- So, we need to track when we lift a binding out of a recursive RHS and add
-- the binding to the same recursive group as the enclosing recursive binding
-- (which must have either already been at the top-level or decided to be
-- lifted itself in order to preserve the known call).
--
-- This is done by expressing this kind of nesting structure as a 'Writer' over
-- @['FloatLang']@ and flattening this expression in 'runLiftM' by a call to
-- 'collectFloats'.
-- API-wise, the analysis will not need to know about the whole 'FloatLang'
-- business and will just manipulate it indirectly through actions in 'LiftM'.
-- | We need to detect when we are lifting something out of the RHS of a
-- recursive binding (c.f. "GHC.Stg.Lift.Monad#floats"), in which case that
-- binding needs to be added to the same top-level recursive group. This
-- requires we detect a certain nesting structure, which is encoded by
-- 'StartBindingGroup' and 'EndBindingGroup'.
--
-- Although 'collectFloats' will only ever care if the current binding to be
-- lifted (through 'LiftedBinding') will occur inside such a binding group or
-- not, e.g. doesn't care about the nesting level as long as its greater than 0.
data FloatLang
= StartBindingGroup
| EndBindingGroup
| PlainTopBinding OutStgTopBinding
| LiftedBinding OutStgBinding
instance Outputable FloatLang where
ppr StartBindingGroup = char '('
ppr EndBindingGroup = char ')'
ppr (PlainTopBinding StgTopStringLit{}) = text "<str>"
ppr (PlainTopBinding (StgTopLifted b)) = ppr (LiftedBinding b)
ppr (LiftedBinding bind) = (if isRec rec then char 'r' else char 'n') <+> ppr (map fst pairs)
where
(rec, pairs) = decomposeStgBinding bind
-- | Flattens an expression in @['FloatLang']@ into an STG program, see #floats.
-- Important pre-conditions: The nesting of opening 'StartBindinGroup's and
-- closing 'EndBindinGroup's is balanced. Also, it is crucial that every binding
-- group has at least one recursive binding inside. Otherwise there's no point
-- in announcing the binding group in the first place and an @ASSERT@ will
-- trigger.
collectFloats :: [FloatLang] -> [OutStgTopBinding]
collectFloats = go (0 :: Int) []
where
go 0 [] [] = []
go _ _ [] = pprPanic "collectFloats" (text "unterminated group")
go n binds (f:rest) = case f of
StartBindingGroup -> go (n+1) binds rest
EndBindingGroup
| n == 0 -> pprPanic "collectFloats" (text "no group to end")
| n == 1 -> StgTopLifted (merge_binds binds) : go 0 [] rest
| otherwise -> go (n-1) binds rest
PlainTopBinding top_bind
| n == 0 -> top_bind : go n binds rest
| otherwise -> pprPanic "collectFloats" (text "plain top binding inside group")
LiftedBinding bind
| n == 0 -> StgTopLifted (rm_cccs bind) : go n binds rest
| otherwise -> go n (bind:binds) rest
map_rhss f = uncurry mkStgBinding . second (map (second f)) . decomposeStgBinding
rm_cccs = map_rhss removeRhsCCCS
merge_binds binds = ASSERT( any is_rec binds )
StgRec (concatMap (snd . decomposeStgBinding . rm_cccs) binds)
is_rec StgRec{} = True
is_rec _ = False
-- | Omitting this makes for strange closure allocation schemes that crash the
-- GC.
removeRhsCCCS :: GenStgRhs pass -> GenStgRhs pass
removeRhsCCCS (StgRhsClosure ext ccs upd bndrs body)
| isCurrentCCS ccs
= StgRhsClosure ext dontCareCCS upd bndrs body
removeRhsCCCS (StgRhsCon ccs con args)
| isCurrentCCS ccs
= StgRhsCon dontCareCCS con args
removeRhsCCCS rhs = rhs
-- | The analysis monad consists of the following 'RWST' components:
--
-- * 'Env': Reader-like context. Contains a substitution, info about how
-- how lifted identifiers are to be expanded into applications and details
-- such as 'DynFlags'.
--
-- * @'OrdList' 'FloatLang'@: Writer output for the resulting STG program.
--
-- * No pure state component
--
-- * But wrapping around 'UniqSM' for generating fresh lifted binders.
-- (The @uniqAway@ approach could give the same name to two different
-- lifted binders, so this is necessary.)
newtype LiftM a
= LiftM { unwrapLiftM :: RWST Env (OrdList FloatLang) () UniqSM a }
deriving (Functor, Applicative, Monad)
instance HasDynFlags LiftM where
getDynFlags = LiftM (RWS.asks e_dflags)
instance MonadUnique LiftM where
getUniqueSupplyM = LiftM (lift getUniqueSupplyM)
getUniqueM = LiftM (lift getUniqueM)
getUniquesM = LiftM (lift getUniquesM)
runLiftM :: DynFlags -> UniqSupply -> LiftM () -> [OutStgTopBinding]
runLiftM dflags us (LiftM m) = collectFloats (fromOL floats)
where
(_, _, floats) = initUs_ us (runRWST m (emptyEnv dflags) ())
-- | Writes a plain 'StgTopStringLit' to the output.
addTopStringLit :: OutId -> ByteString -> LiftM ()
addTopStringLit id = LiftM . RWS.tell . unitOL . PlainTopBinding . StgTopStringLit id
-- | Starts a recursive binding group. See #floats# and 'collectFloats'.
startBindingGroup :: LiftM ()
startBindingGroup = LiftM $ RWS.tell $ unitOL $ StartBindingGroup
-- | Ends a recursive binding group. See #floats# and 'collectFloats'.
endBindingGroup :: LiftM ()
endBindingGroup = LiftM $ RWS.tell $ unitOL $ EndBindingGroup
-- | Lifts a binding to top-level. Depending on whether it's declared inside
-- a recursive RHS (see #floats# and 'collectFloats'), this might be added to
-- an existing recursive top-level binding group.
addLiftedBinding :: OutStgBinding -> LiftM ()
addLiftedBinding = LiftM . RWS.tell . unitOL . LiftedBinding
-- | Takes a binder and a continuation which is called with the substituted
-- binder. The continuation will be evaluated in a 'LiftM' context in which that
-- binder is deemed in scope. Think of it as a 'RWS.local' computation: After
-- the continuation finishes, the new binding won't be in scope anymore.
withSubstBndr :: Id -> (Id -> LiftM a) -> LiftM a
withSubstBndr bndr inner = LiftM $ do
subst <- RWS.asks e_subst
let (bndr', subst') = substBndr bndr subst
RWS.local (\e -> e { e_subst = subst' }) (unwrapLiftM (inner bndr'))
-- | See 'withSubstBndr'.
withSubstBndrs :: Traversable f => f Id -> (f Id -> LiftM a) -> LiftM a
withSubstBndrs = runContT . traverse (ContT . withSubstBndr)
-- | Similarly to 'withSubstBndr', this function takes a set of variables to
-- abstract over, the binder to lift (and generate a fresh, substituted name
-- for) and a continuation in which that fresh, lifted binder is in scope.
--
-- It takes care of all the details involved with copying and adjusting the
-- binder and fresh name generation.
withLiftedBndr :: DIdSet -> Id -> (Id -> LiftM a) -> LiftM a
withLiftedBndr abs_ids bndr inner = do
uniq <- getUniqueM
let str = "$l" ++ occNameString (getOccName bndr)
let ty = mkLamTypes (dVarSetElems abs_ids) (idType bndr)
let bndr'
-- See Note [transferPolyIdInfo] in Id.hs. We need to do this at least
-- for arity information.
= transferPolyIdInfo bndr (dVarSetElems abs_ids)
. mkSysLocal (mkFastString str) uniq
$ ty
LiftM $ RWS.local
(\e -> e
{ e_subst = extendSubst bndr bndr' $ extendInScope bndr' $ e_subst e
, e_expansions = extendVarEnv (e_expansions e) bndr abs_ids
})
(unwrapLiftM (inner bndr'))
-- | See 'withLiftedBndr'.
withLiftedBndrs :: Traversable f => DIdSet -> f Id -> (f Id -> LiftM a) -> LiftM a
withLiftedBndrs abs_ids = runContT . traverse (ContT . withLiftedBndr abs_ids)
-- | Substitutes a binder /occurrence/, which was brought in scope earlier by
-- 'withSubstBndr'\/'withLiftedBndr'.
substOcc :: Id -> LiftM Id
substOcc id = LiftM (RWS.asks (lookupIdSubst id . e_subst))
-- | Whether the given binding was decided to be lambda lifted.
isLifted :: InId -> LiftM Bool
isLifted bndr = LiftM (RWS.asks (elemVarEnv bndr . e_expansions))
-- | Returns an empty list for a binding that was not lifted and the list of all
-- local variables the binding abstracts over (so, exactly the additional
-- arguments at adjusted call sites) otherwise.
formerFreeVars :: InId -> LiftM [OutId]
formerFreeVars f = LiftM $ do
expansions <- RWS.asks e_expansions
pure $ case lookupVarEnv expansions f of
Nothing -> []
Just fvs -> dVarSetElems fvs
-- | Creates an /expander function/ for the current set of lifted binders.
-- This expander function will replace any 'InId' by their corresponding 'OutId'
-- and, in addition, will expand any lifted binders by the former free variables
-- it abstracts over.
liftedIdsExpander :: LiftM (DIdSet -> DIdSet)
liftedIdsExpander = LiftM $ do
expansions <- RWS.asks e_expansions
subst <- RWS.asks e_subst
-- We use @noWarnLookupIdSubst@ here in order to suppress "not in scope"
-- warnings generated by 'lookupIdSubst' due to local bindings within RHS.
-- These are not in the InScopeSet of @subst@ and extending the InScopeSet in
-- @goodToLift@/@closureGrowth@ before passing it on to @expander@ is too much
-- trouble.
let go set fv = case lookupVarEnv expansions fv of
Nothing -> extendDVarSet set (noWarnLookupIdSubst fv subst) -- Not lifted
Just fvs' -> unionDVarSet set fvs'
let expander fvs = foldl' go emptyDVarSet (dVarSetElems fvs)
pure expander
| sdiehl/ghc | compiler/GHC/Stg/Lift/Monad.hs | bsd-3-clause | 12,947 | 0 | 16 | 2,556 | 2,332 | 1,256 | 1,076 | 156 | 7 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.SamplerObjects
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.SamplerObjects (
-- * Extension Support
glGetARBSamplerObjects,
gl_ARB_sampler_objects,
-- * Enums
pattern GL_SAMPLER_BINDING,
-- * Functions
glBindSampler,
glDeleteSamplers,
glGenSamplers,
glGetSamplerParameterIiv,
glGetSamplerParameterIuiv,
glGetSamplerParameterfv,
glGetSamplerParameteriv,
glIsSampler,
glSamplerParameterIiv,
glSamplerParameterIuiv,
glSamplerParameterf,
glSamplerParameterfv,
glSamplerParameteri,
glSamplerParameteriv
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/ARB/SamplerObjects.hs | bsd-3-clause | 1,024 | 0 | 5 | 140 | 96 | 69 | 27 | 22 | 0 |
module Main(main) where
import Weeder
import System.Exit
import System.Environment
import Control.Monad
main :: IO ()
main = do
bad <- weeder =<< getArgs
when (bad > 0) exitFailure
| ndmitchell/weeder | src/Main.hs | bsd-3-clause | 191 | 0 | 9 | 38 | 68 | 37 | 31 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ElmBot (eval) where
import qualified System.IO.Silently as Sys
import qualified Environment as Env
import qualified Eval.Code as Elm
eval :: String -> IO String
eval s = fst <$> Sys.capture (run s)
run :: String -> IO ()
run s = Env.run (Env.empty "elm-make" "node") (Elm.eval (Nothing, s))
| svanderbleek/elm-bot | src/ElmBot.hs | bsd-3-clause | 337 | 0 | 8 | 57 | 121 | 69 | 52 | 9 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module NotifSpec
( spec
)
where
import Kis
import Control.Concurrent
import Control.Exception.Base
import Control.Monad
import Data.Time.Clock
import System.IO.Temp
import Test.Hspec
import qualified Data.Aeson as J
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text as T
type RequestType = T.Text
spec :: Spec
spec = do
describe "runKis" $ do
it "can be run with single service" $ do
collectedNotifs <- newMVar []
let client =
do bed <- createBed "xy"
pat <- createPatient (Patient "Simon")
void $ placePatient pat bed
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [client] [simpleNotifHandler collectedNotifs "notif1"] (T.pack fp)
notifs <- takeMVar collectedNotifs
tail notifs `shouldBe`
[ T.pack (show (CreatePatient (Patient "Simon")))
, T.pack (show (CreateBed "xy"))
]
describe "Notification handlers" $ do
it "are notified of Notifications" $
do mvar1 <- newMVar []
mvar2 <- newMVar []
let client1 = void $ createPatient $ Patient "Simon"
client2 =
do void $ createBed "xy"
void $ createPatient (Patient "Thomas")
void getPatients
nh1 = simpleNotifHandler mvar1 "notifH1"
nh2 = simpleNotifHandler mvar2 "notifH2"
allHandlers = [nh1, nh2]
allClients = [client1, client2]
prop l =
T.pack (show (CreatePatient $ Patient "Simon")) `elem` l
&& T.pack (show (CreatePatient $ Patient "Thomas")) `elem` l
&& T.pack (show (CreateBed "xy")) `elem` l
&& length l == 3
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis allClients allHandlers (T.pack fp)
notifList1 <- takeMVar mvar1
notifList2 <- takeMVar mvar2
notifList1 `shouldSatisfy` prop
notifList2 `shouldSatisfy` prop
it "does not block if nothing happens in service" $
(withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [] [] (T.pack fp))
-- ^ The reason for this test was a bug where the notifications thread
-- was blocked and didnt wakeup on the stop signal.
it "can use the Kis interface to access DB" $
do resMvar <- newEmptyMVar
let client =
do pat <- createPatient $ Patient "Simon"
bed <- createBed "xy"
void $ placePatient pat bed
saveFunction :: (Monad m, KisRead m) => (KisRequest a, a) -> m (Maybe BS.ByteString)
saveFunction (request, _) =
case request of
PlacePatient patId _ ->
do patient <- getPatient patId
return $ Just (BSL.toStrict (J.encode patient))
_ -> return Nothing
processFunction _ bs =
putMVar resMvar res
where Just res = J.decode (BSL.fromStrict bs)
nh = NotificationHandler saveFunction processFunction "nh1"
withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [client] [nh] (T.pack fp)
result <- takeMVar resMvar
result `shouldBe` Patient "Simon"
it "cannot add two notifHandlers with equal signature" $
let nh1 = NotificationHandler (\_ -> return Nothing) (\_ _ -> return ()) "nh1"
in (withTempFile "/tmp/" "tmpKisDB" $ \fp _ ->
runKis [] [nh1, nh1] (T.pack fp))
`shouldThrow` (== ErrorCall "two notifhandlers with the same signature were added")
it "correctly reads notification timestamps" $
withTempFile "/tmp/" "tmpKisDB" $ \dbFile _ ->
do currentTime <- getCurrentTime
let processNotif timestamp _ = timestamp `shouldBe` currentTime
nh = NotificationHandler (\_ -> return (Just "")) processNotif "nh"
run kis = runClient kis (void $ createPatient (Patient "Simon"))
poolBackend = PoolBackendType (T.pack dbFile) 10
void $ withSqliteKisWithNotifs poolBackend (KisConfig (constClock currentTime)) [nh] run
simpleNotifHandler :: MVar [RequestType] -> T.Text -> NotificationHandler
simpleNotifHandler notifList sig =
NotificationHandler
{ nh_saveNotif = saveRequest
, nh_processNotif = processNotification notifList
, nh_signature = sig
}
saveRequest ::
(Monad m, KisRead m)
=> (KisRequest a, a)
-> m (Maybe BS.ByteString)
saveRequest (request, _) =
return (Just $ BSL.toStrict (J.encode (T.pack (show request))))
processNotification :: MVar [RequestType] -> UTCTime -> BS.ByteString -> IO ()
processNotification notifList _ payload =
do oldList <- takeMVar notifList
let Just reqType = J.decode (BSL.fromStrict payload)
putMVar notifList (reqType:oldList)
| lslah/kis-proto | test/NotifSpec.hs | bsd-3-clause | 5,385 | 0 | 28 | 1,914 | 1,463 | 728 | 735 | 109 | 2 |
module Util.HTML
( Html
, Attribute
, Attributable
, renderHtml
, toHtml
, attribute
, empty
, parent
, leaf
, makeAttr
, makePar
, makeLeaf
, (!)
, ($<)
) where
import Data.Monoid
data HtmlM a
= Parent !String -- ^ Tag
!String -- ^ Opening tag
!String
!String -- ^ Closing tag
!(HtmlM a) -- ^ Child element
| Leaf !String -- ^ Tag
!String -- ^ Opening tag
!String -- ^ Closing tag
| Content !String -- ^ HTML content
| forall b c.
Append (HtmlM b) -- ^ Concatenation of two
(HtmlM c) -- ^ HTML elements
| Attr !String -- ^ Raw key
!String -- ^ Attribute key
!String -- ^ Attribute value
!(HtmlM a) -- ^ Target element
| Empty -- ^ Empty element
type Html = HtmlM ()
data Attribute = Attribute !String !String !String
instance Monoid a => Monoid (HtmlM a) where
mempty = Empty
mappend = Append
mconcat = foldr Append Empty
instance Monad HtmlM where
return _ = Empty
(>>) = Append
h1 >>= f = h1 >> f (error "")
class Attributable h where
(!) :: h -> Attribute -> h
instance Attributable (HtmlM a) where
(!) h (Attribute raw key val) = Attr raw key val h
instance Attributable (HtmlM a -> HtmlM b) where
(!) f (Attribute raw key val) = Attr raw key val . f
renderHtml :: HtmlM t -> String
renderHtml = go ""
where go :: String -> HtmlM t -> String
go s (Parent _ open r close content)
= open ++ s ++ r ++ renderHtml content ++ close
go s (Leaf _ open close)
= open ++ s ++ close
go s (Content content) = escapeHtmlEntities content
go s (Append h1 h2) = go s h1 ++ go s h2
go s (Attr _ key value h)
= flip go h
$ key
++ escapeHtmlEntities value
++ "\""
++ s
go _ Empty = ""
escapeHtmlEntities :: String -> String
escapeHtmlEntities "" = ""
escapeHtmlEntities (c:cs) =
let c' = case c of
'<' -> "<"
'>' -> ">"
'&' -> "&"
'"' -> """
'\'' -> "'"
x -> [x]
in c' ++ escapeHtmlEntities cs
attribute :: String -> String -> String -> Attribute
attribute = Attribute
empty :: Html
empty = Empty
parent :: String -> String -> String -> String -> Html -> Html
parent = Parent
leaf :: String -> String -> String -> Html
leaf = Leaf
toHtml :: String -> HtmlM a
toHtml = Content
makeAttr :: String -> String -> Attribute
makeAttr a = Attribute a (' ':a ++ "=\"")
makePar :: String -> Html -> Html
makePar h = Parent h ('<':h) ">" ("</" ++ h ++ ">")
makeLeaf :: String -> Html
makeLeaf a = Leaf a ('<':a) ">"
-- Shorthand infix operator
($<) :: (Html -> Html) -> String -> Html
($<) a = a . toHtml
| johanneshilden/liquid-epsilon | Util/HTML.hs | bsd-3-clause | 3,029 | 0 | 12 | 1,116 | 971 | 511 | 460 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Development.Shake.Internal.Rules.Rerun(
defaultRuleRerun, alwaysRerun
) where
import Development.Shake.Internal.Core.Rules
import Development.Shake.Internal.Core.Types
import Development.Shake.Internal.Core.Build
import Development.Shake.Internal.Core.Action
import Development.Shake.Classes
import qualified Data.ByteString as BS
import General.Binary
newtype AlwaysRerunQ = AlwaysRerunQ ()
deriving (Typeable,Eq,Hashable,Binary,BinaryEx,NFData)
instance Show AlwaysRerunQ where show _ = "alwaysRerun"
type instance RuleResult AlwaysRerunQ = ()
-- | Always rerun the associated action. Useful for defining rules that query
-- the environment. For example:
--
-- @
-- \"ghcVersion.txt\" 'Development.Shake.%>' \\out -> do
-- 'alwaysRerun'
-- 'Development.Shake.Stdout' stdout <- 'Development.Shake.cmd' \"ghc --numeric-version\"
-- 'Development.Shake.writeFileChanged' out stdout
-- @
--
-- In @make@, the @.PHONY@ attribute on file-producing rules has a similar effect.
--
-- Note that 'alwaysRerun' is applied when a rule is executed. Modifying an existing rule
-- to insert 'alwaysRerun' will /not/ cause that rule to rerun next time.
alwaysRerun :: Action ()
alwaysRerun = do
historyDisable
apply1 $ AlwaysRerunQ ()
defaultRuleRerun :: Rules ()
defaultRuleRerun =
addBuiltinRuleEx noLint noIdentity $
\AlwaysRerunQ{} _ _ -> pure $ RunResult ChangedRecomputeDiff BS.empty ()
| ndmitchell/shake | src/Development/Shake/Internal/Rules/Rerun.hs | bsd-3-clause | 1,560 | 0 | 9 | 231 | 231 | 140 | 91 | 23 | 1 |
{-# LANGUAGE QuantifiedConstraints #-}
module Error
( Err
, runErr
, throw
, throwMany
, context
, contextShow
, fromEither
, fromEitherShow
, note
, sequenceV
, traverseV
, traverseV_
, forV
, forV_
, HasErr
, Sem
)
where
import Data.Vector as V
hiding ( toList )
import Polysemy
import qualified Polysemy.Error as E
import Relude
import Validation
type Err = E.Error (Vector Text)
type HasErr r = MemberWithError Err r
runErr :: forall r a. Sem (Err ': r) a -> Sem r (Either (Vector Text) a)
runErr = E.runError
throw :: forall r a. MemberWithError Err r => Text -> Sem r a
throw = E.throw . singleton
throwMany
:: forall r f a . (MemberWithError Err r, Foldable f) => f Text -> Sem r a
throwMany = E.throw . V.fromList . toList
context :: forall r a . MemberWithError Err r => Text -> Sem r a -> Sem r a
context c m = E.catch @(Vector Text) m $ \e -> E.throw ((c <> ":" <+>) <$> e)
contextShow
:: forall c r a . (Show c, MemberWithError Err r) => c -> Sem r a -> Sem r a
contextShow = context . show
fromEither :: MemberWithError Err r => Either Text a -> Sem r a
fromEither = E.fromEither . first singleton
fromEitherShow :: (Show e, MemberWithError Err r) => Either e a -> Sem r a
fromEitherShow = fromEither . first show
note :: MemberWithError Err r => Text -> Maybe a -> Sem r a
note e = \case
Nothing -> throw e
Just x -> pure x
sequenceV
:: forall f r a . (Traversable f, HasErr r) => f (Sem r a) -> Sem r (f a)
sequenceV xs = do
vs <- traverse
(\x -> E.catch @(Vector Text) (Success <$> x) (pure . Failure))
xs
case sequenceA vs of
Success as -> pure as
Failure es -> E.throw es
traverseV
:: forall f r a b
. (Traversable f, HasErr r)
=> (a -> Sem r b)
-> f a
-> Sem r (f b)
traverseV f = sequenceV . fmap f
traverseV_
:: forall f r a b
. (Foldable f, HasErr r)
=> (a -> Sem r b)
-> f a
-> Sem r ()
traverseV_ f = void . traverseV f . toList
forV
:: forall f r a b
. (Traversable f, HasErr r)
=> f a
-> (a -> Sem r b)
-> Sem r (f b)
forV = flip traverseV
forV_
:: forall f r a
. (Foldable f, HasErr r)
=> f a
-> (a -> Sem r ())
-> Sem r ()
forV_ = flip traverseV_
infixr 5 <+>
(<+>) :: (Semigroup a, IsString a) => a -> a -> a
a <+> b = a <> " " <> b
| expipiplus1/vulkan | generate-new/src/Error.hs | bsd-3-clause | 2,402 | 0 | 14 | 712 | 1,059 | 558 | 501 | -1 | -1 |
module Main where
import qualified Web.JWTTests
import qualified Web.JWTInteropTests
import qualified Web.Base64Tests
import qualified Data.Text.ExtendedTests
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "JWT Tests" [
Web.JWTTests.defaultTestGroup
, Web.JWTInteropTests.defaultTestGroup
, Web.Base64Tests.defaultTestGroup
, Data.Text.ExtendedTests.defaultTestGroup
]
| bitemyapp/haskell-jwt | tests/src/TestRunner.hs | mit | 519 | 0 | 7 | 146 | 92 | 57 | 35 | 14 | 1 |
module Data.Kicad.PcbnewExpr
(
-- * Types
PcbnewExpr(..)
-- * Parse
, parse
, parseWithFilename
, fromSExpr
-- * Write
, pretty
, write
)
where
import Data.Kicad.PcbnewExpr.PcbnewExpr
import Data.Kicad.PcbnewExpr.Parse
import Data.Kicad.PcbnewExpr.Write
| kasbah/haskell-kicad-data | Data/Kicad/PcbnewExpr.hs | mit | 256 | 0 | 5 | 33 | 55 | 39 | 16 | 11 | 0 |
module Workspaces where
import XMonad (WorkspaceId)
-- | Workspaces, a 3x3 grid of workspaces
bl = "1: Workflow" -- Bottom Left
bm = "2: Etc" -- Bottom Middle
br = "3: Mail" -- Bottom Right
ml = "4: Terminal" -- Middle Left
mm = "5: Development" -- Middle Middle
mr = "6: Internet" -- Middle Right
tl = "7: Chat" -- Top Left
tm = "8: Etc" -- Top Middle
tr = "9: Clip" -- Top Right
-- | Where to send applications
workflow_ws = bl
mail_ws = br
web_ws = mr
-- | The workspaces list
myWorkspaces :: [WorkspaceId]
myWorkspaces =
[
tl, tm, tr,
ml, mm, mr,
bl, bm, br
]
-- | The workspace that will be on screen after launch
startupWorkspace = mr
| NorfairKing/sus-depot | shared/shared/xmonad/azerty/Workspaces.hs | gpl-2.0 | 808 | 0 | 5 | 294 | 130 | 86 | 44 | 21 | 1 |
module Nirum.Constructs.TypeExpressionSpec where
import Test.Hspec.Meta
import Nirum.Constructs.TypeExpression (TypeExpression (..), toCode)
spec :: Spec
spec =
describe "toCode TypeExpression" $ do
context "TypeIdentifier" $
it "reverses the given tree to the code string" $ do
toCode (TypeIdentifier "text") `shouldBe` "text"
toCode (TypeIdentifier "enum") `shouldBe` "`enum`"
context "OptionModifier" $
it "reverses the given tree to the code string" $ do
toCode (OptionModifier "text") `shouldBe` "text?"
toCode (OptionModifier $ SetModifier "text")
`shouldBe` "{text}?"
context "SetModifier" $
it "reverses the given tree to the code string" $ do
toCode (SetModifier "text") `shouldBe` "{text}"
toCode (SetModifier $ OptionModifier "text")
`shouldBe` "{text?}"
context "ListModifier" $
it "reverses the given tree to the code string" $
toCode (ListModifier "text") `shouldBe` "[text]"
context "MapModifier" $
it "reverses the given tree to the code string" $ do
toCode (MapModifier "uuid" "text") `shouldBe` "{uuid: text}"
toCode (MapModifier "uuid" $ ListModifier "text")
`shouldBe` "{uuid: [text]}"
| spoqa/nirum | test/Nirum/Constructs/TypeExpressionSpec.hs | gpl-3.0 | 1,417 | 0 | 15 | 455 | 309 | 153 | 156 | 28 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Acquire.Game.Player where
import Acquire.Game.Hotels
import Acquire.Game.Tiles
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..),
object, (.:), (.=))
import qualified Data.Map as M
import GHC.Generics
data PlayerType = Human | Robot deriving (Eq, Show, Read, Generic)
instance ToJSON PlayerType
instance FromJSON PlayerType
newtype Stock = Stock { stock :: M.Map ChainName Int }
deriving (Eq, Show, Read)
emptyStock :: Stock
emptyStock = Stock M.empty
stockLookup :: ChainName -> Stock -> Maybe Int
stockLookup chain (Stock s) = M.lookup chain s
alterStock :: (Maybe Int -> Maybe Int) -> ChainName -> Stock -> Stock
alterStock f chain (Stock s) = Stock $ M.alter f chain s
adjustStock :: (Int -> Int) -> ChainName -> Stock -> Stock
adjustStock f chain (Stock s) = Stock $ M.adjust f chain s
mapStock :: (ChainName -> Int -> a) -> Stock -> M.Map ChainName a
mapStock f (Stock s) = M.mapWithKey f s
listStock :: Stock -> [(ChainName, Int)]
listStock (Stock s) = M.toList s
findOr0 :: ChainName -> Stock -> Int
findOr0 chain (Stock s) = M.findWithDefault 0 chain s
instance ToJSON Stock where
toJSON (Stock s) = object [ "stock" .= M.toList s ]
instance FromJSON Stock where
parseJSON (Object o) = Stock <$>
(M.fromList <$> o .: "stock")
parseJSON v = fail $ "Cannot parse Stock from JSON " ++ show v
data Player = Player { playerName :: PlayerName
, playerType :: PlayerType
, tiles :: [ Tile ]
, ownedStock :: Stock
, ownedCash :: Int
} deriving (Eq, Show, Read, Generic)
instance ToJSON Player
instance FromJSON Player
type Players = M.Map PlayerName Player
type PlayerName = String
isHuman :: Player -> Bool
isHuman (playerType -> Human) = True
isHuman _ = False
isRobot :: Player -> Bool
isRobot (playerType -> Robot) = True
isRobot _ = False
hasEnoughMoneyToBuyStock :: Player -> HotelChain -> Bool
hasEnoughMoneyToBuyStock player chain = let price = stockPrice chain
in ownedCash player >= price
| abailly/hsgames | acquire/src/Acquire/Game/Player.hs | apache-2.0 | 2,371 | 0 | 10 | 692 | 750 | 403 | 347 | 54 | 1 |
{-| Utility functions for the maintenance daemon.
-}
{-
Copyright (C) 2015 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.MaintD.Utils
( annotateOpCode
) where
import Control.Lens.Setter (over)
import qualified Ganeti.Constants as C
import Ganeti.JQueue (reasonTrailTimestamp)
import Ganeti.JQueue.Objects (Timestamp)
import Ganeti.OpCodes (OpCode, MetaOpCode, wrapOpCode)
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
-- | Wrap an `OpCode` into a `MetaOpCode` and adding an indication
-- that the `OpCode` was submitted by the maintenance daemon.
annotateOpCode :: String -> Timestamp -> OpCode -> MetaOpCode
annotateOpCode reason ts =
over (metaParamsL . opReasonL)
(++ [(C.opcodeReasonSrcMaintd, reason, reasonTrailTimestamp ts)])
. wrapOpCode
| bitemyapp/ganeti | src/Ganeti/MaintD/Utils.hs | bsd-2-clause | 2,013 | 0 | 10 | 302 | 150 | 92 | 58 | 13 | 1 |
-- |
-- Utility functions for Mailchimp
--
module Web.Mailchimp.Util
where
import Control.Monad (mzero)
import Data.Aeson (ToJSON(..), FromJSON(..), Value(..), object)
import Data.Text (pack, unpack)
import Data.Char (isAlpha, toLower, isUpper)
import Data.Time.Clock (UTCTime)
import Data.Time.Format (formatTime, parseTime)
import System.Locale (defaultTimeLocale)
-- | Creates Aeson objects after filtering to remove null values.
filterObject list =
object $ filter notNothing list
where
notNothing (_, Null) = False
notNothing _ = True
-- | Represents times in the format expected by Mailchimp's API
newtype MCTime = MCTime {unMCTime :: UTCTime}
deriving (Show, Eq)
mcFormatString :: String
mcFormatString = "%F %T"
instance ToJSON MCTime where
toJSON (MCTime t) = String $ pack $ formatTime defaultTimeLocale mcFormatString t
instance FromJSON MCTime where
parseJSON (String s) = maybe mzero (return . MCTime) $ parseTime defaultTimeLocale mcFormatString (unpack s)
parseJSON _ = mzero
-- | Removes the first Int characters of string, then converts from CamelCase to underscore_case.
-- For use by Aeson template haskell calls.
convertName :: Int -> String -> String
convertName prefixLength pname =
toLower (head name) : camelToUnderscore (tail name)
where
name = drop prefixLength pname
-- | Converts camelcase identifiers to underscored identifiers
camelToUnderscore (x : y : xs) | isAlpha x, isUpper y =
x : '_' : camelToUnderscore (toLower y : xs)
camelToUnderscore (x : xs) = x : camelToUnderscore xs
camelToUnderscore x = x
| tlaitinen/mailchimp | Web/Mailchimp/Util.hs | bsd-3-clause | 1,584 | 0 | 12 | 272 | 434 | 238 | 196 | 29 | 3 |
{-# LANGUAGE
DeriveFunctor,
DeriveFoldable,
DeriveTraversable,
NoMonomorphismRestriction,
GeneralizedNewtypeDeriving,
StandaloneDeriving,
TypeFamilies,
ViewPatterns,
MultiParamTypeClasses,
TypeSynonymInstances, -- TODO remove
FlexibleInstances,
OverloadedStrings,
TypeOperators
#-}
module Trans (
-- * Internal
Trans,
tapp,
runTrans,
TList,
tlist,
tlapp,
tlappWhen,
runTList,
-- Tree,
-- MTree,
-- TMTree,
-- * Transformations
Time,
Dur,
Pitch,
Frequency,
Amplitude,
-- * Score
Behaviour,
Articulation,
Score,
runScore,
)
where
import Data.Monoid.Action
import Data.Monoid.MList -- misplaced Action () instance
import Data.Key
import Data.Default
import Data.Basis
import Data.Maybe
import Data.AffineSpace
import Data.AffineSpace.Point
import Data.AdditiveGroup hiding (Sum, getSum)
import Data.VectorSpace hiding (Sum, getSum)
import Data.LinearMap
import Control.Monad
import Control.Monad.Plus
import Control.Arrow
import Control.Applicative
import Control.Monad.Writer hiding ((<>))
import Data.String
import Data.Semigroup
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import qualified Diagrams.Core.Transform as D
{-
Compare
- Update Monads: Cointerpreting directed containers
-}
-- |
-- 'Trans' is a restricted version of the 'Writer' monad.
--
newtype Trans m a = Trans (Writer m a)
deriving (Monad, MonadWriter m, Functor, Applicative, Foldable, Traversable)
instance (Monoid m, Monoid a) => Semigroup (Trans m a) where
-- TODO not sure this must require Monoid m
Trans w <> Trans u = writer $ runWriter w `mappend` runWriter u
instance (Monoid m, Monoid a) => Monoid (Trans m a) where
mempty = return mempty
mappend = (<>)
type instance Key (Trans m) = m
instance Keyed (Trans m) where
mapWithKey f (Trans w) = Trans $ mapWriter (\(a,w) -> (f w a, w)) w
{-
Alternative implementation:
newtype Write m a = Write (a, m)
deriving (Show, Functor, Foldable, Traversable)
instance Monoid m => Monad (Write m) where
return x = Write (x, mempty)
Write (x1,m1) >>= f = let
Write (x2,m2) = f x1
in Write (x2,m1 `mappend` m2)
Write (x1,m1) >> y = let
Write (x2,m2) = y
in Write (x2,m1 `mappend` m2)
-}
{-
Same thing with orinary pairs:
deriving instance Monoid m => Foldable ((,) m)
deriving instance Monoid m => Traversable ((,) m)
instance Monoid m => Monad ((,) m) where
return x = (mempty, x)
(m1,x1) >>= f = let
(m2,x2) = f x1
in (m1 `mappend` m2,x2)
-}
{-
newtype LTrans m a = LTrans { getLTrans :: Trans m [a] }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
Trans m [a]
Trans m [Trans m [a]] -- fmap (fmap f)
Trans m (Trans m [[a]]) -- fmap sequence
Trans m (Trans m [a]) -- fmap (fmap join)
Trans m [a] -- join
This is NOT equivalent to TList, it will compose transformations over the
*entire* list using monadic sequencing rather than *propagating* the traversion over the list
Compare:
> runTransWith (fmap.appEndo) $ T.sequence $ fmap (tapp (e (+1)) . Trans . return) [1,2,3]
> fmap (runTransWith appEndo) $ T.sequence $ (tapp (e (+1)) . Trans . return) [1,2,3]
-}
{-
TODO
Assure consistency of act with fmap
We need something like:
> tlapp m . fmap g = fmap (act m . g)
> fmap g . tlapp m = fmap (g . act m)
Can this be derived from the Action laws (satisfied for Endo).
> act mempty = id
> act (m1 `mappend` m2) = act m1 . act m2
Try
> fmap g . tlapp m = fmap (g . act m)
-- tlapp law
> fmap g . fmap (tapp m) = fmap (g . act m)
-- definition
> fmap (g . tapp m) = fmap (g . act m)
-- functor law
Need to prove
> fmap (g . tapp m) = fmap (g . act m)
-- theorem
> fmap (g . (tell m >>)) = fmap (g . act m)
-- definition
> fmap (g . (Write ((), m) >>)) = fmap (g . act m)
-- definition
> fmap (g . (\x -> Write ((), m) >> x)) = fmap (g . act m)
-- expand section
> fmap (g . (\Write (x2,m2) -> Write ((), m) >> Write (x2,m2))) = fmap (g . act m)
-- expand
> fmap (g . (\Write (x2,m2) -> Write (x2,m <> m2))) = fmap (g . act m)
-- expand
> \Write (x2,m2) -> Write (x2,m <> m2))) = act m
-- simplify
> act mempty = id
> act (m1 `mappend` m2) = act m1 . act m2
Try
> fmap g . tlapp m = fmap (g . act m)
-- tlapp law
> fmap g . fmap (ar . tapp m) = fmap (g . act m)
-- definition
> fmap (g . ar . tapp m) = fmap (g . act m)
-- functor law
Need to prove
> fmap (g . ar . tapp m) = fmap (g . act m)
-- theorem
> fmap (g . ar . (tell m >>)) = fmap (g . act m)
-- definition
> fmap (g . ar . (Write ((), m) >>)) = fmap (g . act m)
-- definition
> fmap (g . ar . (\x -> Write ((), m) >> x)) = fmap (g . act m)
-- expand section
> fmap (g . ar . (\Write (x2,m2) -> Write ((), m) >> Write (x2,m2))) = fmap (g . act m)
-- expand
> fmap (g . ar . (\Write (x2,m2) -> Write (x2,m <> m2))) = fmap (g . act m)
-- expand
> ar . \Write (x2,m2) -> Write (x2,m <> m2) = act m
-- simplify
> return . uncurry (flip act) . runWriter . \Write (x2,m2) -> Write (x2,m <> m2) = act m
-- simplify
> return . uncurry (flip act) . \(x2,m2) -> (x2,m <> m2))) = act m
-- removes Write wrapper
> (\x -> (x,mempty)) . uncurry (flip act) . \(x2,m2) -> (x2,m <> m2) = act m
> (\x -> (uncurry (flip act) x,mempty)) . \(x2,m2) -> (x2,m <> m2) = act m
> (\(x,m2) -> (act m2 x, mempty)) . fmap (m <>) = act m
> (\(x,m2) -> (act (m <> m2) x, mempty)) = act m
ar = return . uncurry (flip act) . runWriter
tell w = Write ((), w)
Write (_,m1) >> Write (x2,m2) = Write (x2,m1 `mappend` m2)
-}
-- |
-- Transformable list.
--
-- > type TList m a = [Trans m a]
--
-- See Jones and Duponcheel, /Composing Monads/ (1993).
--
newtype TList m a = TList { getTList :: [Trans m a] }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TList m a) where
fromString = return . fromString
instance Monoid m => Applicative (TList m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TList m) where
return = TList . return . return
TList xs >>= f = TList $ join . fmap (fmap join . T.sequence . fmap (getTList . f)) $ xs
instance Monoid m => MonadPlus (TList m) where
mzero = mempty
mplus = (<>)
type instance Key (TList m) = m
instance Keyed (TList m) where
mapWithKey f (TList xs) = TList $ fmap (mapWithKey f) xs
-- [Trans m a]
-- [Trans m [Trans m a]] -- fmap (fmap f)
-- [[Trans m (Trans m a)]] -- fmap sequence
-- [[Trans m a]] -- fmap (fmap join)
-- [Trans m a] -- join
runTrans :: Action m a => Trans m a -> a
runTrans = runTransWith act
runTransWith :: (m -> a -> a) -> Trans m a -> a
runTransWith f = uncurry (flip f) . renderTrans
assureRun :: (Monoid m, Action m a) => Trans m a -> Trans m a
assureRun = return . runTrans
renderTrans :: Trans m a -> (a, m)
renderTrans (Trans x) = runWriter x
-- |
-- > tapp m = fmap (act m)
tapp :: (Action m a, Monoid m) => m -> Trans m a -> Trans m a
tapp m = assureRun . tapp' m
tapp' :: Monoid m => m -> Trans m a -> Trans m a
tapp' m = (tell m >>)
-- | Construct a 'TList' from a transformation and a list.
tlist :: (Action m a, Monoid m) => m -> [a] -> TList m a
tlist m xs = tlapp m (fromList xs)
-- | Construct a 'TList' from a list.
fromList :: Monoid m => [a] -> TList m a
fromList = mfromList
-- | Transform a list.
--
-- > tlapp m = fmap (act m)
--
-- TODO does it follow:
--
-- > tlapp (f <> g) = tlapp f . tlapp g
--
tlapp :: (Action m a, Monoid m) => m -> TList m a -> TList m a
tlapp m (TList xs) = TList $ fmap (tapp m) xs
-- FIXME violates which law?
-- | Transform a list if the predicate holds.
--
tlappWhen :: (Action m a, Monoid m) => (a -> Bool) -> m -> TList m a -> TList m a
tlappWhen p f xs = let (ts, fs) = mpartition p xs
in tlapp f ts `mplus` fs
-- | Extract the components.
runTList :: Action m a => TList m a -> [a]
runTList (TList xs) = fmap runTrans xs
-- | Extract the components using the supplied function to render the cached transformations.
runTListWith :: (m -> a -> a) -> TList m a -> [a]
runTListWith f (TList xs) = fmap (runTransWith f) xs
-- FIXME not what you'd expect!
getTListMonoid :: Monoid m => TList m a -> m
getTListMonoid = mconcat . runTListWith (const) . fmap (const undefined)
-- | Extract the components and cached transformations.
renderTList :: TList m a -> [(a, m)]
renderTList (TList xs) = fmap renderTrans xs
data Tree a = Tip a | Bin (Tree a) (Tree a)
deriving (Functor, Foldable, Traversable)
instance Semigroup (Tree a) where
(<>) = Bin
-- TODO Default
instance Monoid a => Monoid (Tree a) where
mempty = Tip mempty
mappend = (<>)
instance Monad Tree where
return = Tip
Tip x >>= f = f x
Bin x y >>= f = Bin (x >>= f) (y >>= f)
newtype TTree m a = TTree { getTTree :: Tree (Trans m a) }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TTree m a) where
fromString = return . fromString
instance Monoid m => Applicative (TTree m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TTree m) where
return = TTree . return . return
TTree xs >>= f = TTree $ join . fmap (fmap join . T.mapM (getTTree . f)) $ xs
newtype MTree a = MTree { getMTree :: (Maybe (Tree a)) }
deriving (Semigroup, Functor, Foldable, Traversable)
instance Monoid (MTree a) where
mempty = MTree Nothing
mappend = (<>)
instance Monad MTree where
return = MTree . return . return
MTree xs >>= f = MTree $ join . fmap (fmap join . T.mapM (getMTree . f)) $ xs
instance MonadPlus MTree where
mzero = mempty
mplus = (<>)
newtype TMTree m a = TMTree { getTMTree :: MTree (Trans m a) }
deriving (Semigroup, Monoid, Functor, Foldable, Traversable)
instance (IsString a, Monoid m) => IsString (TMTree m a) where
fromString = return . fromString
instance Monoid m => Applicative (TMTree m) where
pure = return
(<*>) = ap
instance Monoid m => Monad (TMTree m) where
return = TMTree . return . return
TMTree xs >>= f = TMTree $ join . fmap (fmap join . T.mapM (getTMTree . f)) $ xs
instance Monoid m => MonadPlus (TMTree m) where
mzero = mempty
mplus = (<>)
{-
----------------------------------------------------------------------
-- Minimal API
type Transformation t p a = TT ::: PT ::: AT ::: () -- Monoid
class HasTransformation a where
makeTransformation :: a -> Transformation t p a
instance HasTransformation TT where
makeTransformation = inj
instance HasTransformation PT where
makeTransformation = inj
instance HasTransformation AT where
makeTransformation = inj
-- Use identity if no such transformation
get' = option mempty id . get
transform :: Transformation t p a -> (Amplitude,Pitch,Span) -> (Amplitude,Pitch,Span)
transform u (a,p,s) = (a2,p2,s2)
where
a2 = act (get' u :: AT) a
p2 = act (get' u :: PT) p
s2 = act (get' u :: TT) s
----------------------------------------------------------------------
newtype TT = TT (D.Transformation Span)
deriving (Monoid, Semigroup)
-- TODO generalize all of these from TT to arbitrary T
instance Action TT Span where
act (TT t) = unPoint . D.papply t . P
delaying :: Time -> Transformation t p a
delaying x = makeTransformation $ TT $ D.translation (x,0)
stretching :: Dur -> Transformation t p a
stretching = makeTransformation . TT . D.scaling
----------------------------------------------------------------------
newtype PT = PT (D.Transformation Pitch)
deriving (Monoid, Semigroup)
instance Action PT Pitch where
act (PT t) = unPoint . D.papply t . P
transposing :: Pitch -> Transformation t p a
transposing x = makeTransformation $ PT $ D.translation x
----------------------------------------------------------------------
newtype AT = AT (D.Transformation Amplitude)
deriving (Monoid, Semigroup)
instance Action AT Amplitude where
act (AT t) = unPoint . D.papply t . P
amplifying :: Amplitude -> Transformation t p a
amplifying = makeTransformation . AT . D.scaling
----------------------------------------------------------------------
-- Accumulate transformations
delay x = tlapp (delaying x)
stretch x = tlapp (stretching x)
transpose x = tlapp (transposing x)
amplify x = tlapp (amplifying x)
-}
type Time = Double
type Dur = Double
type Span = (Time, Dur)
type Pitch = Double
type Amplitude = Double
-- foo :: Score String
-- foo = stretch 2 $ "c" <> (delay 1 ("d" <> stretch 0.1 "e"))
--
-- foo :: Score String
-- foo = amplify 2 $ transpose 1 $ delay 2 $ "c"
type Onset = Sum Time
type Offset = Sum Time
type Frequency = Double
type Part = Int
type Behaviour a = Time -> a
type R2 = (Double, Double)
-- Time transformation is a function that acts over (time,dur) notes by ?
-- Pitch transformation is a pitch function that acts over notes by fmap
-- Dynamic transformation is a pitch function that acts over notes by fmap
-- Space transformation is a pitch function that acts over notes by fmap
-- Part transformation is a pitch function that acts over notes by fmap
-- (Most part functions are const!)
-- Articulation is a transformation that acts over (pitch, dynamics, onset, offset) by ?
type Articulation = (Endo (Pitch -> Pitch), Endo (Amplitude -> Amplitude))
{-
return x
-}
type Score a = TList
((Sum Time, Sum Time),
(Time -> Product Pitch, Time -> Product Amplitude),
Option (Data.Semigroup.Last Part),
Time -> Endo (R2 -> R2),
Time -> Articulation
)
(Either Pitch (Behaviour Pitch),
Either Amplitude (Behaviour Amplitude),
Part,
Behaviour R2,
a)
foo :: Score a
foo = undefined
-- This requires the transformation type to be a Monoid
bar = join (return foo)
-- runScore :: {-(Action m-type n-type) =>-} Score a -> [n-type]
runScore = runTList . asScore
asScore = (id :: Score a -> Score a)
{-
Time:
For each note: onset and onset (or equivalently onset and duration)
Optionally more paramters such as pre-onset, post-onset, post-offset
[preOn A on D postOn S off R postOff]
Pitch:
For each note a custom pitch value (usually Common.Pitch)
Optionally for each note a gliss/slide curve, indicating shape to next note
(generally a simple slope function)
Alternatively, for each part a (Behaviour Frequency) etc
Dynamics:
For each note an integral dynamic value (usually Common.Level)
Optionally for each note a cresc/dim curve, indicating shape to next note
(generally a simple slope function)
Alternatively, for each part a (Behaviour Amplitude) etc
Part:
For each note an ordered integral (or fractional) indicator of instrument and/or subpart
Space:
For each note a point in R2 or R3
Alternatively, for each part a (Behaviour R2) etc
Misc/Timbre:
Instrument changes, playing technique or timbral changes, i.e "sul pont -> sul tasto"
Articulation:
Affects pitch, dynamics and timbre
-}
-- ((0.0,2.0),"c")
-- ((2.0,2.0),"d")
-- ((2.0,0.2),"e")
-- ((["stretch 2.0"],(0,1)),"c")
-- ((["stretch 2.0","delay 1.0"],(0,1)),"d")
-- ((["stretch 2.0","delay 1.0","stretch 0.1"],(0,1)),"e")
-- (0,1)
-- (0,0.5)
-- (1,0.5)
-- (2,1)
{-
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e, Monoid f) => Monoid (a,b,c,d,e,f) where
mempty = (mempty,mempty,mempty,mempty,mempty)
(a,b,c,d,e,f) `mappend` (a1,b1,c1,d1,e1,f1) =
(a <> a1, b <> b1, c <> c1, d <> d1, e <> e1, f <> f1)
where (<>) = mappend
-}
{-
unpack3 :: ((a, b), c) -> (a, b, c)
unpack4 :: (((a, b), c), d) -> (a, b, c, d)
unpack5 :: ((((a, b), c), d), e) -> (a, b, c, d, e)
unpack6 :: (((((a, b), c), d), e), f) -> (a, b, c, d, e, f)
unpack3 ((c,b),a) = (c,b,a)
unpack4 ((unpack3 -> (d,c,b),a)) = (d,c,b,a)
unpack5 ((unpack4 -> (e,d,c,b),a)) = (e,d,c,b,a)
unpack6 ((unpack5 -> (f,e,d,c,b),a)) = (f,e,d,c,b,a)
pack3 :: (b, c, a) -> ((b, c), a)
pack4 :: (c, d, b, a) -> (((c, d), b), a)
pack5 :: (d, e, c, b, a) -> ((((d, e), c), b), a)
pack6 :: (e, f, d, c, b, a) -> (((((e, f), d), c), b), a)
pack3 (c,b,a) = ((c,b),a)
pack4 (d,c,b,a) = (pack3 (d,c,b),a)
pack5 (e,d,c,b,a) = (pack4 (e,d,c,b),a)
pack6 (f,e,d,c,b,a) = (pack5 (f,e,d,c,b),a)
-}
{-
-- TODO move
mapplyIf :: (Functor f, MonadPlus f) => (a -> Maybe a) -> f a -> f a
mapplyIf f = mapplyWhen (predicate f) (fromMaybe (error "mapplyIf") . f)
mapplyWhen :: (Functor f, MonadPlus f) => (a -> Bool) -> (a -> a) -> f a -> f a
mapplyWhen p f xs = let (ts, fs) = mpartition p xs
in fmap f ts `mplus` fs
-}
e = Endo
appE = tlapp . e
appWhenE p = tlappWhen p . e
default (Integer)
test :: [Integer]
test = runTList $
appWhenE (/= (0::Integer)) (*(10::Integer)) $ (return (-1)) <> return 2
main = print test
swap (x,y) = (y,x)
-- FIXME move
instance Action (Endo a) a where
act = appEndo
| FranklinChen/music-score | sketch/old/trans/trans.hs | bsd-3-clause | 17,874 | 0 | 13 | 4,750 | 2,783 | 1,528 | 1,255 | 193 | 1 |
{-# LANGUAGE CPP #-}
module System.Console.CmdArgs.Explicit.Type where
import Control.Arrow
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
#if __GLASGOW_HASKELL__ < 709
import Data.Monoid
#endif
-- | A name, either the name of a flag (@--/foo/@) or the name of a mode.
type Name = String
-- | A help message that goes with either a flag or a mode.
type Help = String
-- | The type of a flag, i.e. @--foo=/TYPE/@.
type FlagHelp = String
---------------------------------------------------------------------
-- UTILITY
-- | Parse a boolean, accepts as True: true yes on enabled 1.
parseBool :: String -> Maybe Bool
parseBool s | ls `elem` true = Just True
| ls `elem` false = Just False
| otherwise = Nothing
where
ls = map toLower s
true = ["true","yes","on","enabled","1"]
false = ["false","no","off","disabled","0"]
---------------------------------------------------------------------
-- GROUPS
-- | A group of items (modes or flags). The items are treated as a list, but the
-- group structure is used when displaying the help message.
data Group a = Group
{groupUnnamed :: [a] -- ^ Normal items.
,groupHidden :: [a] -- ^ Items that are hidden (not displayed in the help message).
,groupNamed :: [(Help, [a])] -- ^ Items that have been grouped, along with a description of each group.
} deriving Show
instance Functor Group where
fmap f (Group a b c) = Group (map f a) (map f b) (map (second $ map f) c)
instance Monoid (Group a) where
mempty = Group [] [] []
mappend (Group x1 x2 x3) (Group y1 y2 y3) = Group (x1++y1) (x2++y2) (x3++y3)
-- | Convert a group into a list.
fromGroup :: Group a -> [a]
fromGroup (Group x y z) = x ++ y ++ concatMap snd z
-- | Convert a list into a group, placing all fields in 'groupUnnamed'.
toGroup :: [a] -> Group a
toGroup x = Group x [] []
---------------------------------------------------------------------
-- TYPES
-- | A mode. Do not use the 'Mode' constructor directly, instead
-- use 'mode' to construct the 'Mode' and then record updates.
-- Each mode has three main features:
--
-- * A list of submodes ('modeGroupModes')
--
-- * A list of flags ('modeGroupFlags')
--
-- * Optionally an unnamed argument ('modeArgs')
--
-- To produce the help information for a mode, either use 'helpText' or 'show'.
data Mode a = Mode
{modeGroupModes :: Group (Mode a) -- ^ The available sub-modes
,modeNames :: [Name] -- ^ The names assigned to this mode (for the root mode, this name is used as the program name)
,modeValue :: a -- ^ Value to start with
,modeCheck :: a -> Either String a -- ^ Check the value reprsented by a mode is correct, after applying all flags
,modeReform :: a -> Maybe [String] -- ^ Given a value, try to generate the input arguments.
,modeExpandAt :: Bool -- ^ Expand @\@@ arguments with 'expandArgsAt', defaults to 'True', only applied if using an 'IO' processing function.
-- Only the root 'Mode's value will be used.
,modeHelp :: Help -- ^ Help text
,modeHelpSuffix :: [String] -- ^ A longer help suffix displayed after a mode
,modeArgs :: ([Arg a], Maybe (Arg a)) -- ^ The unnamed arguments, a series of arguments, followed optionally by one for all remaining slots
,modeGroupFlags :: Group (Flag a) -- ^ Groups of flags
}
-- | Extract the modes from a 'Mode'
modeModes :: Mode a -> [Mode a]
modeModes = fromGroup . modeGroupModes
-- | Extract the flags from a 'Mode'
modeFlags :: Mode a -> [Flag a]
modeFlags = fromGroup . modeGroupFlags
-- | The 'FlagInfo' type has the following meaning:
--
--
-- > FlagReq FlagOpt FlagOptRare/FlagNone
-- > -xfoo -x=foo -x=foo -x -foo
-- > -x foo -x=foo -x foo -x foo
-- > -x=foo -x=foo -x=foo -x=foo
-- > --xx foo --xx=foo --xx foo --xx foo
-- > --xx=foo --xx=foo --xx=foo --xx=foo
data FlagInfo
= FlagReq -- ^ Required argument
| FlagOpt String -- ^ Optional argument
| FlagOptRare String -- ^ Optional argument that requires an = before the value
| FlagNone -- ^ No argument
deriving (Eq,Ord,Show)
-- | Extract the value from inside a 'FlagOpt' or 'FlagOptRare', or raises an error.
fromFlagOpt :: FlagInfo -> String
fromFlagOpt (FlagOpt x) = x
fromFlagOpt (FlagOptRare x) = x
-- | A function to take a string, and a value, and either produce an error message
-- (@Left@), or a modified value (@Right@).
type Update a = String -> a -> Either String a
-- | A flag, consisting of a list of flag names and other information.
data Flag a = Flag
{flagNames :: [Name] -- ^ The names for the flag.
,flagInfo :: FlagInfo -- ^ Information about a flag's arguments.
,flagValue :: Update a -- ^ The way of processing a flag.
,flagType :: FlagHelp -- ^ The type of data for the flag argument, i.e. FILE\/DIR\/EXT
,flagHelp :: Help -- ^ The help message associated with this flag.
}
-- | An unnamed argument. Anything not starting with @-@ is considered an argument,
-- apart from @\"-\"@ which is considered to be the argument @\"-\"@, and any arguments
-- following @\"--\"@. For example:
--
-- > programname arg1 -j - --foo arg3 -- -arg4 --arg5=1 arg6
--
-- Would have the arguments:
--
-- > ["arg1","-","arg3","-arg4","--arg5=1","arg6"]
data Arg a = Arg
{argValue :: Update a -- ^ A way of processing the argument.
,argType :: FlagHelp -- ^ The type of data for the argument, i.e. FILE\/DIR\/EXT
,argRequire :: Bool -- ^ Is at least one of these arguments required, the command line will fail if none are set
}
---------------------------------------------------------------------
-- CHECK FLAGS
-- | Check that a mode is well formed.
checkMode :: Mode a -> Maybe String
checkMode x = msum
[checkNames "modes" $ concatMap modeNames $ modeModes x
,msum $ map checkMode $ modeModes x
,checkGroup $ modeGroupModes x
,checkGroup $ modeGroupFlags x
,checkNames "flag names" $ concatMap flagNames $ modeFlags x]
where
checkGroup :: Group a -> Maybe String
checkGroup x = msum
[check "Empty group name" $ all (not . null . fst) $ groupNamed x
,check "Empty group contents" $ all (not . null . snd) $ groupNamed x]
checkNames :: String -> [Name] -> Maybe String
checkNames msg xs = check "Empty names" (all (not . null) xs) `mplus` do
bad <- listToMaybe $ xs \\ nub xs
let dupe = filter (== bad) xs
return $ "Sanity check failed, multiple " ++ msg ++ ": " ++ unwords (map show dupe)
check :: String -> Bool -> Maybe String
check msg True = Nothing
check msg False = Just msg
---------------------------------------------------------------------
-- REMAP
class Remap m where
remap :: (a -> b) -- ^ Embed a value
-> (b -> (a, a -> b)) -- ^ Extract the mode and give a way of re-embedding
-> m a -> m b
remap2 :: Remap m => (a -> b) -> (b -> a) -> m a -> m b
remap2 f g = remap f (\x -> (g x, f))
instance Remap Mode where
remap f g x = x
{modeGroupModes = fmap (remap f g) $ modeGroupModes x
,modeValue = f $ modeValue x
,modeCheck = \v -> let (a,b) = g v in fmap b $ modeCheck x a
,modeReform = modeReform x . fst . g
,modeArgs = (fmap (remap f g) *** fmap (remap f g)) $ modeArgs x
,modeGroupFlags = fmap (remap f g) $ modeGroupFlags x}
instance Remap Flag where
remap f g x = x{flagValue = remapUpdate f g $ flagValue x}
instance Remap Arg where
remap f g x = x{argValue = remapUpdate f g $ argValue x}
remapUpdate f g upd = \s v -> let (a,b) = g v in fmap b $ upd s a
---------------------------------------------------------------------
-- MODE/MODES CREATORS
-- | Create an empty mode specifying only 'modeValue'. All other fields will usually be populated
-- using record updates.
modeEmpty :: a -> Mode a
modeEmpty x = Mode mempty [] x Right (const Nothing) True "" [] ([],Nothing) mempty
-- | Create a mode with a name, an initial value, some help text, a way of processing arguments
-- and a list of flags.
mode :: Name -> a -> Help -> Arg a -> [Flag a] -> Mode a
mode name value help arg flags = (modeEmpty value){modeNames=[name], modeHelp=help, modeArgs=([],Just arg), modeGroupFlags=toGroup flags}
-- | Create a list of modes, with a program name, an initial value, some help text and the child modes.
modes :: String -> a -> Help -> [Mode a] -> Mode a
modes name value help xs = (modeEmpty value){modeNames=[name], modeHelp=help, modeGroupModes=toGroup xs}
---------------------------------------------------------------------
-- FLAG CREATORS
-- | Create a flag taking no argument value, with a list of flag names, an update function
-- and some help text.
flagNone :: [Name] -> (a -> a) -> Help -> Flag a
flagNone names f help = Flag names FlagNone upd "" help
where upd _ x = Right $ f x
-- | Create a flag taking an optional argument value, with an optional value, a list of flag names,
-- an update function, the type of the argument and some help text.
flagOpt :: String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a
flagOpt def names upd typ help = Flag names (FlagOpt def) upd typ help
-- | Create a flag taking a required argument value, with a list of flag names,
-- an update function, the type of the argument and some help text.
flagReq :: [Name] -> Update a -> FlagHelp -> Help -> Flag a
flagReq names upd typ help = Flag names FlagReq upd typ help
-- | Create an argument flag, with an update function and the type of the argument.
flagArg :: Update a -> FlagHelp -> Arg a
flagArg upd typ = Arg upd typ False
-- | Create a boolean flag, with a list of flag names, an update function and some help text.
flagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a
flagBool names f help = Flag names (FlagOptRare "") upd "" help
where
upd s x = case if s == "" then Just True else parseBool s of
Just b -> Right $ f b x
Nothing -> Left "expected boolean value (true/false)"
| copland/cmdargs | System/Console/CmdArgs/Explicit/Type.hs | bsd-3-clause | 10,204 | 0 | 14 | 2,422 | 2,312 | 1,254 | 1,058 | 125 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti data collector types.
-}
{-
Copyright (C) 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.DataCollectors.Types
( DCReport(..)
, buildReport
) where
import Data.Maybe
import Text.JSON
import Ganeti.Constants as C
import Ganeti.THH
import Ganeti.Utils (getCurrentTime)
-- | This is the format of the report produced by each data collector.
$(buildObject "DCReport" "dcReport"
[ simpleField "name" [t| String |]
, simpleField "version" [t| String |]
, simpleField "format_version" [t| Int |]
, simpleField "timestamp" [t| Integer |]
, simpleField "data" [t| JSValue |]
])
-- | Utility function for building a report automatically adding the current
-- timestamp (rounded up to seconds).
-- If the version is not specified, it will be set to the value indicating
-- a builtin collector.
buildReport :: String -> Maybe String -> Int -> JSValue -> IO DCReport
buildReport name version format_version jsonData = do
now <- getCurrentTime
let timestamp = now * 1000000000 :: Integer
ver = fromMaybe C.builtinDataCollectorVersion version
return $ DCReport name ver format_version timestamp jsonData
| sarahn/ganeti | src/Ganeti/DataCollectors/Types.hs | gpl-2.0 | 1,895 | 0 | 11 | 359 | 227 | 132 | 95 | 21 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- We never want to link against terminfo while bootstrapping.
#if defined(BOOTSTRAPPING)
#if defined(WITH_TERMINFO)
#undef WITH_TERMINFO
#endif
#endif
-----------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2004-2009.
--
-- Package management tool
--
-----------------------------------------------------------------------------
module Main (main) where
import Version ( version, targetOS, targetARCH )
import qualified GHC.PackageDb as GhcPkg
import GHC.PackageDb (BinaryStringRep(..))
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Data.Graph as Graph
import qualified Distribution.ModuleName as ModuleName
import Distribution.ModuleName (ModuleName)
import Distribution.InstalledPackageInfo as Cabal
import Distribution.Compat.ReadP hiding (get)
import Distribution.ParseUtils
import Distribution.Package hiding (installedUnitId)
import Distribution.Text
import Distribution.Version
import Distribution.Backpack
import Distribution.Types.UnqualComponentName
import Distribution.Types.MungedPackageName
import Distribution.Types.MungedPackageId
import Distribution.Simple.Utils (fromUTF8BS, toUTF8BS, writeUTF8File, readUTF8File)
import qualified Data.Version as Version
import System.FilePath as FilePath
import qualified System.FilePath.Posix as FilePath.Posix
import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing,
getModificationTime )
import Text.Printf
import Prelude
import System.Console.GetOpt
import qualified Control.Exception as Exception
import Data.Maybe
import Data.Char ( isSpace, toLower )
import Control.Monad
import System.Directory ( doesDirectoryExist, getDirectoryContents,
doesFileExist, removeFile,
getCurrentDirectory )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
#if defined(darwin_HOST_OS) || defined(linux_HOST_OS)
import System.Environment ( getExecutablePath )
#endif
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import Data.List
import Control.Concurrent
import qualified Data.Foldable as F
import qualified Data.Traversable as F
import qualified Data.Set as Set
import qualified Data.Map as Map
#if defined(mingw32_HOST_OS)
-- mingw32 needs these for getExecDir
import Foreign
import Foreign.C
import System.Directory ( canonicalizePath )
import GHC.ConsoleHandler
#else
import System.Posix hiding (fdToHandle)
#endif
#if defined(GLOB)
import qualified System.Info(os)
#endif
#if defined(WITH_TERMINFO)
import System.Console.Terminfo as Terminfo
#endif
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# else
# error Unknown mingw32 arch
# endif
#endif
-- | Short-circuit 'any' with a \"monadic predicate\".
anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool
anyM _ [] = return False
anyM p (x:xs) = do
b <- p x
if b
then return True
else anyM p xs
-- -----------------------------------------------------------------------------
-- Entry point
main :: IO ()
main = do
args <- getArgs
case getOpt Permute (flags ++ deprecFlags) args of
(cli,_,[]) | FlagHelp `elem` cli -> do
prog <- getProgramName
bye (usageInfo (usageHeader prog) flags)
(cli,_,[]) | FlagVersion `elem` cli ->
bye ourCopyright
(cli,nonopts,[]) ->
case getVerbosity Normal cli of
Right v -> runit v cli nonopts
Left err -> die err
(_,_,errors) -> do
prog <- getProgramName
die (concat errors ++ shortUsage prog)
-- -----------------------------------------------------------------------------
-- Command-line syntax
data Flag
= FlagUser
| FlagGlobal
| FlagHelp
| FlagVersion
| FlagConfig FilePath
| FlagGlobalConfig FilePath
| FlagUserConfig FilePath
| FlagForce
| FlagForceFiles
| FlagMultiInstance
| FlagExpandEnvVars
| FlagExpandPkgroot
| FlagNoExpandPkgroot
| FlagSimpleOutput
| FlagNamesOnly
| FlagIgnoreCase
| FlagNoUserDb
| FlagVerbosity (Maybe String)
| FlagUnitId
deriving Eq
flags :: [OptDescr Flag]
flags = [
Option [] ["user"] (NoArg FlagUser)
"use the current user's package database",
Option [] ["global"] (NoArg FlagGlobal)
"use the global package database",
Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database",
Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR")
"use the specified package database (DEPRECATED)",
Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR")
"location of the global package database",
Option [] ["no-user-package-db"] (NoArg FlagNoUserDb)
"never read the user package database",
Option [] ["user-package-db"] (ReqArg FlagUserConfig "DIR")
"location of the user package database (use instead of default)",
Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
"never read the user package database (DEPRECATED)",
Option [] ["force"] (NoArg FlagForce)
"ignore missing dependencies, directories, and libraries",
Option [] ["force-files"] (NoArg FlagForceFiles)
"ignore missing directories and libraries only",
Option [] ["enable-multi-instance"] (NoArg FlagMultiInstance)
"allow registering multiple instances of the same package version",
Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars)
"expand environment variables (${name}-style) in input package descriptions",
Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot)
"expand ${pkgroot}-relative paths to absolute in output package descriptions",
Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot)
"preserve ${pkgroot}-relative paths in output package descriptions",
Option ['?'] ["help"] (NoArg FlagHelp)
"display this help and exit",
Option ['V'] ["version"] (NoArg FlagVersion)
"output version information and exit",
Option [] ["simple-output"] (NoArg FlagSimpleOutput)
"print output in easy-to-parse format for some commands",
Option [] ["names-only"] (NoArg FlagNamesOnly)
"only print package names, not versions; can only be used with list --simple-output",
Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
"ignore case for substring matching",
Option [] ["ipid", "unit-id"] (NoArg FlagUnitId)
"interpret package arguments as unit IDs (e.g. installed package IDs)",
Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
"verbosity level (0-2, default 1)"
]
data Verbosity = Silent | Normal | Verbose
deriving (Show, Eq, Ord)
getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
getVerbosity v [] = Right v
getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
getVerbosity v (_ : fs) = getVerbosity v fs
deprecFlags :: [OptDescr Flag]
deprecFlags = [
-- put deprecated flags here
]
ourCopyright :: String
ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
shortUsage :: String -> String
shortUsage prog = "For usage information see '" ++ prog ++ " --help'."
usageHeader :: String -> String
usageHeader prog = substProg prog $
"Usage:\n" ++
" $p init {path}\n" ++
" Create and initialise a package database at the location {path}.\n" ++
" Packages can be registered in the new database using the register\n" ++
" command with --package-db={path}. To use the new database with GHC,\n" ++
" use GHC's -package-db flag.\n" ++
"\n" ++
" $p register {filename | -}\n" ++
" Register the package using the specified installed package\n" ++
" description. The syntax for the latter is given in the $p\n" ++
" documentation. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p update {filename | -}\n" ++
" Register the package, overwriting any other package with the\n" ++
" same name. The input file should be encoded in UTF-8.\n" ++
"\n" ++
" $p unregister [pkg-id] \n" ++
" Unregister the specified packages in the order given.\n" ++
"\n" ++
" $p expose {pkg-id}\n" ++
" Expose the specified package.\n" ++
"\n" ++
" $p hide {pkg-id}\n" ++
" Hide the specified package.\n" ++
"\n" ++
" $p trust {pkg-id}\n" ++
" Trust the specified package.\n" ++
"\n" ++
" $p distrust {pkg-id}\n" ++
" Distrust the specified package.\n" ++
"\n" ++
" $p list [pkg]\n" ++
" List registered packages in the global database, and also the\n" ++
" user database if --user is given. If a package name is given\n" ++
" all the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p dot\n" ++
" Generate a graph of the package dependencies in a form suitable\n" ++
" for input for the graphviz tools. For example, to generate a PDF\n" ++
" of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf\n" ++
"\n" ++
" $p find-module {module}\n" ++
" List registered packages exposing module {module} in the global\n" ++
" database, and also the user database if --user is given.\n" ++
" All the registered versions will be listed in ascending order.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p latest {pkg-id}\n" ++
" Prints the highest registered version of a package.\n" ++
"\n" ++
" $p check\n" ++
" Check the consistency of package dependencies and list broken packages.\n" ++
" Accepts the --simple-output flag.\n" ++
"\n" ++
" $p describe {pkg}\n" ++
" Give the registered description for the specified package. The\n" ++
" description is returned in precisely the syntax required by $p\n" ++
" register.\n" ++
"\n" ++
" $p field {pkg} {field}\n" ++
" Extract the specified field of the package description for the\n" ++
" specified package. Accepts comma-separated multiple fields.\n" ++
"\n" ++
" $p dump\n" ++
" Dump the registered description for every package. This is like\n" ++
" \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
" by tools that parse the results, rather than humans. The output is\n" ++
" always encoded in UTF-8, regardless of the current locale.\n" ++
"\n" ++
" $p recache\n" ++
" Regenerate the package database cache. This command should only be\n" ++
" necessary if you added a package to the database by dropping a file\n" ++
" into the database directory manually. By default, the global DB\n" ++
" is recached; to recache a different DB use --user or --package-db\n" ++
" as appropriate.\n" ++
"\n" ++
" Substring matching is supported for {module} in find-module and\n" ++
" for {pkg} in list, describe, and field, where a '*' indicates\n" ++
" open substring ends (prefix*, *suffix, *infix*). Use --ipid to\n" ++
" match against the installed package ID instead.\n" ++
"\n" ++
" When asked to modify a database (register, unregister, update,\n"++
" hide, expose, and also check), ghc-pkg modifies the global database by\n"++
" default. Specifying --user causes it to act on the user database,\n"++
" or --package-db can be used to act on another database\n"++
" entirely. When multiple of these options are given, the rightmost\n"++
" one is used as the database to act upon.\n"++
"\n"++
" Commands that query the package database (list, tree, latest, describe,\n"++
" field) operate on the list of databases specified by the flags\n"++
" --user, --global, and --package-db. If none of these flags are\n"++
" given, the default is --global --user.\n"++
"\n" ++
" The following optional flags are also accepted:\n"
substProg :: String -> String -> String
substProg _ [] = []
substProg prog ('$':'p':xs) = prog ++ substProg prog xs
substProg prog (c:xs) = c : substProg prog xs
-- -----------------------------------------------------------------------------
-- Do the business
data Force = NoForce | ForceFiles | ForceAll | CannotForce
deriving (Eq,Ord)
-- | Enum flag representing argument type
data AsPackageArg
= AsUnitId
| AsDefault
-- | Represents how a package may be specified by a user on the command line.
data PackageArg
-- | A package identifier foo-0.1, or a glob foo-*
= Id GlobPackageIdentifier
-- | An installed package ID foo-0.1-HASH. This is guaranteed to uniquely
-- match a single entry in the package database.
| IUId UnitId
-- | A glob against the package name. The first string is the literal
-- glob, the second is a function which returns @True@ if the argument
-- matches.
| Substring String (String->Bool)
runit :: Verbosity -> [Flag] -> [String] -> IO ()
runit verbosity cli nonopts = do
installSignalHandlers -- catch ^C and clean up
when (verbosity >= Verbose)
(putStr ourCopyright)
prog <- getProgramName
let
force
| FlagForce `elem` cli = ForceAll
| FlagForceFiles `elem` cli = ForceFiles
| otherwise = NoForce
as_arg | FlagUnitId `elem` cli = AsUnitId
| otherwise = AsDefault
multi_instance = FlagMultiInstance `elem` cli
expand_env_vars= FlagExpandEnvVars `elem` cli
mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli
where accumExpandPkgroot _ FlagExpandPkgroot = Just True
accumExpandPkgroot _ FlagNoExpandPkgroot = Just False
accumExpandPkgroot x _ = x
splitFields fields = unfoldr splitComma (',':fields)
where splitComma "" = Nothing
splitComma fs = Just $ break (==',') (tail fs)
-- | Parses a glob into a predicate which tests if a string matches
-- the glob. Returns Nothing if the string in question is not a glob.
-- At the moment, we only support globs at the beginning and/or end of
-- strings. This function respects case sensitivity.
--
-- >>> fromJust (substringCheck "*") "anything"
-- True
--
-- >>> fromJust (substringCheck "string") "string"
-- True
--
-- >>> fromJust (substringCheck "*bar") "foobar"
-- True
--
-- >>> fromJust (substringCheck "foo*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "*ooba*") "foobar"
-- True
--
-- >>> fromJust (substringCheck "f*bar") "foobar"
-- False
substringCheck :: String -> Maybe (String -> Bool)
substringCheck "" = Nothing
substringCheck "*" = Just (const True)
substringCheck [_] = Nothing
substringCheck (h:t) =
case (h, init t, last t) of
('*',s,'*') -> Just (isInfixOf (f s) . f)
('*',_, _ ) -> Just (isSuffixOf (f t) . f)
( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
_ -> Nothing
where f | FlagIgnoreCase `elem` cli = map toLower
| otherwise = id
#if defined(GLOB)
glob x | System.Info.os=="mingw32" = do
-- glob echoes its argument, after win32 filename globbing
(_,o,_,_) <- runInteractiveCommand ("glob "++x)
txt <- hGetContents o
return (read txt)
glob x | otherwise = return [x]
#endif
--
-- first, parse the command
case nonopts of
#if defined(GLOB)
-- dummy command to demonstrate usage and permit testing
-- without messing things up; use glob to selectively enable
-- windows filename globbing for file parameters
-- register, update, FlagGlobalConfig, FlagConfig; others?
["glob", filename] -> do
print filename
glob filename >>= print
#endif
["init", filename] ->
initPackageDB filename verbosity cli
["register", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars False force
["update", filename] ->
registerPackage filename verbosity cli
multi_instance
expand_env_vars True force
"unregister" : pkgarg_strs@(_:_) -> do
forM_ pkgarg_strs $ \pkgarg_str -> do
pkgarg <- readPackageArg as_arg pkgarg_str
unregisterPackage pkgarg verbosity cli force
["expose", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
exposePackage pkgarg verbosity cli force
["hide", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
hidePackage pkgarg verbosity cli force
["trust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
trustPackage pkgarg verbosity cli force
["distrust", pkgarg_str] -> do
pkgarg <- readPackageArg as_arg pkgarg_str
distrustPackage pkgarg verbosity cli force
["list"] -> do
listPackages verbosity cli Nothing Nothing
["list", pkgarg_str] ->
case substringCheck pkgarg_str of
Nothing -> do pkgarg <- readPackageArg as_arg pkgarg_str
listPackages verbosity cli (Just pkgarg) Nothing
Just m -> listPackages verbosity cli
(Just (Substring pkgarg_str m)) Nothing
["dot"] -> do
showPackageDot verbosity cli
["find-module", mod_name] -> do
let match = maybe (==mod_name) id (substringCheck mod_name)
listPackages verbosity cli Nothing (Just match)
["latest", pkgid_str] -> do
pkgid <- readGlobPkgId pkgid_str
latestPackage verbosity cli pkgid
["describe", pkgid_str] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot)
["field", pkgid_str, fields] -> do
pkgarg <- case substringCheck pkgid_str of
Nothing -> readPackageArg as_arg pkgid_str
Just m -> return (Substring pkgid_str m)
describeField verbosity cli pkgarg
(splitFields fields) (fromMaybe True mexpand_pkgroot)
["check"] -> do
checkConsistency verbosity cli
["dump"] -> do
dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot)
["recache"] -> do
recache verbosity cli
[] -> do
die ("missing command\n" ++ shortUsage prog)
(_cmd:_) -> do
die ("command-line syntax error\n" ++ shortUsage prog)
parseCheck :: ReadP a a -> String -> String -> IO a
parseCheck parser str what =
case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
[x] -> return x
_ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
-- | Either an exact 'PackageIdentifier', or a glob for all packages
-- matching 'PackageName'.
data GlobPackageIdentifier
= ExactPackageIdentifier MungedPackageId
| GlobPackageIdentifier MungedPackageName
displayGlobPkgId :: GlobPackageIdentifier -> String
displayGlobPkgId (ExactPackageIdentifier pid) = display pid
displayGlobPkgId (GlobPackageIdentifier pn) = display pn ++ "-*"
readGlobPkgId :: String -> IO GlobPackageIdentifier
readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
parseGlobPackageId :: ReadP r GlobPackageIdentifier
parseGlobPackageId =
fmap ExactPackageIdentifier parse
+++
(do n <- parse
_ <- string "-*"
return (GlobPackageIdentifier n))
readPackageArg :: AsPackageArg -> String -> IO PackageArg
readPackageArg AsUnitId str =
parseCheck (IUId `fmap` parse) str "installed package id"
readPackageArg AsDefault str = Id `fmap` readGlobPkgId str
-- -----------------------------------------------------------------------------
-- Package databases
-- Some commands operate on a single database:
-- register, unregister, expose, hide, trust, distrust
-- however these commands also check the union of the available databases
-- in order to check consistency. For example, register will check that
-- dependencies exist before registering a package.
--
-- Some commands operate on multiple databases, with overlapping semantics:
-- list, describe, field
data PackageDB (mode :: GhcPkg.DbMode)
= PackageDB {
location, locationAbsolute :: !FilePath,
-- We need both possibly-relative and definitely-absolute package
-- db locations. This is because the relative location is used as
-- an identifier for the db, so it is important we do not modify it.
-- On the other hand we need the absolute path in a few places
-- particularly in relation to the ${pkgroot} stuff.
packageDbLock :: !(GhcPkg.DbOpenMode mode GhcPkg.PackageDbLock),
-- If package db is open in read write mode, we keep its lock around for
-- transactional updates.
packages :: [InstalledPackageInfo]
}
type PackageDBStack = [PackageDB 'GhcPkg.DbReadOnly]
-- A stack of package databases. Convention: head is the topmost
-- in the stack.
-- | Selector for picking the right package DB to modify as 'register' and
-- 'recache' operate on the database on top of the stack, whereas 'modify'
-- changes the first database that contains a specific package.
data DbModifySelector = TopOne | ContainsPkg PackageArg
allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
allPackagesInStack = concatMap packages
getPkgDatabases :: Verbosity
-> GhcPkg.DbOpenMode mode DbModifySelector
-> Bool -- use the user db
-> Bool -- read caches, if available
-> Bool -- expand vars, like ${pkgroot} and $topdir
-> [Flag]
-> IO (PackageDBStack,
-- the real package DB stack: [global,user] ++
-- DBs specified on the command line with -f.
GhcPkg.DbOpenMode mode (PackageDB mode),
-- which one to modify, if any
PackageDBStack)
-- the package DBs specified on the command
-- line, or [global,user] otherwise. This
-- is used as the list of package DBs for
-- commands that just read the DB, such as 'list'.
getPkgDatabases verbosity mode use_user use_cache expand_vars my_flags = do
-- first we determine the location of the global package config. On Windows,
-- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
-- location is passed to the binary using the --global-package-db flag by the
-- wrapper script.
let err_msg = "missing --global-package-db option, location of global package database unknown\n"
global_conf <-
case [ f | FlagGlobalConfig f <- my_flags ] of
[] -> do mb_dir <- getLibDir
case mb_dir of
Nothing -> die err_msg
Just dir -> do
r <- lookForPackageDBIn dir
case r of
Nothing -> die ("Can't find package database in " ++ dir)
Just path -> return path
fs -> return (last fs)
-- The value of the $topdir variable used in some package descriptions
-- Note that the way we calculate this is slightly different to how it
-- is done in ghc itself. We rely on the convention that the global
-- package db lives in ghc's libdir.
top_dir <- absolutePath (takeDirectory global_conf)
let no_user_db = FlagNoUserDb `elem` my_flags
-- get the location of the user package database, and create it if necessary
-- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
e_appdir <- tryIO $ getAppUserDataDirectory "ghc"
mb_user_conf <-
case [ f | FlagUserConfig f <- my_flags ] of
_ | no_user_db -> return Nothing
[] -> case e_appdir of
Left _ -> return Nothing
Right appdir -> do
let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
dir = appdir </> subdir
r <- lookForPackageDBIn dir
case r of
Nothing -> return (Just (dir </> "package.conf.d", False))
Just f -> return (Just (f, True))
fs -> return (Just (last fs, True))
-- If the user database exists, and for "use_user" commands (which includes
-- "ghc-pkg check" and all commands that modify the db) we will attempt to
-- use the user db.
let sys_databases
| Just (user_conf,user_exists) <- mb_user_conf,
use_user || user_exists = [user_conf, global_conf]
| otherwise = [global_conf]
e_pkg_path <- tryIO (System.Environment.getEnv "GHC_PACKAGE_PATH")
let env_stack =
case e_pkg_path of
Left _ -> sys_databases
Right path
| not (null path) && isSearchPathSeparator (last path)
-> splitSearchPath (init path) ++ sys_databases
| otherwise
-> splitSearchPath path
-- The "global" database is always the one at the bottom of the stack.
-- This is the database we modify by default.
virt_global_conf = last env_stack
let db_flags = [ f | Just f <- map is_db_flag my_flags ]
where is_db_flag FlagUser
| Just (user_conf, _user_exists) <- mb_user_conf
= Just user_conf
is_db_flag FlagGlobal = Just virt_global_conf
is_db_flag (FlagConfig f) = Just f
is_db_flag _ = Nothing
let flag_db_names | null db_flags = env_stack
| otherwise = reverse (nub db_flags)
-- For a "modify" command, treat all the databases as
-- a stack, where we are modifying the top one, but it
-- can refer to packages in databases further down the
-- stack.
-- -f flags on the command line add to the database
-- stack, unless any of them are present in the stack
-- already.
let final_stack = filter (`notElem` env_stack)
[ f | FlagConfig f <- reverse my_flags ]
++ env_stack
top_db = if null db_flags
then virt_global_conf
else last db_flags
(db_stack, db_to_operate_on) <- getDatabases top_dir mb_user_conf
flag_db_names final_stack top_db
let flag_db_stack = [ db | db_name <- flag_db_names,
db <- db_stack, location db == db_name ]
when (verbosity > Normal) $ do
infoLn ("db stack: " ++ show (map location db_stack))
F.forM_ db_to_operate_on $ \db ->
infoLn ("modifying: " ++ (location db))
infoLn ("flag db stack: " ++ show (map location flag_db_stack))
return (db_stack, db_to_operate_on, flag_db_stack)
where
getDatabases top_dir mb_user_conf flag_db_names
final_stack top_db = case mode of
-- When we open in read only mode, we simply read all of the databases/
GhcPkg.DbOpenReadOnly -> do
db_stack <- mapM readDatabase final_stack
return (db_stack, GhcPkg.DbOpenReadOnly)
-- The only package db we open in read write mode is the one on the top of
-- the stack.
GhcPkg.DbOpenReadWrite TopOne -> do
(db_stack, mto_modify) <- stateSequence Nothing
[ \case
to_modify@(Just _) -> (, to_modify) <$> readDatabase db_path
Nothing -> if db_path /= top_db
then (, Nothing) <$> readDatabase db_path
else do
db <- readParseDatabase verbosity mb_user_conf
mode use_cache db_path
`Exception.catch` couldntOpenDbForModification db_path
let ro_db = db { packageDbLock = GhcPkg.DbOpenReadOnly }
return (ro_db, Just db)
| db_path <- final_stack ]
to_modify <- case mto_modify of
Just db -> return db
Nothing -> die "no database selected for modification"
return (db_stack, GhcPkg.DbOpenReadWrite to_modify)
-- The package db we open in read write mode is the first one included in
-- flag_db_names that contains specified package. Therefore we need to
-- open each one in read/write mode first and decide whether it's for
-- modification based on its contents.
GhcPkg.DbOpenReadWrite (ContainsPkg pkgarg) -> do
(db_stack, mto_modify) <- stateSequence Nothing
[ \case
to_modify@(Just _) -> (, to_modify) <$> readDatabase db_path
Nothing -> if db_path `notElem` flag_db_names
then (, Nothing) <$> readDatabase db_path
else do
let hasPkg :: PackageDB mode -> Bool
hasPkg = not . null . findPackage pkgarg . packages
openRo (e::IOError) = do
db <- readDatabase db_path
if hasPkg db
then couldntOpenDbForModification db_path e
else return (db, Nothing)
-- If we fail to open the database in read/write mode, we need
-- to check if it's for modification first before throwing an
-- error, so we attempt to open it in read only mode.
Exception.handle openRo $ do
db <- readParseDatabase verbosity mb_user_conf
mode use_cache db_path
let ro_db = db { packageDbLock = GhcPkg.DbOpenReadOnly }
if hasPkg db
then return (ro_db, Just db)
else do
-- If the database is not for modification after all,
-- drop the write lock as we are already finished with
-- the database.
case packageDbLock db of
GhcPkg.DbOpenReadWrite lock ->
GhcPkg.unlockPackageDb lock
return (ro_db, Nothing)
| db_path <- final_stack ]
to_modify <- case mto_modify of
Just db -> return db
Nothing -> cannotFindPackage pkgarg Nothing
return (db_stack, GhcPkg.DbOpenReadWrite to_modify)
where
couldntOpenDbForModification :: FilePath -> IOError -> IO a
couldntOpenDbForModification db_path e = die $ "Couldn't open database "
++ db_path ++ " for modification: " ++ show e
-- Parse package db in read-only mode.
readDatabase :: FilePath -> IO (PackageDB 'GhcPkg.DbReadOnly)
readDatabase db_path = do
db <- readParseDatabase verbosity mb_user_conf
GhcPkg.DbOpenReadOnly use_cache db_path
if expand_vars
then return $ mungePackageDBPaths top_dir db
else return db
stateSequence :: Monad m => s -> [s -> m (a, s)] -> m ([a], s)
stateSequence s [] = return ([], s)
stateSequence s (m:ms) = do
(a, s') <- m s
(as, s'') <- stateSequence s' ms
return (a : as, s'')
lookForPackageDBIn :: FilePath -> IO (Maybe FilePath)
lookForPackageDBIn dir = do
let path_dir = dir </> "package.conf.d"
exists_dir <- doesDirectoryExist path_dir
if exists_dir then return (Just path_dir) else do
let path_file = dir </> "package.conf"
exists_file <- doesFileExist path_file
if exists_file then return (Just path_file) else return Nothing
readParseDatabase :: forall mode t. Verbosity
-> Maybe (FilePath,Bool)
-> GhcPkg.DbOpenMode mode t
-> Bool -- use cache
-> FilePath
-> IO (PackageDB mode)
readParseDatabase verbosity mb_user_conf mode use_cache path
-- the user database (only) is allowed to be non-existent
| Just (user_conf,False) <- mb_user_conf, path == user_conf
= do lock <- F.forM mode $ \_ -> do
createDirectoryIfMissing True path
GhcPkg.lockPackageDb cache
mkPackageDB [] lock
| otherwise
= do e <- tryIO $ getDirectoryContents path
case e of
Left err
| ioeGetErrorType err == InappropriateType -> do
-- We provide a limited degree of backwards compatibility for
-- old single-file style db:
mdb <- tryReadParseOldFileStyleDatabase verbosity
mb_user_conf mode use_cache path
case mdb of
Just db -> return db
Nothing ->
die $ "ghc no longer supports single-file style package "
++ "databases (" ++ path ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
| otherwise -> ioError err
Right fs
| not use_cache -> ignore_cache (const $ return ())
| otherwise -> do
e_tcache <- tryIO $ getModificationTime cache
case e_tcache of
Left ex -> do
whenReportCacheErrors $
if isDoesNotExistError ex
then
-- It's fine if the cache is not there as long as the
-- database is empty.
when (not $ null confs) $ do
warn ("WARNING: cache does not exist: " ++ cache)
warn ("ghc will fail to read this package db. " ++
recacheAdvice)
else do
warn ("WARNING: cache cannot be read: " ++ show ex)
warn "ghc will fail to read this package db."
ignore_cache (const $ return ())
Right tcache -> do
when (verbosity >= Verbose) $ do
warn ("Timestamp " ++ show tcache ++ " for " ++ cache)
-- If any of the .conf files is newer than package.cache, we
-- assume that cache is out of date.
cache_outdated <- (`anyM` confs) $ \conf ->
(tcache <) <$> getModificationTime conf
if not cache_outdated
then do
when (verbosity > Normal) $
infoLn ("using cache: " ++ cache)
GhcPkg.readPackageDbForGhcPkg cache mode
>>= uncurry mkPackageDB
else do
whenReportCacheErrors $ do
warn ("WARNING: cache is out of date: " ++ cache)
warn ("ghc will see an old view of this " ++
"package db. " ++ recacheAdvice)
ignore_cache $ \file -> do
when (verbosity >= Verbose) $ do
tFile <- getModificationTime file
let rel = case tcache `compare` tFile of
LT -> " (NEWER than cache)"
GT -> " (older than cache)"
EQ -> " (same as cache)"
warn ("Timestamp " ++ show tFile
++ " for " ++ file ++ rel)
where
confs = map (path </>) $ filter (".conf" `isSuffixOf`) fs
ignore_cache :: (FilePath -> IO ()) -> IO (PackageDB mode)
ignore_cache checkTime = do
-- If we're opening for modification, we need to acquire a
-- lock even if we don't open the cache now, because we are
-- going to modify it later.
lock <- F.mapM (const $ GhcPkg.lockPackageDb cache) mode
let doFile f = do checkTime f
parseSingletonPackageConf verbosity f
pkgs <- mapM doFile confs
mkPackageDB pkgs lock
-- We normally report cache errors for read-only commands,
-- since modify commands will usually fix the cache.
whenReportCacheErrors = when $ verbosity > Normal
|| verbosity >= Normal && GhcPkg.isDbOpenReadMode mode
where
cache = path </> cachefilename
recacheAdvice
| Just (user_conf, True) <- mb_user_conf, path == user_conf
= "Use 'ghc-pkg recache --user' to fix."
| otherwise
= "Use 'ghc-pkg recache' to fix."
mkPackageDB :: [InstalledPackageInfo]
-> GhcPkg.DbOpenMode mode GhcPkg.PackageDbLock
-> IO (PackageDB mode)
mkPackageDB pkgs lock = do
path_abs <- absolutePath path
return $ PackageDB {
location = path,
locationAbsolute = path_abs,
packageDbLock = lock,
packages = pkgs
}
parseSingletonPackageConf :: Verbosity -> FilePath -> IO InstalledPackageInfo
parseSingletonPackageConf verbosity file = do
when (verbosity > Normal) $ infoLn ("reading package config: " ++ file)
readUTF8File file >>= fmap fst . parsePackageInfo
cachefilename :: FilePath
cachefilename = "package.cache"
mungePackageDBPaths :: FilePath -> PackageDB mode -> PackageDB mode
mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } =
db { packages = map (mungePackagePaths top_dir pkgroot) pkgs }
where
pkgroot = takeDirectory $ dropTrailingPathSeparator (locationAbsolute db)
-- It so happens that for both styles of package db ("package.conf"
-- files and "package.conf.d" dirs) the pkgroot is the parent directory
-- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/
-- TODO: This code is duplicated in compiler/main/Packages.hs
mungePackagePaths :: FilePath -> FilePath
-> InstalledPackageInfo -> InstalledPackageInfo
-- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
-- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
-- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
-- The "pkgroot" is the directory containing the package database.
--
-- Also perform a similar substitution for the older GHC-specific
-- "$topdir" variable. The "topdir" is the location of the ghc
-- installation (obtained from the -B option).
mungePackagePaths top_dir pkgroot pkg =
pkg {
importDirs = munge_paths (importDirs pkg),
includeDirs = munge_paths (includeDirs pkg),
libraryDirs = munge_paths (libraryDirs pkg),
libraryDynDirs = munge_paths (libraryDynDirs pkg),
frameworkDirs = munge_paths (frameworkDirs pkg),
haddockInterfaces = munge_paths (haddockInterfaces pkg),
-- haddock-html is allowed to be either a URL or a file
haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg))
}
where
munge_paths = map munge_path
munge_urls = map munge_url
munge_path p
| Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
| Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
| otherwise = p
munge_url p
| Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
| Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
| otherwise = p
toUrlPath r p = "file:///"
-- URLs always use posix style '/' separators:
++ FilePath.Posix.joinPath
(r : -- We need to drop a leading "/" or "\\"
-- if there is one:
dropWhile (all isPathSeparator)
(FilePath.splitDirectories p))
-- We could drop the separator here, and then use </> above. However,
-- by leaving it in and using ++ we keep the same path separator
-- rather than letting FilePath change it to use \ as the separator
stripVarPrefix var path = case stripPrefix var path of
Just [] -> Just []
Just cs@(c : _) | isPathSeparator c -> Just cs
_ -> Nothing
-- -----------------------------------------------------------------------------
-- Workaround for old single-file style package dbs
-- Single-file style package dbs have been deprecated for some time, but
-- it turns out that Cabal was using them in one place. So this code is for a
-- workaround to allow older Cabal versions to use this newer ghc.
-- We check if the file db contains just "[]" and if so, we look for a new
-- dir-style db in path.d/, ie in a dir next to the given file.
-- We cannot just replace the file with a new dir style since Cabal still
-- assumes it's a file and tries to overwrite with 'writeFile'.
-- ghc itself also cooperates in this workaround
tryReadParseOldFileStyleDatabase :: Verbosity -> Maybe (FilePath, Bool)
-> GhcPkg.DbOpenMode mode t -> Bool -> FilePath
-> IO (Maybe (PackageDB mode))
tryReadParseOldFileStyleDatabase verbosity mb_user_conf
mode use_cache path = do
-- assumes we've already established that path exists and is not a dir
content <- readFile path `catchIO` \_ -> return ""
if take 2 content == "[]"
then do
path_abs <- absolutePath path
let path_dir = adjustOldDatabasePath path
warn $ "Warning: ignoring old file-style db and trying " ++ path_dir
direxists <- doesDirectoryExist path_dir
if direxists
then do
db <- readParseDatabase verbosity mb_user_conf mode use_cache path_dir
-- but pretend it was at the original location
return $ Just db {
location = path,
locationAbsolute = path_abs
}
else do
lock <- F.forM mode $ \_ -> do
createDirectoryIfMissing True path_dir
GhcPkg.lockPackageDb $ path_dir </> cachefilename
return $ Just PackageDB {
location = path,
locationAbsolute = path_abs,
packageDbLock = lock,
packages = []
}
-- if the path is not a file, or is not an empty db then we fail
else return Nothing
adjustOldFileStylePackageDB :: PackageDB mode -> IO (PackageDB mode)
adjustOldFileStylePackageDB db = do
-- assumes we have not yet established if it's an old style or not
mcontent <- liftM Just (readFile (location db)) `catchIO` \_ -> return Nothing
case fmap (take 2) mcontent of
-- it is an old style and empty db, so look for a dir kind in location.d/
Just "[]" -> return db {
location = adjustOldDatabasePath $ location db,
locationAbsolute = adjustOldDatabasePath $ locationAbsolute db
}
-- it is old style but not empty, we have to bail
Just _ -> die $ "ghc no longer supports single-file style package "
++ "databases (" ++ location db ++ ") use 'ghc-pkg init'"
++ "to create the database with the correct format."
-- probably not old style, carry on as normal
Nothing -> return db
adjustOldDatabasePath :: FilePath -> FilePath
adjustOldDatabasePath = (<.> "d")
-- -----------------------------------------------------------------------------
-- Creating a new package DB
initPackageDB :: FilePath -> Verbosity -> [Flag] -> IO ()
initPackageDB filename verbosity _flags = do
let eexist = die ("cannot create: " ++ filename ++ " already exists")
b1 <- doesFileExist filename
when b1 eexist
b2 <- doesDirectoryExist filename
when b2 eexist
createDirectoryIfMissing True filename
lock <- GhcPkg.lockPackageDb $ filename </> cachefilename
filename_abs <- absolutePath filename
changeDB verbosity [] PackageDB {
location = filename,
locationAbsolute = filename_abs,
packageDbLock = GhcPkg.DbOpenReadWrite lock,
packages = []
}
-- -----------------------------------------------------------------------------
-- Registering
registerPackage :: FilePath
-> Verbosity
-> [Flag]
-> Bool -- multi_instance
-> Bool -- expand_env_vars
-> Bool -- update
-> Force
-> IO ()
registerPackage input verbosity my_flags multi_instance
expand_env_vars update force = do
(db_stack, GhcPkg.DbOpenReadWrite db_to_operate_on, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite TopOne)
True{-use user-} True{-use cache-} False{-expand vars-} my_flags
let to_modify = location db_to_operate_on
s <-
case input of
"-" -> do
when (verbosity >= Normal) $
info "Reading package info from stdin ... "
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdin utf8
getContents
f -> do
when (verbosity >= Normal) $
info ("Reading package info from " ++ show f ++ " ... ")
readUTF8File f
expanded <- if expand_env_vars then expandEnvVars s force
else return s
(pkg, ws) <- parsePackageInfo expanded
when (verbosity >= Normal) $
infoLn "done."
-- report any warnings from the parse phase
_ <- reportValidateErrors verbosity [] ws
(display (mungedId pkg) ++ ": Warning: ") Nothing
-- validate the expanded pkg, but register the unexpanded
pkgroot <- absolutePath (takeDirectory to_modify)
let top_dir = takeDirectory (location (last db_stack))
pkg_expanded = mungePackagePaths top_dir pkgroot pkg
let truncated_stack = dropWhile ((/= to_modify).location) db_stack
-- truncate the stack for validation, because we don't allow
-- packages lower in the stack to refer to those higher up.
validatePackageConfig pkg_expanded verbosity truncated_stack
multi_instance update force
let
-- In the normal mode, we only allow one version of each package, so we
-- remove all instances with the same source package id as the one we're
-- adding. In the multi instance mode we don't do that, thus allowing
-- multiple instances with the same source package id.
removes = [ RemovePackage p
| not multi_instance,
p <- packages db_to_operate_on,
mungedId p == mungedId pkg,
-- Only remove things that were instantiated the same way!
instantiatedWith p == instantiatedWith pkg ]
--
changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on
parsePackageInfo
:: String
-> IO (InstalledPackageInfo, [ValidateWarning])
parsePackageInfo str =
case parseInstalledPackageInfo str of
ParseOk warnings ok -> return (mungePackageInfo ok, ws)
where
ws = [ msg | PWarning msg <- warnings
, not ("Unrecognized field pkgroot" `isPrefixOf` msg) ]
ParseFailed err -> case locatedErrorMsg err of
(Nothing, s) -> die s
(Just l, s) -> die (show l ++ ": " ++ s)
mungePackageInfo :: InstalledPackageInfo -> InstalledPackageInfo
mungePackageInfo ipi = ipi
-- -----------------------------------------------------------------------------
-- Making changes to a package database
data DBOp = RemovePackage InstalledPackageInfo
| AddPackage InstalledPackageInfo
| ModifyPackage InstalledPackageInfo
changeDB :: Verbosity -> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite -> IO ()
changeDB verbosity cmds db = do
let db' = updateInternalDB db cmds
db'' <- adjustOldFileStylePackageDB db'
createDirectoryIfMissing True (location db'')
changeDBDir verbosity cmds db''
updateInternalDB :: PackageDB 'GhcPkg.DbReadWrite
-> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite
updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds }
where
do_cmd pkgs (RemovePackage p) =
filter ((/= installedUnitId p) . installedUnitId) pkgs
do_cmd pkgs (AddPackage p) = p : pkgs
do_cmd pkgs (ModifyPackage p) =
do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p)
changeDBDir :: Verbosity -> [DBOp] -> PackageDB 'GhcPkg.DbReadWrite -> IO ()
changeDBDir verbosity cmds db = do
mapM_ do_cmd cmds
updateDBCache verbosity db
where
do_cmd (RemovePackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("removing " ++ file)
removeFileSafe file
do_cmd (AddPackage p) = do
let file = location db </> display (installedUnitId p) <.> "conf"
when (verbosity > Normal) $ infoLn ("writing " ++ file)
writeUTF8File file (showInstalledPackageInfo p)
do_cmd (ModifyPackage p) =
do_cmd (AddPackage p)
updateDBCache :: Verbosity -> PackageDB 'GhcPkg.DbReadWrite -> IO ()
updateDBCache verbosity db = do
let filename = location db </> cachefilename
pkgsCabalFormat :: [InstalledPackageInfo]
pkgsCabalFormat = packages db
pkgsGhcCacheFormat :: [PackageCacheFormat]
pkgsGhcCacheFormat = map convertPackageInfoToCacheFormat pkgsCabalFormat
when (verbosity > Normal) $
infoLn ("writing cache " ++ filename)
GhcPkg.writePackageDb filename pkgsGhcCacheFormat pkgsCabalFormat
`catchIO` \e ->
if isPermissionError e
then die $ filename ++ ": you don't have permission to modify this file"
else ioError e
case packageDbLock db of
GhcPkg.DbOpenReadWrite lock -> GhcPkg.unlockPackageDb lock
type PackageCacheFormat = GhcPkg.InstalledPackageInfo
ComponentId
PackageIdentifier
PackageName
UnitId
OpenUnitId
ModuleName
OpenModule
convertPackageInfoToCacheFormat :: InstalledPackageInfo -> PackageCacheFormat
convertPackageInfoToCacheFormat pkg =
GhcPkg.InstalledPackageInfo {
GhcPkg.unitId = installedUnitId pkg,
GhcPkg.componentId = installedComponentId pkg,
GhcPkg.instantiatedWith = instantiatedWith pkg,
GhcPkg.sourcePackageId = sourcePackageId pkg,
GhcPkg.packageName = packageName pkg,
GhcPkg.packageVersion = Version.Version (versionNumbers (packageVersion pkg)) [],
GhcPkg.sourceLibName =
fmap (mkPackageName . unUnqualComponentName) (sourceLibName pkg),
GhcPkg.depends = depends pkg,
GhcPkg.abiDepends = map (\(AbiDependency k v) -> (k,unAbiHash v)) (abiDepends pkg),
GhcPkg.abiHash = unAbiHash (abiHash pkg),
GhcPkg.importDirs = importDirs pkg,
GhcPkg.hsLibraries = hsLibraries pkg,
GhcPkg.extraLibraries = extraLibraries pkg,
GhcPkg.extraGHCiLibraries = extraGHCiLibraries pkg,
GhcPkg.libraryDirs = libraryDirs pkg,
GhcPkg.libraryDynDirs = libraryDynDirs pkg,
GhcPkg.frameworks = frameworks pkg,
GhcPkg.frameworkDirs = frameworkDirs pkg,
GhcPkg.ldOptions = ldOptions pkg,
GhcPkg.ccOptions = ccOptions pkg,
GhcPkg.includes = includes pkg,
GhcPkg.includeDirs = includeDirs pkg,
GhcPkg.haddockInterfaces = haddockInterfaces pkg,
GhcPkg.haddockHTMLs = haddockHTMLs pkg,
GhcPkg.exposedModules = map convertExposed (exposedModules pkg),
GhcPkg.hiddenModules = hiddenModules pkg,
GhcPkg.indefinite = indefinite pkg,
GhcPkg.exposed = exposed pkg,
GhcPkg.trusted = trusted pkg
}
where
convertExposed (ExposedModule n reexport) = (n, reexport)
instance GhcPkg.BinaryStringRep ComponentId where
fromStringRep = mkComponentId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageName where
fromStringRep = mkPackageName . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep PackageIdentifier where
fromStringRep = fromMaybe (error "BinaryStringRep PackageIdentifier")
. simpleParse . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep ModuleName where
fromStringRep = ModuleName.fromString . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.BinaryStringRep String where
fromStringRep = fromUTF8BS
toStringRep = toUTF8BS
instance GhcPkg.BinaryStringRep UnitId where
fromStringRep = mkUnitId . fromStringRep
toStringRep = toStringRep . display
instance GhcPkg.DbUnitIdModuleRep UnitId ComponentId OpenUnitId ModuleName OpenModule where
fromDbModule (GhcPkg.DbModule uid mod_name) = OpenModule uid mod_name
fromDbModule (GhcPkg.DbModuleVar mod_name) = OpenModuleVar mod_name
toDbModule (OpenModule uid mod_name) = GhcPkg.DbModule uid mod_name
toDbModule (OpenModuleVar mod_name) = GhcPkg.DbModuleVar mod_name
fromDbUnitId (GhcPkg.DbUnitId cid insts) = IndefFullUnitId cid (Map.fromList insts)
fromDbUnitId (GhcPkg.DbInstalledUnitId uid)
= DefiniteUnitId (unsafeMkDefUnitId uid)
toDbUnitId (IndefFullUnitId cid insts) = GhcPkg.DbUnitId cid (Map.toList insts)
toDbUnitId (DefiniteUnitId def_uid)
= GhcPkg.DbInstalledUnitId (unDefUnitId def_uid)
-- -----------------------------------------------------------------------------
-- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar
exposePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True})
hidePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False})
trustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True})
distrustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False})
unregisterPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
unregisterPackage = modifyPackage RemovePackage
modifyPackage
:: (InstalledPackageInfo -> DBOp)
-> PackageArg
-> Verbosity
-> [Flag]
-> Force
-> IO ()
modifyPackage fn pkgarg verbosity my_flags force = do
(db_stack, GhcPkg.DbOpenReadWrite db, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite $ ContainsPkg pkgarg)
True{-use user-} True{-use cache-} False{-expand vars-} my_flags
let db_name = location db
pkgs = packages db
-- Get package respecting flags...
ps = findPackage pkgarg pkgs
-- This shouldn't happen if getPkgDatabases picks the DB correctly.
when (null ps) $ cannotFindPackage pkgarg $ Just db
let pks = map installedUnitId ps
cmds = [ fn pkg | pkg <- pkgs, installedUnitId pkg `elem` pks ]
new_db = updateInternalDB db cmds
new_db_ro = new_db { packageDbLock = GhcPkg.DbOpenReadOnly }
-- ...but do consistency checks with regards to the full stack
old_broken = brokenPackages (allPackagesInStack db_stack)
rest_of_stack = filter ((/= db_name) . location) db_stack
new_stack = new_db_ro : rest_of_stack
new_broken = brokenPackages (allPackagesInStack new_stack)
newly_broken = filter ((`notElem` map installedUnitId old_broken)
. installedUnitId) new_broken
--
let displayQualPkgId pkg
| [_] <- filter ((== pkgid) . mungedId)
(allPackagesInStack db_stack)
= display pkgid
| otherwise = display pkgid ++ "@" ++ display (installedUnitId pkg)
where pkgid = mungedId pkg
when (not (null newly_broken)) $
dieOrForceAll force ("unregistering would break the following packages: "
++ unwords (map displayQualPkgId newly_broken))
changeDB verbosity cmds db
recache :: Verbosity -> [Flag] -> IO ()
recache verbosity my_flags = do
(_db_stack, GhcPkg.DbOpenReadWrite db_to_operate_on, _flag_dbs) <-
getPkgDatabases verbosity (GhcPkg.DbOpenReadWrite TopOne)
True{-use user-} False{-no cache-} False{-expand vars-} my_flags
changeDB verbosity [] db_to_operate_on
-- -----------------------------------------------------------------------------
-- Listing packages
listPackages :: Verbosity -> [Flag] -> Maybe PackageArg
-> Maybe (String->Bool)
-> IO ()
listPackages verbosity my_flags mPackageName mModuleName = do
let simple_output = FlagSimpleOutput `elem` my_flags
(db_stack, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} False{-expand vars-} my_flags
let db_stack_filtered -- if a package is given, filter out all other packages
| Just this <- mPackageName =
[ db{ packages = filter (this `matchesPkg`) (packages db) }
| db <- flag_db_stack ]
| Just match <- mModuleName = -- packages which expose mModuleName
[ db{ packages = filter (match `exposedInPkg`) (packages db) }
| db <- flag_db_stack ]
| otherwise = flag_db_stack
db_stack_sorted
= [ db{ packages = sort_pkgs (packages db) }
| db <- db_stack_filtered ]
where sort_pkgs = sortBy cmpPkgIds
cmpPkgIds pkg1 pkg2 =
case mungedName p1 `compare` mungedName p2 of
LT -> LT
GT -> GT
EQ -> case mungedVersion p1 `compare` mungedVersion p2 of
LT -> LT
GT -> GT
EQ -> installedUnitId pkg1 `compare` installedUnitId pkg2
where (p1,p2) = (mungedId pkg1, mungedId pkg2)
stack = reverse db_stack_sorted
match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
pkg_map = allPackagesInStack db_stack
broken = map installedUnitId (brokenPackages pkg_map)
show_normal PackageDB{ location = db_name, packages = pkg_confs } =
do hPutStrLn stdout db_name
if null pkg_confs
then hPutStrLn stdout " (no packages)"
else hPutStrLn stdout $ unlines (map (" " ++) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = printf "{%s}" doc
| exposed p = doc
| otherwise = printf "(%s)" doc
where doc | verbosity >= Verbose = printf "%s (%s)" pkg (display (installedUnitId p))
| otherwise = pkg
where
pkg = display (mungedId p)
show_simple = simplePackageList my_flags . allPackagesInStack
when (not (null broken) && not simple_output && verbosity /= Silent) $ do
prog <- getProgramName
warn ("WARNING: there are broken packages. Run '" ++ prog ++ " check' for more details.")
if simple_output then show_simple stack else do
#if !defined(WITH_TERMINFO)
mapM_ show_normal stack
#else
let
show_colour withF db@PackageDB{ packages = pkg_confs } =
if null pkg_confs
then termText (location db) <#> termText "\n (no packages)\n"
else
mconcat $ map (<#> termText "\n") $
(termText (location db)
: map (termText " " <#>) (map pp_pkg pkg_confs))
where
pp_pkg p
| installedUnitId p `elem` broken = withF Red doc
| exposed p = doc
| otherwise = withF Blue doc
where doc | verbosity >= Verbose
= termText (printf "%s (%s)" pkg (display (installedUnitId p)))
| otherwise
= termText pkg
where
pkg = display (mungedId p)
is_tty <- hIsTerminalDevice stdout
if not is_tty
then mapM_ show_normal stack
else do tty <- Terminfo.setupTermFromEnv
case Terminfo.getCapability tty withForegroundColor of
Nothing -> mapM_ show_normal stack
Just w -> runTermOutput tty $ mconcat $
map (show_colour w) stack
#endif
simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
simplePackageList my_flags pkgs = do
let showPkg = if FlagNamesOnly `elem` my_flags then display . mungedName
else display
strs = map showPkg $ map mungedId pkgs
when (not (null pkgs)) $
hPutStrLn stdout $ concat $ intersperse " " strs
showPackageDot :: Verbosity -> [Flag] -> IO ()
showPackageDot verbosity myflags = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} False{-expand vars-} myflags
let all_pkgs = allPackagesInStack flag_db_stack
ipix = PackageIndex.fromList all_pkgs
putStrLn "digraph {"
let quote s = '"':s ++ "\""
mapM_ putStrLn [ quote from ++ " -> " ++ quote to
| p <- all_pkgs,
let from = display (mungedId p),
key <- depends p,
Just dep <- [PackageIndex.lookupUnitId ipix key],
let to = display (mungedId dep)
]
putStrLn "}"
-- -----------------------------------------------------------------------------
-- Prints the highest (hidden or exposed) version of a package
-- ToDo: This is no longer well-defined with unit ids, because the
-- dependencies may be varying versions
latestPackage :: Verbosity -> [Flag] -> GlobPackageIdentifier -> IO ()
latestPackage verbosity my_flags pkgid = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} False{-expand vars-} my_flags
ps <- findPackages flag_db_stack (Id pkgid)
case ps of
[] -> die "no matches"
_ -> show_pkg . maximum . map mungedId $ ps
where
show_pkg pid = hPutStrLn stdout (display pid)
-- -----------------------------------------------------------------------------
-- Describe
describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO ()
describePackage verbosity my_flags pkgarg expand_pkgroot = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} expand_pkgroot my_flags
dbs <- findPackagesByDB flag_db_stack pkgarg
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| (db, pkgs) <- dbs, pkg <- pkgs ]
dumpPackages :: Verbosity -> [Flag] -> Bool -> IO ()
dumpPackages verbosity my_flags expand_pkgroot = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} expand_pkgroot my_flags
doDump expand_pkgroot [ (pkg, locationAbsolute db)
| db <- flag_db_stack, pkg <- packages db ]
doDump :: Bool -> [(InstalledPackageInfo, FilePath)] -> IO ()
doDump expand_pkgroot pkgs = do
-- fix the encoding to UTF-8, since this is an interchange format
hSetEncoding stdout utf8
putStrLn $
intercalate "---\n"
[ if expand_pkgroot
then showInstalledPackageInfo pkg
else showInstalledPackageInfo pkg ++ pkgrootField
| (pkg, pkgloc) <- pkgs
, let pkgroot = takeDirectory pkgloc
pkgrootField = "pkgroot: " ++ show pkgroot ++ "\n" ]
-- PackageId is can have globVersion for the version
findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
findPackages db_stack pkgarg
= fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
findPackage :: PackageArg -> [InstalledPackageInfo] -> [InstalledPackageInfo]
findPackage pkgarg pkgs = filter (pkgarg `matchesPkg`) pkgs
findPackagesByDB :: PackageDBStack -> PackageArg
-> IO [(PackageDB 'GhcPkg.DbReadOnly, [InstalledPackageInfo])]
findPackagesByDB db_stack pkgarg
= case [ (db, matched)
| db <- db_stack,
let matched = findPackage pkgarg $ packages db,
not (null matched) ] of
[] -> cannotFindPackage pkgarg Nothing
ps -> return ps
cannotFindPackage :: PackageArg -> Maybe (PackageDB mode) -> IO a
cannotFindPackage pkgarg mdb = die $ "cannot find package " ++ pkg_msg pkgarg
++ maybe "" (\db -> " in " ++ location db) mdb
where
pkg_msg (Id pkgid) = displayGlobPkgId pkgid
pkg_msg (IUId ipid) = display ipid
pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
matches :: GlobPackageIdentifier -> MungedPackageId -> Bool
GlobPackageIdentifier pn `matches` pid'
= (pn == mungedName pid')
ExactPackageIdentifier pid `matches` pid'
= mungedName pid == mungedName pid' &&
(mungedVersion pid == mungedVersion pid' || mungedVersion pid == nullVersion)
matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
(Id pid) `matchesPkg` pkg = pid `matches` mungedId pkg
(IUId ipid) `matchesPkg` pkg = ipid == installedUnitId pkg
(Substring _ m) `matchesPkg` pkg = m (display (mungedId pkg))
-- -----------------------------------------------------------------------------
-- Field
describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO ()
describeField verbosity my_flags pkgarg fields expand_pkgroot = do
(_, GhcPkg.DbOpenReadOnly, flag_db_stack) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
False{-use user-} True{-use cache-} expand_pkgroot my_flags
fns <- mapM toField fields
ps <- findPackages flag_db_stack pkgarg
mapM_ (selectFields fns) ps
where showFun = if FlagSimpleOutput `elem` my_flags
then showSimpleInstalledPackageInfoField
else showInstalledPackageInfoField
toField f = case showFun f of
Nothing -> die ("unknown field: " ++ f)
Just fn -> return fn
selectFields fns pinfo = mapM_ (\fn->putStrLn (fn pinfo)) fns
-- -----------------------------------------------------------------------------
-- Check: Check consistency of installed packages
checkConsistency :: Verbosity -> [Flag] -> IO ()
checkConsistency verbosity my_flags = do
(db_stack, GhcPkg.DbOpenReadOnly, _) <-
getPkgDatabases verbosity GhcPkg.DbOpenReadOnly
True{-use user-} True{-use cache-} True{-expand vars-} my_flags
-- although check is not a modify command, we do need to use the user
-- db, because we may need it to verify package deps.
let simple_output = FlagSimpleOutput `elem` my_flags
let pkgs = allPackagesInStack db_stack
checkPackage p = do
(_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack
True True
if null es
then do when (not simple_output) $ do
_ <- reportValidateErrors verbosity [] ws "" Nothing
return ()
return []
else do
when (not simple_output) $ do
reportError ("There are problems in package " ++ display (mungedId p) ++ ":")
_ <- reportValidateErrors verbosity es ws " " Nothing
return ()
return [p]
broken_pkgs <- concat `fmap` mapM checkPackage pkgs
let filterOut pkgs1 pkgs2 = filter not_in pkgs2
where not_in p = mungedId p `notElem` all_ps
all_ps = map mungedId pkgs1
let not_broken_pkgs = filterOut broken_pkgs pkgs
(_, trans_broken_pkgs) = closure [] not_broken_pkgs
all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
when (not (null all_broken_pkgs)) $ do
if simple_output
then simplePackageList my_flags all_broken_pkgs
else do
reportError ("\nThe following packages are broken, either because they have a problem\n"++
"listed above, or because they depend on a broken package.")
mapM_ (hPutStrLn stderr . display . mungedId) all_broken_pkgs
when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
-> ([InstalledPackageInfo], [InstalledPackageInfo])
closure pkgs db_stack = go pkgs db_stack
where
go avail not_avail =
case partition (depsAvailable avail) not_avail of
([], not_avail') -> (avail, not_avail')
(new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
-> Bool
depsAvailable pkgs_ok pkg = null dangling
where dangling = filter (`notElem` pids) (depends pkg)
pids = map installedUnitId pkgs_ok
-- we want mutually recursive groups of package to show up
-- as broken. (#1750)
brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
brokenPackages pkgs = snd (closure [] pkgs)
-----------------------------------------------------------------------------
-- Sanity-check a new package config, and automatically build GHCi libs
-- if requested.
type ValidateError = (Force,String)
type ValidateWarning = String
newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) }
instance Functor Validate where
fmap = liftM
instance Applicative Validate where
pure a = V $ pure (a, [], [])
(<*>) = ap
instance Monad Validate where
m >>= k = V $ do
(a, es, ws) <- runValidate m
(b, es', ws') <- runValidate (k a)
return (b,es++es',ws++ws')
verror :: Force -> String -> Validate ()
verror f s = V (return ((),[(f,s)],[]))
vwarn :: String -> Validate ()
vwarn s = V (return ((),[],["Warning: " ++ s]))
liftIO :: IO a -> Validate a
liftIO k = V (k >>= \a -> return (a,[],[]))
-- returns False if we should die
reportValidateErrors :: Verbosity -> [ValidateError] -> [ValidateWarning]
-> String -> Maybe Force -> IO Bool
reportValidateErrors verbosity es ws prefix mb_force = do
mapM_ (warn . (prefix++)) ws
oks <- mapM report es
return (and oks)
where
report (f,s)
| Just force <- mb_force
= if (force >= f)
then do when (verbosity >= Normal) $
reportError (prefix ++ s ++ " (ignoring)")
return True
else if f < CannotForce
then do reportError (prefix ++ s ++ " (use --force to override)")
return False
else do reportError err
return False
| otherwise = do reportError err
return False
where
err = prefix ++ s
validatePackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Force
-> IO ()
validatePackageConfig pkg verbosity db_stack
multi_instance update force = do
(_,es,ws) <- runValidate $
checkPackageConfig pkg verbosity db_stack
multi_instance update
ok <- reportValidateErrors verbosity es ws
(display (mungedId pkg) ++ ": ") (Just force)
when (not ok) $ exitWith (ExitFailure 1)
checkPackageConfig :: InstalledPackageInfo
-> Verbosity
-> PackageDBStack
-> Bool -- multi_instance
-> Bool -- update, or check
-> Validate ()
checkPackageConfig pkg verbosity db_stack
multi_instance update = do
checkPackageId pkg
checkUnitId pkg db_stack update
checkDuplicates db_stack pkg multi_instance update
mapM_ (checkDep db_stack) (depends pkg)
checkDuplicateDepends (depends pkg)
mapM_ (checkDir False "import-dirs") (importDirs pkg)
mapM_ (checkDir True "library-dirs") (libraryDirs pkg)
mapM_ (checkDir True "dynamic-library-dirs") (libraryDynDirs pkg)
mapM_ (checkDir True "include-dirs") (includeDirs pkg)
mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg)
mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg)
mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg)
checkDuplicateModules pkg
checkExposedModules db_stack pkg
checkOtherModules pkg
let has_code = Set.null (openModuleSubstFreeHoles (Map.fromList (instantiatedWith pkg)))
when has_code $ mapM_ (checkHSLib verbosity (libraryDirs pkg ++ libraryDynDirs pkg)) (hsLibraries pkg)
-- ToDo: check these somehow?
-- extra_libraries :: [String],
-- c_includes :: [String],
-- When the package name and version are put together, sometimes we can
-- end up with a package id that cannot be parsed. This will lead to
-- difficulties when the user wants to refer to the package later, so
-- we check that the package id can be parsed properly here.
checkPackageId :: InstalledPackageInfo -> Validate ()
checkPackageId ipi =
let str = display (mungedId ipi) in
case [ x :: MungedPackageId | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[_] -> return ()
[] -> verror CannotForce ("invalid package identifier: " ++ str)
_ -> verror CannotForce ("ambiguous package identifier: " ++ str)
checkUnitId :: InstalledPackageInfo -> PackageDBStack -> Bool
-> Validate ()
checkUnitId ipi db_stack update = do
let uid = installedUnitId ipi
when (null (display uid)) $ verror CannotForce "missing id field"
when (display uid /= compatPackageKey ipi) $
verror CannotForce $ "installed package info from too old version of Cabal "
++ "(key field does not match id field)"
let dups = [ p | p <- allPackagesInStack db_stack,
installedUnitId p == uid ]
when (not update && not (null dups)) $
verror CannotForce $
"package(s) with this id already exist: " ++
unwords (map (display.installedUnitId) dups)
checkDuplicates :: PackageDBStack -> InstalledPackageInfo
-> Bool -> Bool-> Validate ()
checkDuplicates db_stack pkg multi_instance update = do
let
pkgid = mungedId pkg
pkgs = packages (head db_stack)
--
-- Check whether this package id already exists in this DB
--
when (not update && not multi_instance
&& (pkgid `elem` map mungedId pkgs)) $
verror CannotForce $
"package " ++ display pkgid ++ " is already installed"
let
uncasep = map toLower . display
dups = filter ((== uncasep pkgid) . uncasep) (map mungedId pkgs)
when (not update && not multi_instance
&& not (null dups)) $ verror ForceAll $
"Package names may be treated case-insensitively in the future.\n"++
"Package " ++ display pkgid ++
" overlaps with: " ++ unwords (map display dups)
checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate ()
checkDir = checkPath False True
checkFile = checkPath False False
checkDirURL = checkPath True True
checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate ()
checkPath url_ok is_dir warn_only thisfield d
| url_ok && ("http://" `isPrefixOf` d
|| "https://" `isPrefixOf` d) = return ()
| url_ok
, Just d' <- stripPrefix "file://" d
= checkPath False is_dir warn_only thisfield d'
-- Note: we don't check for $topdir/${pkgroot} here. We rely on these
-- variables having been expanded already, see mungePackagePaths.
| isRelative d = verror ForceFiles $
thisfield ++ ": " ++ d ++ " is a relative path which "
++ "makes no sense (as there is nothing for it to be "
++ "relative to). You can make paths relative to the "
++ "package database itself by using ${pkgroot}."
-- relative paths don't make any sense; #4134
| otherwise = do
there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d
when (not there) $
let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a "
++ if is_dir then "directory" else "file"
in
if warn_only
then vwarn msg
else verror ForceFiles msg
checkDep :: PackageDBStack -> UnitId -> Validate ()
checkDep db_stack pkgid
| pkgid `elem` pkgids = return ()
| otherwise = verror ForceAll ("dependency \"" ++ display pkgid
++ "\" doesn't exist")
where
all_pkgs = allPackagesInStack db_stack
pkgids = map installedUnitId all_pkgs
checkDuplicateDepends :: [UnitId] -> Validate ()
checkDuplicateDepends deps
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate dependencies: " ++
unwords (map display dups))
where
dups = [ p | (p:_:_) <- group (sort deps) ]
checkHSLib :: Verbosity -> [String] -> String -> Validate ()
checkHSLib _verbosity dirs lib = do
let filenames = ["lib" ++ lib ++ ".a",
"lib" ++ lib ++ ".p_a",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".so",
"lib" ++ lib ++ "-ghc" ++ Version.version ++ ".dylib",
lib ++ "-ghc" ++ Version.version ++ ".dll"]
b <- liftIO $ doesFileExistOnPath filenames dirs
when (not b) $
verror ForceFiles ("cannot find any of " ++ show filenames ++
" on library path")
doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO Bool
doesFileExistOnPath filenames paths = anyM doesFileExist fullFilenames
where fullFilenames = [ path </> filename
| filename <- filenames
, path <- paths ]
-- | Perform validation checks (module file existence checks) on the
-- @hidden-modules@ field.
checkOtherModules :: InstalledPackageInfo -> Validate ()
checkOtherModules pkg = mapM_ (checkModuleFile pkg) (hiddenModules pkg)
-- | Perform validation checks (module file existence checks and module
-- reexport checks) on the @exposed-modules@ field.
checkExposedModules :: PackageDBStack -> InstalledPackageInfo -> Validate ()
checkExposedModules db_stack pkg =
mapM_ checkExposedModule (exposedModules pkg)
where
checkExposedModule (ExposedModule modl reexport) = do
let checkOriginal = checkModuleFile pkg modl
checkReexport = checkModule "module reexport" db_stack pkg
maybe checkOriginal checkReexport reexport
-- | Validates the existence of an appropriate @hi@ file associated with
-- a module. Used for both @hidden-modules@ and @exposed-modules@ which
-- are not reexports.
checkModuleFile :: InstalledPackageInfo -> ModuleName -> Validate ()
checkModuleFile pkg modl =
-- there's no interface file for GHC.Prim
unless (modl == ModuleName.fromString "GHC.Prim") $ do
let files = [ ModuleName.toFilePath modl <.> extension
| extension <- ["hi", "p_hi", "dyn_hi" ] ]
b <- liftIO $ doesFileExistOnPath files (importDirs pkg)
when (not b) $
verror ForceFiles ("cannot find any of " ++ show files)
-- | Validates that @exposed-modules@ and @hidden-modules@ do not have duplicate
-- entries.
-- ToDo: this needs updating for signatures: signatures can validly show up
-- multiple times in the @exposed-modules@ list as long as their backing
-- implementations agree.
checkDuplicateModules :: InstalledPackageInfo -> Validate ()
checkDuplicateModules pkg
| null dups = return ()
| otherwise = verror ForceAll ("package has duplicate modules: " ++
unwords (map display dups))
where
dups = [ m | (m:_:_) <- group (sort mods) ]
mods = map exposedName (exposedModules pkg) ++ hiddenModules pkg
-- | Validates an original module entry, either the origin of a module reexport
-- or the backing implementation of a signature, by checking that it exists,
-- really is an original definition, and is accessible from the dependencies of
-- the package.
-- ToDo: If the original module in question is a backing signature
-- implementation, then we should also check that the original module in
-- question is NOT a signature (however, if it is a reexport, then it's fine
-- for the original module to be a signature.)
checkModule :: String
-> PackageDBStack
-> InstalledPackageInfo
-> OpenModule
-> Validate ()
checkModule _ _ _ (OpenModuleVar _) = error "Impermissible reexport"
checkModule field_name db_stack pkg
(OpenModule (DefiniteUnitId def_uid) definingModule) =
let definingPkgId = unDefUnitId def_uid
mpkg = if definingPkgId == installedUnitId pkg
then Just pkg
else PackageIndex.lookupUnitId ipix definingPkgId
in case mpkg of
Nothing
-> verror ForceAll (field_name ++ " refers to a non-existent " ++
"defining package: " ++
display definingPkgId)
Just definingPkg
| not (isIndirectDependency definingPkgId)
-> verror ForceAll (field_name ++ " refers to a defining " ++
"package that is not a direct (or indirect) " ++
"dependency of this package: " ++
display definingPkgId)
| otherwise
-> case find ((==definingModule).exposedName)
(exposedModules definingPkg) of
Nothing ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is not exposed in the " ++
"defining package " ++ display definingPkgId)
Just (ExposedModule {exposedReexport = Just _} ) ->
verror ForceAll (field_name ++ " refers to a module " ++
display definingModule ++ " " ++
"that is reexported but not defined in the " ++
"defining package " ++ display definingPkgId)
_ -> return ()
where
all_pkgs = allPackagesInStack db_stack
ipix = PackageIndex.fromList all_pkgs
isIndirectDependency pkgid = fromMaybe False $ do
thispkg <- graphVertex (installedUnitId pkg)
otherpkg <- graphVertex pkgid
return (Graph.path depgraph thispkg otherpkg)
(depgraph, _, graphVertex) =
PackageIndex.dependencyGraph (PackageIndex.insert pkg ipix)
checkModule _ _ _ (OpenModule (IndefFullUnitId _ _) _) =
-- TODO: add some checks here
return ()
-- ---------------------------------------------------------------------------
-- expanding environment variables in the package configuration
expandEnvVars :: String -> Force -> IO String
expandEnvVars str0 force = go str0 ""
where
go "" acc = return $! reverse acc
go ('$':'{':str) acc | (var, '}':rest) <- break close str
= do value <- lookupEnvVar var
go rest (reverse value ++ acc)
where close c = c == '}' || c == '\n' -- don't span newlines
go (c:str) acc
= go str (c:acc)
lookupEnvVar :: String -> IO String
lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special,
lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them
lookupEnvVar nm =
catchIO (System.Environment.getEnv nm)
(\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
show nm)
return "")
-----------------------------------------------------------------------------
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
where str `withoutSuffix` suff
| suff `isSuffixOf` str = take (length str - length suff) str
| otherwise = str
bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess
die :: String -> IO a
die = dieWith 1
dieWith :: Int -> String -> IO a
dieWith ec s = do
prog <- getProgramName
reportError (prog ++ ": " ++ s)
exitWith (ExitFailure ec)
dieOrForceAll :: Force -> String -> IO ()
dieOrForceAll ForceAll s = ignoreError s
dieOrForceAll _other s = dieForcible s
warn :: String -> IO ()
warn = reportError
-- send info messages to stdout
infoLn :: String -> IO ()
infoLn = putStrLn
info :: String -> IO ()
info = putStr
ignoreError :: String -> IO ()
ignoreError s = reportError (s ++ " (ignoring)")
reportError :: String -> IO ()
reportError s = do hFlush stdout; hPutStrLn stderr s
dieForcible :: String -> IO ()
dieForcible s = die (s ++ " (use --force to override)")
-----------------------------------------
-- Cut and pasted from ghc/compiler/main/SysTools
getLibDir :: IO (Maybe String)
#if defined(mingw32_HOST_OS)
subst :: Char -> Char -> String -> String
subst a b ls = map (\ x -> if x == a then b else x) ls
unDosifyPath :: FilePath -> FilePath
unDosifyPath xs = subst '\\' '/' xs
getLibDir = do base <- getExecDir "/ghc-pkg.exe"
case base of
Nothing -> return Nothing
Just base' -> do
libdir <- canonicalizePath $ base' </> "../lib"
exists <- doesDirectoryExist libdir
if exists
then return $ Just libdir
else return Nothing
-- (getExecDir cmd) returns the directory in which the current
-- executable, which should be called 'cmd', is running
-- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
-- you'll get "/a/b/c" back as the result
getExecDir :: String -> IO (Maybe String)
getExecDir cmd =
getExecPath >>= maybe (return Nothing) removeCmdSuffix
where initN n = reverse . drop n . reverse
removeCmdSuffix = return . Just . initN (length cmd) . unDosifyPath
getExecPath :: IO (Maybe String)
getExecPath = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return Nothing
_ | ret < size -> fmap Just $ peekCWString buf
| otherwise -> try_size (size * 2)
foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
#elif defined(darwin_HOST_OS) || defined(linux_HOST_OS)
-- TODO: a) this is copy-pasta from SysTools.hs / getBaseDir. Why can't we reuse
-- this here? and parameterise getBaseDir over the executable (for
-- windows)?
-- Answer: we can not, because if we share `getBaseDir` via `ghc-boot`,
-- that would add `base` as a dependency for windows.
-- b) why is the windows getBaseDir logic, not part of getExecutablePath?
-- it would be much wider available then and we could drop all the
-- custom logic?
-- Answer: yes this should happen. No one has found the time just yet.
getLibDir = Just . (\p -> p </> "lib") . takeDirectory . takeDirectory <$> getExecutablePath
#else
getLibDir = return Nothing
#endif
-----------------------------------------
-- Adapted from ghc/compiler/utils/Panic
installSignalHandlers :: IO ()
installSignalHandlers = do
threadid <- myThreadId
let
interrupt = Exception.throwTo threadid
(Exception.ErrorCall "interrupted")
--
#if !defined(mingw32_HOST_OS)
_ <- installHandler sigQUIT (Catch interrupt) Nothing
_ <- installHandler sigINT (Catch interrupt) Nothing
return ()
#else
-- GHC 6.3+ has support for console events on Windows
-- NOTE: running GHCi under a bash shell for some reason requires
-- you to press Ctrl-Break rather than Ctrl-C to provoke
-- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
-- why --SDM 17/12/2004
let sig_handler ControlC = interrupt
sig_handler Break = interrupt
sig_handler _ = return ()
_ <- installHandler (Catch sig_handler)
return ()
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
tryIO :: IO a -> IO (Either Exception.IOException a)
tryIO = Exception.try
-- removeFileSave doesn't throw an exceptions, if the file is already deleted
removeFileSafe :: FilePath -> IO ()
removeFileSafe fn =
removeFile fn `catchIO` \ e ->
when (not $ isDoesNotExistError e) $ ioError e
-- | Turn a path relative to the current directory into a (normalised)
-- absolute path.
absolutePath :: FilePath -> IO FilePath
absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
| ezyang/ghc | utils/ghc-pkg/Main.hs | bsd-3-clause | 90,493 | 872 | 101 | 25,756 | 15,461 | 8,909 | 6,552 | 1,490 | 32 |
{-# Language FlexibleContexts, ScopedTypeVariables #-}
-- | A multitap looper.
module Csound.Air.Looper (
LoopSpec(..), LoopControl(..),
sigLoop, midiLoop, sfLoop, patchLoop
) where
import Control.Monad
import Data.List
import Data.Default
import Data.Boolean
import Csound.Typed
import Csound.Typed.Gui hiding (button)
import Csound.Control.Evt
import Csound.Control.Instr
import Csound.Control.Gui
import Csound.Control.Sf
import Csound.Typed.Opcode hiding (space, button)
import Csound.SigSpace
import Csound.Air.Live
import Csound.Air.Wave
import Csound.Air.Fx
import Csound.Air.Filter
import Csound.Air.Patch
import Csound.Air.Misc
-- | The type for fine tuning of the looper. Let's review the values:
--
-- * @loopMixVal@ - list of initial values for mix levels (default is 0.5 for all taps)
--
-- * @loopPrefx@ - list of pre-loop effects (the default is do-nothing effect)
--
-- * @loopPostfx@ - list of post-loop effects (the default is do-nothing effect)
--
-- * @loopPrefxVal@ - list of dry/wet values for pre-looop effects (the default is 0.5 for all taps)
--
-- * @loopPostfxVal@ - list of dry/wet values for post-looop effects (the default is 0.5 for all taps)
--
-- * @loopInitInstr@ - the initial sounding tap (sound source) (what tap we are going to record when the looper starts up).
--
-- * @loopFades@ - the list of instrument groups to fade/out. Eachl list item is a list of integers
-- where an integer points to a tap number. By default a single fader is given to each tap.
-- with lists of integers we can group the sound sources by their functions in the song.
-- We may group all harmonic instruments in a single group and all drums into another group.
--
-- * @loopReeatFades@ -- a repeat fade weight is a value that represents
-- an amount of repetition. A looping tap is implemented as a delay tap with
-- big feedback. The repeat fades equals to the feedback amount. It have to be not bigger
-- than 1. If the value equals to 1 than the loop is repeated forever. If it's lower
-- than 1 the loop is gradually going to fade.
--
-- * @loopControl@ -- specifies an external controllers for the looper.
-- See the docs for the type @LoopSpec@.
data LoopSpec = LoopSpec
{ loopMixVal :: [Sig]
, loopPrefx :: [FxFun]
, loopPostfx :: [FxFun]
, loopPrefxVal :: [Sig]
, loopPostfxVal :: [Sig]
, loopInitInstr :: Int
, loopFades :: [[Int]]
, loopRepeatFades :: [Sig]
, loopControl :: LoopControl
}
instance Default LoopSpec where
def = LoopSpec {
loopPrefx = []
, loopPostfx = []
, loopPrefxVal = []
, loopPostfxVal = []
, loopMixVal = []
, loopInitInstr = 0
, loopFades = []
, loopRepeatFades = []
, loopControl = def
}
-- | External controllers. We can control the looper with
-- UI-widgets but sometimes it's convenient to control the
-- loper with some external midi-device. This structure mocks
-- all controls (except knobs for effects and mix).
--
-- * @loopTap@ - selects the current tap. It's a stream of integers (from 0 to a given integer).
--
-- * @loopFade@ - can fade in or fade out a group of taps. It's a list of toggle-like event streams.
-- they produce 1s for on and 0s for off.
--
-- * @loopDel@ - is for deleting the content of a given tap. It's just a click of the button.
-- So the value should be an event stream of units (which is @Tick = Evt Unit@).
--
-- * @loopThrough@ - is an event stream of toggles.
--
-- All values are wrapped in the @Maybe@ type. If the value is @Nothing@ in the given cell
-- the looper is controled only with virtual widgets.
--
-- There is an instance of @Default@ for @LoopControl@ with all values set to @Nothing@.
-- It's useful when we want to control only a part of parameters externally.
-- We can use the value @def@ to set the rest parameters:
--
-- > def { loopTap = Just someEvt }
data LoopControl = LoopControl
{ loopTap :: Maybe (Evt D)
, loopFade :: Maybe ([Evt D])
, loopDel :: Maybe Tick
, loopThrough :: Maybe (Evt D)
}
instance Default LoopControl where
def = LoopControl {
loopTap = Nothing
, loopFade = Nothing
, loopDel = Nothing
, loopThrough = Nothing }
type TapControl = [String] -> Int -> Source Sig
type FadeControl = [String -> Source (Evt D)]
type DelControl = Source Tick
type ThroughControl = Source Sig
-- | The @midiLoop@ that is adapted for usage with soundfonts.
-- It takes in a list of pairs of sound fonts as sound sources.
-- The second value in the pair is the release time for the given sound font.
sfLoop :: LoopSpec -> D -> [D] -> [(Sf, D)] -> Source Sig2
sfLoop spec dtBpm times fonts = midiLoop spec dtBpm times $ fmap (uncurry sfMsg) fonts
-- | The @sigLoop@ that is adapted for usage with midi instruments.
-- It takes a list of midi instruments in place of signal inputs. The rest is the same
midiLoop :: LoopSpec -> D -> [D] -> [Msg -> SE Sig2] -> Source Sig2
midiLoop = genLoop $ \cond midiInstr -> midi $ playWhen cond midiInstr
-- | Some instruments not work well with the looper. Alwo be aware of limitation of software resources.
patchLoop :: LoopSpec -> D -> [D] -> [Patch2] -> Source Sig2
patchLoop = genLoop $ \cond p -> atMidi (patchWhen cond p)
-- | Simple multitap Looper. We can create as many taps as we like
-- also we can create fade outs/ins insert effects and control mix.
--
-- > sigLoop spec bpm times imputs
--
-- Arguments:
--
-- * looper @spec@ (see the docs for the type)
--
-- * main @bpm@ rate. All taps are aligned with the main rate
--
-- * list of multipliers for each tap. Each tap is going to have a fixed
-- length that is a multiplier of the main rate. It doesn't have to be
-- an integer. So we can create weird drum patterns with odd loop durations.
--
-- * list of signal sources. By convention all sources are stereo signals.
-- We can use the function @fromMono@ to convert the mono signal to stereo.
sigLoop :: LoopSpec -> D -> [D] -> [Sig2] -> Source Sig2
sigLoop = genLoop $ \cond asig -> return $ mul (ifB cond 1 0) asig
getControls :: LoopControl -> (TapControl, FadeControl, DelControl, ThroughControl)
getControls a =
( maybe hradioSig (hradioSig' . evtToSig (-1)) (loopTap a)
, fmap (\f x -> f x True) $ maybe (repeat toggle) (\xs -> fmap toggle' xs ++ repeat toggle) (loopFade a)
, ( $ "del") $ maybe button button' (loopDel a)
, (\f -> f "through" False) $ maybe toggleSig (toggleSig' . evtToSig (-1)) (loopThrough a))
genLoop :: forall a. (BoolSig -> a -> SE Sig2) -> LoopSpec -> D -> [D] -> [a] -> Source Sig2
genLoop playInstr spec dtBpm times' instrs = do
(preFxKnobGui, preFxKnobWrite, preFxKnobRead) <- setKnob "pre" (linSpan 0 1) 0.5
(postFxKnobGui, postFxKnobWrite, postFxKnobRead) <- setKnob "post" (linSpan 0 1) 0.5
(mixKnobGui, mixKnobWrite, mixKnobRead) <- setKnob "mix" (linSpan 0 1) 0.5
let knobGuis = ver [mixKnobGui, preFxKnobGui, postFxKnobGui]
mapGuiSource (\gs -> hor [knobGuis, sca 12 gs]) $ joinSource $ vlift3 (\(thr, delEvt) x sils -> do
-- knobs
mixCoeffs <- tabSigs mixKnobWrite mixKnobRead x initMixVals
preCoeffs <- tabSigs preFxKnobWrite preFxKnobRead x initPreVals
postCoeffs <- tabSigs postFxKnobWrite postFxKnobRead x initPostVals
refs <- mapM (const $ newRef (1 :: Sig)) ids
delRefs <- mapM (const $ newRef (0 :: Sig)) ids
zipWithM_ (setSilencer refs) silencer sils
at smallRoom2 $ sum $ zipWith3 (f delEvt thr x) (zip3 times ids repeatFades) (zip5 mixCoeffs preFx preCoeffs postFx postCoeffs) $ zip3 delRefs refs instrs) throughDel sw sil
where
(tapControl, fadeControl, delControl, throughControl) = getControls (loopControl spec)
dt = 60 / dtBpm
times = take len $ times' ++ repeat 1
postFx = take len $ loopPostfx spec ++ repeat return
preFx = take len $ loopPrefx spec ++ repeat return
repeatFades = loopRepeatFades spec ++ repeat 1
len = length ids
initMixVals = take len $ loopMixVal spec ++ repeat 0.5
initPreVals = take len $ loopPrefxVal spec ++ repeat 0.5
initPostVals = take len $ loopPostfxVal spec ++ repeat 0.5
silencer
| null (loopFades spec) = fmap return ids
| otherwise = loopFades spec
initInstr = loopInitInstr spec
ids = [0 .. length instrs - 1]
through = throughControl
delete = delControl
throughDel = hlift2' 6 1 (\a b -> (a, b)) through delete
sw = tapControl (fmap show ids) initInstr
sil = hlifts id $ zipWith (\f n -> f (show n)) fadeControl [0 .. length silencer - 1]
maxDel = 3
f :: Tick -> Sig -> Sig -> (D, Int, Sig) -> (Sig, FxFun, Sig, FxFun, Sig) -> (Ref Sig, Ref Sig, a) -> SE Sig2
f delEvt thr x (t, n, repeatFadeWeight) (mixCoeff, preFx, preCoeff, postFx, postCoeff) (delRef, silRef, instr) = do
silVal <- readRef silRef
runEvt delEvt $ \_ -> do
a <- readRef delRef
when1 isCurrent $ writeRef delRef (ifB (a + 1 `lessThan` maxDel) (a + 1) 0)
delVal <- readRef delRef
echoSig <- playSf 0
let d0 = delVal ==* 0
d1 = delVal ==* 1
d2 = delVal ==* 2
let playEcho dId = mul (smooth 0.05 $ ifB dId 1 0) $ mul (smooth 0.1 silVal) $ at (echo (dt * t) (ifB dId repeatFadeWeight 0)) $ ifB dId echoSig 0
mul mixCoeff $ mixAt postCoeff postFx $ sum [ sum $ fmap playEcho [d0, d1, d2]
, playSf 1]
where
playSf thrVal = mixAt preCoeff preFx $ playInstr (isCurrent &&* thr ==* thrVal) instr
isCurrent = x ==* (sig $ int n)
setSilencer refs silIds evt = runEvt evt $ \v ->
mapM_ (\ref -> writeRef ref $ sig v) $ fmap (refs !! ) silIds
tabSigs :: Output Sig -> Input Sig -> Sig -> [Sig] -> SE [Sig]
tabSigs writeWidget readWidget switch initVals = do
refs <- mapM newGlobalRef initVals
vs <- mapM readRef refs
runEvt (changedE [switch]) $ \_ -> do
mapM_ (\(v, x) -> when1 (x ==* switch) $ writeWidget v) $ zip vs $ fmap (sig . int) [0 .. length initVals - 1]
forM_ (zip [0..] refs) $ \(n, ref) -> do
when1 ((sig $ int n) ==* switch) $ writeRef ref readWidget
return vs
| isomorphism/csound-expression | src/Csound/Air/Looper.hs | bsd-3-clause | 9,934 | 63 | 19 | 2,071 | 2,592 | 1,405 | 1,187 | 134 | 1 |
-- This is a modification of the calendar program described in section 4.5
-- of Bird and Wadler's ``Introduction to functional programming'', with
-- two ways of printing the calendar ... as in B+W, or like UNIX `cal':
import IO -- 1.3
import System -- 1.3
import List -- 1.3
import Char -- 1.3
-- Picture handling:
infixr 5 `above`, `beside`
type Picture = [[Char]]
height, width :: Picture -> Int
height p = length p
width p = length (head p)
above, beside :: Picture -> Picture -> Picture
above = (++)
beside = zipWith (++)
stack, spread :: [Picture] -> Picture
stack = foldr1 above
spread = foldr1 beside
empty :: (Int,Int) -> Picture
empty (h,w) = copy h (copy w ' ')
block, blockT :: Int -> [Picture] -> Picture
block n = stack . map spread . groop n
blockT n = spread . map stack . groop n
groop :: Int -> [a] -> [[a]]
groop n [] = []
groop n xs = take n xs : groop n (drop n xs)
lframe :: (Int,Int) -> Picture -> Picture
lframe (m,n) p = (p `beside` empty (h,n-w)) `above` empty (m-h,n)
where h = height p
w = width p
-- Information about the months in a year:
monthLengths year = [31,feb,31,30,31,30,31,31,30,31,30,31]
where feb | leap year = 29
| otherwise = 28
leap year = if year`mod`100 == 0 then year`mod`400 == 0
else year`mod`4 == 0
monthNames = ["January","February","March","April",
"May","June","July","August",
"September","October","November","December"]
jan1st year = (year + last`div`4 - last`div`100 + last`div`400) `mod` 7
where last = year - 1
firstDays year = take 12
(map (`mod`7)
(scanl (+) (jan1st year) (monthLengths year)))
-- Producing the information necessary for one month:
dates fd ml = map (date ml) [1-fd..42-fd]
where date ml d | d<1 || ml<d = [" "]
| otherwise = [rjustify 3 (show d)]
-- The original B+W calendar:
calendar :: Int -> String
calendar = unlines . block 3 . map picture . months
where picture (mn,yr,fd,ml) = title mn yr `above` table fd ml
title mn yr = lframe (2,25) [mn ++ " " ++ show yr]
table fd ml = lframe (8,25)
(daynames `beside` entries fd ml)
daynames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
entries fd ml = blockT 7 (dates fd ml)
months year = zip4 monthNames
(copy 12 year)
(firstDays year)
(monthLengths year)
-- In a format somewhat closer to UNIX cal:
cal year = unlines (banner year `above` body year)
where banner yr = [cjustify 75 (show yr)] `above` empty (1,75)
body = block 3 . map (pad . pic) . months
pic (mn,fd,ml) = title mn `above` table fd ml
pad p = (side`beside`p`beside`side)`above`end
side = empty (8,2)
end = empty (1,25)
title mn = [cjustify 21 mn]
table fd ml = daynames `above` entries fd ml
daynames = [" Su Mo Tu We Th Fr Sa"]
entries fd ml = block 7 (dates fd ml)
months year = zip3 monthNames
(firstDays year)
(monthLengths year)
-- For a standalone calendar program:
main = do
strs <- getArgs
case strs of [year] -> calFor year
_ -> fail ("Usage: cal year\n")
calFor year | illFormed = fail ("Bad argument")
| otherwise = putStr (cal yr)
where illFormed = null ds || not (null rs)
(ds,rs) = span isDigit year
yr = atoi ds
atoi s = foldl (\a d -> 10*a+d) 0 (map toDigit s)
toDigit d = fromEnum d - fromEnum '0'
-- End of calendar program
-- tacked on by partain
copy :: Int -> a -> [a]
copy n x = take n (repeat x)
cjustify, ljustify, rjustify :: Int -> String -> String
cjustify n s = space halfm ++ s ++ space (m - halfm)
where m = n - length s
halfm = m `div` 2
ljustify n s = s ++ space (n - length s)
rjustify n s = space (n - length s) ++ s
space :: Int -> String
space n = copy n ' '
-- end of tack
| hvr/jhc | regress/tests/9_nofib/spectral/Calendar.hs | mit | 4,727 | 5 | 12 | 1,891 | 1,653 | 894 | 759 | 90 | 2 |
{-# LANGUAGE BangPatterns, CPP, MagicHash, UnboxedTuples #-}
{-# OPTIONS_GHC -O #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 1997-2006
--
-- Character encodings
--
-- -----------------------------------------------------------------------------
module Encoding (
-- * UTF-8
utf8DecodeChar#,
utf8PrevChar,
utf8CharStart,
utf8DecodeChar,
utf8DecodeString,
utf8EncodeChar,
utf8EncodeString,
utf8EncodedLength,
countUTF8Chars,
-- * Z-encoding
zEncodeString,
zDecodeString
) where
#include "HsVersions.h"
import Foreign
import Data.Char
import Numeric
import ExtsCompat46
-- -----------------------------------------------------------------------------
-- UTF-8
-- We can't write the decoder as efficiently as we'd like without
-- resorting to unboxed extensions, unfortunately. I tried to write
-- an IO version of this function, but GHC can't eliminate boxed
-- results from an IO-returning function.
--
-- We assume we can ignore overflow when parsing a multibyte character here.
-- To make this safe, we add extra sentinel bytes to unparsed UTF-8 sequences
-- before decoding them (see StringBuffer.hs).
{-# INLINE utf8DecodeChar# #-}
utf8DecodeChar# :: Addr# -> (# Char#, Addr# #)
utf8DecodeChar# a# =
let !ch0 = word2Int# (indexWord8OffAddr# a# 0#) in
case () of
_ | ch0 <=# 0x7F# -> (# chr# ch0, a# `plusAddr#` 1# #)
| ch0 >=# 0xC0# && ch0 <=# 0xDF# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
(# chr# (((ch0 -# 0xC0#) `uncheckedIShiftL#` 6#) +#
(ch1 -# 0x80#)),
a# `plusAddr#` 2# #)
| ch0 >=# 0xE0# && ch0 <=# 0xEF# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
(# chr# (((ch0 -# 0xE0#) `uncheckedIShiftL#` 12#) +#
((ch1 -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ch2 -# 0x80#)),
a# `plusAddr#` 3# #)
| ch0 >=# 0xF0# && ch0 <=# 0xF8# ->
let !ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
let !ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
let !ch3 = word2Int# (indexWord8OffAddr# a# 3#) in
if ch3 <# 0x80# || ch3 >=# 0xC0# then fail 3# else
(# chr# (((ch0 -# 0xF0#) `uncheckedIShiftL#` 18#) +#
((ch1 -# 0x80#) `uncheckedIShiftL#` 12#) +#
((ch2 -# 0x80#) `uncheckedIShiftL#` 6#) +#
(ch3 -# 0x80#)),
a# `plusAddr#` 4# #)
| otherwise -> fail 1#
where
-- all invalid sequences end up here:
fail n = (# '\0'#, a# `plusAddr#` n #)
-- '\xFFFD' would be the usual replacement character, but
-- that's a valid symbol in Haskell, so will result in a
-- confusing parse error later on. Instead we use '\0' which
-- will signal a lexer error immediately.
utf8DecodeChar :: Ptr Word8 -> (Char, Ptr Word8)
utf8DecodeChar (Ptr a#) =
case utf8DecodeChar# a# of (# c#, b# #) -> ( C# c#, Ptr b# )
-- UTF-8 is cleverly designed so that we can always figure out where
-- the start of the current character is, given any position in a
-- stream. This function finds the start of the previous character,
-- assuming there *is* a previous character.
utf8PrevChar :: Ptr Word8 -> IO (Ptr Word8)
utf8PrevChar p = utf8CharStart (p `plusPtr` (-1))
utf8CharStart :: Ptr Word8 -> IO (Ptr Word8)
utf8CharStart p = go p
where go p = do w <- peek p
if w >= 0x80 && w < 0xC0
then go (p `plusPtr` (-1))
else return p
utf8DecodeString :: Ptr Word8 -> Int -> IO [Char]
STRICT2(utf8DecodeString)
utf8DecodeString (Ptr a#) (I# len#)
= unpack a#
where
!end# = addr2Int# (a# `plusAddr#` len#)
unpack p#
| addr2Int# p# >=# end# = return []
| otherwise =
case utf8DecodeChar# p# of
(# c#, q# #) -> do
chs <- unpack q#
return (C# c# : chs)
countUTF8Chars :: Ptr Word8 -> Int -> IO Int
countUTF8Chars ptr bytes = go ptr 0
where
end = ptr `plusPtr` bytes
STRICT2(go)
go ptr n
| ptr >= end = return n
| otherwise = do
case utf8DecodeChar# (unPtr ptr) of
(# _, a #) -> go (Ptr a) (n+1)
unPtr :: Ptr a -> Addr#
unPtr (Ptr a) = a
utf8EncodeChar :: Char -> Ptr Word8 -> IO (Ptr Word8)
utf8EncodeChar c ptr =
let x = ord c in
case () of
_ | x > 0 && x <= 0x007f -> do
poke ptr (fromIntegral x)
return (ptr `plusPtr` 1)
-- NB. '\0' is encoded as '\xC0\x80', not '\0'. This is so that we
-- can have 0-terminated UTF-8 strings (see GHC.Base.unpackCStringUtf8).
| x <= 0x07ff -> do
poke ptr (fromIntegral (0xC0 .|. ((x `shiftR` 6) .&. 0x1F)))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 2)
| x <= 0xffff -> do
poke ptr (fromIntegral (0xE0 .|. (x `shiftR` 12) .&. 0x0F))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x `shiftR` 6) .&. 0x3F))
pokeElemOff ptr 2 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 3)
| otherwise -> do
poke ptr (fromIntegral (0xF0 .|. (x `shiftR` 18)))
pokeElemOff ptr 1 (fromIntegral (0x80 .|. ((x `shiftR` 12) .&. 0x3F)))
pokeElemOff ptr 2 (fromIntegral (0x80 .|. ((x `shiftR` 6) .&. 0x3F)))
pokeElemOff ptr 3 (fromIntegral (0x80 .|. (x .&. 0x3F)))
return (ptr `plusPtr` 4)
utf8EncodeString :: Ptr Word8 -> String -> IO ()
utf8EncodeString ptr str = go ptr str
where STRICT2(go)
go _ [] = return ()
go ptr (c:cs) = do
ptr' <- utf8EncodeChar c ptr
go ptr' cs
utf8EncodedLength :: String -> Int
utf8EncodedLength str = go 0 str
where STRICT2(go)
go n [] = n
go n (c:cs)
| ord c > 0 && ord c <= 0x007f = go (n+1) cs
| ord c <= 0x07ff = go (n+2) cs
| ord c <= 0xffff = go (n+3) cs
| otherwise = go (n+4) cs
-- -----------------------------------------------------------------------------
-- The Z-encoding
{-
This is the main name-encoding and decoding function. It encodes any
string into a string that is acceptable as a C name. This is done
right before we emit a symbol name into the compiled C or asm code.
Z-encoding of strings is cached in the FastString interface, so we
never encode the same string more than once.
The basic encoding scheme is this.
* Tuples (,,,) are coded as Z3T
* Alphabetic characters (upper and lower) and digits
all translate to themselves;
except 'Z', which translates to 'ZZ'
and 'z', which translates to 'zz'
We need both so that we can preserve the variable/tycon distinction
* Most other printable characters translate to 'zx' or 'Zx' for some
alphabetic character x
* The others translate as 'znnnU' where 'nnn' is the decimal number
of the character
Before After
--------------------------
Trak Trak
foo_wib foozuwib
> zg
>1 zg1
foo# foozh
foo## foozhzh
foo##1 foozhzh1
fooZ fooZZ
:+ ZCzp
() Z0T 0-tuple
(,,,,) Z5T 5-tuple
(# #) Z1H unboxed 1-tuple (note the space)
(#,,,,#) Z5H unboxed 5-tuple
(NB: There is no Z1T nor Z0H.)
-}
type UserString = String -- As the user typed it
type EncodedString = String -- Encoded form
zEncodeString :: UserString -> EncodedString
zEncodeString cs = case maybe_tuple cs of
Just n -> n -- Tuples go to Z2T etc
Nothing -> go cs
where
go [] = []
go (c:cs) = encode_digit_ch c ++ go' cs
go' [] = []
go' (c:cs) = encode_ch c ++ go' cs
unencodedChar :: Char -> Bool -- True for chars that don't need encoding
unencodedChar 'Z' = False
unencodedChar 'z' = False
unencodedChar c = c >= 'a' && c <= 'z'
|| c >= 'A' && c <= 'Z'
|| c >= '0' && c <= '9'
-- If a digit is at the start of a symbol then we need to encode it.
-- Otherwise package names like 9pH-0.1 give linker errors.
encode_digit_ch :: Char -> EncodedString
encode_digit_ch c | c >= '0' && c <= '9' = encode_as_unicode_char c
encode_digit_ch c | otherwise = encode_ch c
encode_ch :: Char -> EncodedString
encode_ch c | unencodedChar c = [c] -- Common case first
-- Constructors
encode_ch '(' = "ZL" -- Needed for things like (,), and (->)
encode_ch ')' = "ZR" -- For symmetry with (
encode_ch '[' = "ZM"
encode_ch ']' = "ZN"
encode_ch ':' = "ZC"
encode_ch 'Z' = "ZZ"
-- Variables
encode_ch 'z' = "zz"
encode_ch '&' = "za"
encode_ch '|' = "zb"
encode_ch '^' = "zc"
encode_ch '$' = "zd"
encode_ch '=' = "ze"
encode_ch '>' = "zg"
encode_ch '#' = "zh"
encode_ch '.' = "zi"
encode_ch '<' = "zl"
encode_ch '-' = "zm"
encode_ch '!' = "zn"
encode_ch '+' = "zp"
encode_ch '\'' = "zq"
encode_ch '\\' = "zr"
encode_ch '/' = "zs"
encode_ch '*' = "zt"
encode_ch '_' = "zu"
encode_ch '%' = "zv"
encode_ch c = encode_as_unicode_char c
encode_as_unicode_char :: Char -> EncodedString
encode_as_unicode_char c = 'z' : if isDigit (head hex_str) then hex_str
else '0':hex_str
where hex_str = showHex (ord c) "U"
-- ToDo: we could improve the encoding here in various ways.
-- eg. strings of unicode characters come out as 'z1234Uz5678U', we
-- could remove the 'U' in the middle (the 'z' works as a separator).
zDecodeString :: EncodedString -> UserString
zDecodeString [] = []
zDecodeString ('Z' : d : rest)
| isDigit d = decode_tuple d rest
| otherwise = decode_upper d : zDecodeString rest
zDecodeString ('z' : d : rest)
| isDigit d = decode_num_esc d rest
| otherwise = decode_lower d : zDecodeString rest
zDecodeString (c : rest) = c : zDecodeString rest
decode_upper, decode_lower :: Char -> Char
decode_upper 'L' = '('
decode_upper 'R' = ')'
decode_upper 'M' = '['
decode_upper 'N' = ']'
decode_upper 'C' = ':'
decode_upper 'Z' = 'Z'
decode_upper ch = {-pprTrace "decode_upper" (char ch)-} ch
decode_lower 'z' = 'z'
decode_lower 'a' = '&'
decode_lower 'b' = '|'
decode_lower 'c' = '^'
decode_lower 'd' = '$'
decode_lower 'e' = '='
decode_lower 'g' = '>'
decode_lower 'h' = '#'
decode_lower 'i' = '.'
decode_lower 'l' = '<'
decode_lower 'm' = '-'
decode_lower 'n' = '!'
decode_lower 'p' = '+'
decode_lower 'q' = '\''
decode_lower 'r' = '\\'
decode_lower 's' = '/'
decode_lower 't' = '*'
decode_lower 'u' = '_'
decode_lower 'v' = '%'
decode_lower ch = {-pprTrace "decode_lower" (char ch)-} ch
-- Characters not having a specific code are coded as z224U (in hex)
decode_num_esc :: Char -> EncodedString -> UserString
decode_num_esc d rest
= go (digitToInt d) rest
where
go n (c : rest) | isHexDigit c = go (16*n + digitToInt c) rest
go n ('U' : rest) = chr n : zDecodeString rest
go n other = error ("decode_num_esc: " ++ show n ++ ' ':other)
decode_tuple :: Char -> EncodedString -> UserString
decode_tuple d rest
= go (digitToInt d) rest
where
-- NB. recurse back to zDecodeString after decoding the tuple, because
-- the tuple might be embedded in a longer name.
go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest
go 0 ('T':rest) = "()" ++ zDecodeString rest
go n ('T':rest) = '(' : replicate (n-1) ',' ++ ")" ++ zDecodeString rest
go 1 ('H':rest) = "(# #)" ++ zDecodeString rest
go n ('H':rest) = '(' : '#' : replicate (n-1) ',' ++ "#)" ++ zDecodeString rest
go n other = error ("decode_tuple: " ++ show n ++ ' ':other)
{-
Tuples are encoded as
Z3T or Z3H
for 3-tuples or unboxed 3-tuples respectively. No other encoding starts
Z<digit>
* "(# #)" is the tycon for an unboxed 1-tuple (not 0-tuple)
There are no unboxed 0-tuples.
* "()" is the tycon for a boxed 0-tuple.
There are no boxed 1-tuples.
-}
maybe_tuple :: UserString -> Maybe EncodedString
maybe_tuple "(# #)" = Just("Z1H")
maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
(n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
_ -> Nothing
maybe_tuple "()" = Just("Z0T")
maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of
(n, ')' : _) -> Just ('Z' : shows (n+1) "T")
_ -> Nothing
maybe_tuple _ = Nothing
count_commas :: Int -> String -> (Int, String)
count_commas n (',' : cs) = count_commas (n+1) cs
count_commas n cs = (n,cs)
| ryantm/ghc | compiler/utils/Encoding.hs | bsd-3-clause | 13,525 | 0 | 29 | 4,017 | 3,646 | 1,856 | 1,790 | -1 | -1 |
-- Check that "->" is an instance of Eval
module ShouldSucceed where
instance Show (a->b) where
show _ = error "attempt to show function"
instance (Eq b) => Eq (a -> b) where
(==) f g = error "attempt to compare functions"
-- Since Eval is a superclass of Num this fails
-- unless -> is an instance of Eval
instance (Num b) => Num (a -> b) where
f + g = \a -> f a + g a
f - g = \a -> f a - g a
f * g = \a -> f a * g a
negate f = \a -> negate (f a)
abs f = \a -> abs (f a)
signum f = \a -> signum (f a)
fromInteger n = \a -> fromInteger n
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/typecheck/should_compile/tc088.hs | bsd-3-clause | 715 | 0 | 9 | 310 | 256 | 130 | 126 | 13 | 0 |
-- This one killed GHC 6.4 because it bogusly attributed
-- the CPR property to the construtor T
-- Result: a mkWWcpr crash
-- Needs -prof -auto-all to show it up
module ShouldCompile where
newtype T a = T { unT :: a }
f = unT
test cs = f $ case cs of
[] -> T []
(x:xs) -> T $ test cs
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/stranal/should_compile/newtype.hs | bsd-3-clause | 300 | 0 | 10 | 80 | 76 | 44 | 32 | 6 | 2 |
{-# LANGUAGE Trustworthy #-}
module Check03_A (
trace
) where
import qualified Debug.Trace as D
import qualified Data.ByteString.Lazy.Char8 as BS
-- | Allowed declasification
trace :: String -> a -> a
trace s = D.trace $ s ++ show a3
a3 :: BS.ByteString
a3 = BS.take 3 $ BS.repeat 'a'
| urbanslug/ghc | testsuite/tests/safeHaskell/check/Check03_A.hs | bsd-3-clause | 301 | 0 | 7 | 66 | 89 | 52 | 37 | 9 | 1 |
module Tests.Machine (tests) where
import Machine
import Data.Machine
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
import Test.QuickCheck.Property as Property
tests :: [Test]
tests = [ (testProperty "concatenation of result equal to input" prop_groupBy_concat)
, (testProperty "sublists contain only equal elements" prop_groupBy_equalelem)
, (testProperty "adjacent sublists do not contain equal elements" prop_groupBy_adjacentsNotEqual)]
prop_groupBy_concat :: [Int] -> Property.Result
prop_groupBy_concat xs =
mkResult (Just $ concat grouped == xs) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
prop_groupBy_equalelem :: [Int] -> Property.Result
prop_groupBy_equalelem xs =
mkResult (Just $ all sublistEq grouped) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
sublistEq [] = True
sublistEq (x:xs) = all (==x) xs
prop_groupBy_adjacentsNotEqual :: [Int] -> Property.Result
prop_groupBy_adjacentsNotEqual xs =
mkResult (Just $ adjNotEqual grouped) msg
where
grouped = run (source xs ~> groupBy (==))
msg = "grouping: " ++ (show grouped)
adjNotEqual (a:b:xs) = (not $ eq a b) && adjNotEqual (b:xs)
adjNotEqual _ = True
eq (a:_) (b:_) = a == b
eq _ _ = False
mkResult :: Maybe Bool -> String -> Property.Result
mkResult result msg = MkResult result True msg Nothing False [] []
| danstiner/clod | test/Tests/Machine.hs | mit | 1,504 | 0 | 10 | 285 | 504 | 269 | 235 | 34 | 3 |
{-|
Module : Language.Vigil.Simplify.Top
Description :
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : [email protected]
Stability : experimental
Simplifications for the top-level (globals and function declarations).
-}
{-# LANGUAGE OverloadedStrings #-}
module Language.Vigil.Simplify.Top where
import Data.List ( partition )
import Language.Common.Monad.Traverse
import Language.GoLite.Syntax.Types as G
import qualified Language.GoLite.Types as T
import Language.Vigil.Simplify.Core
import Language.Vigil.Simplify.Expr
import Language.Vigil.Simplify.Stmt
import Language.Vigil.Syntax as V
import Language.Vigil.Syntax.TyAnn
import Language.Vigil.Types
import Language.X86.Mangling
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe ( catMaybes )
import Data.Tuple ( swap )
-- | Simplifies a GoLite package into a Vigil program.
--
-- Global variables are separated from functions, and their initializations are
-- moved to a specific function. Functions themselves have their body simplified.
simplifyPackage :: TySrcAnnPackage -> Simplify TyAnnProgram
simplifyPackage (Package _ decls) = do
let (globs, funs) = partition isGlob decls
let globs' = filter isVar globs
fs <- fmap catMaybes $ forM funs $ \(G.TopLevelFun (G.FunDecl i ps _ bod)) -> do
modify (\s -> s { newDeclarations = [] }) -- Reset state of declarations.
bod' <- forM bod simplifyStmt -- Simplify body
ps' <- fmap catMaybes $ forM ps $ \(pid, _) -> do
m <- reinterpretGlobalIdEx pid
pure $ case m of
Nothing -> Nothing
Just i' -> Just $ V.VarDecl i'
nis' <- gets newDeclarations
let nvs' = map (swap . fmap V.VarDecl . swap) nis'
-- Look at the
forM_ nvs' (\(V.VarDecl i, b) ->
when (not b) $ modify $ \s -> s { inis = S.insert i $ inis s })
m <- reinterpretGlobalIdEx i
case m of
Nothing -> pure Nothing
Just i' -> pure $ Just $ V.FunDecl
{ _funDeclName = i'
, _funDeclArgs = ps'
, _funDeclVars = map fst nvs'
, _funDeclBody = concat bod'
}
vs <- forM globs' $ \(G.TopLevelDecl (G.VarDecl (G.VarDeclBody is _ es))) -> do
case es of
[] -> forM is $ \i -> do
m <- reinterpretGlobalIdEx i
case m of
Nothing -> pure (Nothing, [])
-- Come up with an initializer right here
Just i' -> pure (Just $ V.VarDecl i', [Fix $ V.Initialize i'])
_ -> forM (zip is es) $ \(i, e) -> do
m <- reinterpretGlobalIdEx i
(e', s) <- realizeToExpr =<< simplifyExpr e
pure $ case m of
Nothing ->
( Nothing
, s ++ [Fix $ V.ExprStmt e']
)
Just i' ->
( Just $ V.VarDecl i'
, s ++ [
Fix $ V.Assign (Ann (gidTy i') $ ValRef $ IdentVal i') e'
]
)
ss <- gets strings
-- create the initialization calls for the string literals
(vs2, ss') <- fmap unzip $ forM (M.assocs ss) $ \(g, str) -> do
gi <- makeIdent
stringType
(T.symbolFromString $ T.stringFromSymbol (gidOrigName g) ++ "data")
pure $
( ( Just $ V.VarDecl g
, [Fix $ V.Assign
(Ann (gidTy g) $ ValRef $ IdentVal g)
(Ann stringType $ V.InternalCall
(mangleFuncName "from_cstr")
[IdentValD gi]
)
]
)
, (gi, str)
)
modify $ \s -> s { strings = M.fromList ss' }
-- vs: pairs of declarations and their initializing statements
let vs' = concat vs ++ vs2
nis <- gets newDeclarations
let nvs = map (swap . fmap V.VarDecl . swap) nis
let fInit = V.FunDecl
{ _funDeclName = artificialGlobalId
(-1)
(mangleFuncName "gocode_init")
(funcType [] voidType)
, _funDeclArgs = []
, _funDeclVars = (map fst nvs)
, _funDeclBody = concat $ map snd vs'
}
let (main, notMain) = partition
(\(V.FunDecl i _ _ _) -> gidOrigName i == "main") (fInit:fs)
when (length main > 1) (throwError $ InvariantViolation "More than one main")
pure V.Program
{ _globals = catMaybes $ map fst vs'
, _funcs = notMain
, _main = case main of
[x] -> Just x
[] -> Nothing
_ -> error "Laws of physics broken"
}
where
isGlob (TopLevelDecl _) = True
isGlob _ = False
isVar (TopLevelDecl (G.VarDecl _)) = True
isVar _ = False
| djeik/goto | libgoto/Language/Vigil/Simplify/Top.hs | mit | 5,105 | 0 | 33 | 1,915 | 1,430 | 739 | 691 | 98 | 10 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
module Hickory.Graphics.Shader
( loadShader,
loadShaderFromPaths,
useShader,
getAttribLocation,
UniformLoc,
retrieveLoc,
ShaderID,
Shader (..),
)
where
import Control.Monad
import qualified Data.HashMap.Strict as HashMap
import Data.Int (Int32)
import Data.Text (Text, unpack)
import qualified Data.Text.Foreign as FText
import Data.Word (Word32)
import Foreign.C.String
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import Graphics.GL.Compatibility41 as GL
import Hickory.Utils.Utils
import Data.Maybe (catMaybes, fromMaybe)
data Shader = Shader
{ program :: ProgramID,
shaderIds :: [ShaderID],
uniformLocs :: HashMap.HashMap String UniformLoc
}
deriving (Show)
type UniformLoc = Int32
type ShaderID = Word32
type ProgramID = Word32
retrieveLoc :: String -> Shader -> Maybe UniformLoc
retrieveLoc name shader = HashMap.lookup name (uniformLocs shader)
glGetShaderi shaderId x = alloca (\ptr -> glGetShaderiv shaderId x ptr >> peek ptr)
glGetProgrami programId x = alloca (\ptr -> glGetProgramiv programId x ptr >> peek ptr)
glGetBoolean boolean = (== GL_TRUE) <$> alloca (\ptr -> glGetBooleanv boolean ptr >> peek ptr)
retrieveLog :: (GLenum -> IO GLint) -> (GLsizei -> Ptr GLsizei -> Ptr GLchar -> IO ()) -> IO (Maybe String)
retrieveLog lenFun infoFun = do
infoLen <- lenFun GL_INFO_LOG_LENGTH
let infoLen' = fromIntegral infoLen
if infoLen > 1
then do
info <- allocaArray infoLen' $ \buf -> do
infoFun infoLen nullPtr buf
peekCStringLen (buf, infoLen' - 1)
return $ Just info
else return Nothing
compileShader :: Text -> GLenum -> IO (Maybe GLuint)
compileShader source shaderType = do
compileSupported <- glGetBoolean GL_SHADER_COMPILER
unless compileSupported (error "ERROR: Shader compilation not supported.")
shaderId <- glCreateShader shaderType
withMany FText.withCStringLen [source] $ \strLens -> do
let (strs, lengths) = unzip strLens
withArray strs $ \strsArr ->
withArray (map fromIntegral lengths) $ \lenArr ->
glShaderSource shaderId 1 strsArr lenArr
glCompileShader shaderId
compiled <- glGetShaderi shaderId GL_COMPILE_STATUS
let didCompile = compiled /= 0
if didCompile
then return $ Just shaderId
else do
infoLog <- retrieveLog (glGetShaderi shaderId) (glGetShaderInfoLog shaderId)
case infoLog of
Just i -> do
print ("*** ERROR: Couldn't compile shader" :: String)
print i
_ -> return ()
glDeleteShader shaderId
return Nothing
linkProgram :: GLuint -> [GLuint] -> IO Bool
linkProgram programId shaders = do
mapM_ (glAttachShader programId) shaders
glLinkProgram programId
linked <- glGetProgrami programId GL_LINK_STATUS
let didLink = linked /= 0
unless didLink $ do
infoLog <- retrieveLog (glGetProgrami programId) (glGetProgramInfoLog programId)
case infoLog of
Just i -> do
print ("*** ERROR: Can't link shader program" :: String)
print i
_ -> return ()
return didLink
getAttribLocation progId name = withCString name (glGetAttribLocation progId)
getUniformLocation progId name = withCString name (glGetUniformLocation progId)
shaderSourceForPath :: String -> IO Text
shaderSourceForPath = readFileAsText
loadShaderFromPaths :: String -> String -> String -> [String] -> IO Shader
loadShaderFromPaths resPath vert frag uniforms = do
let prefix = resPath ++ "/Shaders/"
vpath = prefix ++ vert
fpath = prefix ++ frag
vsource <- shaderSourceForPath vpath
fsource <- shaderSourceForPath fpath
loadShader vsource Nothing fsource uniforms
loadShader :: Text -> Maybe Text -> Text -> [String] -> IO Shader
loadShader vert mgeom frag uniforms = do
let shaders = catMaybes
[ (,GL_GEOMETRY_SHADER) <$> mgeom
, Just (vert, GL_VERTEX_SHADER)
, Just (frag, GL_FRAGMENT_SHADER)
]
shIds <- forM shaders \(source, typ) -> do
fromMaybe (error $ "Couldn't compile shader: " ++ unpack source) <$>
compileShader source typ
prog <- buildShaderProgram shIds uniforms
case prog of
Just pr -> return pr
Nothing -> do
mapM_ glDeleteShader shIds
error $ "Failed to link shader program: " ++ unpack vert ++ "\n\n" ++ maybe "" unpack mgeom ++ "\n\n" ++ unpack frag
buildShaderProgram :: [ShaderID] -> [String] -> IO (Maybe Shader)
buildShaderProgram shaders uniforms = do
programId <- glCreateProgram
linked <- linkProgram programId shaders
if not linked
then return Nothing
else do
let sh = Shader programId shaders
res <-
sh
<$> ( foldM
( \hsh name -> do
loc <- getUniformLocation programId name
return $ HashMap.insert name loc hsh
)
HashMap.empty
uniforms
)
return $ Just res
useShader :: Shader -> IO ()
useShader Shader {program} = glUseProgram program
| asivitz/Hickory | Hickory/Graphics/Shader.hs | mit | 5,182 | 0 | 20 | 1,200 | 1,552 | 771 | 781 | -1 | -1 |
import Data.List
phi :: Int -> Int
phi n = product xs
where
xs = map (\(p, m) -> (p - 1) * p ^ (m - 1)) (primeFactorsMult n)
primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult = map encoder . group . primeFactors
where
encoder xs = (head xs, length xs)
primeFactors :: Int -> [Int]
primeFactors n = primeFactors' n 2
primeFactors' :: Int -> Int -> [Int]
primeFactors' n p
| isFactor n p && n' > 1 = p : primeFactors' n' p
| not $ isFactor n p && n > 1 = primeFactors' n (p + 1)
| otherwise = [p]
where
n' = n `div` p
isFactor n p = n `mod` p == 0
nextPrime :: Int -> Int
nextPrime n
| isPrime (n + 1) = n + 1
| otherwise = nextPrime (n + 1)
isPrime :: Int -> Bool
isPrime n = isPrime' n 2
isPrime' :: Int -> Int -> Bool
isPrime' 2 _ = True
isPrime' n k
| (n - 1) == k = True
| n `mod` k == 0 = False
| otherwise = isPrime' n (k + 1)
| curiousily/haskell-99problems | 37.hs | mit | 870 | 0 | 13 | 226 | 466 | 238 | 228 | 28 | 1 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.List
import Data.HashTable.IO as HT
import Control.Monad
type HashTable k v = HT.BasicHashTable k v
createHashTable ::IO (HashTable Int Int)
createHashTable = do
ht <- HT.new
return ht
solveProblem :: String -> String -> IO [Int]
solveProblem ips nsstr = do
htable <- createHashTable
let [n, k] = map read . words $ ips
let ns = map read . words $ nsstr
forM_ ns $ \n -> do
check <- HT.lookup htable n
if check == Nothing
then do
HT.insert htable n 1
else do
let Just val = check
HT.insert htable n (val+1)
kvs <- HT.toList htable
let fns = map fst . filter ((>=k) . snd) $ kvs
let os = filter (`elem` fns) $ ns
if null os then return [-1] else return (nub os)
runTestCase :: Int -> IO ()
runTestCase 0 = return ()
runTestCase n = do
ips <- getLine
ns <- getLine
ans <- solveProblem ips ns
putStrLn $ unwords . map show $ ans
runTestCase (n-1)
main :: IO ()
main = do
ntc <- getLine
runTestCase (read ntc)
| cbrghostrider/Hacking | HackerRank/FunctionalProgramming/Recursion/filterElements_HashTable_fast.hs | mit | 1,458 | 0 | 17 | 367 | 471 | 230 | 241 | 37 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Firestone.Player ( drawCard
, summonMinionAt
) where
import Firestone.Types
import Firestone.Utils
import Control.Monad.State
import Control.Lens
drawCard :: State Player ()
drawCard = do
player <- get
case length (player^.deck.cards) of
0 -> do
hero.health -= player^.fatigue
fatigue += 1
otherwise -> do
let (x:xs) = player^.deck.cards
hand %= take 10 . (|> x)
deck.cards .= xs
summonMinionAt :: Int -> Minion -> State Player ()
summonMinionAt pos m = activeMinions %= insertAt pos m
| Jinxit/firestone | src/Firestone/Player.hs | mit | 870 | 0 | 16 | 263 | 205 | 107 | 98 | -1 | -1 |
module Test (
testWorldRod
, testWorldCircle
, testWorldRigidSkin
, testWorldBlob
, testWorldGrid
) where
import Data.Tuple
import Control.Monad as M
import Control.Monad.State.Lazy
import Control.Applicative
import Internal
import Vector
import Types
testWorldRod :: World
testWorldRod = execState f $ makeEmptyWorld "testWorldRod"
where
f = do
node1 <- insPointMass (PointMass (Vector2D 100 100) (Vector2D 0 0) 1)
node2 <- insPointMass (PointMass (Vector2D 200 200) (Vector2D 0 0) 1)
insSpring (Spring 1 50 0) node1 node2
testWorldCircle :: World
testWorldCircle = execState f $ makeEmptyWorld "testWorldCircle"
where
f = let nodeCount = 32
r = 100
(cx, cy) = (400, 200)
spring = Spring 1 25 0
rotate n = take . length <*> drop n . cycle
in do
nodeList <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r + cx)
((sin angle) * r + cy))
(Vector2D 0 0)
1
M.sequence $ zipWith (insSpring spring) <*> rotate 1 $ nodeList
testWorldBlob :: World
testWorldBlob = execState f $ makeEmptyWorld "testWorldBlob"
where
f = let nodeCount = 16
r1 = 100
r2 = 150
(cx, cy) = (400, 200)
innerSpring = Spring 0.3 70 0.5
outerSpring = Spring 1 50 0.5
rigidSpring = Spring 3 70 0.5
rotate n = take . length <*> drop n . cycle
in do
centerNode <- insPointMass $ PointMass (Vector2D cx cy) (Vector2D 0 0) 1
nodeList1 <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r1 + cx)
((sin angle) * r1 + cy))
(Vector2D 0 0)
1
nodeList2 <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r2 + cx)
((sin angle) * r2 + cy))
(Vector2D 0 0)
1
M.sequence_ $ zipWith (insSpring outerSpring) <*> rotate 1 $ nodeList1
M.sequence_ $ zipWith (insSpring outerSpring) <*> rotate 1 $ nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) nodeList1 nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) (rotate 1 nodeList1) nodeList2
M.sequence_ $ zipWith (insSpring innerSpring) nodeList1 (rotate 1 nodeList2)
M.forM nodeList1 $ insSpring rigidSpring centerNode
testWorldRigidSkin :: World
testWorldRigidSkin = execState f $ makeEmptyWorld "testWorldRigidSkin"
where
f = let nodeCount = 16
r = 100
(cx, cy) = (400, 200)
spring1 = Spring 5 50 0.1
spring2 = Spring 5 60 0.1
spring3 = Spring 5 70 0.1
rotate n = take . length <*> drop n . cycle
in do
nodeList <- M.forM (drop 1 [0, 2 * pi / nodeCount .. 2 * pi]) $ \angle ->
insPointMass $ PointMass (Vector2D ((cos angle) * r + cx)
((sin angle) * r + cy))
(Vector2D 0 0)
1
M.sequence_ $ zipWith (insSpring spring1) <*> rotate 1 $ nodeList
M.sequence_ $ zipWith (insSpring spring2) <*> rotate 2 $ nodeList
M.sequence_ $ zipWith (insSpring spring3) <*> rotate 3 $ nodeList
testWorldGrid :: World
testWorldGrid = execState f $ makeEmptyWorld "testWorldGrid"
where
f = let spring = Spring 50 50 0.1
in do
nodeListXY <- M.forM [0, 1..5] $ \x -> do
nodeListY <- M.forM [0, 1..5] $ \y -> do
let sx = x * 50
sy = y * 50
insPointMass (PointMass (Vector2D (400 + sx) (50 + sy)) (Vector2D 0 0) 1)
M.sequence_ $ zipWith (insSpring spring) <*> drop 1 $ nodeListY
return nodeListY
M.sequence_ $ concat $ zipWith (zipWith (insSpring spring)) (drop 1 nodeListXY) nodeListXY
| ThatSnail/hs-softbody | Test.hs | mit | 4,841 | 0 | 27 | 2,155 | 1,511 | 757 | 754 | 91 | 1 |
module Main where
import LI11718
import SimulateT6
import AnimateT6
import System.Environment
import Text.Read
main = do
animaT6 (${mapa}) (${pista}) (${frames}) (${players}) | hpacheco/HAAP | examples/plab/oracle/AnimateT6Match.hs | mit | 182 | 4 | 9 | 28 | 59 | 41 | 18 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (void)
import Data.Monoid ((<>))
import qualified Data.Vector.Storable.Mutable as V
import Foreign.C.Types
import Foreign.ForeignPtr (mallocForeignPtrBytes)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import qualified Language.Haskell.TH as TH
import Prelude
import qualified Test.Hspec as Hspec
import Text.RawString.QQ (r)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Storable (peek, poke)
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Unsafe as CU
import qualified Language.C.Inline.Interruptible as CI
import qualified Language.C.Inline.Internal as C
import qualified Language.C.Inline.ContextSpec
import qualified Language.C.Inline.ParseSpec
import qualified Language.C.Types as C
import qualified Language.C.Types.ParseSpec
import Dummy
C.context (C.baseCtx <> C.fptrCtx <> C.funCtx <> C.vecCtx <> C.bsCtx)
C.include "<math.h>"
C.include "<stddef.h>"
C.include "<stdint.h>"
C.include "<stdio.h>"
C.verbatim [r|
int francescos_mul(int x, int y) {
return x * y;
}
|]
foreign import ccall "francescos_mul" francescos_mul :: Int -> Int -> Int
main :: IO ()
main = Hspec.hspec $ do
Hspec.describe "Language.C.Types.Parse" Language.C.Types.ParseSpec.spec
Hspec.describe "Language.C.Inline.Context" Language.C.Inline.ContextSpec.spec
Hspec.describe "Language.C.Inline.Parse" Language.C.Inline.ParseSpec.spec
Hspec.describe "TH integration" $ do
Hspec.it "inlineCode" $ do
let c_add = $(C.inlineCode $ C.Code
TH.Unsafe -- Call safety
Nothing
[t| Int -> Int -> Int |] -- Call type
"francescos_add" -- Call name
-- C Code
[r| int francescos_add(int x, int y) { int z = x + y; return z; } |]
False) -- not a function pointer
c_add 3 4 `Hspec.shouldBe` 7
Hspec.it "inlineItems" $ do
let c_add3 = $(do
here <- TH.location
C.inlineItems
TH.Unsafe
False -- not a function pointer
Nothing -- no postfix
here
[t| CInt -> CInt |]
(C.quickCParser_ True "int" C.parseType)
[("x", C.quickCParser_ True "int" C.parseType)]
[r| return x + 3; |])
c_add3 1 `Hspec.shouldBe` 1 + 3
Hspec.it "inlineExp" $ do
let x = $(do
here <- TH.location
C.inlineExp
TH.Safe
here
[t| CInt |]
(C.quickCParser_ True "int" C.parseType)
[]
[r| 1 + 4 |])
x `Hspec.shouldBe` 1 + 4
Hspec.it "inlineCode" $ do
francescos_mul 3 4 `Hspec.shouldBe` 12
Hspec.it "exp" $ do
let x = 3
let y = 4
z <- [C.exp| int{ $(int x) + $(int y) + 5 } |]
z `Hspec.shouldBe` x + y + 5
Hspec.it "pure" $ do
let x = 2
let y = 10
let z = [C.pure| int{ $(int x) + 10 + $(int y) } |]
z `Hspec.shouldBe` x + y + 10
Hspec.it "unsafe exp" $ do
let x = 2
let y = 10
z <- [CU.exp| int{ 7 + $(int x) + $(int y) } |]
z `Hspec.shouldBe` x + y + 7
Hspec.it "interruptible exp" $ do
let x = 2
let y = 10
z <- [CI.exp| int{ 7 + $(int x) + $(int y) } |]
z `Hspec.shouldBe` x + y + 7
Hspec.it "void exp" $ do
[C.exp| void { printf("Hello\n") } |]
Hspec.it "Foreign.C.Types library types" $ do
let x = 1
pd <- [C.block| ptrdiff_t { char a[2]; return &a[1] - &a[0] + $(ptrdiff_t x); } |]
pd `Hspec.shouldBe` 2
sz <- [C.exp| size_t { sizeof (char) } |]
sz `Hspec.shouldBe` 1
um <- [C.exp| uintmax_t { UINTMAX_MAX } |]
um `Hspec.shouldBe` maxBound
Hspec.it "stdint.h types" $ do
let x = 2
i16 <- [C.exp| int16_t { 1 + $(int16_t x) } |]
i16 `Hspec.shouldBe` 3
let y = 9
u32 <- [C.exp| uint32_t { $(uint32_t y) * 7 } |]
u32 `Hspec.shouldBe` 63
Hspec.it "foreign pointer argument" $ do
fptr <- mallocForeignPtrBytes 32
ptr <- [C.exp| int* { $fptr-ptr:(int *fptr) } |]
ptr `Hspec.shouldBe` unsafeForeignPtrToPtr fptr
Hspec.it "function pointer argument" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
ackermannPtr <- $(C.mkFunPtr [t| CInt -> CInt -> IO CInt |]) $ \m n -> return $ ackermann m n
let x = 3
let y = 4
z <- [C.exp| int { $(int (*ackermannPtr)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "function pointer result" $ do
c_add <- [C.exp| int (*)(int, int) { &francescos_add } |]
x <- $(C.peekFunPtr [t| CInt -> CInt -> IO CInt |]) c_add 1 2
x `Hspec.shouldBe` 1 + 2
Hspec.it "quick function pointer argument" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
let ackermann_ m n = return $ ackermann m n
let x = 3
let y = 4
z <- [C.exp| int { $fun:(int (*ackermann_)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "function pointer argument (pure)" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
ackermannPtr <- $(C.mkFunPtr [t| CInt -> CInt -> CInt |]) ackermann
let x = 3
let y = 4
let z = [C.pure| int { $(int (*ackermannPtr)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "quick function pointer argument (pure)" $ do
let ackermann m n
| m == 0 = n + 1
| m > 0 && n == 0 = ackermann (m - 1) 1
| m > 0 && n > 0 = ackermann (m - 1) (ackermann m (n - 1))
| otherwise = error "ackermann"
let x = 3
let y = 4
let z = [C.pure| int { $fun:(int (*ackermann)(int, int))($(int x), $(int y)) } |]
z `Hspec.shouldBe` ackermann x y
Hspec.it "test mkFunPtrFromName" $ do
fun <- $(C.mkFunPtrFromName 'dummyFun)
z <- [C.exp| double { $(double (*fun)(double))(3.0) } |]
z' <- dummyFun 3.0
z `Hspec.shouldBe` z'
Hspec.it "vectors" $ do
let n = 10
vec <- V.replicate (fromIntegral n) 3
sum' <- V.unsafeWith vec $ \ptr -> [C.block| int {
int i;
int x = 0;
for (i = 0; i < $(int n); i++) {
x += $(int *ptr)[i];
}
return x;
} |]
sum' `Hspec.shouldBe` 3 * 10
Hspec.it "quick vectors" $ do
vec <- V.replicate 10 3
sum' <- [C.block| int {
int i;
int x = 0;
for (i = 0; i < $vec-len:vec; i++) {
x += $vec-ptr:(int *vec)[i];
}
return x;
} |]
sum' `Hspec.shouldBe` 3 * 10
Hspec.it "bytestrings" $ do
let bs = "foo"
bits <- [C.block| int {
int i, bits = 0;
for (i = 0; i < $bs-len:bs; i++) {
char ch = $bs-ptr:bs[i];
bits += (ch * 01001001001ULL & 042104210421ULL) % 017;
}
return bits;
} |]
bits `Hspec.shouldBe` 16
Hspec.it "Haskell identifiers" $ do
let x' = 3
void $ [C.exp| int { $(int x') } |]
let ä = 3
void $ [C.exp| int { $(int ä) } |]
void $ [C.exp| int { $(int Prelude.maxBound) } |]
Hspec.it "Function pointers" $ do
alloca $ \x_ptr -> do
poke x_ptr 7
let fp = [C.funPtr| void poke42(int *ptr) { *ptr = 42; } |]
[C.exp| void { $(void (*fp)(int *))($(int *x_ptr)) } |]
x <- peek x_ptr
x `Hspec.shouldBe` 42
Hspec.it "cpp namespace identifiers" $ do
C.cIdentifierFromString True "Test::Test" `Hspec.shouldBe` Right "Test::Test"
Hspec.it "cpp template identifiers" $ do
C.cIdentifierFromString True "std::vector" `Hspec.shouldBe` Right "std::vector"
| fpco/inline-c | inline-c/test/tests.hs | mit | 8,498 | 0 | 25 | 2,818 | 2,516 | 1,297 | 1,219 | 196 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | This is a Haskell port of the Hashids library by Ivan Akimov.
-- This is /not/ a cryptographic hashing algorithm. Hashids is typically
-- used to encode numbers to a format suitable for appearance in places
-- like urls.
--
-- See the official Hashids home page: <http://hashids.org>
--
-- Hashids is a small open-source library that generates short, unique,
-- non-sequential ids from numbers. It converts numbers like 347 into
-- strings like @yr8@, or a list of numbers like [27, 986] into @3kTMd@.
-- You can also decode those ids back. This is useful in bundling several
-- parameters into one or simply using them as short UIDs.
module Web.Hashids
( HashidsContext
-- * How to use
-- $howto
-- ** Encoding
-- $encoding
-- ** Decoding
-- $decoding
-- ** Randomness
-- $randomness
-- *** Repeating numbers
-- $repeating
-- *** Incrementing number sequence
-- $incrementing
-- ** Curses\! \#\$\%\@
-- $curses
-- * API
, version
-- ** Context object constructors
, createHashidsContext
, hashidsSimple
, hashidsMinimum
-- ** Encoding and decoding
, encodeHex
, decodeHex
, encode
, encodeList
, decode
-- ** Convenience wrappers
, encodeUsingSalt
, encodeListUsingSalt
, decodeUsingSalt
, encodeHexUsingSalt
, decodeHexUsingSalt
) where
import Data.ByteString ( ByteString )
import Data.Foldable ( toList )
import Data.List ( (\\), nub, intersect, foldl' )
import Data.List.Split ( chunksOf )
import Data.Sequence ( Seq )
import Numeric ( showHex, readHex )
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.Sequence as Seq
-- $howto
--
-- Note that most of the examples on this page require the OverloadedStrings extension.
-- $encoding
--
-- Unless you require a minimum length for the generated hash, create a
-- context using 'hashidsSimple' and then call 'encode' and 'decode' with
-- this object.
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Web.Hashids
-- >
-- > main :: IO ()
-- > main = do
-- > let context = hashidsSimple "oldsaltyswedishseadog"
-- > print $ encode context 42
--
-- This program will output
--
-- > "kg"
--
-- To specify a minimum hash length, use 'hashidsMinimum' instead.
--
-- > main = do
-- > let context = hashidsMinimum "oldsaltyswedishseadog" 12
-- > print $ encode context 42
--
-- The output will now be
--
-- > "W3xbdkgdy42v"
--
-- If you only need the context once, you can use one of the provided wrappers
-- to simplify things.
--
-- > main :: IO ()
-- > main = print $ encodeUsingSalt "oldsaltyswedishseadog" 42
--
-- On the other hand, if your implementation invokes the hashing algorithm
-- frequently without changing the configuration, it is probably better to
-- define partially applied versions of 'encode', 'encodeList', and 'decode'.
--
-- > import Web.Hashids
-- >
-- > context :: HashidsContext
-- > context = createHashidsContext "oldsaltyswedishseadog" 12 "abcdefghijklmnopqrstuvwxyz"
-- >
-- > encode' = encode context
-- > encodeList' = encodeList context
-- > decode' = decode context
-- >
-- > main :: IO ()
-- > main = print $ encode' 12345
--
-- Use a custom alphabet and 'createHashidsContext' if you want to make your
-- hashes \"unique\".
--
-- > main = do
-- > let context = createHashidsContext "oldsaltyswedishseadog" 0 "XbrNfdylm5qtnP19R"
-- > print $ encode context 1
--
-- The output is now
--
-- > "Rd"
--
-- To encode a list of numbers, use `encodeList`.
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [0, 1, 2]
--
-- > "yJUWHx"
-- $decoding
--
-- Decoding a hash returns a list of numbers,
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
-- Decoding will not work if the salt is changed:
--
-- > main = do
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5
-- >
-- > print $ decodeUsingSalt "this is my pepper" hash
--
-- When decoding fails, the empty list is returned.
--
-- > []
--
-- $randomness
--
-- Hashids is based on a modified version of the Fisher-Yates shuffle. The
-- primary purpose is to obfuscate ids, and it is not meant for security
-- purposes or compression. Having said that, the algorithm does try to make
-- hashes unguessable and unpredictable. See the official Hashids home page
-- for details: <http://hashids.org>
-- $repeating
--
-- > let context = hashidsSimple "this is my salt" in encodeList context $ replicate 4 5
--
-- There are no repeating patterns in the hash to suggest that four identical
-- numbers are used:
--
-- > "1Wc8cwcE"
--
-- The same is true for increasing numbers:
--
-- > let context = hashidsSimple "this is my salt" in encodeList context [1..10]
--
-- > "kRHnurhptKcjIDTWC3sx"
-- $incrementing
--
-- > let context = hashidsSimple "this is my salt" in map (encode context) [1..5]
--
-- > ["NV","6m","yD","2l","rD"]
-- $curses
--
-- The algorithm tries to avoid generating common curse words in English by
-- never placing the following letters next to each other:
--
-- > c, C, s, S, f, F, h, H, u, U, i, I, t, T
{-# INLINE (|>) #-}
(|>) :: a -> (a -> b) -> b
(|>) a f = f a
{-# INLINE splitOn #-}
splitOn :: ByteString -> ByteString -> [ByteString]
splitOn = BS.splitWith . flip BS.elem
-- | Opaque data type with various internals required for encoding and decoding.
data HashidsContext = Context
{ guards :: !ByteString
, seps :: !ByteString
, salt :: !ByteString
, minHashLength :: !Int
, alphabet :: !ByteString }
-- | Hashids version number.
version :: String
version = "1.0.2"
-- | Create a context object using the given salt, a minimum hash length, and
-- a custom alphabet. If you only need to supply the salt, or the first two
-- arguments, use 'hashidsSimple' or 'hashidsMinimum' instead.
--
-- Changing the alphabet is useful if you want to make your hashes unique,
-- i.e., create hashes different from those generated by other applications
-- relying on the same algorithm.
createHashidsContext :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> String -- ^ Alphabet
-> HashidsContext
createHashidsContext salt minHashLen alphabet
| length uniqueAlphabet < minAlphabetLength
= error $ "alphabet must contain at least " ++ show minAlphabetLength ++ " unique characters"
| ' ' `elem` uniqueAlphabet
= error "alphabet cannot contain spaces"
| BS.null seps'' || fromIntegral (BS.length alphabet') / fromIntegral (BS.length seps'') > sepDiv
= case sepsLength - BS.length seps'' of
diff | diff > 0
-> res (BS.drop diff alphabet') (seps'' `BS.append` BS.take diff alphabet')
_ -> res alphabet' (BS.take sepsLength seps'')
| otherwise = res alphabet' seps''
where
res ab _seps =
let shuffled = consistentShuffle ab salt
guardCount = ceiling (fromIntegral (BS.length shuffled) / guardDiv)
context = Context
{ guards = BS.take guardCount _seps
, seps = BS.drop guardCount _seps
, salt = salt
, minHashLength = minHashLen
, alphabet = shuffled }
in if BS.length shuffled < 3
then context
else context{ guards = BS.take guardCount shuffled
, seps = _seps
, alphabet = BS.drop guardCount shuffled }
seps' = C8.pack $ uniqueAlphabet `intersect` seps
seps'' = consistentShuffle seps' salt
sepsLength =
case ceiling (fromIntegral (BS.length alphabet') / sepDiv) of
1 -> 2
n -> n
uniqueAlphabet = nub alphabet
alphabet' = C8.pack $ uniqueAlphabet \\ seps
minAlphabetLength = 16
sepDiv = 3.5
guardDiv = 12
seps = "cfhistuCFHISTU"
defaultAlphabet :: String
defaultAlphabet = ['a'..'z'] ++ ['A'..'Z'] ++ "1234567890"
-- | Create a context object using the default alphabet and the provided salt,
-- without any minimum required length.
hashidsSimple :: ByteString -- ^ Salt
-> HashidsContext
hashidsSimple salt = createHashidsContext salt 0 defaultAlphabet
-- | Create a context object using the default alphabet and the provided salt.
-- The generated hashes will have a minimum length as specified by the second
-- argument.
hashidsMinimum :: ByteString -- ^ Salt
-> Int -- ^ Minimum required hash length
-> HashidsContext
hashidsMinimum salt minimum = createHashidsContext salt minimum defaultAlphabet
-- | Decode a hash generated with 'encodeHex'.
--
-- /Example use:/
--
-- > decodeHex context "yzgwD"
--
decodeHex :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> String
decodeHex context hash = concatMap (drop 1 . flip showHex "") numbers
where
numbers = decode context hash
-- | Encode a hexadecimal number.
--
-- /Example use:/
--
-- > encodeHex context "ff83"
--
encodeHex :: HashidsContext -- ^ A Hashids context object
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHex context str
| not (all hexChar str) = ""
| otherwise = encodeList context $ map go $ chunksOf 12 str
where
go str = let [(a,_)] = readHex ('1':str) in a
hexChar c = c `elem` ("0123456789abcdefABCDEF" :: String)
-- | Decode a hash.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = decode context "rD" -- == [5]
--
decode :: HashidsContext -- ^ A Hashids context object
-> ByteString -- ^ Hash
-> [Int]
decode ctx@Context{..} hash
| BS.null hash = []
| encodeList ctx res /= hash = []
| otherwise = res
where
res = splitOn seps tail
|> foldl' go ([], alphabet)
|> fst
|> reverse
hashArray = splitOn guards hash
alphabetLength = BS.length alphabet
Just str@(lottery, tail) =
BS.uncons $ hashArray !! case length hashArray of
0 -> error "Internal error."
2 -> 1
3 -> 1
_ -> 0
prefix = BS.cons lottery salt
go (xs, ab) ssh =
let buffer = prefix `BS.append` ab
ab' = consistentShuffle ab buffer
in (unhash ssh ab':xs, ab')
numbersHashInt :: [Int] -> Int
numbersHashInt xs = foldr ((+) . uncurry mod) 0 $ zip xs [100 .. ]
-- | Encode a single number.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encode context 5 -- == "rD"
--
encode :: HashidsContext -- ^ A Hashids context object
-> Int -- ^ Number to encode
-> ByteString
encode context n = encodeList context [n]
-- | Encode a list of numbers.
--
-- /Example use:/
--
-- > let context = hashidsSimple "this is my salt"
-- > hash = encodeList context [2, 3, 5, 7, 11] -- == "EOurh6cbTD"
--
encodeList :: HashidsContext -- ^ A Hashids context object
-> [Int] -- ^ List of numbers
-> ByteString
encodeList _ [] = error "encodeList: empty list"
encodeList Context{..} numbers =
res |> expand False |> BS.reverse
|> expand True |> BS.reverse
|> expand' alphabet'
where
(res, alphabet') = foldl' go (BS.singleton lottery, alphabet) (zip [0 .. ] numbers)
expand rep str
| BS.length str < minHashLength
= let ix = if rep then BS.length str - 3 else 0
jx = fromIntegral (BS.index str ix) + hashInt
in BS.index guards (jx `mod` guardsLength) `BS.cons` str
| otherwise = str
expand' ab str
| BS.length str < minHashLength
= let ab' = consistentShuffle ab ab
str' = BS.concat [BS.drop halfLength ab', str, BS.take halfLength ab']
in expand' ab' $ case BS.length str' - minHashLength of
n | n > 0
-> BS.take minHashLength $ BS.drop (div n 2) str'
_ -> str'
| otherwise = str
hashInt = numbersHashInt numbers
lottery = alphabet `BS.index` (hashInt `mod` alphabetLength)
prefix = BS.cons lottery salt
numLast = length numbers - 1
guardsLength = BS.length guards
alphabetLength = BS.length alphabet
halfLength = div alphabetLength 2
go (r, ab) (i, number)
| number < 0 = error "all numbers must be non-negative"
| otherwise =
let shuffled = consistentShuffle ab (BS.append prefix ab)
last = hash number shuffled
n = number `mod` (fromIntegral (BS.head last) + i) `mod` BS.length seps
suffix = if i < numLast
then BS.singleton (seps `BS.index` n)
else BS.empty
in (BS.concat [r,last,suffix], shuffled)
-- Exchange elements at positions i and j in a sequence.
exchange :: Int -> Int -> Seq a -> Seq a
exchange i j seq = i <--> j $ j <--> i $ seq
where
a <--> b = Seq.update a $ Seq.index seq b
consistentShuffle :: ByteString -> ByteString -> ByteString
consistentShuffle alphabet salt
| 0 == saltLength = alphabet
| otherwise = BS.pack $ toList x
where
(_,x) = zip3 [len, pred len .. 1] xs ys |> foldl' go (0, toSeq alphabet)
xs = cycle [0 .. saltLength - 1]
ys = map (fromIntegral . saltLookup) xs
saltLookup ix = BS.index salt (ix `mod` saltLength)
saltLength = BS.length salt
toSeq = BS.foldl' (Seq.|>) Seq.empty
len = BS.length alphabet - 1
go (p, ab) (i, v, ch) =
let shuffled = exchange i j ab
p' = p + ch
j = mod (ch + v + p') i
in (p', shuffled)
unhash :: ByteString -> ByteString -> Int
unhash input alphabet = BS.foldl' go 0 input
where
go carry item =
let Just index = BS.elemIndex item alphabet
in carry * alphabetLength + index
alphabetLength = BS.length alphabet
hash :: Int -> ByteString -> ByteString
hash input alphabet
| 0 == input = BS.take 1 alphabet
| otherwise = BS.reverse $ BS.unfoldr go input
where
len = BS.length alphabet
go 0 = Nothing
go i = Just (alphabet `BS.index` (i `mod` len), div i len)
-- | Encode a number using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encode' with one of the
-- constructors instead.
encodeUsingSalt :: ByteString -- ^ Salt
-> Int -- ^ Number
-> ByteString
encodeUsingSalt = encode . hashidsSimple
-- | Encode a list of numbers using the provided salt.
--
-- This function wrapper creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'encodeList' with one of the
-- constructors instead.
encodeListUsingSalt :: ByteString -- ^ Salt
-> [Int] -- ^ Numbers
-> ByteString
encodeListUsingSalt = encodeList . hashidsSimple
-- | Decode a hash using the provided salt.
--
-- This convenience function creates a context with the default alphabet.
-- If the same context is used repeatedly, use 'decode' with one of the
-- constructors instead.
decodeUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> [Int]
decodeUsingSalt = decode . hashidsSimple
-- | Shortcut for 'encodeHex'.
encodeHexUsingSalt :: ByteString -- ^ Salt
-> String -- ^ Hexadecimal number represented as a string
-> ByteString
encodeHexUsingSalt = encodeHex . hashidsSimple
-- | Shortcut for 'decodeHex'.
decodeHexUsingSalt :: ByteString -- ^ Salt
-> ByteString -- ^ Hash
-> String
decodeHexUsingSalt = decodeHex . hashidsSimple
| jkramarz/hashids-haskell | Web/Hashids.hs | mit | 16,464 | 0 | 19 | 4,709 | 2,946 | 1,650 | 1,296 | 237 | 4 |
-- vim: set ts=2 sw=2 sts=0 ff=unix foldmethod=indent:
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["-isrc/lib", "src/cli/Main.hs"]
| eji/mix-kenall-geocode | test/doctest.hs | mit | 159 | 0 | 6 | 26 | 34 | 20 | 14 | 4 | 1 |
module Main where
f::Int -> Int -> Int -> Int
f x1 x2 x3 = if x1 == 1
then x2
else f (x1 - 1) x3 ((x2 * x2) + (x3 * x3))
main = do x1 <- readLn
print (f x1 1 1)
| sebschrader/programmierung-ss2015 | E12/A2b.hs | mit | 202 | 0 | 10 | 86 | 108 | 57 | 51 | 7 | 2 |
{-
Mackerel: a strawman device definition DSL for Barrelfish
Copyright (c) 2007-2011, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Main where
import System.IO
import System.IO.Error
import System.Console.GetOpt
import System.FilePath
import System.Exit
import System.Environment
import Data.Maybe
import Data.List
import Text.ParserCombinators.Parsec as Parsec
import Text.Printf
import qualified MackerelParser
import qualified BitFieldDriver
import qualified ShiftDriver
import Checks
import Dev
import Control.Exception
--
-- Command line options and parsing code
--
-- Datatypes for carrying command options around
data Target = BitFieldDriver | ShiftDriver | NullDriver deriving (Eq, Show)
data Options = Options {
opt_infilename :: Maybe String,
opt_outfilename :: Maybe String,
opt_includedirs :: [String],
opt_target :: Target,
opt_usage_error :: Bool,
opt_verbosity :: Integer
} deriving (Show,Eq)
defaultOptions :: Options
defaultOptions = Options {
opt_infilename = Nothing,
opt_outfilename = Nothing,
opt_includedirs = [],
opt_target = ShiftDriver,
opt_usage_error = False,
opt_verbosity = 1 }
-- For driving System.GetOpt
options :: [OptDescr (Options -> Options)]
options =
[ Option ['c'] ["input-file"]
(ReqArg (\f opts -> opts { opt_infilename = Just f } ) "file")
"input file"
, Option ['I'] ["include-dir"]
(ReqArg (\ d opts -> opts { opt_includedirs = opt_includedirs opts ++ [d] }) "dir")
"include directory (can be given multiple times)"
, Option ['v'] ["verbose"]
(NoArg (\ opts -> opts { opt_verbosity = opt_verbosity opts + 1 } ))
"increase verbosity level"
, Option ['o'] ["output"]
(ReqArg (\ f opts -> opts { opt_outfilename = Just f }) "file")
"output file name"
, Option ['S'] ["shift-driver"]
(NoArg (\ opts -> opts { opt_target = ShiftDriver } ))
"use shift driver (default; preferred)"
, Option ['n'] ["null-driver"]
(NoArg (\ opts -> opts { opt_target = NullDriver } ))
"use null output driver (don't generate any C)"
, Option ['B'] ["bitfield-driver"]
(NoArg (\ opts -> opts { opt_target = BitFieldDriver } ))
"use bitfield driver (deprecrated: do not use)"
]
--
-- Set the correct default input and output files
--
defaultOutput :: Options -> Options
defaultOutput opts =
case opt_outfilename opts of
(Just _) ->
opts
Nothing ->
opts { opt_outfilename =
Just (case opt_infilename opts of
(Just i) ->
((dropExtension $ takeFileName i) ++ "_dev.h")
Nothing -> "mackerel_output.h"
)
}
defaultInput :: Options -> [String] -> IO (Options)
defaultInput opts [f] =
if isNothing $ opt_infilename opts
then return (defaultOutput (opts { opt_infilename = Just f }))
else usageError []
defaultInput opts [] =
if (isJust $ opt_infilename opts)
then return (defaultOutput opts)
else usageError []
defaultInput _ _ = usageError []
compilerOpts :: [String] -> IO (Options)
compilerOpts argv =
case getOpt Permute options argv of
(o,n,[]) -> defaultInput (foldl (flip id) defaultOptions o) n
(_,_,errs) -> usageError errs
usageError :: [String] -> IO (Options)
usageError errs =
ioError (userError (concat errs ++ usageInfo usage options))
where usage = "Usage: mackerel <options> <input file>"
--
-- Processing source files
---
-- Null compilation
nullCompiler :: String -> String -> Dev.Rec -> String
nullCompiler _ _ _ = ""
-- Perform run-time checks
run_checks :: String -> Dev.Rec -> IO String
run_checks input_fn dev =
case (Checks.check_all input_fn dev) of
Just errors ->
do { (hPutStrLn stderr (unlines [ e ++ "\n" | e <-errors]))
; System.Exit.exitWith (ExitFailure 1)
}
Nothing -> do { return "" }
-- Parsing the input file into an AST
parseFile :: String -> IO MackerelParser.DeviceFile
parseFile fname = do
src <- readFile fname
case (runParser MackerelParser.devfile () fname src) of
Left err -> ioError $ userError ("Parse error at: " ++ (show err))
Right x -> return x
-- Traverse the include path to find an import file
findImport :: [String] -> String -> IO MackerelParser.DeviceFile
findImport [] f =
ioError (userError $ printf "Can't find import '%s'" f)
findImport (d:t) f =
do
Control.Exception.catch (parseFile (d </> f))
(\e -> (if isDoesNotExistError e then findImport t f else ioError e))
-- Perform the transitive closure of all the imports
resolveImports :: [MackerelParser.DeviceFile] -> [String]
-> IO [MackerelParser.DeviceFile]
resolveImports dfl path =
let allimports = nub $ concat [ il | (MackerelParser.DeviceFile _ il) <- dfl ]
gotimports = [ n | (MackerelParser.DeviceFile (MackerelParser.Device n _ _ _ _) _) <- dfl ]
required = allimports \\ gotimports
in
case required of
[] -> return dfl
(t:_) -> do { i <- (findImport path (t ++ ".dev"))
; resolveImports (dfl ++ [i]) path
}
testentry :: IO ()
testentry =
let input_fn = "../../devices/xapic.dev"
output_fn = "x2apic.dev.h"
includedirs = ["../../devices"]
in
do { hPutStrLn stdout ("IN: " ++ input_fn)
; hPutStrLn stdout ("OUT: " ++ output_fn)
; df <- parseFile input_fn
; dfl <- resolveImports [df] includedirs
; let dev = make_dev df (tail dfl) in
do { _ <- run_checks input_fn dev
; outFileD <- openFile output_fn WriteMode
; hPutStr outFileD (ShiftDriver.compile input_fn output_fn dev)
; hClose outFileD
}
}
-- Main entry point of Mackernel
main :: IO ()
main = do { cli <- System.Environment.getArgs
; opts <- compilerOpts cli
; let input_fn = fromJust $ opt_infilename opts
output_fn = fromJust $ opt_outfilename opts
in
do { df <- parseFile input_fn
; dfl <- resolveImports [df] (opt_includedirs opts)
; let dev = make_dev df (tail dfl) in
do { _ <- run_checks input_fn dev
; outFileD <- openFile output_fn WriteMode
; hPutStr outFileD ((case (opt_target opts) of
NullDriver -> nullCompiler
ShiftDriver -> ShiftDriver.compile
BitFieldDriver -> BitFieldDriver.compile)
input_fn output_fn dev)
; hClose outFileD
}
}
}
| gandro/mackerel-standalone | src/Main.hs | mit | 6,947 | 0 | 22 | 1,927 | 1,923 | 1,026 | 897 | 149 | 3 |
{-# LANGUAGE RecordWildCards #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Yacht (yacht, Category(..))
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "yacht" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = yacht category dice `shouldBe` expected
data Case = Case { description :: String
, dice :: [Int]
, category :: Category
, expected :: Int
}
cases :: [Case]
cases = [ Case { description = "Yacht"
, dice = [5, 5, 5, 5, 5]
, category = Yacht
, expected = 50
}
, Case { description = "Not Yacht"
, dice = [1, 3, 3, 2, 5]
, category = Yacht
, expected = 0
}
, Case { description = "Ones"
, dice = [1, 1, 1, 3, 5]
, category = Ones
, expected = 3
}
, Case { description = "Ones, out of order"
, dice = [3, 1, 1, 5, 1]
, category = Ones
, expected = 3
}
, Case { description = "No ones"
, dice = [4, 3, 6, 5, 5]
, category = Ones
, expected = 0
}
, Case { description = "Twos"
, dice = [2, 3, 4, 5, 6]
, category = Twos
, expected = 2
}
, Case { description = "Fours"
, dice = [1, 4, 1, 4, 1]
, category = Fours
, expected = 8
}
, Case { description = "Yacht counted as threes"
, dice = [3, 3, 3, 3, 3]
, category = Threes
, expected = 15
}
, Case { description = "Yacht of 3s counted as fives"
, dice = [3, 3, 3, 3, 3]
, category = Fives
, expected = 0
}
, Case { description = "Sixes"
, dice = [2, 3, 4, 5 ,6]
, category = Sixes
, expected = 6
}
, Case { description = "Full house two small, three big"
, dice = [2, 2, 4, 4, 4]
, category = FullHouse
, expected = 16
}
, Case { description = "Full house three small, two big"
, dice = [5, 3, 3, 5, 3]
, category = FullHouse
, expected = 19
}
, Case { description = "Two pair is not a full house"
, dice = [2, 2, 4, 4, 5]
, category = FullHouse
, expected = 0
}
, Case { description = "Four of a kind is not a full house"
, dice = [1, 4, 4, 4, 4]
, category = FullHouse
, expected = 0
}
, Case { description = "Yacht is not a full house"
, dice = [2, 2, 2, 2, 2]
, category = FullHouse
, expected = 0
}
, Case { description = "Four of a Kind"
, dice = [6, 6, 4, 6, 6]
, category = FourOfAKind
, expected = 24
}
, Case { description = "Yacht can be scored as Four of a Kind"
, dice = [3, 3, 3, 3, 3]
, category = FourOfAKind
, expected = 12
}
, Case { description = "Full house is not Four of a Kind"
, dice = [3, 3, 3, 5, 5]
, category = FourOfAKind
, expected = 0
}
, Case { description = "Little Straight"
, dice = [3, 5, 4, 1, 2]
, category = LittleStraight
, expected = 30
}
, Case { description = "Little Straight as Big Straight"
, dice = [1, 2, 3, 4, 5]
, category = BigStraight
, expected = 0
}
, Case { description = "Four in order but not a little straight"
, dice = [1, 1, 2, 3, 4]
, category = LittleStraight
, expected = 0
}
, Case { description = "No pairs but not a little straight"
, dice = [1, 2, 3, 4, 6]
, category = LittleStraight
, expected = 0
}
, Case { description = "Minimum is 1, maximum is 5, but not a little straight"
, dice = [1, 1, 3, 4, 5]
, category = LittleStraight
, expected = 0
}
, Case { description = "Big Straight"
, dice = [4, 6, 2, 5, 3]
, category = BigStraight
, expected = 30
}
, Case { description = "Big Straight as little straight"
, dice = [6, 5, 4, 3, 2]
, category = LittleStraight
, expected = 0
}
, Case { description = "No pairs but not a big straight"
, dice = [6, 5, 4, 3, 1]
, category = BigStraight
, expected = 0
}
, Case { description = "Choice"
, dice = [3, 3, 5, 6, 6]
, category = Choice
, expected = 23
}
, Case { description = "Yacht as choice"
, dice = [2, 2, 2, 2, 2]
, category = Choice
, expected = 10
}
]
-- e49e29f23b211af8433c17fccd71adfb852fda37
| exercism/xhaskell | exercises/practice/yacht/test/Tests.hs | mit | 5,789 | 0 | 10 | 2,850 | 1,434 | 930 | 504 | 128 | 1 |
module Lists where
import System.Random (getStdRandom, randomR)
import Control.Monad
import Data.List (sortBy, groupBy)
{-
- 1 Problem 1
- (*) Find the last element of a list.
-
- Example in Haskell:
- Prelude> myLast [1,2,3,4]
- 4
- Prelude> myLast ['x','y','z']
- 'z'
-}
myLast :: [a] -> a
myLast [] = error "list is empty"
myLast [x] = x
myLast (_:xs) = myLast xs
{-
- 2 Problem 2
- (*) Find the last but one element of a list.
-
- Example in Haskell:
- Prelude> myButLast [1,2,3,4]
- 3
- Prelude> myButLast ['a'..'z']
- 'y'
-}
myButLast :: [a] -> a
myButLast [] = error "list is empty"
myButLast [_] = error "list has only one element"
myButLast [x, _] = x
myButLast (_:xs) = myButLast xs
{-
- 3 Problem 3
- (*) Find the K'th element of a list. The first element in the list is number 1.
-
- Example in Haskell:
- Prelude> elementAt [1,2,3] 2
- 2
- Prelude> elementAt "haskell" 5
- 'e'
-}
elementAt :: [a] -> Int -> a
elementAt [] _ = error "list is empty"
elementAt _ n | n < 1 = error $ "invalid index:" ++ show n
elementAt (x:_) 1 = x
elementAt (_:xs) n = elementAt xs $ n - 1
{-
- 4 Problem 4
- (*) Find the number of elements of a list.
-
- Example in Haskell:
- Prelude> myLength [123, 456, 789]
- 3
- Prelude> myLength "Hello, world!"
- 13
-}
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + myLength xs
{-
- 5 Problem 5
- (*) Reverse a list.
-
- Example in Haskell:
- Prelude> myReverse "A man, a plan, a canal, panama!"
- "!amanap ,lanac a ,nalp a ,nam A"
- Prelude> myReverse [1,2,3,4]
- [4,3,2,1]
-}
myReverse :: [a] -> [a]
myReverse xs = myReverse' xs []
where myReverse' [] ls = ls
myReverse' (h:ts) ls = myReverse' ts (h:ls)
{-
- 6 Problem 6
- (*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).
-
- Example in Haskell:
- *Main> isPalindrome [1,2,3]
- False
- *Main> isPalindrome "madamimadam"
- True
- *Main> isPalindrome [1,2,4,8,16,8,4,2,1]
- True
-}
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = xs == myReverse xs
{-
- 7 Problem 7
- (**) Flatten a nested list structure.
-
- Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).
-
- Example in Haskell:
- We have to define a new data type, because lists in Haskell are homogeneous.
-
- data NestedList a = Elem a | List [NestedList a]
- *Main> flatten (Elem 5)
- [5]
- *Main> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])
- [1,2,3,4,5]
- *Main> flatten (List [])
- []
-}
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List []) = []
flatten (List (x:xs)) = flatten x ++ flatten (List xs)
{-
- 8 Problem 8
- (**) Eliminate consecutive duplicates of list elements.
-
- If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
-
- Example in Haskell:
- > compress "aaaabccaadeeee"
- "abcade"
-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress [x] = [x]
compress (x:y:zs) | x == y = compress $ y:zs
| otherwise = x:(compress $ y:zs)
{-
- 9 Problem 9
- (**) Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.
-
- Example in Haskell:
- *Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a',
- 'a', 'd', 'e', 'e', 'e', 'e']
- ["aaaa","b","cc","aa","d","eeee"]
-}
pack :: (Eq a) => [a] -> [[a]]
pack [] = []
pack (x:xs) = (x:takeWhile (== x) xs):(pack $ dropWhile (== x) xs)
{-
- 10 Problem 10
- (*) Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method.
- Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.
-
- Example in Haskell:
- encode "aaaabccaadeeee"
- [(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')]
-}
encode :: (Eq a) => [a] -> [(Int, a)]
encode ls = map (\x -> (length x, head x)) $ pack ls
{-
- 1 Problem 11
- (*) Modified run-length encoding.
-
- Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list.
- Only elements with duplicates are transferred as (N E) lists.
-
- Example in Haskell:
- P11> encodeModified "aaaabccaadeeee"
- [Multiple 4 'a',Single 'b',Multiple 2 'c',
- Multiple 2 'a',Single 'd',Multiple 4 'e']
-}
data Code a = Single a | Multiple Int a
deriving (Show, Eq)
encodeModified :: (Eq a) => [a] -> [Code a]
encodeModified ls = map f $ encode ls
where f (n, x) | n == 1 = Single x
| otherwise = Multiple n x
{-
- 2 Problem 12
- (**) Decode a run-length encoded list.
-
- Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.
-
- Example in Haskell:
-
- P12> decodeModified
- [Multiple 4 'a',Single 'b',Multiple 2 'c',
- Multiple 2 'a',Single 'd',Multiple 4 'e']
- "aaaabccaadeeee"
-}
decodeModified :: [Code a] -> [a]
decodeModified [] = []
decodeModified (Single x:xs) = x:decodeModified xs
decodeModified (Multiple n x:xs) = multi x n ++ decodeModified xs
where multi _ 0 = []
multi y k = x:multi y (k - 1)
{-
- 3 Problem 13
- (**) Run-length encoding of a list (direct solution).
-
- Implement the so-called run-length encoding data compression method directly.
- I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them.
- As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.
-
- Example in Haskell:
- P13> encodeDirect "aaaabccaadeeee"
- [Multiple 4 'a',Single 'b',Multiple 2 'c',
- Multiple 2 'a',Single 'd',Multiple 4 'e']
-}
encodeDirect :: Eq a => [a] -> [Code a]
encodeDirect [] = []
encodeDirect ls = foldr f [] ls
where f x [] = [Multiple 1 x]
f x (Multiple n y:ys) | x == y = Multiple (n + 1) y:ys
| otherwise = Multiple 1 x:Multiple n y:ys
f _ _ = error "unexpected pattern"
{-
- 4 Problem 14
- (*) Duplicate the elements of a list.
-
- Example in Haskell:
- > dupli [1, 2, 3]
- [1,1,2,2,3,3]
-}
dupli :: [a] -> [a]
dupli [] = []
dupli (x:xs) = x:x:dupli xs
{-
- 5 Problem 15
- (**) Replicate the elements of a list a given number of times.
-
- Example in Haskell:
- > repli "abc" 3
- "aaabbbccc"
-}
repli :: [a] -> Int -> [a]
repli [] _ = []
repli (x:xs) n | n < 0 = error ("illegal argument n:" ++ show n)
| otherwise = foldr (const (x:)) (repli xs n) [1..n]
{-
- 6 Problem 16
- (**) Drop every N'th element from a list.
-
- Example in Haskell:
- *Main> dropEvery "abcdefghik" 3
- "abdeghk"
-}
dropEvery :: [a] -> Int -> [a]
dropEvery _ n | n <= 0 = error ("illegal argument n:" ++ show n)
dropEvery ls n = dropEvery' ls n
where dropEvery' [] _ = []
dropEvery' (_:xs) 1 = dropEvery' xs n
dropEvery' (x:xs) k = x:dropEvery' xs (k - 1)
{-
- 7 Problem 17
- (*) Split a list into two parts; the length of the first part is given.
-
- Do not use any predefined predicates.
-
- Example in Haskell:
- *Main> split "abcdefghik" 3
- ("abc", "defghik")
-}
split :: [a] -> Int -> ([a], [a])
split _ n | n < 0 = error ("illegal argument n:" ++ show n)
split ls n = (take n ls, drop n ls)
{-
- 8 Problem 18
- (**) Extract a slice from a list.
-
- Given two indices, i and k, the slice is the list containing the elements between the i'th and k'th element
- of the original list (both limits included). Start counting the elements with 1.
-
- Example in Haskell:
- *Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7
- "cdefg"
-}
slice :: [a] -> Int -> Int -> [a]
slice _ i j | j < i = []
slice ls i j = drop (i - 1) $ take j ls
{-
- 9 Problem 19
- (**) Rotate a list N places to the left.
-
- Hint: Use the predefined functions length and (++).
-
- Examples in Haskell:
- *Main> rotate ['a','b','c','d','e','f','g','h'] 3
- "defghabc"
-
- *Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
- "ghabcdef"
-}
rotate :: [a] -> Int -> [a]
rotate [] _ = []
rotate ls 0 = ls
rotate ls n | length ls < n = rotate ls $ mod n $ length ls
| n < 0 = rotate ls $ n + length ls
| otherwise = (drop n ls) ++ (take n ls)
{-
- 10 Problem 20
- (*) Remove the K'th element from a list.
-
- Example in Haskell:
- *Main> removeAt 2 "abcd"
- ('b',"acd")
-}
removeAt :: Int -> [a] -> (a, [a])
removeAt n ls | length ls == 0 = error "list is empty"
| length ls < n = error $ "illegal argument n:" ++ show n
| n <= 0 = error $ "illegal argument n:" ++ show n
| otherwise = (head ls2, ls1 ++ tail ls2)
where (ls1, ls2) = split ls $ n - 1
{-
- 1 Problem 21
- Insert an element at a given position into a list.
-
- Example in Haskell:
- P21> insertAt 'X' "abcd" 2
- "aXbcd"
-}
insertAt :: a -> [a] -> Int -> [a]
insertAt e [] _ = [e]
insertAt e (x:xs) n | n <= 1 = e:x:xs
| otherwise = x:insertAt e xs (n - 1)
{-
- 2 Problem 22
- Create a list containing all integers within a given range.
-
- Example in Haskell:
- Prelude> range 4 9
- [4,5,6,7,8,9]
-}
range :: Int -> Int -> [Int]
range s e | e < s = []
| s == e = [e]
| otherwise = s:range (s + 1) e
{-
- 3 Problem 23
- Extract a given number of randomly selected elements from a list.
-
- Example in Haskell:
- Prelude System.Random>rnd_select "abcdefgh" 3 >>= putStrLn
- eda
-}
rnd_select :: [a] -> Int -> IO [a]
rnd_select _ 0 = return []
rnd_select [] _ = error "list is empty"
rnd_select ls n | n < 0 = error $ "illegal argument n:" ++ show n
| otherwise = do pos <- replicateM n $ getStdRandom $ randomR (0, length ls - 1)
return [ls !! p | p <- pos]
{-
- 4 Problem 24
- Lotto: Draw N different random numbers from the set 1..M.
-
- Example in Haskell:
- Prelude System.Random>diff_select 6 49
- Prelude System.Random>[23,1,17,33,21,37]
-}
diff_select :: Int -> Int -> IO [Int]
diff_select n m | n < 0 = error $ "illegal argument n:" ++ show n
| m <= 0 = error $ "illegal argument m:" ++ show m
| otherwise = rnd_select [1..m] n
{-
- 5 Problem 25
- Generate a random permutation of the elements of a list.
-
- Example:
-
- * (rnd-permu '(a b c d e f))
- (B A D C E F)
- Example in Haskell:
-
- Prelude System.Random>rnd_permu "abcdef"
- Prelude System.Random>"badcef"
-}
rnd_permu :: [a] -> IO [a]
rnd_permu ls = rnd_select ls $ length ls
{-
- 6 Problem 26
- (**) Generate the combinations of K distinct objects chosen from the N elements of a list
-
- In how many ways can a committee of 3 be chosen from a group of 12 people?
- We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients).
- For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list.
-
- Example in Haskell:
- > combinations 3 "abcdef"
- ["abc","abd","abe",...]
-}
combinations :: Int -> [a] -> [[a]]
combinations r ls | r < 0 = error $ "illegal argument r:" ++ show r
| r > length ls = []
| r == 0 = [[]]
| otherwise = (map (x:) $ combinations (r - 1) xs) ++ combinations r xs
where (x:xs) = ls
{-
- 7 Problem 27
- Group the elements of a set into disjoint subsets.
-
- a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list.
-
- b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups.
-
- Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...).
- However, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...).
-
- You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients".
-
- Example in Haskell:
- P27> group [2,3,4] ["aldo","beat","carla","david","evi","flip","gary","hugo","ida"]
- [[["aldo","beat"],["carla","david","evi"],["flip","gary","hugo","ida"]],...]
- (altogether 1260 solutions)
-
- 27> group [2,2,5] ["aldo","beat","carla","david","evi","flip","gary","hugo","ida"]
- [[["aldo","beat"],["carla","david"],["evi","flip","gary","hugo","ida"]],...]
- (altogether 756 solutions)
-}
group3 :: Eq a => [a] -> [[[a]]]
-- group3 ls = concatMap group2 $ combinations 2 ls
-- where group2 g1 = map (\g2 -> [g1, g2, remove_all g2 g1]) $ combinations 3 xs
-- where xs = remove_all g1 ls
-- remove_all _ [] = []
-- remove_all [] ys = ys
-- remove_all (e:es) ys = filter (/= e) $ remove_all es ys
group3 ls = group [2, 3, 4] ls
group :: Eq a => [Int] -> [a] -> [[[a]]]
group [] _ = [[]]
group ns ls | sum ns /= length ls = error "Cannot create groups"
| minimum ns < 0 = error "Cannot create groups"
| otherwise = concatMap group2 $ combinations n ls
where (n:ms) = ns
group2 g1 = map (g1:) $ group ms xs
where xs = remove_all g1 ls
remove_all _ [] = []
remove_all [] ys = ys
remove_all (e:es) ys = filter (/= e) $ remove_all es ys
{-
- Sorting a list of lists according to length of sublists
-
- a) We suppose that a list contains elements that are lists themselves.
- The objective is to sort the elements of this list according to their length.
- E.g. short lists first, longer lists later, or vice versa.
-
- Example in Haskell:
- Prelude>lsort ["abc","de","fgh","de","ijkl","mn","o"]
- Prelude>["o","de","de","mn","abc","fgh","ijkl"]
-
- b) Again, we suppose that a list contains elements that are lists themselves.
- But this time the objective is to sort the elements of this list according to their length frequency;
- i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.
-
- Example in Haskell:
- lfsort ["abc", "de", "fgh", "de", "ijkl", "mn", "o"]
- ["ijkl","o","abc","fgh","de","de","mn"]
-}
lsort :: [[a]] -> [[a]]
lsort ls = sortBy (\x y -> compare (length x) (length y)) ls
lfsort :: [[a]] -> [[a]]
lfsort ls = concatMap (fst) $ sortBy (\x y -> compare (snd x) (snd y)) $ freq ls
where freq xs = map (\x -> (x, length x)) $ groupBy (\x y -> length x == length y) $ sortBy (\x y -> compare (length y) (length x)) xs
| yyotti/99Haskell | src/main/Lists.hs | mit | 15,556 | 0 | 13 | 4,302 | 3,115 | 1,594 | 1,521 | 136 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GADTs #-}
module Bench.Rec where
import Data.Vinyl
import Data.Vinyl.Syntax ()
type Fields = '[ '( "a0", Int ), '( "a1", Int ), '( "a2", Int ), '( "a3", Int )
, '( "a4", Int ), '( "a5", Int ), '( "a6", Int ), '( "a7", Int )
, '( "a8", Int ), '( "a9", Int ), '( "a10", Int ), '( "a11", Int )
, '( "a12", Int ), '( "a13", Int ), '( "a14", Int ), '( "a15", Int )
]
mkRec :: Int -> Rec ElField Fields
mkRec i= Field i :& Field i :& Field i :& Field i :&
Field i :& Field i :& Field i :& Field i :&
Field i :& Field i :& Field i :& Field i :&
Field i :& Field i :& Field i :& Field 99 :&
RNil
sumRec :: Rec ElField Fields -> Int
sumRec str =
get #a0 str + get #a1 str + get #a2 str + get #a3 str + get #a4 str
+ get #a5 str + get #a6 str + get #a7 str + get #a8 str
+ get #a9 str + get #a10 str + get #a11 str + get #a12 str
+ get #a13 str + get #a14 str + get #a15 str
where
get (_label :: Label s) r =
let (Field v) = rget @'(s, _) r
in v
{-# INLINE get #-}
| VinylRecords/Vinyl | benchmarks/Bench/Rec.hs | mit | 1,312 | 0 | 21 | 435 | 562 | 296 | 266 | 29 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-|
Module : Web.Facebook.Messenger.Types.Requests.Attachment.Templates.AirlineBoardingPass
Copyright : (c) Felix Paulusma, 2016
License : MIT
Maintainer : [email protected]
Stability : semi-experimental
Send a message that contains boarding passes for one or more flights or one more passengers.
Message bubbles will be grouped by flight information. (/if the flight information matches, all passengers will be share the same bubble/)
Multiple bubbles are automatically sent for all `BoardingPass` elements with different values for `AirlineFlightInfo`.
In the future, we may group all boarding passes into the same bubble.
https://developers.facebook.com/docs/messenger-platform/send-messages/template/airline-boarding-pass
-}
module Web.Facebook.Messenger.Types.Requests.Attachment.Templates.AirlineBoardingPass (
-- * Boarding Pass Template
AirlineBoardingPass (..)
, BoardingPass (..)
-- ** QR / Barcode
, qrCode
, barCode
, AirlineQRBarCode (..)
, AirlineQRCode (..)
, AirlineBarCode (..)
-- * Custom Fields
, AirlineField (..)
)
where
import Control.Monad (unless)
import Data.Aeson
import Data.Aeson.Types (Parser)
import qualified Data.HashMap.Strict as HM
import Data.Text (Text, unpack)
import Web.Facebook.Messenger.Internal
import Web.Facebook.Messenger.Types.Requests.Attachment.Templates.Airline (AirlineFlightInfo)
import Web.Facebook.Messenger.Types.Static (URL)
-- ------------------------------- --
-- AIRLINE BOARDING PASS REQUEST --
-- ------------------------------- --
-- | Template for sending boarding passes to users
data AirlineBoardingPass = AirlineBoardingPass
{ abptIntroMessage :: Text -- ^ Introduction message
, abptLocale :: Text
-- ^ Locale must be a two-letter ISO 639-1 language code and a ISO 3166-1 alpha-2 region code
-- separated by an underscore character. Used to translate field labels (e.g. en_US).
--
-- https://developers.facebook.com/docs/messenger-platform/messenger-profile/supported-locales
, abptThemeColor :: Maybe Text -- ^ Background color of the attachment. Must be a RGB hexadecimal string (default #009ddc)
, abptBoardingPass :: [BoardingPass] -- ^ Boarding passes for passengers
} deriving (Eq, Show, Read, Ord)
-- | Boarding pass for a passenger
--
-- N.B. `abpAuxiliaryFields` and `abpSecondaryFields` are rendered left first to right last
data BoardingPass = BoardingPass
{ abpPassengerName :: Text -- ^ Passenger name (e.g. @"SMITH/NICOLAS"@)
, abpPnrNumber :: Text -- ^ Passenger name record number (Booking Number)
, abpSeat :: Maybe Text -- ^ Seat number for passenger
, abpAuxiliaryFields :: [AirlineField] -- ^ Flexible information to display in the auxiliary section (limited to 5)
, abpSecondaryFields :: [AirlineField] -- ^ Flexible information to display in the secondary section (limited to 5)
, abpLogoImageUrl :: URL -- ^ URL for the logo image
, abpHeaderImageUrl :: Maybe URL -- ^ URL for the header image
, abpHeaderTextField :: Maybe AirlineField -- ^ Text for the header field
, abpQrBarCode :: AirlineQRBarCode -- ^ /use `qrCode` or `barCode` to construct the `AirlineQRBarCode`/
, abpAboveBarCodeImageUrl :: URL -- ^ URL of thin image above the barcode
, abpFlightInfo :: AirlineFlightInfo -- ^ Information about the flight
} deriving (Eq, Show, Read, Ord)
-- | QR code or Bar code used as the boarding pass
data AirlineQRBarCode = AirlineQR AirlineQRCode
| AirlineBar AirlineBarCode
deriving (Eq, Show, Read, Ord)
-- | Takes Aztec or QR text.
qrCode :: Text -> AirlineQRBarCode
qrCode = AirlineQR . AirlineQRCode
-- | Aztec or QR code
newtype AirlineQRCode =
AirlineQRCode { getQRCode :: Text }
deriving (Eq, Show, Read, Ord, FromJSON, ToJSON)
-- | Takes an image URL.
barCode :: URL -> AirlineQRBarCode
barCode = AirlineBar . AirlineBarCode
-- | URL of the barcode image
newtype AirlineBarCode =
AirlineBarCode { barCodeImageUrl :: URL }
deriving (Eq, Show, Read, Ord, FromJSON, ToJSON)
-- | Custom field to add information to the `BoardingPass`
data AirlineField = AirlineField
{ afLabel :: Text -- Label for the additional field
, afValue :: Text -- Value for the additional field
} deriving (Eq, Show, Read, Ord)
-- ----------------------- --
-- AIRLINE INSTANCES --
-- ----------------------- --
instance ToJSON AirlineBoardingPass where
toJSON (AirlineBoardingPass intro loc theme passes) =
object' [ "template_type" .=! String "airline_boardingpass"
, "intro_message" .=! intro
, "locale" .=! loc
, "theme_color" .=!! theme
, "boarding_pass" .=! passes
]
instance ToJSON BoardingPass where
toJSON abp = object' $ extra : basis
where
extra = case abpQrBarCode abp of
AirlineQR qr -> "qr_code" .=! qr
AirlineBar bar -> "barcode_image_url" .=! bar
basis = [ "passenger_name" .=! abpPassengerName abp
, "pnr_number" .=! abpPnrNumber abp
, "seat" .=!! abpSeat abp
, "logo_image_url" .=! abpLogoImageUrl abp
, "header_image_url" .=!! abpHeaderImageUrl abp
, "header_text_field" .=!! abpHeaderTextField abp
, "above_bar_code_image_url" .=! abpAboveBarCodeImageUrl abp
, "flight_info" .=! abpFlightInfo abp
, mEmptyList "auxiliary_fields" $ take 5 $ abpAuxiliaryFields abp
, mEmptyList "secondary_fields" $ take 5 $ abpSecondaryFields abp
]
instance ToJSON AirlineField where
toJSON (AirlineField label value) =
object [ "label" .= label
, "value" .= value
]
-- ---------------------------- --
-- FromJSON AIRLINE INSTANCES --
-- ---------------------------- --
instance FromJSON AirlineBoardingPass where
parseJSON = withObject "AirlineBoardingPass" $ \o -> do
typ <- o .: "template_type" :: Parser Text
unless (typ == "airline_boardingpass") $
fail $ "AirlineBoardingPass: wrong \"type\" value: " `mappend` unpack typ
AirlineBoardingPass <$> o .: "intro_message"
<*> o .: "locale"
<*> o .:? "theme_color"
<*> o .:? "boarding_pass" .!= []
instance FromJSON BoardingPass where
parseJSON = withObject "BoardingPass" $ \o -> do
let mQRCode = "qr_code" `HM.lookup` o
mBarCode = "barcode_image_url" `HM.lookup` o
eitherQrBar = case (mQRCode,mBarCode) of
(Just v,Nothing) -> AirlineQR <$> parseJSON v
(Nothing,Just v) -> AirlineBar <$> parseJSON v
_ -> fail "BoardingPass: needs either \"qr_code\" or \"barcode_image_url\""
BoardingPass <$> o .: "passenger_name"
<*> o .: "pnr_number"
<*> o .:? "seat"
<*> o .:? "auxiliary_fields" .!= []
<*> o .:? "secondary_fields" .!= []
<*> o .: "logo_image_url"
<*> o .:? "header_image_url"
<*> o .:? "header_text_field"
<*> eitherQrBar
<*> o .: "above_bar_code_image_url"
<*> o .: "flight_info"
instance FromJSON AirlineField where
parseJSON = withObject "AirlineField" $ \o ->
AirlineField <$> o .: "label"
<*> o .: "value"
| Vlix/facebookmessenger | src/Web/Facebook/Messenger/Types/Requests/Attachment/Templates/AirlineBoardingPass.hs | mit | 7,456 | 0 | 32 | 1,775 | 1,221 | 693 | 528 | 112 | 1 |
-- | Random AI (RAI) Charles, playing not really randomly.
module RaiCharles (aiRaiCharles) where
import AI
import Yinsh
heuristic :: RaiCharles -> AIValue
heuristic _ = 42 -- yeah..
data RaiCharles = RaiCharles { gs :: GameState
, pl :: Int
}
instance AIPlayer RaiCharles where
valueForWhite = heuristic
getGamestate = gs
getPlies = pl
update ai gs' = ai { gs = gs' }
aiRaiCharles :: Int -> AIFunction
aiRaiCharles plies' gs' = aiTurn RaiCharles { gs = gs', pl = plies' }
| sharkdp/yinsh | src/RaiCharles.hs | mit | 553 | 0 | 8 | 164 | 132 | 77 | 55 | 14 | 1 |
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BL8 (putStrLn)
import Data.List (sortBy, intersect)
import Data.Function (on)
import Crypto.Common (genCandidates)
import System.Environment (getArgs)
import Text.Printf (printf)
-- XORs stdin with each ASCII character, and ranks the
-- resulting strings by their character distribution's similarity to that
-- expected of english text
-- example usage:
-- echo -n '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' | ../set1ch3
-- use -a or --display-all to display all results
main :: IO ()
main = do displayAll <- fmap (not . null . intersect ["-a", "--display-all"]) $ getArgs
lbs <- BL.getContents
let results = sortBy (flip compare `on` snd) $ genCandidates lbs
if displayAll
then mapM_ formatAndPrint results
else BL8.putStrLn . snd . fst . last $ results
where formatAndPrint ((c, str), dist) = printf fStr (show c) dist (show str)
fStr = "%-6s : %.4f : %s\n"
| ckw/matasano | set1/challenge3.hs | mit | 1,092 | 0 | 14 | 252 | 255 | 143 | 112 | 16 | 2 |
-- Project Euler Problem 15 lattice paths
--
-- Given a 20x20 grid and only movements down and to the right, how many paths are there from the top left to bottom right.
--
factorial = scanl (*) 1 [1..]
main = do
print (factorial!!40 `div` (factorial!!20)^2)
| yunwilliamyu/programming-exercises | project_euler/p015_lattice_path.hs | cc0-1.0 | 263 | 2 | 12 | 52 | 59 | 34 | 25 | 3 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell, ConstraintKinds, TypeFamilies, DeriveDataTypeable #-}
module Lamdu.CodeEdit.ExpressionEdit.ExpressionGui.Monad
( ExprGuiM, WidgetT, runWidget
, widgetEnv
, Payload(..), SugarExpr
, transaction, localEnv, withFgColor
, getP, assignCursor, assignCursorPrefix
, wrapDelegated
--
, makeSubexpresion
--
, readSettings, readCodeAnchors
, getCodeAnchor, mkPrejumpPosSaver
--
, addResultPicker, listenResultPickers
, AccessedVars, markVariablesAsUsed, listenUsedVariables
, memo, memoT
, liftMemo, liftMemoT
, HoleNumber, nextHoleNumber
, inCollapsedExpression
, isInCollapsedExpression
, appendToTopLevelEventMap
) where
import Control.Applicative (Applicative(..), (<$>))
import Control.Lens.Operators
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.RWS (RWST, runRWST)
import Control.Monad.Trans.State (StateT(..), mapStateT)
import Control.MonadA (MonadA)
import Data.Binary (Binary(..))
import Data.Cache (Cache)
import Data.Derive.Binary (makeBinary)
import Data.Derive.Monoid (makeMonoid)
import Data.DeriveTH (derive)
import Data.Monoid (Monoid(..))
import Data.Store.Guid (Guid)
import Data.Store.Transaction (Transaction)
import Data.Typeable (Typeable)
import Graphics.UI.Bottle.Widget (Widget)
import Lamdu.CodeEdit.ExpressionEdit.ExpressionGui.Types (ExpressionGui, WidgetT, ParentPrecedence(..), Precedence)
import Lamdu.CodeEdit.Settings (Settings)
import Lamdu.WidgetEnvT (WidgetEnvT)
import qualified Control.Lens as Lens
import qualified Control.Monad.Trans.RWS as RWS
import qualified Data.Cache as Cache
import qualified Data.Store.Transaction as Transaction
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.FocusDelegator as FocusDelegator
import qualified Lamdu.BottleWidgets as BWidgets
import qualified Lamdu.CodeEdit.Sugar as Sugar
import qualified Lamdu.Data.Anchors as Anchors
import qualified Lamdu.Data.Ops as DataOps
import qualified Lamdu.WidgetEnvT as WE
type T = Transaction
type AccessedVars = [Guid]
data Output m = Output
{ oAccessedVars :: AccessedVars
, oHolePickers :: [Sugar.PrefixAction m]
, oTopLevelEventMap :: Widget.EventHandlers (T m)
}
derive makeMonoid ''Output
data Payload = Payload
{ plGuids :: [Guid]
, plInjected :: [Bool]
} deriving (Typeable)
derive makeMonoid ''Payload
derive makeBinary ''Payload
type SugarExpr m = Sugar.ExpressionN m Payload
data Askable m = Askable
{ _aSettings :: Settings
, _aMakeSubexpression ::
ParentPrecedence ->
Sugar.ExpressionN m Payload ->
ExprGuiM m (ExpressionGui m)
, _aCodeAnchors :: Anchors.CodeProps m
, _aInCollapsedExpression :: Bool
}
type HoleNumber = Int
data GuiState = GuiState
{ _gsCache :: Cache
, _gsNextHoleNumber :: HoleNumber
}
newtype ExprGuiM m a = ExprGuiM
{ _exprGuiM :: RWST (Askable m) (Output m) GuiState (WidgetEnvT (T m)) a
}
deriving (Functor, Applicative, Monad)
Lens.makeLenses ''Askable
Lens.makeLenses ''ExprGuiM
Lens.makeLenses ''GuiState
nextHoleNumber :: MonadA m => ExprGuiM m HoleNumber
nextHoleNumber = ExprGuiM $
Lens.use gsNextHoleNumber <* (gsNextHoleNumber += 1)
-- TODO: To lens
localEnv :: MonadA m => (WE.Env -> WE.Env) -> ExprGuiM m a -> ExprGuiM m a
localEnv = (exprGuiM %~) . RWS.mapRWST . WE.localEnv
withFgColor :: MonadA m => Draw.Color -> ExprGuiM m a -> ExprGuiM m a
withFgColor = localEnv . WE.setTextColor
readSettings :: MonadA m => ExprGuiM m Settings
readSettings = ExprGuiM $ Lens.view aSettings
readCodeAnchors :: MonadA m => ExprGuiM m (Anchors.CodeProps m)
readCodeAnchors = ExprGuiM $ Lens.view aCodeAnchors
mkPrejumpPosSaver :: MonadA m => ExprGuiM m (T m ())
mkPrejumpPosSaver =
DataOps.savePreJumpPosition <$> readCodeAnchors <*> widgetEnv WE.readCursor
-- TODO: makeSubexpresSion
makeSubexpresion ::
MonadA m => Precedence -> SugarExpr m -> ExprGuiM m (ExpressionGui m)
makeSubexpresion parentPrecedence expr = do
maker <- ExprGuiM $ Lens.view aMakeSubexpression
maker (ParentPrecedence parentPrecedence) expr
liftMemo :: MonadA m => StateT Cache (WidgetEnvT (T m)) a -> ExprGuiM m a
liftMemo act = ExprGuiM . Lens.zoom gsCache $ do
cache <- RWS.get
(val, newCache) <- lift $ runStateT act cache
RWS.put newCache
return val
liftMemoT :: MonadA m => StateT Cache (T m) a -> ExprGuiM m a
liftMemoT = liftMemo . mapStateT lift
memo ::
(Cache.Key k, Binary v, MonadA m) =>
(k -> WidgetEnvT (T m) v) -> k -> ExprGuiM m v
memo f key = liftMemo $ Cache.memoS f key
memoT ::
(Cache.Key k, Binary v, MonadA m) =>
(k -> T m v) -> k -> ExprGuiM m v
memoT f = memo (lift . f)
inCollapsedExpression :: MonadA m => ExprGuiM m a -> ExprGuiM m a
inCollapsedExpression =
exprGuiM %~ RWS.local (aInCollapsedExpression .~ True)
isInCollapsedExpression :: MonadA m => ExprGuiM m Bool
isInCollapsedExpression = ExprGuiM $ Lens.view aInCollapsedExpression
run ::
MonadA m =>
(ParentPrecedence -> SugarExpr m -> ExprGuiM m (ExpressionGui m)) ->
Anchors.CodeProps m -> Settings -> ExprGuiM m a ->
StateT Cache (WidgetEnvT (T m)) (Widget.EventHandlers (T m), a)
run makeSubexpression codeAnchors settings (ExprGuiM action) =
StateT $ \cache ->
fmap f $ runRWST action
Askable
{ _aSettings = settings
, _aMakeSubexpression = makeSubexpression
, _aCodeAnchors = codeAnchors
, _aInCollapsedExpression = False
}
(GuiState cache 1)
where
f (x, GuiState newCache _, output) = ((oTopLevelEventMap output, x), newCache)
runWidget ::
MonadA m =>
(ParentPrecedence -> SugarExpr m -> ExprGuiM m (ExpressionGui m)) ->
Anchors.CodeProps m -> Settings -> ExprGuiM m (Widget (T m)) ->
StateT Cache (WidgetEnvT (T m)) (Widget (T m))
runWidget makeSubexpression codeAnchors settings action =
uncurry Widget.weakerEvents <$> run makeSubexpression codeAnchors settings action
widgetEnv :: MonadA m => WidgetEnvT (T m) a -> ExprGuiM m a
widgetEnv = ExprGuiM . lift
transaction :: MonadA m => T m a -> ExprGuiM m a
transaction = widgetEnv . lift
getP :: MonadA m => Transaction.MkProperty m a -> ExprGuiM m a
getP = transaction . Transaction.getP
getCodeAnchor ::
MonadA m => (Anchors.CodeProps m -> Transaction.MkProperty m b) -> ExprGuiM m b
getCodeAnchor anchor = getP . anchor =<< readCodeAnchors
assignCursor :: MonadA m => Widget.Id -> Widget.Id -> ExprGuiM m a -> ExprGuiM m a
assignCursor x y = localEnv $ WE.envAssignCursor x y
assignCursorPrefix :: MonadA m => Widget.Id -> Widget.Id -> ExprGuiM m a -> ExprGuiM m a
assignCursorPrefix x y = localEnv $ WE.envAssignCursorPrefix x y
wrapDelegated ::
(MonadA f, MonadA m) =>
FocusDelegator.Config -> FocusDelegator.IsDelegating ->
((Widget f -> Widget f) -> a -> b) ->
(Widget.Id -> ExprGuiM m a) ->
Widget.Id -> ExprGuiM m b
wrapDelegated =
BWidgets.wrapDelegatedWith (widgetEnv WE.readCursor) (widgetEnv WE.readConfig)
(localEnv . (WE.envCursor %~))
-- Used vars:
listener :: MonadA m => (Output m -> b) -> ExprGuiM m a -> ExprGuiM m (a, b)
listener f =
exprGuiM %~ RWS.listen
& Lens.mapped . Lens.mapped . Lens._2 %~ f
listenUsedVariables :: MonadA m => ExprGuiM m a -> ExprGuiM m (a, [Guid])
listenUsedVariables = listener oAccessedVars
listenResultPickers :: MonadA m => ExprGuiM m a -> ExprGuiM m (a, [T m ()])
listenResultPickers = listener oHolePickers
markVariablesAsUsed :: MonadA m => AccessedVars -> ExprGuiM m ()
markVariablesAsUsed vars = ExprGuiM $ RWS.tell mempty { oAccessedVars = vars }
addResultPicker :: MonadA m => T m () -> ExprGuiM m ()
addResultPicker picker = ExprGuiM $ RWS.tell mempty { oHolePickers = [picker] }
appendToTopLevelEventMap :: MonadA m => Widget.EventHandlers (T m) -> ExprGuiM m ()
appendToTopLevelEventMap eventMap =
ExprGuiM $ RWS.tell mempty { oTopLevelEventMap = eventMap }
| Mathnerd314/lamdu | src/Lamdu/CodeEdit/ExpressionEdit/ExpressionGui/Monad.hs | gpl-3.0 | 7,882 | 0 | 14 | 1,284 | 2,627 | 1,406 | 1,221 | -1 | -1 |
module LightSource where
import DMX
import Data.Word
data Color = Color Word8 Word8 Word8 deriving (Show)
data Light = Light {
address :: Int
, bus :: Bus
}
setLight (Light addr bus) (Color r g b) = do
setChannel bus (addr+1) (not10 r)
setChannel bus (addr+2) (not10 g)
setChannel bus (addr+3) (not10 b)
-- |DXM bus seems to go crazy with values of 10. Maybe some mysterious
-- |unix2dos conversions at serial line.
not10 10 = 11
not10 x = x
-- |Simple helper function for testing. Not efficient if there are
-- multiple DMX devices to control concurrently.
setLightInstantly light color = do
setLight light color
sendDMX (bus light)
| zouppen/valo | LightSource.hs | gpl-3.0 | 665 | 0 | 9 | 142 | 200 | 104 | 96 | 16 | 1 |
module Main where
import Slash
import Slash.Handler
import Java.AST
import Control.Lens
import Graphics.Vty as G
import Language.Java.Pretty
import Language.Java.Syntax
data ClassPart = ClassName | Class | Done deriving Eq
data Builder = ClassBuilder ClassDecl ClassPart
newClassBuilder :: Builder
newClassBuilder = ClassBuilder emptyClass Class
isBuilt :: Builder -> Bool
isBuilt (ClassBuilder _ Done) = True
isBuilt (ClassBuilder _ _) = False
builderContent :: Builder -> String
builderContent (ClassBuilder cd _) = show . pretty $ cd
data MySlash = MySlash
{ insertMode :: Bool
, building :: Maybe Builder
}
main :: IO ()
main = slash mySlash myHandler
mySlash :: MySlash
mySlash = MySlash False Nothing
myHandler :: Handler (Slash MySlash)
myHandler e s =
case building . userData $ s of
Just b -> checkBuilder b e s
Nothing ->
if insertMode . userData $ s then handleInsert e s
else handleNormal e s
handleInsert :: Handler (Slash MySlash)
handleInsert =
withKey putKey
<+> onEnter (putKey '\n')
<+> onBack (delete 1)
<+> onCtrl 'c' (changeUserData toggleInsert)
setBuilder :: Builder -> MySlash -> MySlash
setBuilder b u = u { building = return b }
handleNormal :: Handler (Slash MySlash)
handleNormal =
onKey 'b' (deleteBy Slash.Word 1)
<+> onKey 'i' (changeUserData toggleInsert)
<+> onKey 'c' (changeUserData . setBuilder $ newClassBuilder)
toggleInsert :: MySlash -> MySlash
toggleInsert m = m { insertMode = not . insertMode $ m }
checkBuilder :: Builder -> Handler (Slash MySlash)
checkBuilder b e =
if isBuilt b then
(putString . builderContent $ b)
. changeUserData (\u -> u { building = Nothing })
else changeUserData . setBuilder . handleBuilder e $ b
handleBuilder :: Handler Builder
handleBuilder e cb@(ClassBuilder c p) =
case p of
Class -> case e of
EvKey (KASCII 'c') [MCtrl] -> ClassBuilder c Done
EvKey (KASCII 'P') _ -> ClassBuilder (c & modifyClass <>~ [Public]) p
EvKey (KASCII 'n') _ -> ClassBuilder c ClassName
_ -> cb
ClassName -> case e of
EvKey (KASCII 'c') [MCtrl] -> ClassBuilder c Class
EvKey KBS _ -> ClassBuilder (c & identifyClass %~ removeLast) p
EvKey (KASCII k) _ -> ClassBuilder (c & identifyClass <>~ [k]) p
_ -> cb
Done -> cb
removeLast :: [a] -> [a]
removeLast = reverse . drop 1 . reverse
| josuf107/Slash | Java.hs | gpl-3.0 | 2,484 | 0 | 14 | 621 | 860 | 444 | 416 | 68 | 9 |
{-# LANGUAGE FlexibleInstances #-}
module Ennel.Dictionary.Data where
import Ennel.Linguistics
import Data.JustParse
import Data.JustParse.Char
import Data.JustParse.Combinator
import Data.Monoid
type Rules = [Rule]
data Rule = Rule { target :: String, signature :: TypeSignature, prebinds :: [Bind], postbinds :: [Bind], definition :: SemanticTree }
deriving (Show, Eq)
data TypeSignature = TypeSignature { arguments :: [LexicalCategory], result :: LexicalCategory }
deriving (Show, Eq)
data Bind = Bind { selector :: String, variableName :: String }
deriving (Show, Eq)
type Word = String
type Phrase = [Word]
data Template = Template { before :: [Binding], phrase :: Phrase, after :: [Binding], semantics :: SemanticTree }
deriving (Eq, Show)
type Binding = (Bind, LexicalCategory)
type TemplateTable = [(LexicalCategory, Template)]
type Interpreter = LexicalCategory -> Parser Phrase SemanticTree | trehansiddharth/ennel | Ennel/Dictionary/Data.hs | gpl-3.0 | 934 | 8 | 9 | 155 | 282 | 175 | 107 | 21 | 0 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Memory.Output.Fancy.SoundMemory
(
soundMemoryIterationFailure,
) where
import MyPrelude
import Game
import Game.Memory
import OpenAL
import OpenAL.Helpers
soundMemoryIterationFailure :: SoundMemory -> IO ()
soundMemoryIterationFailure sound = do
alSourcePlay $ soundMemorySrc sound
| karamellpelle/grid | source/Game/Memory/Output/Fancy/SoundMemory.hs | gpl-3.0 | 1,062 | 0 | 8 | 185 | 84 | 56 | 28 | 11 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Java2js.Mangle ( Manglable(..) ) where
import Java2js.JVM.ClassFile
import Data.ByteString.Lazy.Char8 (unpack, ByteString)
import Data.List (intercalate)
class Manglable a where
mangleMethod :: a -> String
sigToSym :: FieldType -> String
sigToSym SignedByte = "B"
sigToSym CharByte = "C"
sigToSym DoubleType = "D"
sigToSym FloatType = "F"
sigToSym IntType = "I"
sigToSym LongInt = "J"
sigToSym ShortInt = "S"
sigToSym BoolType = "Z"
sigToSym (ObjectType cls) = 'L':cls++";"
sigToSym (Array _ ft) = '[':(sigToSym ft)
mangleMethod' :: ByteString -> MethodSignature -> String
mangleMethod' name (MethodSignature args _) = (unpack name) ++ "("++(concat (fmap sigToSym args))++")"
where
--
mangleReturn' :: ByteString -> MethodSignature -> String
mangleReturn' name (MethodSignature _ ret) = retToSym ret
where
retToSym :: ReturnSignature -> String
retToSym ReturnsVoid = "V"
retToSym (Returns v) = sigToSym v
--
instance Manglable (NameType (Method Direct)) where
mangleMethod nt = mangleMethod' (ntName nt) (ntSignature nt) ++ mangleReturn' (ntName nt) (ntSignature nt)
--
instance Manglable (Method Direct) where
mangleMethod meth = mangleMethod' (methodName meth) (methodSignature meth) ++ mangleReturn' (methodName meth) (methodSignature meth)
| ledyba/java.js | lib/Java2js/Mangle.hs | gpl-3.0 | 1,418 | 0 | 10 | 303 | 449 | 233 | 216 | 29 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.BigQuery.DataSets.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates information in an existing dataset. The update method replaces
-- the entire dataset resource, whereas the patch method only replaces
-- fields that are provided in the submitted dataset resource.
--
-- /See:/ <https://cloud.google.com/bigquery/ BigQuery API Reference> for @bigquery.datasets.update@.
module Network.Google.Resource.BigQuery.DataSets.Update
(
-- * REST Resource
DataSetsUpdateResource
-- * Creating a Request
, dataSetsUpdate
, DataSetsUpdate
-- * Request Lenses
, dsuPayload
, dsuDataSetId
, dsuProjectId
) where
import Network.Google.BigQuery.Types
import Network.Google.Prelude
-- | A resource alias for @bigquery.datasets.update@ method which the
-- 'DataSetsUpdate' request conforms to.
type DataSetsUpdateResource =
"bigquery" :>
"v2" :>
"projects" :>
Capture "projectId" Text :>
"datasets" :>
Capture "datasetId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DataSet :> Put '[JSON] DataSet
-- | Updates information in an existing dataset. The update method replaces
-- the entire dataset resource, whereas the patch method only replaces
-- fields that are provided in the submitted dataset resource.
--
-- /See:/ 'dataSetsUpdate' smart constructor.
data DataSetsUpdate = DataSetsUpdate'
{ _dsuPayload :: !DataSet
, _dsuDataSetId :: !Text
, _dsuProjectId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DataSetsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dsuPayload'
--
-- * 'dsuDataSetId'
--
-- * 'dsuProjectId'
dataSetsUpdate
:: DataSet -- ^ 'dsuPayload'
-> Text -- ^ 'dsuDataSetId'
-> Text -- ^ 'dsuProjectId'
-> DataSetsUpdate
dataSetsUpdate pDsuPayload_ pDsuDataSetId_ pDsuProjectId_ =
DataSetsUpdate'
{ _dsuPayload = pDsuPayload_
, _dsuDataSetId = pDsuDataSetId_
, _dsuProjectId = pDsuProjectId_
}
-- | Multipart request metadata.
dsuPayload :: Lens' DataSetsUpdate DataSet
dsuPayload
= lens _dsuPayload (\ s a -> s{_dsuPayload = a})
-- | Dataset ID of the dataset being updated
dsuDataSetId :: Lens' DataSetsUpdate Text
dsuDataSetId
= lens _dsuDataSetId (\ s a -> s{_dsuDataSetId = a})
-- | Project ID of the dataset being updated
dsuProjectId :: Lens' DataSetsUpdate Text
dsuProjectId
= lens _dsuProjectId (\ s a -> s{_dsuProjectId = a})
instance GoogleRequest DataSetsUpdate where
type Rs DataSetsUpdate = DataSet
type Scopes DataSetsUpdate =
'["https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform"]
requestClient DataSetsUpdate'{..}
= go _dsuProjectId _dsuDataSetId (Just AltJSON)
_dsuPayload
bigQueryService
where go
= buildClient (Proxy :: Proxy DataSetsUpdateResource)
mempty
| rueshyna/gogol | gogol-bigquery/gen/Network/Google/Resource/BigQuery/DataSets/Update.hs | mpl-2.0 | 3,837 | 0 | 15 | 874 | 468 | 281 | 187 | 73 | 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.Classroom.UserProFiles.GuardianInvitations.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a specific guardian invitation. This method returns the
-- following error codes: * \`PERMISSION_DENIED\` if the requesting user is
-- not permitted to view guardian invitations for the student identified by
-- the \`student_id\`, if guardians are not enabled for the domain in
-- question, or for other access errors. * \`INVALID_ARGUMENT\` if a
-- \`student_id\` is specified, but its format cannot be recognized (it is
-- not an email address, nor a \`student_id\` from the API, nor the literal
-- string \`me\`). * \`NOT_FOUND\` if Classroom cannot find any record of
-- the given student or \`invitation_id\`. May also be returned if the
-- student exists, but the requesting user does not have access to see that
-- student.
--
-- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.userProfiles.guardianInvitations.get@.
module Network.Google.Resource.Classroom.UserProFiles.GuardianInvitations.Get
(
-- * REST Resource
UserProFilesGuardianInvitationsGetResource
-- * Creating a Request
, userProFilesGuardianInvitationsGet
, UserProFilesGuardianInvitationsGet
-- * Request Lenses
, upfgigStudentId
, upfgigXgafv
, upfgigUploadProtocol
, upfgigPp
, upfgigAccessToken
, upfgigUploadType
, upfgigInvitationId
, upfgigBearerToken
, upfgigCallback
) where
import Network.Google.Classroom.Types
import Network.Google.Prelude
-- | A resource alias for @classroom.userProfiles.guardianInvitations.get@ method which the
-- 'UserProFilesGuardianInvitationsGet' request conforms to.
type UserProFilesGuardianInvitationsGetResource =
"v1" :>
"userProfiles" :>
Capture "studentId" Text :>
"guardianInvitations" :>
Capture "invitationId" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GuardianInvitation
-- | Returns a specific guardian invitation. This method returns the
-- following error codes: * \`PERMISSION_DENIED\` if the requesting user is
-- not permitted to view guardian invitations for the student identified by
-- the \`student_id\`, if guardians are not enabled for the domain in
-- question, or for other access errors. * \`INVALID_ARGUMENT\` if a
-- \`student_id\` is specified, but its format cannot be recognized (it is
-- not an email address, nor a \`student_id\` from the API, nor the literal
-- string \`me\`). * \`NOT_FOUND\` if Classroom cannot find any record of
-- the given student or \`invitation_id\`. May also be returned if the
-- student exists, but the requesting user does not have access to see that
-- student.
--
-- /See:/ 'userProFilesGuardianInvitationsGet' smart constructor.
data UserProFilesGuardianInvitationsGet = UserProFilesGuardianInvitationsGet'
{ _upfgigStudentId :: !Text
, _upfgigXgafv :: !(Maybe Text)
, _upfgigUploadProtocol :: !(Maybe Text)
, _upfgigPp :: !Bool
, _upfgigAccessToken :: !(Maybe Text)
, _upfgigUploadType :: !(Maybe Text)
, _upfgigInvitationId :: !Text
, _upfgigBearerToken :: !(Maybe Text)
, _upfgigCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UserProFilesGuardianInvitationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upfgigStudentId'
--
-- * 'upfgigXgafv'
--
-- * 'upfgigUploadProtocol'
--
-- * 'upfgigPp'
--
-- * 'upfgigAccessToken'
--
-- * 'upfgigUploadType'
--
-- * 'upfgigInvitationId'
--
-- * 'upfgigBearerToken'
--
-- * 'upfgigCallback'
userProFilesGuardianInvitationsGet
:: Text -- ^ 'upfgigStudentId'
-> Text -- ^ 'upfgigInvitationId'
-> UserProFilesGuardianInvitationsGet
userProFilesGuardianInvitationsGet pUpfgigStudentId_ pUpfgigInvitationId_ =
UserProFilesGuardianInvitationsGet'
{ _upfgigStudentId = pUpfgigStudentId_
, _upfgigXgafv = Nothing
, _upfgigUploadProtocol = Nothing
, _upfgigPp = True
, _upfgigAccessToken = Nothing
, _upfgigUploadType = Nothing
, _upfgigInvitationId = pUpfgigInvitationId_
, _upfgigBearerToken = Nothing
, _upfgigCallback = Nothing
}
-- | The ID of the student whose guardian invitation is being requested.
upfgigStudentId :: Lens' UserProFilesGuardianInvitationsGet Text
upfgigStudentId
= lens _upfgigStudentId
(\ s a -> s{_upfgigStudentId = a})
-- | V1 error format.
upfgigXgafv :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigXgafv
= lens _upfgigXgafv (\ s a -> s{_upfgigXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
upfgigUploadProtocol :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigUploadProtocol
= lens _upfgigUploadProtocol
(\ s a -> s{_upfgigUploadProtocol = a})
-- | Pretty-print response.
upfgigPp :: Lens' UserProFilesGuardianInvitationsGet Bool
upfgigPp = lens _upfgigPp (\ s a -> s{_upfgigPp = a})
-- | OAuth access token.
upfgigAccessToken :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigAccessToken
= lens _upfgigAccessToken
(\ s a -> s{_upfgigAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
upfgigUploadType :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigUploadType
= lens _upfgigUploadType
(\ s a -> s{_upfgigUploadType = a})
-- | The \`id\` field of the \`GuardianInvitation\` being requested.
upfgigInvitationId :: Lens' UserProFilesGuardianInvitationsGet Text
upfgigInvitationId
= lens _upfgigInvitationId
(\ s a -> s{_upfgigInvitationId = a})
-- | OAuth bearer token.
upfgigBearerToken :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigBearerToken
= lens _upfgigBearerToken
(\ s a -> s{_upfgigBearerToken = a})
-- | JSONP
upfgigCallback :: Lens' UserProFilesGuardianInvitationsGet (Maybe Text)
upfgigCallback
= lens _upfgigCallback
(\ s a -> s{_upfgigCallback = a})
instance GoogleRequest
UserProFilesGuardianInvitationsGet where
type Rs UserProFilesGuardianInvitationsGet =
GuardianInvitation
type Scopes UserProFilesGuardianInvitationsGet = '[]
requestClient UserProFilesGuardianInvitationsGet'{..}
= go _upfgigStudentId _upfgigInvitationId
_upfgigXgafv
_upfgigUploadProtocol
(Just _upfgigPp)
_upfgigAccessToken
_upfgigUploadType
_upfgigBearerToken
_upfgigCallback
(Just AltJSON)
classroomService
where go
= buildClient
(Proxy ::
Proxy UserProFilesGuardianInvitationsGetResource)
mempty
| rueshyna/gogol | gogol-classroom/gen/Network/Google/Resource/Classroom/UserProFiles/GuardianInvitations/Get.hs | mpl-2.0 | 8,012 | 0 | 20 | 1,773 | 951 | 559 | 392 | 141 | 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.SWF.RegisterWorkflowType
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Registers a new /workflow type/ and its configuration settings in the specified
-- domain.
--
-- The retention period for the workflow history is set by the 'RegisterDomain'
-- action.
--
-- If the type already exists, then a 'TypeAlreadyExists' fault is returned. You
-- cannot change the configuration settings of a workflow type once it is
-- registered and it must be registered as a new version. Access Control
--
-- You can use IAM policies to control this action's access to Amazon SWF
-- resources as follows:
--
-- Use a 'Resource' element with the domain name to limit the action to only
-- specified domains. Use an 'Action' element to allow or deny permission to call
-- this action. Constrain the following parameters by using a 'Condition' element
-- with the appropriate keys. 'defaultTaskList.name': String constraint. The key
-- is 'swf:defaultTaskList.name'. 'name': String constraint. The key is 'swf:name'. 'version': String constraint. The key is 'swf:version'. If the caller does not have
-- sufficient permissions to invoke the action, or the parameter values fall
-- outside the specified constraints, the action fails. The associated event
-- attribute's cause parameter will be set to OPERATION_NOT_PERMITTED. For
-- details and example IAM policies, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html Using IAM to Manage Access to AmazonSWF Workflows>.
--
-- <http://docs.aws.amazon.com/amazonswf/latest/apireference/API_RegisterWorkflowType.html>
module Network.AWS.SWF.RegisterWorkflowType
(
-- * Request
RegisterWorkflowType
-- ** Request constructor
, registerWorkflowType
-- ** Request lenses
, rwtDefaultChildPolicy
, rwtDefaultExecutionStartToCloseTimeout
, rwtDefaultTaskList
, rwtDefaultTaskPriority
, rwtDefaultTaskStartToCloseTimeout
, rwtDescription
, rwtDomain
, rwtName
, rwtVersion
-- * Response
, RegisterWorkflowTypeResponse
-- ** Response constructor
, registerWorkflowTypeResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SWF.Types
import qualified GHC.Exts
data RegisterWorkflowType = RegisterWorkflowType
{ _rwtDefaultChildPolicy :: Maybe ChildPolicy
, _rwtDefaultExecutionStartToCloseTimeout :: Maybe Text
, _rwtDefaultTaskList :: Maybe TaskList
, _rwtDefaultTaskPriority :: Maybe Text
, _rwtDefaultTaskStartToCloseTimeout :: Maybe Text
, _rwtDescription :: Maybe Text
, _rwtDomain :: Text
, _rwtName :: Text
, _rwtVersion :: Text
} deriving (Eq, Read, Show)
-- | 'RegisterWorkflowType' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rwtDefaultChildPolicy' @::@ 'Maybe' 'ChildPolicy'
--
-- * 'rwtDefaultExecutionStartToCloseTimeout' @::@ 'Maybe' 'Text'
--
-- * 'rwtDefaultTaskList' @::@ 'Maybe' 'TaskList'
--
-- * 'rwtDefaultTaskPriority' @::@ 'Maybe' 'Text'
--
-- * 'rwtDefaultTaskStartToCloseTimeout' @::@ 'Maybe' 'Text'
--
-- * 'rwtDescription' @::@ 'Maybe' 'Text'
--
-- * 'rwtDomain' @::@ 'Text'
--
-- * 'rwtName' @::@ 'Text'
--
-- * 'rwtVersion' @::@ 'Text'
--
registerWorkflowType :: Text -- ^ 'rwtDomain'
-> Text -- ^ 'rwtName'
-> Text -- ^ 'rwtVersion'
-> RegisterWorkflowType
registerWorkflowType p1 p2 p3 = RegisterWorkflowType
{ _rwtDomain = p1
, _rwtName = p2
, _rwtVersion = p3
, _rwtDescription = Nothing
, _rwtDefaultTaskStartToCloseTimeout = Nothing
, _rwtDefaultExecutionStartToCloseTimeout = Nothing
, _rwtDefaultTaskList = Nothing
, _rwtDefaultTaskPriority = Nothing
, _rwtDefaultChildPolicy = Nothing
}
-- | If set, specifies the default policy to use for the child workflow executions
-- when a workflow execution of this type is terminated, by calling the 'TerminateWorkflowExecution' action explicitly or due to an expired timeout. This default can be
-- overridden when starting a workflow execution using the 'StartWorkflowExecution'
-- action or the 'StartChildWorkflowExecution' 'Decision'.
--
-- The supported child policies are:
--
-- TERMINATE: the child executions will be terminated. REQUEST_CANCEL: a
-- request to cancel will be attempted for each child execution by recording a 'WorkflowExecutionCancelRequested' event in its history. It is up to the decider to take appropriate actions
-- when it receives an execution history with this event. ABANDON: no action
-- will be taken. The child executions will continue to run.
rwtDefaultChildPolicy :: Lens' RegisterWorkflowType (Maybe ChildPolicy)
rwtDefaultChildPolicy =
lens _rwtDefaultChildPolicy (\s a -> s { _rwtDefaultChildPolicy = a })
-- | If set, specifies the default maximum duration for executions of this
-- workflow type. You can override this default when starting an execution
-- through the 'StartWorkflowExecution' Action or 'StartChildWorkflowExecution' 'Decision'.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- Unlike some of the other timeout parameters in Amazon SWF, you cannot specify
-- a value of "NONE" for 'defaultExecutionStartToCloseTimeout'; there is a
-- one-year max limit on the time that a workflow execution can run. Exceeding
-- this limit will always cause the workflow execution to time out.
rwtDefaultExecutionStartToCloseTimeout :: Lens' RegisterWorkflowType (Maybe Text)
rwtDefaultExecutionStartToCloseTimeout =
lens _rwtDefaultExecutionStartToCloseTimeout
(\s a -> s { _rwtDefaultExecutionStartToCloseTimeout = a })
-- | If set, specifies the default task list to use for scheduling decision tasks
-- for executions of this workflow type. This default is used only if a task
-- list is not provided when starting the execution through the 'StartWorkflowExecution' Action or 'StartChildWorkflowExecution' 'Decision'.
rwtDefaultTaskList :: Lens' RegisterWorkflowType (Maybe TaskList)
rwtDefaultTaskList =
lens _rwtDefaultTaskList (\s a -> s { _rwtDefaultTaskList = a })
-- | The default task priority to assign to the workflow type. If not assigned,
-- then "0" will be used. Valid values are integers that range from Java's 'Integer.MIN_VALUE' (-2147483648) to 'Integer.MAX_VALUE' (2147483647). Higher numbers indicate
-- higher priority.
--
-- For more information about setting task priority, see <http://docs.aws.amazon.com/amazonswf/latest/developerguide/programming-priority.html Setting Task Priority>
-- in the /Amazon Simple Workflow Developer Guide/.
rwtDefaultTaskPriority :: Lens' RegisterWorkflowType (Maybe Text)
rwtDefaultTaskPriority =
lens _rwtDefaultTaskPriority (\s a -> s { _rwtDefaultTaskPriority = a })
-- | If set, specifies the default maximum duration of decision tasks for this
-- workflow type. This default can be overridden when starting a workflow
-- execution using the 'StartWorkflowExecution' action or the 'StartChildWorkflowExecution' 'Decision'.
--
-- The duration is specified in seconds; an integer greater than or equal to 0.
-- The value "NONE" can be used to specify unlimited duration.
rwtDefaultTaskStartToCloseTimeout :: Lens' RegisterWorkflowType (Maybe Text)
rwtDefaultTaskStartToCloseTimeout =
lens _rwtDefaultTaskStartToCloseTimeout
(\s a -> s { _rwtDefaultTaskStartToCloseTimeout = a })
-- | Textual description of the workflow type.
rwtDescription :: Lens' RegisterWorkflowType (Maybe Text)
rwtDescription = lens _rwtDescription (\s a -> s { _rwtDescription = a })
-- | The name of the domain in which to register the workflow type.
rwtDomain :: Lens' RegisterWorkflowType Text
rwtDomain = lens _rwtDomain (\s a -> s { _rwtDomain = a })
-- | The name of the workflow type.
--
-- The specified string must not start or end with whitespace. It must not
-- contain a ':' (colon), '/' (slash), '|' (vertical bar), or any control characters
-- (\u0000-\u001f | \u007f - \u009f). Also, it must not contain the literal
-- string quotarnquot.
rwtName :: Lens' RegisterWorkflowType Text
rwtName = lens _rwtName (\s a -> s { _rwtName = a })
-- | The version of the workflow type.
--
-- The workflow type consists of the name and version, the combination of which
-- must be unique within the domain. To get a list of all currently registered
-- workflow types, use the 'ListWorkflowTypes' action. The specified string must
-- not start or end with whitespace. It must not contain a ':' (colon), '/' (slash), '|' (vertical bar), or any control characters (\u0000-\u001f | \u007f -
-- \u009f). Also, it must not contain the literal string quotarnquot.
rwtVersion :: Lens' RegisterWorkflowType Text
rwtVersion = lens _rwtVersion (\s a -> s { _rwtVersion = a })
data RegisterWorkflowTypeResponse = RegisterWorkflowTypeResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'RegisterWorkflowTypeResponse' constructor.
registerWorkflowTypeResponse :: RegisterWorkflowTypeResponse
registerWorkflowTypeResponse = RegisterWorkflowTypeResponse
instance ToPath RegisterWorkflowType where
toPath = const "/"
instance ToQuery RegisterWorkflowType where
toQuery = const mempty
instance ToHeaders RegisterWorkflowType
instance ToJSON RegisterWorkflowType where
toJSON RegisterWorkflowType{..} = object
[ "domain" .= _rwtDomain
, "name" .= _rwtName
, "version" .= _rwtVersion
, "description" .= _rwtDescription
, "defaultTaskStartToCloseTimeout" .= _rwtDefaultTaskStartToCloseTimeout
, "defaultExecutionStartToCloseTimeout" .= _rwtDefaultExecutionStartToCloseTimeout
, "defaultTaskList" .= _rwtDefaultTaskList
, "defaultTaskPriority" .= _rwtDefaultTaskPriority
, "defaultChildPolicy" .= _rwtDefaultChildPolicy
]
instance AWSRequest RegisterWorkflowType where
type Sv RegisterWorkflowType = SWF
type Rs RegisterWorkflowType = RegisterWorkflowTypeResponse
request = post "RegisterWorkflowType"
response = nullResponse RegisterWorkflowTypeResponse
| dysinger/amazonka | amazonka-swf/gen/Network/AWS/SWF/RegisterWorkflowType.hs | mpl-2.0 | 11,548 | 0 | 9 | 2,493 | 969 | 602 | 367 | 104 | 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.RegisterVolume
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Registers an Amazon EBS volume with a specified stack. A volume can be
-- registered with only one stack at a time. If the volume is already
-- registered, you must first deregister it by calling 'DeregisterVolume'. For
-- more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>.
--
-- 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_RegisterVolume.html>
module Network.AWS.OpsWorks.RegisterVolume
(
-- * Request
RegisterVolume
-- ** Request constructor
, registerVolume
-- ** Request lenses
, rvEc2VolumeId
, rvStackId
-- * Response
, RegisterVolumeResponse
-- ** Response constructor
, registerVolumeResponse
-- ** Response lenses
, rvrVolumeId
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
data RegisterVolume = RegisterVolume
{ _rvEc2VolumeId :: Maybe Text
, _rvStackId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'RegisterVolume' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rvEc2VolumeId' @::@ 'Maybe' 'Text'
--
-- * 'rvStackId' @::@ 'Text'
--
registerVolume :: Text -- ^ 'rvStackId'
-> RegisterVolume
registerVolume p1 = RegisterVolume
{ _rvStackId = p1
, _rvEc2VolumeId = Nothing
}
-- | The Amazon EBS volume ID.
rvEc2VolumeId :: Lens' RegisterVolume (Maybe Text)
rvEc2VolumeId = lens _rvEc2VolumeId (\s a -> s { _rvEc2VolumeId = a })
-- | The stack ID.
rvStackId :: Lens' RegisterVolume Text
rvStackId = lens _rvStackId (\s a -> s { _rvStackId = a })
newtype RegisterVolumeResponse = RegisterVolumeResponse
{ _rvrVolumeId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'RegisterVolumeResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rvrVolumeId' @::@ 'Maybe' 'Text'
--
registerVolumeResponse :: RegisterVolumeResponse
registerVolumeResponse = RegisterVolumeResponse
{ _rvrVolumeId = Nothing
}
-- | The volume ID.
rvrVolumeId :: Lens' RegisterVolumeResponse (Maybe Text)
rvrVolumeId = lens _rvrVolumeId (\s a -> s { _rvrVolumeId = a })
instance ToPath RegisterVolume where
toPath = const "/"
instance ToQuery RegisterVolume where
toQuery = const mempty
instance ToHeaders RegisterVolume
instance ToJSON RegisterVolume where
toJSON RegisterVolume{..} = object
[ "Ec2VolumeId" .= _rvEc2VolumeId
, "StackId" .= _rvStackId
]
instance AWSRequest RegisterVolume where
type Sv RegisterVolume = OpsWorks
type Rs RegisterVolume = RegisterVolumeResponse
request = post "RegisterVolume"
response = jsonResponse
instance FromJSON RegisterVolumeResponse where
parseJSON = withObject "RegisterVolumeResponse" $ \o -> RegisterVolumeResponse
<$> o .:? "VolumeId"
| dysinger/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/RegisterVolume.hs | mpl-2.0 | 4,287 | 0 | 9 | 896 | 519 | 315 | 204 | 61 | 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.EC2.DescribeReservedInstancesOfferings
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes Reserved Instance offerings that are available for purchase. With
-- Reserved Instances, you purchase the right to launch instances for a period
-- of time. During that time period, you do not receive insufficient capacity
-- errors, and you pay a lower usage rate than the rate charged for On-Demand
-- instances for the actual time used.
--
-- For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html Reserved Instance Marketplace> in the /AmazonElastic Compute Cloud User Guide for Linux/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesOfferings.html>
module Network.AWS.EC2.DescribeReservedInstancesOfferings
(
-- * Request
DescribeReservedInstancesOfferings
-- ** Request constructor
, describeReservedInstancesOfferings
-- ** Request lenses
, drioAvailabilityZone
, drioDryRun
, drioFilters
, drioIncludeMarketplace
, drioInstanceTenancy
, drioInstanceType
, drioMaxDuration
, drioMaxInstanceCount
, drioMaxResults
, drioMinDuration
, drioNextToken
, drioOfferingType
, drioProductDescription
, drioReservedInstancesOfferingIds
-- * Response
, DescribeReservedInstancesOfferingsResponse
-- ** Response constructor
, describeReservedInstancesOfferingsResponse
-- ** Response lenses
, driorNextToken
, driorReservedInstancesOfferings
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DescribeReservedInstancesOfferings = DescribeReservedInstancesOfferings
{ _drioAvailabilityZone :: Maybe Text
, _drioDryRun :: Maybe Bool
, _drioFilters :: List "Filter" Filter
, _drioIncludeMarketplace :: Maybe Bool
, _drioInstanceTenancy :: Maybe Tenancy
, _drioInstanceType :: Maybe InstanceType
, _drioMaxDuration :: Maybe Integer
, _drioMaxInstanceCount :: Maybe Int
, _drioMaxResults :: Maybe Int
, _drioMinDuration :: Maybe Integer
, _drioNextToken :: Maybe Text
, _drioOfferingType :: Maybe OfferingTypeValues
, _drioProductDescription :: Maybe RIProductDescription
, _drioReservedInstancesOfferingIds :: List "ReservedInstancesOfferingId" Text
} deriving (Eq, Read, Show)
-- | 'DescribeReservedInstancesOfferings' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drioAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'drioDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'drioFilters' @::@ ['Filter']
--
-- * 'drioIncludeMarketplace' @::@ 'Maybe' 'Bool'
--
-- * 'drioInstanceTenancy' @::@ 'Maybe' 'Tenancy'
--
-- * 'drioInstanceType' @::@ 'Maybe' 'InstanceType'
--
-- * 'drioMaxDuration' @::@ 'Maybe' 'Integer'
--
-- * 'drioMaxInstanceCount' @::@ 'Maybe' 'Int'
--
-- * 'drioMaxResults' @::@ 'Maybe' 'Int'
--
-- * 'drioMinDuration' @::@ 'Maybe' 'Integer'
--
-- * 'drioNextToken' @::@ 'Maybe' 'Text'
--
-- * 'drioOfferingType' @::@ 'Maybe' 'OfferingTypeValues'
--
-- * 'drioProductDescription' @::@ 'Maybe' 'RIProductDescription'
--
-- * 'drioReservedInstancesOfferingIds' @::@ ['Text']
--
describeReservedInstancesOfferings :: DescribeReservedInstancesOfferings
describeReservedInstancesOfferings = DescribeReservedInstancesOfferings
{ _drioDryRun = Nothing
, _drioReservedInstancesOfferingIds = mempty
, _drioInstanceType = Nothing
, _drioAvailabilityZone = Nothing
, _drioProductDescription = Nothing
, _drioFilters = mempty
, _drioInstanceTenancy = Nothing
, _drioOfferingType = Nothing
, _drioNextToken = Nothing
, _drioMaxResults = Nothing
, _drioIncludeMarketplace = Nothing
, _drioMinDuration = Nothing
, _drioMaxDuration = Nothing
, _drioMaxInstanceCount = Nothing
}
-- | The Availability Zone in which the Reserved Instance can be used.
drioAvailabilityZone :: Lens' DescribeReservedInstancesOfferings (Maybe Text)
drioAvailabilityZone =
lens _drioAvailabilityZone (\s a -> s { _drioAvailabilityZone = a })
drioDryRun :: Lens' DescribeReservedInstancesOfferings (Maybe Bool)
drioDryRun = lens _drioDryRun (\s a -> s { _drioDryRun = a })
-- | One or more filters.
--
-- 'availability-zone' - The Availability Zone where the Reserved Instance can
-- be used.
--
-- 'duration' - The duration of the Reserved Instance (for example, one year or
-- three years), in seconds ('31536000' | '94608000').
--
-- 'fixed-price' - The purchase price of the Reserved Instance (for example,
-- 9800.0).
--
-- 'instance-type' - The instance type on which the Reserved Instance can be
-- used.
--
-- 'marketplace' - Set to 'true' to show only Reserved Instance Marketplace
-- offerings. When this filter is not used, which is the default behavior, all
-- offerings from AWS and Reserved Instance Marketplace are listed.
--
-- 'product-description' - The description of the Reserved Instance ('Linux/UNIX'
-- | 'Linux/UNIX (Amazon VPC)' | 'Windows' | 'Windows (Amazon VPC)').
--
-- 'reserved-instances-offering-id' - The Reserved Instances offering ID.
--
-- 'usage-price' - The usage price of the Reserved Instance, per hour (for
-- example, 0.84).
--
--
drioFilters :: Lens' DescribeReservedInstancesOfferings [Filter]
drioFilters = lens _drioFilters (\s a -> s { _drioFilters = a }) . _List
-- | Include Marketplace offerings in the response.
drioIncludeMarketplace :: Lens' DescribeReservedInstancesOfferings (Maybe Bool)
drioIncludeMarketplace =
lens _drioIncludeMarketplace (\s a -> s { _drioIncludeMarketplace = a })
-- | The tenancy of the Reserved Instance offering. A Reserved Instance with 'dedicated' tenancy runs on single-tenant hardware and can only be launched within a VPC.
--
-- Default: 'default'
drioInstanceTenancy :: Lens' DescribeReservedInstancesOfferings (Maybe Tenancy)
drioInstanceTenancy =
lens _drioInstanceTenancy (\s a -> s { _drioInstanceTenancy = a })
-- | The instance type on which the Reserved Instance can be used. For more
-- information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html Instance Types> in the /Amazon Elastic Compute Cloud UserGuide for Linux/.
drioInstanceType :: Lens' DescribeReservedInstancesOfferings (Maybe InstanceType)
drioInstanceType = lens _drioInstanceType (\s a -> s { _drioInstanceType = a })
-- | The maximum duration (in seconds) to filter when searching for offerings.
--
-- Default: 94608000 (3 years)
drioMaxDuration :: Lens' DescribeReservedInstancesOfferings (Maybe Integer)
drioMaxDuration = lens _drioMaxDuration (\s a -> s { _drioMaxDuration = a })
-- | The maximum number of instances to filter when searching for offerings.
--
-- Default: 20
drioMaxInstanceCount :: Lens' DescribeReservedInstancesOfferings (Maybe Int)
drioMaxInstanceCount =
lens _drioMaxInstanceCount (\s a -> s { _drioMaxInstanceCount = a })
-- | The maximum number of offerings to return. The maximum is 100.
--
-- Default: 100
drioMaxResults :: Lens' DescribeReservedInstancesOfferings (Maybe Int)
drioMaxResults = lens _drioMaxResults (\s a -> s { _drioMaxResults = a })
-- | The minimum duration (in seconds) to filter when searching for offerings.
--
-- Default: 2592000 (1 month)
drioMinDuration :: Lens' DescribeReservedInstancesOfferings (Maybe Integer)
drioMinDuration = lens _drioMinDuration (\s a -> s { _drioMinDuration = a })
-- | The token to use when requesting the next paginated set of offerings.
drioNextToken :: Lens' DescribeReservedInstancesOfferings (Maybe Text)
drioNextToken = lens _drioNextToken (\s a -> s { _drioNextToken = a })
-- | The Reserved Instance offering type. If you are using tools that predate the
-- 2011-11-01 API version, you only have access to the 'Medium Utilization'
-- Reserved Instance offering type.
drioOfferingType :: Lens' DescribeReservedInstancesOfferings (Maybe OfferingTypeValues)
drioOfferingType = lens _drioOfferingType (\s a -> s { _drioOfferingType = a })
-- | The Reserved Instance description. Instances that include '(Amazon VPC)' in the
-- description are for use with Amazon VPC.
drioProductDescription :: Lens' DescribeReservedInstancesOfferings (Maybe RIProductDescription)
drioProductDescription =
lens _drioProductDescription (\s a -> s { _drioProductDescription = a })
-- | One or more Reserved Instances offering IDs.
drioReservedInstancesOfferingIds :: Lens' DescribeReservedInstancesOfferings [Text]
drioReservedInstancesOfferingIds =
lens _drioReservedInstancesOfferingIds
(\s a -> s { _drioReservedInstancesOfferingIds = a })
. _List
data DescribeReservedInstancesOfferingsResponse = DescribeReservedInstancesOfferingsResponse
{ _driorNextToken :: Maybe Text
, _driorReservedInstancesOfferings :: List "item" ReservedInstancesOffering
} deriving (Eq, Read, Show)
-- | 'DescribeReservedInstancesOfferingsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'driorNextToken' @::@ 'Maybe' 'Text'
--
-- * 'driorReservedInstancesOfferings' @::@ ['ReservedInstancesOffering']
--
describeReservedInstancesOfferingsResponse :: DescribeReservedInstancesOfferingsResponse
describeReservedInstancesOfferingsResponse = DescribeReservedInstancesOfferingsResponse
{ _driorReservedInstancesOfferings = mempty
, _driorNextToken = Nothing
}
-- | The next paginated set of results to return.
driorNextToken :: Lens' DescribeReservedInstancesOfferingsResponse (Maybe Text)
driorNextToken = lens _driorNextToken (\s a -> s { _driorNextToken = a })
-- | A list of Reserved Instances offerings.
driorReservedInstancesOfferings :: Lens' DescribeReservedInstancesOfferingsResponse [ReservedInstancesOffering]
driorReservedInstancesOfferings =
lens _driorReservedInstancesOfferings
(\s a -> s { _driorReservedInstancesOfferings = a })
. _List
instance ToPath DescribeReservedInstancesOfferings where
toPath = const "/"
instance ToQuery DescribeReservedInstancesOfferings where
toQuery DescribeReservedInstancesOfferings{..} = mconcat
[ "AvailabilityZone" =? _drioAvailabilityZone
, "DryRun" =? _drioDryRun
, "Filter" `toQueryList` _drioFilters
, "IncludeMarketplace" =? _drioIncludeMarketplace
, "InstanceTenancy" =? _drioInstanceTenancy
, "InstanceType" =? _drioInstanceType
, "MaxDuration" =? _drioMaxDuration
, "MaxInstanceCount" =? _drioMaxInstanceCount
, "MaxResults" =? _drioMaxResults
, "MinDuration" =? _drioMinDuration
, "NextToken" =? _drioNextToken
, "OfferingType" =? _drioOfferingType
, "ProductDescription" =? _drioProductDescription
, "ReservedInstancesOfferingId" `toQueryList` _drioReservedInstancesOfferingIds
]
instance ToHeaders DescribeReservedInstancesOfferings
instance AWSRequest DescribeReservedInstancesOfferings where
type Sv DescribeReservedInstancesOfferings = EC2
type Rs DescribeReservedInstancesOfferings = DescribeReservedInstancesOfferingsResponse
request = post "DescribeReservedInstancesOfferings"
response = xmlResponse
instance FromXML DescribeReservedInstancesOfferingsResponse where
parseXML x = DescribeReservedInstancesOfferingsResponse
<$> x .@? "nextToken"
<*> x .@? "reservedInstancesOfferingsSet" .!@ mempty
instance AWSPager DescribeReservedInstancesOfferings where
page rq rs
| stop (rs ^. driorNextToken) = Nothing
| otherwise = (\x -> rq & drioNextToken ?~ x)
<$> (rs ^. driorNextToken)
| dysinger/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DescribeReservedInstancesOfferings.hs | mpl-2.0 | 13,241 | 0 | 11 | 2,802 | 1,547 | 927 | 620 | 152 | 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.BigQuery.DataSets.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all datasets in the specified project to which you have been
-- granted the READER dataset role.
--
-- /See:/ <https://cloud.google.com/bigquery/ BigQuery API Reference> for @bigquery.datasets.list@.
module Network.Google.Resource.BigQuery.DataSets.List
(
-- * REST Resource
DataSetsListResource
-- * Creating a Request
, dataSetsList
, DataSetsList
-- * Request Lenses
, dslAll
, dslFilter
, dslPageToken
, dslProjectId
, dslMaxResults
) where
import Network.Google.BigQuery.Types
import Network.Google.Prelude
-- | A resource alias for @bigquery.datasets.list@ method which the
-- 'DataSetsList' request conforms to.
type DataSetsListResource =
"bigquery" :>
"v2" :>
"projects" :>
Capture "projectId" Text :>
"datasets" :>
QueryParam "all" Bool :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :> Get '[JSON] DataSetList
-- | Lists all datasets in the specified project to which you have been
-- granted the READER dataset role.
--
-- /See:/ 'dataSetsList' smart constructor.
data DataSetsList =
DataSetsList'
{ _dslAll :: !(Maybe Bool)
, _dslFilter :: !(Maybe Text)
, _dslPageToken :: !(Maybe Text)
, _dslProjectId :: !Text
, _dslMaxResults :: !(Maybe (Textual Word32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DataSetsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dslAll'
--
-- * 'dslFilter'
--
-- * 'dslPageToken'
--
-- * 'dslProjectId'
--
-- * 'dslMaxResults'
dataSetsList
:: Text -- ^ 'dslProjectId'
-> DataSetsList
dataSetsList pDslProjectId_ =
DataSetsList'
{ _dslAll = Nothing
, _dslFilter = Nothing
, _dslPageToken = Nothing
, _dslProjectId = pDslProjectId_
, _dslMaxResults = Nothing
}
-- | Whether to list all datasets, including hidden ones
dslAll :: Lens' DataSetsList (Maybe Bool)
dslAll = lens _dslAll (\ s a -> s{_dslAll = a})
-- | An expression for filtering the results of the request by label. The
-- syntax is \"labels.[:]\". Multiple filters can be ANDed together by
-- connecting with a space. Example: \"labels.department:receiving
-- labels.active\". See Filtering datasets using labels for details.
dslFilter :: Lens' DataSetsList (Maybe Text)
dslFilter
= lens _dslFilter (\ s a -> s{_dslFilter = a})
-- | Page token, returned by a previous call, to request the next page of
-- results
dslPageToken :: Lens' DataSetsList (Maybe Text)
dslPageToken
= lens _dslPageToken (\ s a -> s{_dslPageToken = a})
-- | Project ID of the datasets to be listed
dslProjectId :: Lens' DataSetsList Text
dslProjectId
= lens _dslProjectId (\ s a -> s{_dslProjectId = a})
-- | The maximum number of results to return
dslMaxResults :: Lens' DataSetsList (Maybe Word32)
dslMaxResults
= lens _dslMaxResults
(\ s a -> s{_dslMaxResults = a})
. mapping _Coerce
instance GoogleRequest DataSetsList where
type Rs DataSetsList = DataSetList
type Scopes DataSetsList =
'["https://www.googleapis.com/auth/bigquery",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient DataSetsList'{..}
= go _dslProjectId _dslAll _dslFilter _dslPageToken
_dslMaxResults
(Just AltJSON)
bigQueryService
where go
= buildClient (Proxy :: Proxy DataSetsListResource)
mempty
| brendanhay/gogol | gogol-bigquery/gen/Network/Google/Resource/BigQuery/DataSets/List.hs | mpl-2.0 | 4,562 | 0 | 17 | 1,075 | 657 | 385 | 272 | 93 | 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.Games.Scores.SubmitMultiple
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Submits multiple scores to leaderboards.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Reference> for @games.scores.submitMultiple@.
module Network.Google.Resource.Games.Scores.SubmitMultiple
(
-- * REST Resource
ScoresSubmitMultipleResource
-- * Creating a Request
, scoresSubmitMultiple
, ScoresSubmitMultiple
-- * Request Lenses
, ssmXgafv
, ssmUploadProtocol
, ssmAccessToken
, ssmUploadType
, ssmPayload
, ssmLanguage
, ssmCallback
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.scores.submitMultiple@ method which the
-- 'ScoresSubmitMultiple' request conforms to.
type ScoresSubmitMultipleResource =
"games" :>
"v1" :>
"leaderboards" :>
"scores" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "language" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PlayerScoreSubmissionList :>
Post '[JSON] PlayerScoreListResponse
-- | Submits multiple scores to leaderboards.
--
-- /See:/ 'scoresSubmitMultiple' smart constructor.
data ScoresSubmitMultiple =
ScoresSubmitMultiple'
{ _ssmXgafv :: !(Maybe Xgafv)
, _ssmUploadProtocol :: !(Maybe Text)
, _ssmAccessToken :: !(Maybe Text)
, _ssmUploadType :: !(Maybe Text)
, _ssmPayload :: !PlayerScoreSubmissionList
, _ssmLanguage :: !(Maybe Text)
, _ssmCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ScoresSubmitMultiple' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ssmXgafv'
--
-- * 'ssmUploadProtocol'
--
-- * 'ssmAccessToken'
--
-- * 'ssmUploadType'
--
-- * 'ssmPayload'
--
-- * 'ssmLanguage'
--
-- * 'ssmCallback'
scoresSubmitMultiple
:: PlayerScoreSubmissionList -- ^ 'ssmPayload'
-> ScoresSubmitMultiple
scoresSubmitMultiple pSsmPayload_ =
ScoresSubmitMultiple'
{ _ssmXgafv = Nothing
, _ssmUploadProtocol = Nothing
, _ssmAccessToken = Nothing
, _ssmUploadType = Nothing
, _ssmPayload = pSsmPayload_
, _ssmLanguage = Nothing
, _ssmCallback = Nothing
}
-- | V1 error format.
ssmXgafv :: Lens' ScoresSubmitMultiple (Maybe Xgafv)
ssmXgafv = lens _ssmXgafv (\ s a -> s{_ssmXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
ssmUploadProtocol :: Lens' ScoresSubmitMultiple (Maybe Text)
ssmUploadProtocol
= lens _ssmUploadProtocol
(\ s a -> s{_ssmUploadProtocol = a})
-- | OAuth access token.
ssmAccessToken :: Lens' ScoresSubmitMultiple (Maybe Text)
ssmAccessToken
= lens _ssmAccessToken
(\ s a -> s{_ssmAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
ssmUploadType :: Lens' ScoresSubmitMultiple (Maybe Text)
ssmUploadType
= lens _ssmUploadType
(\ s a -> s{_ssmUploadType = a})
-- | Multipart request metadata.
ssmPayload :: Lens' ScoresSubmitMultiple PlayerScoreSubmissionList
ssmPayload
= lens _ssmPayload (\ s a -> s{_ssmPayload = a})
-- | The preferred language to use for strings returned by this method.
ssmLanguage :: Lens' ScoresSubmitMultiple (Maybe Text)
ssmLanguage
= lens _ssmLanguage (\ s a -> s{_ssmLanguage = a})
-- | JSONP
ssmCallback :: Lens' ScoresSubmitMultiple (Maybe Text)
ssmCallback
= lens _ssmCallback (\ s a -> s{_ssmCallback = a})
instance GoogleRequest ScoresSubmitMultiple where
type Rs ScoresSubmitMultiple =
PlayerScoreListResponse
type Scopes ScoresSubmitMultiple =
'["https://www.googleapis.com/auth/games"]
requestClient ScoresSubmitMultiple'{..}
= go _ssmXgafv _ssmUploadProtocol _ssmAccessToken
_ssmUploadType
_ssmLanguage
_ssmCallback
(Just AltJSON)
_ssmPayload
gamesService
where go
= buildClient
(Proxy :: Proxy ScoresSubmitMultipleResource)
mempty
| brendanhay/gogol | gogol-games/gen/Network/Google/Resource/Games/Scores/SubmitMultiple.hs | mpl-2.0 | 5,156 | 0 | 19 | 1,245 | 791 | 459 | 332 | 116 | 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="ru-RU">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | secdec/zap-extensions | addOns/directorylistv2_3/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 978 | 83 | 52 | 157 | 395 | 209 | 186 | -1 | -1 |
{-
- Copyright 2012 Fabio Riga
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
{-# LANGUAGE OverloadedStrings,TemplateHaskell #-}
import HFlags
import System.Environment (getEnv)
import System.Process
import System.Directory
import System.Exit
import System.FilePath
import Data.String.Utils
import Data.Version
import Data.List
import Data.Maybe
import Control.Monad (when, unless)
import PkgDB
import Helpers
import Defaults
import Update
-- | The status of a package in the cblrepo database.
data PkgStatus = RepPkg -- ^ A package available in this repository
| DistrPkg -- ^ A package available taken from other repositories
| MainPkg -- ^ A package available in [habs] but not in this repo
| NewPkg -- ^ A package not present in the DB nor in [habs]
deriving (Show, Eq, Ord)
-- | A simplyfied version of CblPkg
data SimplePkg
= DisPkg { pName :: String
, pVersion :: Version
, pRelease :: String
}
| RePkg { pName :: String
, pVersion ::Version
}
deriving (Show, Eq, Ord)
-- | A convenient type
type CabalPkg = (String, Version)
-- Options used in command line
defineFlag "n:dryrun" False "Don't do anything, just try"
defineFlag "u:upgradedistro" False "Upgrade DistroPkgs to version in main repository"
defineFlag "b:build" False "Create pkgbuilds and compile"
defineFlag "y:update" False "Update main repo and Hackage file list"
defineFlag "l:listupdates" False
"list available updates for packages in repository and exit"
main = do
args <- $(initHFlags helpMessage)
when flags_update $ update
home <- getEnv "HOME"
setCurrentDirectory $ home </> thisRepoDir
when flags_listupdates $ do
listUpdates
exitSuccess
thisR <- readDb (home </> thisRepoDir </> "cblrepo.db")
mainR <- readDb (home </> mainRepoDir </> "cblrepo.db")
let upgradeList = if flags_upgradedistro
then distroUpgrades mainR thisR
else []
let list = filter (newCblPkg thisR mainR) args
cabalList <- getCabalList list
let newList = catMaybes $ map (makeSimplePkg thisR mainR) cabalList
let installList = upgradeList ++ newList
let names = getNames installList
-- Do the job!
addCblPkgs installList
unless flags_dryrun $ logNames "updates" names
bump names
when flags_build $ build installList
-- | For each DistroPkg search if there's a newer version in the main
-- repository.
distroUpgrades :: CblDB -> CblDB -> [SimplePkg]
distroUpgrades mainR =
map toSimpleDisPkg . catMaybes . map (\p -> lookupPkg mainR (pkgName p))
. filter (needsUpdateD (mainR)) . filter (isDistroPkg)
where
needsUpdateD mainR pkg =
let Just mainPkg = lookupPkg mainR (pkgName pkg)
prel s = read (pkgRelease s) :: Int
in (pkgVersion mainPkg) > (pkgVersion pkg) ||
((pkgVersion mainPkg) == (pkgVersion pkg) && (prel mainPkg) > (prel pkg))
-- | Check if a package is already in [habs]
-- TODO: it should be in any other repository, not just habs.
newCblPkg thisR mainR name =
if pkgType == MainPkg
then False
else True
where
(pkgType, _) = checkPkgStatus name thisR mainR
-- | Take a list of packages names and return all needed packages as CabalPkg.
-- As cabal command will exclude already installed packages, we run the
-- command in the clean "root" chroot.
getCabalList :: [String] -> IO [CabalPkg]
getCabalList [] = return []
getCabalList pkgNames = do
str <- runCabal (unwords $ map (\x -> "'" ++ x ++ "'") pkgNames)
let list = drop 2 $ lines str
let plist = map getPkg list
-- mapM_ (\(pn,pv) -> putStrLn $ pn ++ ": " ++ show pv) plist
return plist
where
getPkg s =
let l = split "-" s
name = join "-" $ init l
version = last l
in (name, (getVersion version))
runCabal pkgs = do
chroot chrootRootDir "cabal" ["install", "--dry-run", pkgs]
getVersion s = Version (ver s) []
ver s = map (\x -> read x :: Int) (split "." s)
-- | Checks wheter a given package is new, a RepoPkg, a DistroPkg or from the
-- main repository.
checkPkgStatus :: String -> CblDB -> CblDB -> (PkgStatus, Maybe CblPkg)
checkPkgStatus name thisR mainR =
case lookupPkg thisR name of
Just pkg -> if isRepoPkg pkg
then (RepPkg, Just pkg)
else (DistrPkg, Just pkg)
Nothing -> do
case lookupPkg mainR name of
Just pkg -> (MainPkg, Just pkg)
Nothing -> (NewPkg, Nothing)
-- | takes the name and version of a package to be installed from Cabal
-- and returns the appropriate SimplePkg
makeSimplePkg :: CblDB -> CblDB -> CabalPkg -> Maybe SimplePkg
makeSimplePkg thisR mainR (pn, pv) =
case pkgType of
MainPkg -> addDisPkg pkg
NewPkg -> Just $ RePkg pn pv
RepPkg -> updateRepPkg pkg pv
DistrPkg -> Nothing
where
(pkgType, pkg) = checkPkgStatus pn thisR mainR
updateRepPkg (Just pkg) nv =
if (nv > pkgVersion pkg)
then Just $ (toSimplePkg pkg) { pVersion = nv }
else Nothing
addDisPkg pkg =
case pkg of
Just p -> Just $ toSimpleDisPkg p
Nothing -> Nothing
-- | Add all packages with a call to cblrepo.
addCblPkgs :: [SimplePkg] -> IO ()
addCblPkgs list = do
let (disList, reList) = partition isDisPkg list
putStrLn "==> The following DistroPkgs will be added:"
putStrLn $ unlines (map distroPkgString' disList)
putStrLn "\n"
putStrLn "==> The following RepoPkgs will be added:"
putStrLn $ unlines (map repoPkgString' reList)
let args = (map distroPkgString $ disList) ++ (map repoPkgString $ reList)
res <- if flags_dryrun
then do
putStr "(dry-run) "
cblrepoN "add" args
else cblrepo "add" args
putStr res
when (res /= "") exitFailure
putStrLn "Done."
where
distroPkgString pkg =
"--distro-pkg=" ++ repoPkgString pkg ++ "," ++ pRelease pkg
repoPkgString pkg =
pName pkg ++ "," ++ (showVersion $ pVersion pkg)
distroPkgString' pkg =
repoPkgString' pkg ++ "-" ++ pRelease pkg
repoPkgString' pkg =
pName pkg ++ "-" ++ (showVersion $ pVersion pkg)
-- | Call cblrepo to /bump/ packages depending on updated packages.
bump :: [String] -> IO ()
bump [] = return ()
bump names = do
putStrLn "Bumping dependencies..."
res <- if flags_dryrun
then cblrepoN "bump" names
else cblrepo "bump" names
putStrLn res
putStrLn "Done."
-- | Build needed package. If there was a sync with main repository, it will
-- build all database. It needs root privilegs to run in chroot. Sudo should
-- be present in your system and configured as needed.
build :: [SimplePkg] -> IO ()
build [] = return ()
build names = do
list <- if flags_upgradedistro
then do
l <- cblrepo "build" ["base"]
return $ tail (words l)
else do
l <- cblrepo "build" $ getNames (filter isRePkg names)
return $ words l
putStrLn "Preparing pkgbuild for the following packages:"
putStrLn $ unwords list
logNames "builds" list
cblrepo "pkgbuild" list
code <- system $ "sudo ./makeahpkg -x -- " ++ (unwords list)
if code == ExitSuccess
then return()
else exitFailure
code' <- system $ "sudo ./makeahpkg -a i686 -x -- " ++ (unwords list)
if code' == ExitSuccess
then return()
else exitFailure
getNames :: [SimplePkg] -> [String]
getNames [] = []
getNames pkgs = map pName pkgs
-- | Convert CblPkg to SimplePkg
toSimplePkg :: CblPkg -> SimplePkg
toSimplePkg (CP n (DistroPkg v r)) = DisPkg n v r
toSimplePkg (CP n p) = RePkg n (version p)
-- | Convert RepoPkg in main to DisPkg in current repository
toSimpleDisPkg :: CblPkg -> SimplePkg
toSimpleDisPkg (CP n (RepoPkg v _ _ r)) = DisPkg n v r
isDisPkg DisPkg {} = True
isDisPkg _ = False
isRePkg = not . isDisPkg
-- | For tracking changes
logNames :: String -> [String] -> IO ()
logNames f ns = do
date <- readProcess "date" ["+%Y-%m-%d %H:%M:%S"] []
appendFile (f ++ ".log") ((init date) ++ ": " ++ (unwords ns) ++ "\n")
| EffeErre/cbladmin | src/CblAdmin.hs | apache-2.0 | 8,639 | 32 | 15 | 2,130 | 2,257 | 1,114 | 1,143 | 184 | 6 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
module Duckling.Rules.NB
( defaultRules
, langRules
, localeRules
) where
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.AmountOfMoney.NB.Rules as AmountOfMoney
import qualified Duckling.Duration.NB.Rules as Duration
import qualified Duckling.Numeral.NB.Rules as Numeral
import qualified Duckling.Ordinal.NB.Rules as Ordinal
import qualified Duckling.Time.NB.Rules as Time
import qualified Duckling.TimeGrain.NB.Rules as TimeGrain
defaultRules :: Seal Dimension -> [Rule]
defaultRules = langRules
localeRules :: Region -> Seal Dimension -> [Rule]
localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim
localeRules _ _ = []
langRules :: Seal Dimension -> [Rule]
langRules (Seal AmountOfMoney) = AmountOfMoney.rules
langRules (Seal CreditCardNumber) = []
langRules (Seal Distance) = []
langRules (Seal Duration) = Duration.rules
langRules (Seal Email) = []
langRules (Seal Numeral) = Numeral.rules
langRules (Seal Ordinal) = Ordinal.rules
langRules (Seal PhoneNumber) = []
langRules (Seal Quantity) = []
langRules (Seal RegexMatch) = []
langRules (Seal Temperature) = []
langRules (Seal Time) = Time.rules
langRules (Seal TimeGrain) = TimeGrain.rules
langRules (Seal Url) = []
langRules (Seal Volume) = []
langRules (Seal (CustomDimension dim)) = dimLangRules NB dim
| facebookincubator/duckling | Duckling/Rules/NB.hs | bsd-3-clause | 1,587 | 0 | 9 | 221 | 458 | 256 | 202 | 36 | 1 |
{-# LANGUAGE ScopedTypeVariables, TemplateHaskell, TypeOperators #-}
module World where
import Data.Label
import Data.Array
import Data.Map (Map)
import qualified Data.Map as Map
type Coord = (Int, Int)
-- operator to add 2 coordinates together
(|+|) :: Coord -> Coord -> Coord
(|+|) (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
data Tile = Wall
| Tree
| Floor
| Empty
deriving (Eq,Ord,Show)
data Moveable = Moveable { _key :: Int
, _position :: Coord
, _monster :: Monster
} deriving (Eq,Ord,Show)
data Monster = StrayDog { _health :: Int} deriving (Eq,Ord,Show)
type Level = Array Coord Tile
data World = World
{ _hero :: Coord
, _monsters :: Map Int Moveable
, _level :: Level
, _messages :: [String]
} deriving Show
$(mkLabels [''World,''Moveable,''Monster])
initlevel :: Level
initlevel = array ((0,0),(79,24)) [((x,y),
if x `rem` 5 == 0
&& y `rem` 7 == 0
then Tree
else Floor)
| x <- [0..79]
, y <- [0..24]]
initmonsters :: Map Int Moveable
initmonsters = Map.fromList $ zipWith (\n c -> (n,(Moveable n c (StrayDog 10)))) [1..10]
[(x,y)
| x <- [0..79]
, x `rem` 6 == 0
, y <- [0..24]
, y `mod` 6 == 0]
inithero :: Coord
inithero = (2,2)
| pfynan/cabbagesandkings | World.hs | bsd-3-clause | 1,616 | 0 | 13 | 683 | 532 | 313 | 219 | 44 | 2 |
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
module EFA.Application.Optimisation.Balance where
--import qualified EFA.Application.Optimisation.Sweep as Sweep
--import qualified EFA.Application.Optimisation.ReqsAndDofs as ReqsAndDofs
import qualified EFA.Flow.State.Quantity as StateQty
import qualified EFA.Flow.SequenceState.Index as Idx
import qualified EFA.Flow.Topology.Index as TopoIdx
--import qualified EFA.Signal.Signal as Sig
--import qualified EFA.Graph.Topology as Topology
import qualified EFA.Equation.Arithmetic as Arith
import EFA.Equation.Arithmetic ((~+))
import EFA.Equation.Result (Result)
--import EFA.Signal.Record(PowerRecord)
import qualified Data.Map as Map; import Data.Map (Map)
--import Data.Vector(Vector)
import Data.Bimap (Bimap)
import Data.Maybe(fromMaybe)
--import Debug.Trace(trace)
-- | The 'SocDrive' data type should always contain positive values.
-- Use 'getSocDrive' to get the drive with signs corrected.
data SocDrive a =
NoDrive -- ^ No drive
| ChargeDrive a -- ^ Charging states should be prefered
| DischargeDrive a -- ^ Discharging states should be prefered
deriving (Show)
instance Functor SocDrive where
fmap f (ChargeDrive x) = ChargeDrive (f x)
fmap f (DischargeDrive x) = DischargeDrive (f x)
fmap _ NoDrive = NoDrive
--type ForcingPerNode node a = Map node (SocDrive a)
getSocDrive ::
(Arith.Sum a, Arith.Constant a) => SocDrive a -> a
getSocDrive soc =
case soc of
DischargeDrive x -> Arith.negate x
ChargeDrive x -> x
NoDrive -> Arith.zero
setSocDrive ::
(Arith.Sum a, Arith.Constant a,Ord a) => a -> SocDrive a
setSocDrive x =
case Arith.sign x of
Arith.Positive -> ChargeDrive x
Arith.Zero -> NoDrive
Arith.Negative -> DischargeDrive $ Arith.negate x
noforcing ::
(Arith.Constant v) =>
SocDrive v -> StateQty.Graph node b (Result v) -> v
noforcing _ _ = Arith.zero
type IndexConversionMap =
Bimap Idx.State Idx.AbsoluteState
nocondition :: StateQty.Graph node b (Result v) -> Bool
nocondition _ = True
type OptimalPower node = Map Idx.State [(TopoIdx.Position node)]
optimalPower :: [(Idx.State, [(TopoIdx.Position node)])] -> OptimalPower node
optimalPower = Map.fromList
type Balance node a = Map node a
data Absolute
data Step
newtype ForcingMap x a =
ForcingMap { unForcingMap :: a } deriving (Show)
instance Functor (ForcingMap x) where
fmap f (ForcingMap m) = ForcingMap (f m)
type Forcing node a =
ForcingMap Absolute (Map node (SocDrive a))
type ForcingStep node a =
ForcingMap Step (Map node (SocDrive a))
type BestBalance node a = Map node (Maybe (SocDrive a, a), Maybe (SocDrive a, a))
type StateDurations a = Map Idx.AbsoluteState a
rememberBestBalanceForcing ::
(Arith.Constant a, Ord a, Ord node, Show node, Show a) =>
(Maybe (SocDrive a,a), Maybe (SocDrive a,a)) ->
(Forcing node a, Balance node a) ->
node ->
(Maybe (SocDrive a, a), Maybe (SocDrive a, a))
rememberBestBalanceForcing (neg, pos) (forceMap, balMap) sto =
if bal >= Arith.zero then (neg, g pos) else (h neg, pos)
where
bal = getStorageBalance "rememberBestBalanceForcing" balMap sto
force = getStorageForcing "rememberBestBalanceForcing" forceMap sto
-- TODO :: Fix is compensating for non-Monotonic behaviour of Forcing -> Balance
-- Correct solution would be to work with an Balance Intervall
-- Which is calculated by maximum duration charging states to max. duration discharging states
g (Just (f, b)) =
if bal <= b || (getSocDrive force < getSocDrive force && bal > b)
then Just (force, bal)
else Just (f, b)
g Nothing = Just (force, bal)
h (Just (f, b)) =
if (Arith.abs bal <= Arith.abs b) || (getSocDrive force > getSocDrive f && bal < b)
then Just (force, bal)
else Just (f, b)
h Nothing = Just (force, bal)
checkCrossingEverOccured ::
(Maybe (SocDrive a,a), Maybe (SocDrive a, a)) -> Bool
checkCrossingEverOccured (Just _, Just _) = True
checkCrossingEverOccured _ = False
getForcingIntervall :: (Ord a, Arith.Constant a) =>
(Maybe (SocDrive a,a), Maybe (SocDrive a,a)) ->
Maybe (SocDrive a)
getForcingIntervall (Just (n, _), Just (p, _)) =
Just $ setSocDrive $ (Arith.abs $ getSocDrive n) ~+ getSocDrive p
getForcingIntervall _ = Nothing
addForcingStep ::
(Ord node, Ord a, Arith.Constant a, Show node) =>
Forcing node a ->
ForcingStep node a ->
node ->
Forcing node a
addForcingStep forcing stepMap sto =
fmap (Map.adjust f sto) forcing
where f force = setSocDrive $ getSocDrive force ~+ getSocDrive step
step = getStorageForcingStep "addForcingStep" stepMap sto
updateForcingStep ::
(Ord node, Ord a, Arith.Constant a) =>
ForcingStep node a ->
node ->
SocDrive a ->
ForcingStep node a
updateForcingStep forcing storage step =
fmap (Map.adjust (const step) storage) forcing
getStorageForcing ::
(Ord node, Show node) =>
String ->
Forcing node a ->
node ->
SocDrive a
getStorageForcing caller forcing sto =
fromMaybe (error m) $ Map.lookup sto $ unForcingMap forcing
where m = "Error in getStorageForcing called by " ++ caller
++ " - gStorage not in Map: " ++ show sto
getStorageForcingStep ::
(Ord node, Show node) =>
String ->
ForcingStep node a ->
node ->
SocDrive a
getStorageForcingStep caller forcing sto =
fromMaybe (error m) $ Map.lookup sto $ unForcingMap forcing
where m = "Error in getStorageForcing called by " ++ caller
++ " - gStorage not in Map: " ++ show sto
getStorageBalance ::
(Ord node, Show node) =>
String -> Balance node a ->
node -> a
getStorageBalance caller balance sto =
fromMaybe (error m) $ Map.lookup sto balance
where m = "Error in getStorageBalance called by " ++ caller
++ " - gStorage not in Map: " ++ show sto
data StateForcing = StateForcingOn | StateForcingOff deriving (Show)
| energyflowanalysis/efa-2.1 | src/EFA/Application/Optimisation/Balance.hs | bsd-3-clause | 5,990 | 0 | 13 | 1,232 | 1,866 | 994 | 872 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
-- Test that the startEventLog interface works as expected.
main :: IO ()
main = do
putStrLn "Starting eventlog..."
c_init_eventlog
putStrLn "done"
foreign import ccall unsafe "init_eventlog"
c_init_eventlog :: IO ()
| sdiehl/ghc | testsuite/tests/rts/InitEventLogging.hs | bsd-3-clause | 269 | 0 | 7 | 45 | 52 | 25 | 27 | 8 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.