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
{-# htermination notElem :: Eq a => [a] -> [[a]] -> Bool #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_notElem_4.hs
mit
61
0
2
13
3
2
1
1
0
------------------------------------------------------------------------ -- | -- Module : Yesod.Angular -- Description : Yesod Angular JS Integration. -- Copyright : (c) 2014-2015, Christopher Reichert -- License : MIT -- Maintainer : Christopher Reichert <creichert@reichertbrothers.com> -- Stability : unstable -- Portability : POSIX -- -- -- This module is based on Michael Snoyman's original work -- in the <https://github.com/snoyberg/yesod-js> repository. -- -- * This module currently defaults to Angular 1.2.18. Use -- `urlAngularJs_` specify your own Angular location. -- -- * Example can be found at: -- <https://github.com/snoyberg/yesod-js/tree/master/yesod-angular> -- -- * Currently, this module looks for controllers in the -- `templates/angular` directory. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Yesod.Angular ( YesodAngular (..) , runAngular , addCommand , addCtrl , addCtrlRaw , setDefaultRoute , AngularT ) where import Control.Applicative ((<$>)) import Control.Monad.Trans.Writer (WriterT (..), tell) import Data.Aeson (FromJSON, ToJSON) import Data.Char (isAlpha) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid (First (..), Monoid, mappend, mempty, (<>)) import Data.Text (Text) import qualified Data.Text as T import Language.Haskell.TH.Syntax (Exp (AppE, LitE), Lit (StringL), Q) import Text.Hamlet (hamletFile) import Text.Julius (JavascriptUrl, juliusFile, rawJS) import Yesod -- | YesodAngular wraps a widget in an ng-app named @modname@ class Yesod site => YesodAngular site where -- | Default instance loads `angular.min.js` and `angular-route.min.js` from -- cloudflare cdn. urlAngularJs :: site -> [Either (Route site) Text] urlAngularJs _ = [Right "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.18/angular.min.js", Right "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.18/angular-route.min.js"] -- | 'wrapAngular' wraps @widget in an ng-app named @modname. wrapAngular :: Text -> WidgetT site IO () -> HandlerT site IO Html wrapAngular modname widget = defaultLayout [whamlet| <div ng-app=#{modname}>^{widget} |] data AngularWriter site = AngularWriter { awCommands :: Map Text (HandlerT site IO ()) , awPartials :: Map Text (HtmlUrl (Route site)) , awRoutes :: JavascriptUrl (Route site) , awControllers :: JavascriptUrl (Route site) , awDefaultRoute :: First Text } type AngularT site = WriterT (AngularWriter site) (HandlerT site IO) instance Monoid (AngularWriter site) where mempty = AngularWriter mempty mempty mempty mempty mempty AngularWriter a1 a2 a3 a4 a5 `mappend` AngularWriter b1 b2 b3 b4 b5 = AngularWriter (mappend a1 b1) (mappend a2 b2) (mappend a3 b3) (mappend a4 b4) (mappend a5 b5) runAngular :: YesodAngular site => AngularT site () -> HandlerT site IO Html runAngular ga = do site <- getYesod ((), AngularWriter{..}) <- runWriterT ga mc <- lookupGetParam "command" fromMaybe (return ()) $ mc >>= flip Map.lookup awCommands mp <- lookupGetParam "partial" case mp >>= flip Map.lookup awPartials of Nothing -> return () Just htmlurl -> do ps <- getUrlRenderParams let rep = toTypedContent . htmlurl $ ps sendResponse rep modname <- newIdent let defaultRoute = case awDefaultRoute of First (Just x) -> [julius|.otherwise({redirectTo:"#{rawJS x}"})|] First Nothing -> mempty wrapAngular modname $ do mapM_ addScriptEither $ urlAngularJs site [whamlet| <div ng-view> |] toWidget [julius| angular.module("#{rawJS modname}", ['ngRoute']).config(["$routeProvider", function($routeProvider, $locationProvider) { $routeProvider ^{awRoutes} ^{defaultRoute}; }]); ^{awControllers} |] addCommand :: (FromJSON input, ToJSON output) => (input -> HandlerT site IO output) -> AngularT site Text addCommand f = do name <- lift newIdent tell mempty { awCommands = Map.singleton name handler } return $ "?command=" `mappend` name where handler = do input <- requireJsonBody output <- f input repjson <- returnJson output sendResponse repjson setDefaultRoute :: Text -> AngularT site () setDefaultRoute x = tell mempty { awDefaultRoute = First $ Just x } addCtrl :: Text -- ^ route pattern -> Text -- ^ template name -> Q Exp addCtrl route name = do let name' = T.filter isAlpha name [|addCtrlRaw $(liftT name') $(liftT route) $(hamletFile $ fn "hamlet") $(juliusFile $ fn "julius")|] where liftT t = do p <- [|T.pack|] return $ AppE p $ LitE $ StringL $ T.unpack t fn suffix = T.unpack $ T.concat ["angular/", name, ".", suffix] addCtrlRaw :: Text -- ^ user-friendly name -> Text -- ^ route pattern -> HtmlUrl (Route site) -- ^ template -> JavascriptUrl (Route site) -- ^ controller -> AngularT site () addCtrlRaw name' route template controller = do name <- mappend (mappend name' "__") <$> lift newIdent tell mempty { awPartials = Map.singleton name template , awRoutes = [julius| .when("#{rawJS route}", { "controller": #{rawJS name} , "templateUrl": "?partial=#{rawJS name}" }) |] , awControllers = [julius| var #{rawJS name} = ^{controller} |] }
creichert/yesod-angular
src/Yesod/Angular.hs
mit
6,419
0
16
2,083
1,299
698
601
108
3
module Countdown3 where import Data.List import Data.Function import Types countdown3 :: Int -> [Int] -> (Expr, Value) countdown3 n = nearest n . concatMap mkExprs . subseqs unmerges :: [a] -> [([a],[a])] unmerges [x,y] = [([x],[y])] unmerges (x:xs) = [([x],xs), (xs,[x])] ++ map (applyFst (x:)) (unmerges xs) ++ map (applySnd (x:)) (unmerges xs) comb1 :: (Expr, Value) -> (Expr, Value) -> [(Expr, Value)] comb1 (e1,v1) (e2,v2) = (if non Sub e1 && non Sub e2 then [(App Add e1 e2, v1+v2) | non Add e2] ++ [(App Sub e2 e1, v2-v1)] else [] ) ++ (if 1 < v1 && non Div e1 && non Div e2 then [(App Mul e1 e2, v1*v2) | non Mul e2] ++ [(App Div e2 e1, q) | r == 0] else [] ) where (q,r) = divMod v2 v1 comb2 :: (Expr, Value) -> (Expr, Value) -> [(Expr, Value)] comb2 (e1,v1) (e2,v2) = [(App Add e1 e2, v1+v2) | non Sub e1, non Add e2, non Sub e2] ++ (if 1 < v1 && non Div e1 && non Div e2 then [(App Mul e1 e2, v1*v2) | non Mul e2] ++ [(App Div e1 e2, 1)] else []) non :: Op -> Expr -> Bool non op (Num x) = True non op1 (App op2 e1 e2) = op1 /= op2 -- same as countdown2 combine :: (Expr, Value) -> (Expr, Value) -> [(Expr, Value)] combine (e1,v1) (e2,v2) | v1 < v2 = comb1 (e1,v1) (e2,v2) | v1 == v2 = comb2 (e1,v1) (e2,v2) | v1 > v2 = comb1 (e2,v2) (e1,v1) subseqs :: [Value] -> [[Value]] subseqs [x] = [[x]] subseqs (x:xs) = xss ++ [x] : map (x:) xss where xss = subseqs xs value :: Expr -> Value value (Num n) = n value (App op e1 e2) = apply op (value e1) (value e2) apply :: Op -> Value -> Value -> Value apply Add = (+) apply Sub = (-) apply Mul = (*) apply Div = div mkExprs :: [Value] -> [(Expr, Value)] mkExprs [x] = [(Num x, x)] mkExprs xs = [ev | (ys,zs) <- unmerges xs ,ev1 <- mkExprs ys ,ev2 <- mkExprs zs ,ev <- combine ev1 ev2] nearest :: Int -> [(Expr, Value)] -> (Expr, Value) -- nearest n ts = minimumBy (compare `on` snd) [(e, abs $ v - n) | (e,v) <- ts] nearest n ((e,v):evs) = if d == 0 then (e,v) else search n d (e,v) evs where d = abs (n - v) search n d ev [] = ev search n d ev ((e,v):evs) | d' == 0 = (e,v) | d' < d = search n d' (e,v) evs | d' >= d = search n d ev evs where d' = abs (n - v) -- applyFst :: (a -> b) -> (a, c) -> (b, c) applyFst f (x,y) = (f x, y) applySnd :: (b -> c) -> (a, b) -> (a, c) applySnd f (x,y) = (x, f y)
y-kamiya/functional-algorithm-design
src/Countdown/Countdown3.hs
mit
2,722
0
11
965
1,490
819
671
65
3
module Prime(primeList, cutBrackets) where eratos :: Integral a => [a] -> [a] eratos (n:ns) | null ns = n:[] | n * n > last ns = n:ns | otherwise = n:eratos [ i | i<-ns , i `rem` n /= 0] primeList :: Integral a => a -> [a] primeList n = eratos [2..n] cutBrackets :: Show a => [a] -> String cutBrackets (x:xs) | null xs = "P" ++ show x | otherwise = "P" ++ show x ++ " | " ++ cutBrackets xs
mino2357/Hello_Haskell
primeList/Prime.hs
mit
408
0
11
105
241
120
121
12
1
{- Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 -} import Data.List import Debug.Trace max_exp = 6 dsplit :: Int -> [Int] dsplit n = dsplit' n [] where dsplit' n s | n > 0 = dsplit' rest (first:s) | n < 0 = [] | s == [] = [0] | otherwise = s where first = mod n 10 rest = div n 10 champ :: Int -> Int champ n = champ' n 1 where champ' n d | n > m = champ' (n-m) (d+1) | otherwise = (dsplit k) !! p where f = 10^(d-1) -- first number with d digits m = d * f * 9 -- count of numbers with d digits n1 = n-1 k = f + (div n1 d) -- the number containing result p = mod n1 d -- position of digit in k solve = product $ map champ $ map (10^) [0..max_exp] main = do -- print $ map champ [1..200] print solve {- This method is O(log n) in time and O(1) in memory -}
bertdouglas/euler-haskell
001-050/40b.hs
mit
1,303
4
9
446
340
174
166
28
1
module Palindromes (largestPalindrome, smallestPalindrome) where import Data.Function (on) type Comparator a = a -> a -> Ordering type Product2 a = (a, [(a, a)]) isPalindrome :: Integral a => a -> Bool isPalindrome x = x < base || lastDigit /= 0 && digits == reverse digits where base = 10 digits@(lastDigit:_) = revDigitsBase base x revDigitsBase :: Integral a => a -> a -> [a] revDigitsBase base = go where go n = case n `quotRem` base of (0, r) -> [r] (q, r) -> r : go q union2 :: Comparator a -> (a -> a -> a) -> [a] -> [a] -> [a] union2 cmp merge = go where go [] ys = ys go xs [] = xs go (x:xs) (y:ys) = case cmp x y of GT -> y : go (x:xs) ys EQ -> merge x y : go xs ys LT -> x : go xs (y:ys) maybeHead :: [a] -> Maybe a maybeHead [] = Nothing maybeHead (x:_) = Just x largestPalindrome, smallestPalindrome :: Integral a => a -> a -> Maybe (Product2 a) largestPalindrome a b = maybeHead $ bigPalindromes a b smallestPalindrome a b = maybeHead $ smallPalindromes a b bigPalindromes, smallPalindromes :: Integral a => a -> a -> [Product2 a] bigPalindromes a b = palindromes (flip compare) [b, b-1 .. a] smallPalindromes a b = palindromes compare [a .. b] -- Produce a sorted list of palindromes using the factors from range. -- Note that range must be monotonically increasing according to -- cmp. palindromes :: Integral a => Comparator a -> [a] -> [Product2 a] palindromes cmp range = filter (isPalindrome . fst) $ unionAllBy (cmp `on` fst) merge $ combinationsWith combine range where combine a b = (a * b, [(a, b)]) merge (a, as) (_, bs) = (a, as ++ bs) -- All pairwise combinations as a list of lists: -- combinationsWith (,) [1,2,3] = -- [[(1,1), (1,2), (1,3)], [(2, 2), (2, 3)], [(3, 3)]] combinationsWith :: (a -> a -> b) -> [a] -> [[b]] combinationsWith f = go where go [] = [] go xs@(x:xs') = map (f x) xs : go xs' -- union a list of sorted lists, but assume the heads are presorted. -- this optimization reduces comparisons and allows for an infinite number of -- input lists unionAllBy :: Comparator a -> (a -> a -> a) -> [[a]] -> [a] unionAllBy cmp merge = go where union = union2 cmp merge go ((x:xs):(y:ys):rest) = x : union xs (y : ys `union` go rest) go rest = foldr union [] rest
exercism/xhaskell
exercises/practice/palindrome-products/.meta/examples/success-standard/src/Palindromes.hs
mit
2,376
0
13
607
970
518
452
45
5
----------------------------------------------------------------------------- -- -- Module : Language.TypeScript.Types -- Copyright : (c) DICOM Grid Inc. 2013 -- License : MIT -- -- Maintainer : Phillip Freeman <paf31@cantab.net> -- Stability : experimental -- Portability : -- -- | -- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable #-} module Language.TypeScript.Types where import qualified Data.Map as M import Data.Monoid import Data.Data (Typeable, Data) data Comment = Comment { commentText :: [String] , commentOther :: [(String, String)] } deriving (Show, Data, Typeable) instance Monoid Comment where mempty = Comment [] [] mappend (Comment ts os) (Comment ts' os') = Comment (ts ++ ts') (os ++ os') type CommentPlaceholder = Either (Int, Int) Comment data DeclarationElement = InterfaceDeclaration CommentPlaceholder (Maybe Exported) Interface | TypeAliasDeclaration CommentPlaceholder (Maybe Exported) TypeAlias | ExportDeclaration String | AmbientDeclaration CommentPlaceholder (Maybe Exported) Ambient deriving (Show, Data, Typeable) data Exported = Exported deriving (Show, Data, Typeable) data EntityName = EntityName (Maybe ModuleName) String deriving (Show, Data, Typeable) data Interface = Interface CommentPlaceholder String (Maybe [TypeParameter]) (Maybe [TypeRef]) TypeBody deriving (Show, Data, Typeable) data TypeAlias = TypeAlias CommentPlaceholder String Type deriving (Show, Data, Typeable) data Ambient = AmbientVariableDeclaration CommentPlaceholder String (Maybe Type) | AmbientFunctionDeclaration CommentPlaceholder String ParameterListAndReturnType | AmbientClassDeclaration CommentPlaceholder String (Maybe [TypeParameter]) (Maybe [TypeRef]) (Maybe [TypeRef]) [(CommentPlaceholder, AmbientClassBodyElement)] | AmbientInterfaceDeclaration Interface | AmbientEnumDeclaration CommentPlaceholder (Maybe ConstEnum) String [(String, Maybe Integer)] | AmbientTypeAliasDeclaration TypeAlias | AmbientModuleDeclaration CommentPlaceholder [String] [Ambient] | AmbientExternalModuleDeclaration CommentPlaceholder String [AmbientExternalModuleElement] | AmbientImportDeclaration CommentPlaceholder String EntityName | AmbientExternalImportDeclaration CommentPlaceholder String String deriving (Show, Data, Typeable) data AmbientExternalModuleElement = AmbientModuleElement Ambient | ExportAssignment String deriving (Show, Data, Typeable) data TypeRef = TypeRef TypeName (Maybe [Type]) deriving (Show, Data, Typeable) data AmbientClassBodyElement = AmbientConstructorDeclaration [Parameter] | AmbientMemberDeclaration (Maybe PublicOrPrivate) (Maybe Static) String (Either (Maybe Type) ParameterListAndReturnType) | AmbientIndexSignature IndexSignature deriving (Show, Data, Typeable) data Static = Static deriving (Show, Data, Typeable) data Optional = Optional deriving (Show, Data, Typeable) data ConstEnum = ConstEnum deriving (Show, Data, Typeable) data TypeBody = TypeBody [(CommentPlaceholder, TypeMember)] deriving (Show, Data, Typeable) data TypeMember = PropertySignature String (Maybe Optional) (Maybe Type) | CallSignature ParameterListAndReturnType | ConstructSignature (Maybe [TypeParameter]) [Parameter] (Maybe Type) | TypeIndexSignature IndexSignature | MethodSignature String (Maybe Optional) ParameterListAndReturnType deriving (Show, Data, Typeable) data IndexSignature = IndexSignature String StringOrNumber Type deriving (Show, Data, Typeable) data ParameterListAndReturnType = ParameterListAndReturnType (Maybe [TypeParameter]) [Parameter] (Maybe Type) deriving (Show, Data, Typeable) data Parameter = RequiredOrOptionalParameter (Maybe PublicOrPrivate) String (Maybe Optional) (Maybe ParameterType) | RestParameter String (Maybe Type) deriving (Show, Data, Typeable) data ParameterType = ParameterType Type | ParameterSpecialized String deriving (Show, Data, Typeable) data StringOrNumber = String | Number deriving (Show, Data, Typeable) data PublicOrPrivate = Public | Private deriving (Show, Data, Typeable) data TypeParameter = TypeParameter String (Maybe Type) deriving (Show, Data, Typeable) data Type = Predefined PredefinedType | TypeReference TypeRef | ObjectType TypeBody | ArrayType Type | UnionType Type Type | TupleType [Type] | TypeQuery [String] | FunctionType (Maybe [TypeParameter]) [Parameter] Type | ConstructorType (Maybe [TypeParameter]) [Parameter] Type deriving (Show, Data, Typeable) data TypeName = TypeName (Maybe ModuleName) String deriving (Show, Data, Typeable) data ModuleName = ModuleName [String] deriving (Show, Data, Typeable) data PredefinedType = AnyType | NumberType | BooleanType | StringType | VoidType deriving (Show, Data, Typeable)
mgsloan/language-typescript
src/Language/TypeScript/Types.hs
mit
4,848
0
10
684
1,325
739
586
89
0
{-# LANGUAGE OverloadedStrings #-} module ImportSort.Parser ( parseImports ) where import Control.Applicative ((<|>)) import Data.Attoparsec.Text import Data.Text (Text) import qualified Data.Text as T import ImportSort.Types (ModuleImport(..)) parseImports :: String -> Either String [ModuleImport] parseImports = parseOnly (importsParser <* endOfInput) . T.pack importsParser :: Parser [ModuleImport] importsParser = many' moduleImportParser moduleImportParser :: Parser ModuleImport moduleImportParser = qualifiedImportParser <|> nonQualifiedImportParser <|> separatorParser qualifiedImportParser :: Parser ModuleImport qualifiedImportParser = do "import " *> skipSpace *> "qualified" *> skipSpace QualifiedImport <$> toEol nonQualifiedImportParser :: Parser ModuleImport nonQualifiedImportParser = do "import " *> skipSpace NonQualifiedImport <$> toEol separatorParser :: Parser ModuleImport separatorParser = Separator <$> toEol toEol :: Parser Text toEol = takeTill isEndOfLine <* endOfLine
joshuaclayton/import-sort
src/ImportSort/Parser.hs
mit
1,082
0
9
196
239
131
108
29
1
{-# OPTIONS_GHC -F -pgmF htfpp #-} module InternalTests.THTests where import Test.Framework import GraphDB.Util.Prelude import Language.Haskell.TH import qualified GraphDB.Util.TH as T import qualified GraphDB.Util.TH.Parsers as P import qualified GraphDB.Model as M data A a b data B test_parseMultiparamInstance :: IO () test_parseMultiparamInstance = do assertEqual "[(GraphDB.Model.Edge,[ConT InternalTests.THTests.B,ConT InternalTests.THTests.B])]" $( let content = "instance M.Edge B B where" in stringE . show =<< P.runParse content P.instances ) test_parseInstanceWithPolymorphicTypes :: IO () test_parseInstanceWithPolymorphicTypes = do assertEqual "[(GraphDB.Model.Edge,[AppT (AppT (ConT InternalTests.THTests.A) (ConT InternalTests.THTests.B)) (ConT InternalTests.THTests.B),ConT InternalTests.THTests.B])]" $( let content = "instance M.Edge (A B B) B where" in stringE . show =<< P.runParse content P.instances ) test_parseInstanceWithVariables :: IO () test_parseInstanceWithVariables = do assertEqual "[(GraphDB.Model.Edge,[AppT (AppT (ConT InternalTests.THTests.A) (ConT InternalTests.THTests.B)) (VarT a),VarT b])]" $( let content = "instance M.Edge (A B a) b where" in stringE . show =<< P.runParse content P.instances )
nikita-volkov/graph-db
executables/InternalTests/THTests.hs
mit
1,336
0
14
237
224
121
103
-1
-1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.HTMLHeadingElement (setAlign, getAlign, HTMLHeadingElement(..), gTypeHTMLHeadingElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation> setAlign :: (MonadDOM m, ToJSString val) => HTMLHeadingElement -> val -> m () setAlign self val = liftDOM (self ^. jss "align" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement.align Mozilla HTMLHeadingElement.align documentation> getAlign :: (MonadDOM m, FromJSString result) => HTMLHeadingElement -> m result getAlign self = liftDOM ((self ^. js "align") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/HTMLHeadingElement.hs
mit
1,626
0
10
206
419
262
157
26
1
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, FlexibleContexts #-} import Data.Tnorm import Data.Tconorm import Test.PropBox import Test.Laws import Test.Framework (defaultMain, testGroup, Test) import Test.QuickCheck as QC import Control.Applicative ((<$>)) newtype DoubleN = DoubleN Double deriving (Show, Read, Eq, Num, Ord, Fractional) instance Arbitrary DoubleN where arbitrary = DoubleN <$> choose (0, 1) -- instances of Arbitrary for Tnorm instances deriving instance Arbitrary a => Arbitrary (Min a) deriving instance Arbitrary a => Arbitrary (Product a) deriving instance Arbitrary a => Arbitrary (Lukasiewicz a) deriving instance Arbitrary a => Arbitrary (Drastic a) deriving instance Arbitrary a => Arbitrary (NilpotentMin a) deriving instance Arbitrary a => Arbitrary (HamacherProd a) -- instances of Arbitrary for Tconorm instances deriving instance Arbitrary a => Arbitrary (Max a) deriving instance Arbitrary a => Arbitrary (ProbSum a) deriving instance Arbitrary a => Arbitrary (BoundedSum a) deriving instance Arbitrary a => Arbitrary (Codrastic a) deriving instance Arbitrary a => Arbitrary (NilpotentMax a) deriving instance Arbitrary a => Arbitrary (EinsteinSum a) test_both :: (Show (t a), Arbitrary (t a), Tnorm (t a), Show ((DualTconorm t) a), Arbitrary ((DualTconorm t) a), Tconorm ((DualTconorm t) a)) => T (t a) -> [PropBox] test_both t = [prop_Tnorm t, prop_Tconorm (tie t)] where tie :: T (t a) -> T ((DualTconorm t) a) tie = error "tie: test_both" tnormTests :: PropBox tnormTests = propGroup "t-norms" $ concat [ test_both (T :: T (Min DoubleN)) , test_both (T :: T (Product DoubleN)) , test_both (T :: T (Lukasiewicz DoubleN)) , test_both (T :: T (Drastic DoubleN)) , test_both (T :: T (NilpotentMin DoubleN)) , test_both (T :: T (HamacherProd DoubleN)) ] main :: IO () main = defaultMain $ map boxTests [ tnormTests]
pxqr/fuzzy-set
Test/Properties.hs
mit
2,097
17
11
509
733
373
360
42
1
import Data.List import Control.Monad import Control.Applicative import Lexer import Parser main :: IO () main = do input <- getContents -- | The list of characters that make up the source code is zipped with their respective -- line and position in order to allow lex to identify the location of each generated token. let inputList = concatMap (\(a, x) -> [(a, b, c) | (b, c) <- zip [1..] x]) $ zip [1..] $ (++) <$> lines input <*> ["\n"] let tokenList = lexProgram inputList -- A warning is printed if the EOF token is missing. if kind (last tokenList) == Warning then do putStrLn $ "doompiler: " ++ value (last tokenList) print $ parseProgram $ init tokenList else print $ parseProgram tokenList
garrettoreilly/doompiler
src/Main.hs
mit
771
0
21
196
214
112
102
15
2
module RoundableSpec ( main , spec ) where import MLUtil import Test.Hspec spec :: Spec spec = do describe "roundToPrecision" $ do it "should round 0.123456 to 0.12346" $ roundToPrecision 5 0.123456 `shouldBe` (0.12346 :: R) it "should round 0.123455 to 0.12346" $ roundToPrecision 5 0.123455 `shouldBe` (0.12346 :: R) it "should round 0.123454 to 0.12345" $ roundToPrecision 5 0.123454 `shouldBe` (0.12345 :: R) it "should round [0.123456, 0.123455, 0.123454] correctly" $ roundToPrecision 5 (vector [0.123456, 0.123455, 0.123454]) `shouldBe` vector [0.12346, 0.12346, 0.12345] it "should round [[0.123456, 0.123455], [0.123454, 0.123453]] correctly" $ roundToPrecision 5 (matrix 2 [0.123456, 0.123455, 0.123454, 0.123453]) `shouldBe` matrix 2 [0.12346, 0.12346, 0.12345, 0.12345] main :: IO () main = hspec spec
rcook/mlutil
mlutil/spec/RoundableSpec.hs
mit
987
0
15
288
245
132
113
22
1
import Control.Monad.Identity (runIdentity) import Data.Maybe (catMaybes) import Data.List (intercalate) import Control.Monad (replicateM) -- Template haskell doesn't work well when you have a nontrivial build process. data ArgType = O | V deriving (Eq, Show) makeArgs :: String -> [ArgType] makeArgs = map (\x -> if x == 'V' then V else O) dispatcher :: [ArgType] -> (Int -> a, a) -> (Int -> a, a) -> [a] dispatcher sig (f1arg, f1res) (f2arg, f2res) = dispatcher' 1 sig where dispatcher' _ (x:[]) = case x of V -> [f1res] O -> [f2res] dispatcher' n (x:xs) = (case x of V -> f1arg n O -> f2arg n) : dispatcher' (n+1) xs toPyObjectGen :: [ArgType] -> String toPyObjectGen sig = intercalate "\n" $ catMaybes $ toPyObjectGen' sig toPyObjectGen' :: [ArgType] -> [Maybe String] toPyObjectGen' sig = dispatcher sig (\n -> (Just $ " x" ++ show n ++ " <- toPyObject input" ++ show n), Nothing) (const Nothing, Nothing) fromPyObjectGen :: [ArgType] -> String fromPyObjectGen sig = intercalate "\n" $ catMaybes $ fromPyObjectGen' sig fromPyObjectGen' :: [ArgType] -> [Maybe String] fromPyObjectGen' sig = dispatcher sig (const Nothing, Just (" b <- fromPyObject fr\n return b")) (const Nothing, Just (" return fr")) defCallGen :: [ArgType] -> String defCallGen sig = concat [ " fr <- def" , show (length sig) , " s \"" , concatMap show sig , "\" " , intercalate " " ["x" ++ show n | n <- [1..(length sig - 1)]] ] typeargsGen :: [ArgType] -> String typeargsGen sig = let components = typeargsGen' sig in case components of [] -> "" xs -> intercalate " -> " xs typeargsGen' :: [ArgType] -> [String] typeargsGen' sig = dispatcher sig (f1arg, f1res) (f2arg, f2res) where f1arg = \n -> "a" ++ show n f1res = "IO b" f2arg = \n -> "(PyObject a" ++ show n ++ ")" f2res = "IO (PyObject b)" typeclassesGen :: [ArgType] -> String typeclassesGen sig = let components = catMaybes (typeclassesGen' sig) in case components of [] -> "" xs -> concat [ "(" , intercalate ", " xs , ") => " ] typeclassesGen' :: [ArgType] -> [Maybe String] typeclassesGen' sig = dispatcher sig (f1arg, f1res) (f2arg, f2res) where f1arg = \n -> Just ("ToJSON a" ++ show n) f1res = Just ("FromJSON b") f2arg = const Nothing f2res = Nothing funcname :: [ArgType] -> String funcname sig = "def" ++ concat (map show sig) typesigGen :: [ArgType] -> String typesigGen sig = concat [ funcname sig , " :: " , typeclassesGen sig , "String -> " , typeargsGen sig ] funcsigGen :: [ArgType] -> String funcsigGen sig = funcname sig ++ " s " ++ args ++ " = do" where xs = init $ dispatcher sig (\n -> "input" ++ show n, "") (\n -> "x" ++ show n, "") args = intercalate " " xs codeGen :: [ArgType] -> String codeGen sig = runIdentity $ do return . intercalate "\n" . filter ((>0) . length) $ map (flip ($) sig) [ typesigGen , funcsigGen , toPyObjectGen , defCallGen , fromPyObjectGen ] main = do x <- return $ concat $ map (flip replicateM "OV") [1..5] x2 <- return $ map makeArgs x result <- return $ intercalate "\n\n" $ map codeGen x2 putStrLn $ intercalate "\n" $ map (\sig -> " " ++ funcname sig ++ ",") x2 putStrLn result
Russell91/pyfi
codegen.hs
mit
3,701
0
14
1,197
1,285
677
608
80
4
{-- - Problem 20 (*) Remove the K'th element from a list. Example in Prolog: ?‐ remove_at(X,[a,b,c,d],2,R). X = b R = [a,c,d] Example in Lisp: * (remove‐at '(a b c d) 2) (A C D) (Note that this only returns the residue list, while the Prolog version also returns the deleted element.) Example in Haskell: *Main> removeAt 2 "abcd" ('b',"acd") --} removeAt :: Int -> [a] -> (a, [a]) removeAt n xs = (xs!!(n-1), take (n-1) xs ++ drop n xs)
sighingnow/Functional-99-Problems
Haskell/20.hs
mit
514
0
9
155
75
41
34
2
1
module Probability.Distribution.NegativeBinomial where import Probability.Random import MCMC builtin negative_binomial_density 3 "negative_binomial_density" "Distribution" builtin builtin_sample_negative_binomial 3 "sample_negative_binomial" "Distribution" negative_binomial_bounds = integer_above 0 negative_binomial_effect r x = do add_move $ slice_sample_integer_random_variable x negative_binomial_bounds add_move $ inc_dec_mh x negative_binomial_bounds sample_negative_binomial r p = RandomStructure (negative_binomial_effect r) modifiable_structure $ liftIO (IOAction (\s->(s,builtin_sample_negative_binomial r p s))) negative_binomial r p = Distribution "negative_binomial" (make_densities $ negative_binomial_density r p) (no_quantile "negative_binomial") (sample_negative_binomial r p) (negative_binomial_bounds n)
bredelings/BAli-Phy
haskell/Probability/Distribution/NegativeBinomial.hs
gpl-2.0
838
0
12
83
189
93
96
-1
-1
module Utils where import Control.Monad.Error import Data.Char import Data.List import System.Posix import System.Process import System.IO -- Debug Messages ((un)comment to turn on/off) debug :: String -> IO () debug _ = return () --debug s = putStr s >> hFlush stdout debugLn :: String -> IO () debugLn s = debug $ s ++ "\n" -- Does the Maybe is a Just? isJust :: Maybe t -> Bool isJust Nothing = False isJust (Just _) = True -- Run a command and give its output runCmd :: String -> IO String runCmd cmd = do (filepath, handle) <- mkstemp "tables_tmp_XXXXXX" hClose handle system $ cmd ++ " > " ++ filepath str <- readFile filepath removeLink filepath return str sepPred :: (a -> Bool) -> [a] -> [[a]] sepPred p l = aux [] [] $ reverse l where aux res acc [] = acc : res aux res acc (x : q) = if p x then aux (acc : res) [] q else aux res (x : acc) q foldr2 :: (t -> t -> t) -> t -> [t] -> t foldr2 _ init [] = init foldr2 _ _ [x] = x foldr2 f init (x : l) = f x (foldr2 f init l) mapFilterEither :: (a -> Either e b) -> [a] -> [b] mapFilterEither f [] = [] mapFilterEither f (x : l) = case f x of Right y -> y : (mapFilterEither f l) _ -> (mapFilterEither f l) hReadFull :: Handle -> IO [String] hReadFull h = do debug "=> Reading : " aux h where aux h = do debug "=> Testing EOF : " iseof <- hIsEOF h debugLn (show iseof) if iseof then return [] else do debug "=> Getting Line : " l <- hGetLine h debug (show l) if null l then return [] else do q <- aux h return $ l : q -- Name Normalize normalizeName :: String -> String normalizeName s = map f s where f c = if isAlphaNum c then c else '_'
coccinelle/hBugs
src/Utils.hs
gpl-2.0
2,163
0
16
912
743
370
373
56
3
fix :: (a->a) -> a fix f = f (fix f) factorial :: Int -> Int factorial = fix (\f n -> if (n==0) then 1 else n * f (n-1)) fibonacci :: Int -> Int fibonacci = fix (\f n -> if (n==0) then 0 else if (n==1) then 1 else f(n-1) + f (n-2)) fibs n = map fibonacci [0..n] squareroot :: Int -> Double -> Double squareroot 0 x = x squareroot n x = (squareroot (n-1) x + x/squareroot (n-1) x )/2
dalonng/hellos
haskell.hello/FixedPointFunction.hs
gpl-2.0
388
0
13
91
261
139
122
10
3
-- -- Copyright (c) 2014 Citrix Systems, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- {-# LANGUAGE ScopedTypeVariables,PatternGuards,TupleSections,ViewPatterns,FlexibleContexts #-} module Vm.Actions ( configureServiceVm , startServiceVm , trashUnusedServiceVms , createVm, CreateVmPms(..), defaultCreateVmPms , removeVm , restartVm , startVm , startVmInternal , rebootVm , sleepVm , resumeFromSleep , hibernateVm , shutdownVm , invokeShutdownVm , forceShutdownVm , invokeForceShutdownVm , pauseVm , unpauseVm , switchVm , reallySwitchVm , switchGraphicsFallback , bindVmPcis , loginToVm , addNicToVm, addDefaultNicToVm, removeNicFromVm , addDiskToVm, addDefaultDiskToVm, removeDiskFromVm, addVhdDiskToVm, addPhyDiskToVm , addVmFirewallRule, deleteVmFirewallRule, applyVmFirewallRules, unapplyVmFirewallRules , applyVmBackendShift , createAndAddDiskToVm , createVhd , exportVmSwitcherInfo , modifyVmNic , modifyVmDisk , modifyVmPciPtRules , mountVmDisk , unmountVmDisk , generateCryptoKeyIn , generateCryptoKey , parallelVmExec , parallelVmExecByType , parallelVmExecInStages , suspendToFile, resumeFromFile , getMeasureFailAction, setMeasureFailAction , vmSuspendImageStatePath , runEventScript , changeVmNicNetwork , removeVmEnvIso -- property accessors , setVmType , setVmWiredNetwork, setVmWirelessNetwork, setVmCd, setVmGpu , setVmSeamlessTraffic , setVmStartOnBoot, setVmHiddenInSwitcher, setVmHiddenInUi, setVmMemory, setVmName , setVmImagePath, setVmSlot, setVmPvAddons, setVmPvAddonsVersion , setVmTimeOffset, setVmCryptoUser, setVmCryptoKeyDirs, setVmAutoS3Wake , setVmNotify, setVmPae, setVmApic, setVmAcpi, setVmViridian, setVmNx, setVmSound, setVmDisplay , setVmVirtType , setVmBoot, setVmCmdLine, setVmKernel, setVmInitrd, setVmAcpiTable, setVmVcpus, setVmCoresPerSocket , setVmKernelExtract , setVmInitrdExtract , setVmMemoryStaticMax , setVmMemoryMin , setVmVideoram, setVmPassthroughMmio, setVmPassthroughIo , setVmFlaskLabel, setVmInitFlaskLabel, setVmStubdomFlaskLabel , setVmAmtPt, setVmHap, setVmDescription , setVmExtraXenvm, setVmExtraHvm , setVmStartOnBootPriority, setVmKeepAlive, setVmProvidesNetworkBackend , setVmProvidesGraphicsFallback, setVmShutdownPriority, setVmSeamlessId , setVmStartFromSuspendImage, setVmQemuDmPath, setVmQemuDmTimeout, setVmTrackDependencies , setVmSeamlessMouseLeft, setVmSeamlessMouseRight, setVmOs, setVmControlPlatformPowerState , setVmOemAcpiFeatures, setVmUsbEnabled, setVmUsbAutoPassthrough, setVmUsbControl, setVmCpuid , setVmStubdom, setVmStubdomMemory, setVmStubdomCmdline , setVmGreedyPcibackBind , setVmRunPostCreate, setVmRunPreDelete, setVmRunOnStateChange, setVmRunOnAcpiStateChange , setVmRunPreBoot , setVmRunInsteadofStart , setVmUsbGrabDevices , setVmNativeExperience, setVmShowSwitcher, setVmWirelessControl , setVmXciCpuidSignature , setVmS3Mode , setVmS4Mode , setVmVsnd , setVmRealm , setVmSyncUuid , setVmIcbinnPath , setVmOvfTransportIso , setVmDownloadProgress , setVmReady , setVmProvidesDefaultNetworkBackend , setVmVkbd , setVmArgo , setVmRestrictDisplayDepth , setVmRestrictDisplayRes , setVmPreserveOnReboot , setVmBootSentinel , setVmHpet , setVmTimerMode , setVmNestedHvm , setVmSerial , setVmBios , setVmSecureboot , setVmAuthenforce , setVmAutolockCdDrives , setVmHdType , cleanupArgoDevice , setVmDisplayHandlerStrict , setVmLongForm , setVmShortForm , setVmTextColor , setVmDomainColor , setVmBorderWidth , setVmBorderHeight , setVmMosaicVmEnabled , setVmVglassEnabled , setVmMosaicMode , setVmWindowedX , setVmWindowedY , setVmWindowedW , setVmWindowedH , setVmPrimaryDomainColor , setVmSecondaryDomainColor , EventHookFailMode(..) ) where import Prelude hiding (catch, mapM, mapM_) import Data.Char import Data.List import Data.Maybe import Data.Bits import Data.String import Data.Int import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Map as M import qualified Data.Set as Set import Text.Printf import Control.Arrow import Control.Monad import Control.Monad.Error hiding (liftIO) import Control.Monad.Reader import Control.Applicative import Control.Concurrent import qualified Control.Exception as E import System.FilePath.Posix import System.Posix.Files import System.Process import System.Exit import System.IO import System.Timeout import Data.Time import Directory import System.Directory (createDirectoryIfMissing, doesFileExist) import qualified Data.Foldable import Tools.Log import Tools.XenStore import Tools.Misc import Tools.Process import Tools.Text import Tools.IfM import Tools.FreezeIOM import Tools.Future import Tools.File (fileSha1Sum, getDirectoryContents_nonDotted) import Tools.Apptool import Vm.Types import Vm.Config import Vm.ConfigWriter import Vm.Dm import Vm.Queries import Vm.QueriesM import Vm.Pci import Vm.Utility import Vm.Policies import Vm.Templates import Vm.Monad import Vm.Monitor import Vm.State import Vm.DomainCore import {-# SOURCE #-} Vm.React import qualified Vm.ArgoFirewall as Firewall import Vm.Balloon import XenMgr.Rpc import qualified XenMgr.Connect.Xl as Xl import qualified XenMgr.Connect.GuestRpcAgent as RpcAgent import XenMgr.Connect.Xl ( resumeFromSleep, resumeFromFile, suspendToFile ) import XenMgr.Connect.NetworkDaemon import XenMgr.Connect.InputDaemon import XenMgr.Config import XenMgr.Errors import XenMgr.Db import XenMgr.Host import XenMgr.Diskmgr import XenMgr.Notify import XenMgr.XM import XenMgr.CdLock import {-# SOURCE #-} XenMgr.PowerManagement import Rpc.Autogen.XenmgrNotify import XenMgr.Expose.ObjectPaths import Vm.Pci data EventHook = EventScript FilePath | EventRpc (Maybe Uuid) RpcCall deriving (Show) data EventHookFailMode = HardFail | ContinueOnFail deriving (Eq, Show) vmSuspendImageStatePath :: Uuid -> String vmSuspendImageStatePath uuid = "/xenmgr/service-vm-snapshot/" ++ show uuid ++ "/state" startServiceVm :: Uuid -> XM () startServiceVm uuid = xmContext >>= \xm -> liftRpc $ isRunning uuid >>= \r -> case r of False -> do info $ "starting service vm " ++ show uuid file <- getVmStartFromSuspendImage uuid context <- rpcGetContext if (not . null $ file) then liftIO $ do xsWrite (vmSuspendImageStatePath uuid) "start" void . forkIO . xsWaitFor (vmSuspendImageStatePath uuid) $ do status <- (rpc context $ snapshot_request xm file) case status of Right rv -> return rv Left err -> warn (show err) >> return True else liftIO $ do xsWrite (vmSuspendImageStatePath uuid) "start-no-snapshot" runXM xm (startVm uuid) True -> info $ "service vm " ++ show uuid ++ " already running" where snapshot_request xm file = do state <- liftIO $ xsRead (vmSuspendImageStatePath uuid) debug $ "service vm " ++ show uuid ++ " suspend image state = " ++ show state if state /= Just "snapshot" then return False -- continue waiting else do info $ "service vm " ++ show uuid ++ " requested a memory image snapshot" -- take a vm snapshot info $ "taking memory image snapshot for service vm " ++ show uuid liftIO $ Xl.suspendToFile uuid file info $ "DONE taking memory image snapshot for service vm " ++ show uuid liftIO $ xsWrite (vmSuspendImageStatePath uuid) "snapshot-done" -- double start, TODO: maybe wont be necessary runXM xm (startVm uuid) -- finished waiting on this watch return True parseEventHooks :: String -> [EventHook] parseEventHooks = catMaybes . map parseEventHook . split ';' parseEventHook :: String -> Maybe EventHook parseEventHook s = parse s where parse "" = Nothing parse s | "rpc:" `isPrefixOf` s = rpc (drop 4 s) -- assume rpc call parse s = return (EventScript s) -- assume script file rpc s = do let kv = keyvals (filter (not . isSpace) s) objpath = fromMaybe "/" ("objpath" `M.lookup` kv) vm = fromString <$> "vm" `M.lookup` kv dest <- "destination" `M.lookup` kv interface <- "interface" `M.lookup` kv member <- "member" `M.lookup` kv return . EventRpc vm $ RpcCall (fromString dest) (fromString objpath) (fromString interface) (fromString member) [] keyvals = M.fromList . catMaybes . map one . split ',' where one x = case split '=' x of [k,v] -> Just (k,dequote v) _ -> Nothing dequote (x:xs) | is_quote x = reverse (dequote $ reverse xs) where is_quote x = x == '\'' || x =='"' dequote xs = xs runEventScript :: EventHookFailMode -> Uuid -> (Uuid -> Rpc (Maybe String)) -> [String] -> Rpc Bool runEventScript failmode vm get_hooks args = run_hooks =<< get_hooks vm where quote x = "\"" ++ x ++ "\"" run_hooks Nothing = return False run_hooks (Just str) = (catchScriptErrors (mapM_ run_hook . parseEventHooks $ str)) >> return True run_hook (EventScript file) = liftIO $ run_file file run_hook (EventRpc vm call) = void $ run_rpc vm (setCallArgs call args) run_rpc vm rpc = do info $ "event-rpc " ++ show rpc case vm of Nothing -> rpcCall rpc Just uuid -> do domid <- getDomainID uuid let fail = error $ "required VM " ++ show uuid ++ " is not running" call domid = rpcWithDomain (fromIntegral domid) (rpcCall rpc) maybe fail call domid run_file path = do info $ "event-script " ++ show path ++ " " ++ (intercalate " ") (map quote args) exec path return () exec path = -- stderr redirected to warn, stdout to info createProcess (proc path args){ std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe, close_fds = True } >>= \ (_, Just stdout, Just stderr, h) -> do hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering contents_mv <- newEmptyMVar forkIO $ consume_lines stderr warn >> return () forkIO $ putMVar contents_mv =<< consume_lines stdout info contents <- takeMVar contents_mv -- force evaluation of contents exitCode <- contents `seq` waitForProcess h case exitCode of ExitSuccess -> return $ contents _ -> error $ "event-script: " ++ path ++ " FAILED." consume_lines h feed = go h [] where go h ls = continue =<< E.try (hGetLine h) where continue :: Either E.SomeException String -> IO String continue (Right l) = feed l >> go h (l:ls) continue (Left _) = return . unlines . reverse $ ls catchScriptErrors run = run `catchError` reportErrors reportErrors e = warn (show e) >> when (failmode == HardFail) (throwError e) setCallArgs c args = c { callArgs = map toVariant args } configureServiceVm :: String -> Rpc (Maybe Uuid) configureServiceVm tag = do overwrite_settings <- appOverwriteServiceVmSettings tag template <- liftIO $ getServiceVmTemplate tag case getUuidInTemplate template of Nothing -> error "service vm template does not have uuid" Just uuid -> do exists <- dbExists $ "/vm/" ++ show uuid when ( overwrite_settings || not exists ) $ exportTemplate Nothing template >> return () info $ "configured service vm " ++ show tag return . Just $ uuid -- remove service vms which are not in active templates from db trashUnusedServiceVms :: Rpc () trashUnusedServiceVms = do tags <- enumServiceVmTags mapM_ (trash tags) =<< getVms where trash active uuid = getVmType uuid >>= trash_type where trash_type (ServiceVm tag) | not (tag `elem` active) = dbRm $ "/vm/" ++ show uuid trash_type _ = return () -- Returns first empty slot in 1..9 range, or Nothing if all are in use findEmptySlot :: Rpc (Maybe Int) findEmptySlot = fmap (first . inverse) . getSlots =<< getGuestVms where getSlots = mapM getSlot getSlot uuid = fromMaybe 0 <$> readConfigProperty uuid vmSlot inverse slots = [1..9] \\ slots first = listToMaybe . sort -- Create a VM data CreateVmPms = CreateVmPms { cvmUuid :: Maybe Uuid , cvmTemplate :: Maybe String , cvmExtraJson :: String , cvmName :: Maybe String , cvmDescription :: Maybe String , cvmImagePath :: Maybe String , cvmAutoSlot :: Bool } defaultCreateVmPms :: CreateVmPms defaultCreateVmPms = CreateVmPms Nothing Nothing "" Nothing Nothing Nothing True -- | bind passthrough devices to pciback -- this typically might be done early (on daemon start), to prevent the devices going into -- use by other, non-passthrough vms bindVmPcis :: Uuid -> Rpc () bindVmPcis uuid = whenM (getVmGreedyPcibackBind uuid) (mapM_ bind =<< filter (isconfig . pciPtSource) <$> getPciPtDevices uuid) where bind = liftIO . pciBindPciback . devAddr . pciPtDevice isconfig SourceConfig = True isconfig _ = False createVm :: Bool -> CreateVmPms -> XM Uuid createVm unrestricted pms = do unlessM (liftM2 (||) (return unrestricted) policyQueryVmCreation) failActionSuppressedByPolicy info "creating new VM..." -- creation needs a lock around otherwise it produces non unique slots now and then xmWithVmCreationLock do_create where do_create = do let extra = templateFromString (cvmExtraJson pms) template <- mergeTemplates <$> ( case cvmTemplate pms of Nothing -> liftIO getNewVmTemplate Just s | null (strip s) -> return nullTemplate Just n -> liftIO $ getAnyVmTemplate n ) <*> pure extra let auto_allocate_slot = cvmAutoSlot pms && isNothing (getSlotInTemplate template) maybeSlot <- liftRpc findEmptySlot when (auto_allocate_slot && isNothing maybeSlot) $ failTooManyVms uuid <- case catMaybes [ cvmUuid pms, getUuidInTemplate template ] of [] -> liftIO uuidGen (u:_) -> return u info $ "exporting vm template for " ++ show uuid liftRpc (exportTemplate (Just uuid) template) info $ "setting initial properties for " ++ show uuid -- Give it seamless ID, equal to uuid from creation setVmSeamlessId uuid (show uuid) -- Give it name and slot whenM (null <$> liftRpc (getVmName uuid)) $ saveConfigProperty uuid vmName $ fromMaybe ("name-" ++ show uuid) (cvmName pms) when auto_allocate_slot $ let Just n = maybeSlot in saveConfigProperty uuid vmSlot n -- other optional settings maybeM (cvmDescription pms) $ saveConfigProperty uuid vmDescription maybeM (cvmImagePath pms) $ saveConfigProperty uuid vmImagePath -- Begin monitoring monitorAndReactVm uuid return uuid maybeM x f = maybe (return ()) f x -- Remove a VM removeVm :: Uuid -> Rpc () removeVm uuid = do -- not allowing to remove running VMS whenM (isRunning uuid) failCannotRemoveRunning info $ "Removing a VM " ++ show uuid runEventScript HardFail uuid getVmRunPreDelete [uuidStr uuid] -- Delete VHDS, but only if this is not a managed VM unlessM (isManagedVm uuid) removeVhds -- remove ovffiles liftIO $ readProcessOrDie "rm" ["-rf", "/storage/ovffiles/" ++ show uuid] "" -- Away from database dbRm $ "/vm/" ++ show uuid dbRm $ "/dom-store/" ++ show uuid -- Need to quit xenvm -- FIXME: cleanly stop monitoring events removeDefaultEvents uuid --cleanly...stop monitoring events liftIO $ xsRm $ "/state/" ++ show uuid --vm is deleted, no need for state node anymore notifyVmDeleted uuid where removeVhds = Data.Foldable.mapM_ (removeDiskFiles uuid) =<< getDisks uuid removeVhd d | not (diskShared d), diskType d == VirtualHardDisk = do refs <- nub . map fst <$> getVhdReferences (diskPath d) -- only remove when only this vm references the vhd when (refs == [uuid]) $ do let p = diskPath d b | ".vhd" `isSuffixOf` p = take (length p - 4) p | otherwise = p snappaths = map (b ++) [".vhd.hib", ".snap.tmp.vhd", ".snap"] liftIO . whenM (doesFileExist p) $ do info $ "Removing VHD file " ++ p removeLink p let rmSnapshot p = liftIO . whenM (doesFileExist p) $ do info $ "Removing snapshot file " ++ p removeLink p mapM_ rmSnapshot $ snappaths removeVhd _ = return () -- which vms are referencing this vhd -- TODO: handle differencing disks getVhdReferences :: FilePath -> Rpc [(Uuid, Disk)] getVhdReferences vhd = concat <$> (mapM (diskVhdReferences vhd) =<< getVms) where diskVhdReferences vhd vm = zip (repeat vm) . filter (references vhd) . M.elems <$> getDisks vm where references vhd disk = diskPath disk == vhd startVm :: Uuid -> XM () startVm uuid = _startVm False uuid restartVm :: Uuid -> XM () restartVm uuid = _startVm True uuid _startVm :: Bool -> Uuid -> XM () _startVm is_reboot uuid = do withPreCreationState uuid $ do ran <- liftRpc $ runEventScript HardFail uuid getVmRunInsteadofStart [uuidStr uuid] when (not ran) $ startVmInternal uuid is_reboot --Add a passthrough rule to vm config add_pt_rule_bdf uuid dev = modifyVmPciPtRules uuid $ pciAddRule (form_rule_bdf (show (devAddr dev))) form_rule_bdf = rule . fromMaybe (error "error parsing rule") . pciAndSlotFromStr where rule (addr,sl) = PciPtRuleBDF addr sl -- Start a VM! (maybe, because stuff can happen not) startVmInternal :: Uuid -> Bool -> XM () startVmInternal uuid is_reboot = do unlessM (dbExists $ "/vm/" ++ show uuid) $ error ("vm does not have a database entry: " ++ show uuid) info $ "starting VM " ++ show uuid liftRpc $ maybePtGpuFuncs uuid config <- prepareAndCheckConfig uuid case config of Just c -> info ("done checks for VM " ++ show uuid) >> bootVm c is_reboot Nothing-> return () where --Based on bdf get all functions on that device bus:device.function --and pass them through to vm in case of bus level reset. maybePtGpuFuncs uuid = do ok <- isGpuPt uuid if ok then do gfxbdf <- getVmGpu uuid devices <- liftIO pciGetDevices let devMatches = filter (bdFilter (take 7 gfxbdf) gfxbdf) devices in mapM_ (add_pt_rule_bdf uuid) devMatches else return () --Filter function to match on domain:bus and also filter out the video function bdFilter match bdf d = (isInfixOf match (show (devAddr d))) && (bdf /= (show (devAddr d))) --Check if vm has a bdf in gpu isGpuPt uuid = do gpu <- getVmGpu uuid return (gpu /= "") prepareAndCheckConfig uuid = do ok <- stage1 -- early tests / dependency startup if (not ok) then return Nothing else do -- this (config gather) needs to be done after dependency startup to get correct -- backend domids config <- liftRpc $ getVmConfig uuid True info $ "gathered config for VM " ++ show uuid ok <- stage2 config if ok then return (Just config) else return Nothing stage1 = startupCheckVmState uuid `followby` startupCheckHostStates uuid `followby` startupDependencies uuid `followby` startupCheckDiskPaths uuid `followby` startupExtractKernel uuid `followby` startupMeasureVm uuid stage2 config = startupCheckNics config `followby` startupCheckGraphicsConstraints config `followby` startupCheckIntelConstraints config `followby` startupCheckAMTConstraints config `followby` startupCheckPCI config `followby` startupCheckOemFeatures config `followby` startupCheckSyncXTComfortable uuid followby f g = do ok <- f if ok then g else return False startupCheckVmState :: Uuid -> XM Bool startupCheckVmState uuid = do running <- liftRpc (isRunning uuid) if running then do warn ("request to start vm " ++ show uuid ++ " BUT it is already running") return False else do return True startupCheckHostStates :: Uuid -> XM Bool startupCheckHostStates uuid = f =<< (,) <$> liftRpc getHostState <*> liftIO getCurrentRunLevel where f (_, Just 0) = badRunLevel 0 f (_, Just 6) = badRunLevel 6 f (s, _) | s /= HostIdle = badHostState s f _ = return True msg reason = warn ("ignoring request to start VM " ++ show uuid ++ " because of " ++ reason) badRunLevel l = msg ("current runlevel: " ++ show l) >> return False badHostState s = msg ("current host state: " ++ show s) >> return False startupCheckDiskPaths :: Uuid -> XM Bool startupCheckDiskPaths uuid = do disks <- M.assocs <$> liftRpc (getDisks uuid) mapM_ checkPath disks return True where checkPath (ele, disk) = do e <- liftIO $ doesFileExist $ diskPath disk if e then return True else error $ printf "Bad Physical Path for disk %s (%s)" (show ele) (diskPath disk) startupMeasureVm :: Uuid -> XM Bool startupMeasureVm uuid = do measure <- getVmMeasured uuid if not measure then return True else xmRunVm uuid $ addVmDiskHashes >> checkVmDiskHashes startupDependencies :: Uuid -> XM Bool startupDependencies uuid = do deps <- liftRpc $ getVmTrackDependencies uuid if deps then do startDependencies uuid checkDependencies uuid else do return True where checkDependencies uuid = liftRpc $ do missing <- filterM (fmap not . isRunning) =<< (getVmDependencies uuid) if (null missing) then do return True else do warn $ "missing dependencies: " ++ show missing return False startDependencies uuid = do dependentVms <- liftRpc $ getVmDependencies uuid unless (null dependentVms) $ info $ "vm dependencies: " ++ show dependentVms mapM_ startVm =<< (liftRpc $ filterM (fmap not . isRunning) dependentVms) startupExtractKernel :: Uuid -> XM Bool startupExtractKernel uuid = do liftRpc $ extractKernelFromPvDomain uuid liftRpc $ extractInitrdFromPvDomain uuid return True startupCheckNics :: VmConfig -> XM Bool startupCheckNics cfg = mapM_ verify (vmcfgNics cfg) >> return True where verify nic | nicdefBackendDomid nic == Nothing && (nicdefBackendUuid nic /= Nothing || nicdefBackendName nic /= Nothing) = failNetworkDomainNotRunning | otherwise = return () startupCheckGraphicsConstraints :: VmConfig -> XM Bool startupCheckGraphicsConstraints cfg = return True startupCheckAMTConstraints :: VmConfig -> XM Bool startupCheckAMTConstraints cfg = do whenM (liftRpc $ getVmAmtPt $ vmcfgUuid cfg) $ unique return True where unique = liftRpc $ getGuestVms >>= filterM isRunning >>= filterM getVmAmtPt >>= maybe_fail where maybe_fail [] = return () maybe_fail (uuid:_) = failCannotStartBecauseAmtPtRunning startupCheckOemFeatures :: VmConfig -> XM Bool startupCheckOemFeatures config = liftRpc $ do let features = vmcfgOemAcpiFeatures config when features $ getGuestVms >>= filterM isRunning >>= filterM getVmOemAcpiFeatures >>= maybe_fail return True where maybe_fail [] = return () maybe_fail (uuid:_) = failCannotStartBecauseOemFeaturesRunning startupCheckPCI :: VmConfig -> XM Bool startupCheckPCI cfg = liftRpc $ do in_use <- map pciPtDevice <$> online_devices case vm_devices `intersect` in_use of [] -> return True (dev:_) -> failDeviceAlreadyPassedThrough (show dev) where vm_devices = map pciPtDevice (vmcfgPciPtDevices cfg) online_devices = concat <$> (getGuestVms >>= filterM isRunning >>= mapM getPciPtDevices) startupCheckIntelConstraints :: VmConfig -> XM Bool startupCheckIntelConstraints cfg = do mapM_ verify devs return True where devs = vmcfgPciPtDevices cfg verify (PciPtDev { pciPtDevice=d }) = liftRpc $ do info <- liftIO $ pciGetInfo d case info of Nothing -> return () Just info -> do -- intel gpu cannot be passed as secondary adapter case (pciinfoVendor info,pciinfoClass info) of (0x8086,0x300) -> check d (0x8086,0x380) -> check d _ -> return () where check d = do let boot_vga_file = devSysfsPath d </> "boot_vga" boot_vga_exists <- liftIO $ doesFileExist boot_vga_file when boot_vga_exists $ do contents <- chomp <$> (liftIO $ readFile boot_vga_file) case contents of "0" -> failGraphicsCantBePassedAsSecondaryAdapter _ -> return () startupCheckSyncXTComfortable :: Uuid -> XM Bool startupCheckSyncXTComfortable uuid = do bg_op_ok <- liftRpc (getVmReady uuid) -- FIXME: perform this check only for syncxt vms if still needed -- when (not bg_op_ok) $ failVmNotReady return True withPreCreationState :: Uuid -> XM a -> XM a withPreCreationState uuid f = do f `catchError` (\e -> do s <- getVmInternalState uuid -- have to mop up here if something went wrong in pre-create state -- since xenvm does not know about this state when (s == PreCreate) $ do xmRunVm uuid $ vmEvalEvent (VmStateChange Shutdown) throwError e) --Write the xenstore nodes for the backend and the frontend for the argo device --set states to Unknown and Initializing respectively, like xenvm used to do xsp domid = "/local/domain/" ++ show domid xsp_dom0 = "/local/domain/0" argoBack domid = "/backend/argo/" ++ show domid ++ "/0" setupArgoDevice uuid = whenDomainID_ uuid $ \domid -> liftIO $ do xsWrite (xsp domid ++ "/device/argo/0/backend") ("/local/domain/0/backend/argo/" ++ show domid ++ "/0") xsWrite (xsp domid ++ "/device/argo/0/backend-id") "0" xsWrite (xsp domid ++ "/device/argo/0/state") "1" xsChmod (xsp domid ++ "/device/argo/0/backend") ("n"++show domid++",r0") xsChmod (xsp domid ++ "/device/argo/0/backend-id") ("n"++show domid++",r0") xsChmod (xsp domid ++ "/device/argo/0/state") ("n"++show domid++",r0") xsWrite (xsp_dom0 ++ (argoBack domid) ++ "/frontend") (xsp domid ++ "/device/argo/0") xsWrite (xsp_dom0 ++ (argoBack domid) ++ "/frontend-id") $ show domid xsWrite (xsp_dom0 ++ (argoBack domid) ++ "/state") "0" cleanupArgoDevice domid = liftIO $ do xsRm (xsp_dom0 ++ "/backend/argo/" ++ show domid) setupAcpiNode uuid = whenDomainID_ uuid $ \domid -> do stubdom <- getStubDomainID uuid liftIO $ xsWrite (xsp domid ++ "/acpi-state") ("") case stubdom of Just stubdomid -> liftIO $ xsChmod (xsp domid ++ "/acpi-state") ("b" ++ show stubdomid) Nothing -> liftIO $ xsChmod (xsp domid ++ "/acpi-state") ("b" ++ show domid) --Watch acpi state when booting a VM, used to be handled in xenvm monitorAcpi :: Uuid -> VmMonitor -> AcpiState -> IO () monitorAcpi uuid m state = do acpi_state <- Xl.acpiState uuid if state == 5 then do return () else do if state /= acpi_state then do vmStateSubmit m acpi_state threadDelay (10^6) monitorAcpi uuid m acpi_state else do threadDelay (10^6) monitorAcpi uuid m acpi_state -- Creates a snapshot from the primary disk when the disk persistence option is -- set. It first checks to see if a snapshot already exists and deletes it before -- creating a new one. createSnapshot :: Disk -> Bool -> IO Disk createSnapshot disk encrypted = do let path = diskPath disk let splitPath = split '/' path let newname = "snap_" ++ (last splitPath) ++ ".snap.tmp.vhd" let newPath = intercalate "/" $ (init splitPath) ++ [newname] exists <- liftIO $ doesFileExist newPath --ensure we're creating a fresh snapshot when exists (removeFile newPath) if encrypted then createEnc path newPath else create path newPath where create path newPath = do readProcessOrDie "vhd-util" ["snapshot", "-n", newPath, "-p", path] [] info $ "newPath = " ++ newPath return disk { diskPath = newPath } createEnc path newPath = do readProcessOrDie "vhd-util" ["snapshot", "-n", newPath, "-p", path] [] let keyname = head $ split '.' $ last $ split '/' newPath let keypath = "/config/platform-crypto-keys/" ++ keyname ++ ",aes-xts-plain,256.key" urandHandle <- openFile "/dev/urandom" ReadMode key <- B.hGet urandHandle 32 B.writeFile keypath key readProcessOrDie "vhd-util" ["key", "-s", "-n", newPath, "-k", keypath] [] hClose urandHandle info $ "newPath = " ++ newPath return disk { diskPath = newPath } checkAndPerformSnapshotIfReq :: Uuid -> [Disk] -> Rpc [Disk] checkAndPerformSnapshotIfReq uuid disks = do mapM checkDisk disks where checkDisk disk = do let snapshot = diskSnapshotMode disk enc <- getDiskEncryptionKeySet disk case (snapshot, enc) of (Nothing, _) -> return disk --return the same disk we were passed in, no changes required (Just SnapshotTemporary, False) -> liftIO $ createSnapshot disk False (Just SnapshotTemporary, True) -> liftIO $ createSnapshot disk True _ -> return disk --other Snapshot types unimplemented for now since UI can't set them bootVm :: VmConfig -> Bool -> XM () bootVm config reboot = do monitor <- vm_monitor <$> xmRunVm uuid vmContext -- Check persistence type, create snapshot and update path if required newDisks <- liftRpc $ checkAndPerformSnapshotIfReq uuid (vmcfgDisks config) let newConfig = config { vmcfgDisks = newDisks } liftRpc $ updateXVConfig newConfig withPreCreationState uuid (create monitor) where uuid = vmcfgUuid config updateXVConfig :: VmConfig -> Rpc () updateXVConfig c = writeXlConfig c create monitor = do -- create environment iso whenM (getVmOvfTransportIso uuid) . liftIO $ do createDirectoryIfMissing True envIsoDir generateEnvIso uuid (envIsoPath uuid) info $ "generated ovf environment ISO " ++ (envIsoPath uuid) ++ " for VM " ++ show uuid -- try some ballooning if we lack memory -- fork and monitor Acpi state bootstrap <- do -- Clear the hibernated property saveConfigProperty uuid vmHibernated False -- run custom pre boot action liftRpc $ runEventScript HardFail uuid getVmRunPreBoot [uuidStr uuid] -- bind any passthrough devices to pciback if possible liftRpc $ bindVmPcis uuid -- fork xenvm vm startup in the background bootstrap <- future $ liftRpc $ do suspend_file <- getVmStartFromSuspendImage uuid exists <- if null suspend_file then return False else liftIO (doesFileExist suspend_file) if not exists then do if reboot then do liftIO $ Xl.signal uuid else do liftIO $ Xl.start uuid --we start paused by default else do liftIO $ xsWrite (vmSuspendImageStatePath uuid) "resume" liftIO $ Xl.resumeFromFile uuid suspend_file False True return bootstrap -- fork vm creation phase handling in the background phases <- future handleCreationPhases -- ensure bootstrap and phase handling synchronously terminates before returning (and errors get propagated) force bootstrap force phases liftIO . void $ forkIO $ monitorAcpi uuid monitor 0 writable domid path = do xsWrite path "" xsSetPermissions path [ Permission 0 [] , Permission (fromIntegral domid) [PermRead,PermWrite]] setupCDDrives :: Uuid -> Rpc () setupCDDrives uuid = do -- use cd autolocking perhaps setVmAutolockCdDrives uuid =<< appGetAutolockCdDrives -- make bsg device status & req nodes writable by domain whenDomainID_ uuid $ \domid -> liftIO $ do writable domid (xsp domid ++ "/bsgdev") writable domid (xsp domid ++ "/bsgdev-req") -- read drives media state liftIO $ mapM_ updateCdDeviceMediaStatusKey =<< liftIO getHostBSGDevices --setupBiosStrings uuid = -- whenDomainID_ uuid $ \domid -> do -- liftIO $ xsWrite (xsp domid ++ "/bios-strings/xenvendor-manufacturer") "OpenXT" -- liftIO $ xsWrite (xsp domid ++ "/bios-strings/xenvendor-product") "OpenXT 5.0.0" -- liftIO $ xsWrite (xsp domid ++ "/bios-strings/xenvendor-seamless-hint") "0" handleCreationPhases :: XM () handleCreationPhases = do waitForVmInternalState uuid CreatingDevices Running 30 --Move these tasks up earlier in the guest boot process. Prevents the need --for XL to implement a handshake with xenmgr for argo firewall rules. Also speeds up --the boot process liftRpc $ do exportVmSwitcherInfo uuid stubdom <- getVmStubdom uuid when stubdom $ updateStubDomainID uuid applyVmFirewallRules uuid whenDomainID_ uuid $ \domid -> do liftIO $ xsWrite (domainXSPath domid ++ "/argo-firewall-ready") "1" waitForVmInternalState uuid Created Running 30 -- BEFORE DEVICE MODEL info $ "pre-dm setup for " ++ show uuid liftRpc $ do twiddlePermissions uuid setupCDDrives uuid --No longer passing argo in the config, keep in db. argo_enabled <- getVmArgo uuid when argo_enabled $ setupArgoDevice uuid --setupBiosStrings uuid setupAcpiNode uuid -- some little network plumbing gives_network <- getVmProvidesNetworkBackend uuid when gives_network $ whenDomainID_ uuid $ \domid -> do liftIO $ xsWrite backendNode (show domid) liftIO $ xsChmod backendNode "r0" info $ "done pre-dm setup for " ++ show uuid waitForVmInternalState uuid Created Running 60 sentinel <- sentinelPath -- allow writing to sentinel maybe (return()) (\p -> liftIO $ xsWrite p "" >> xsChmod p "b0") sentinel -- AFTER DOMAIN CREATION liftRpc $ do -- assign sticky cd drives mapM_ (\d -> assignCdDevice d uuid) =<< getVmStickyCdDevices uuid info $ "unpause " ++ show uuid liftIO $ Xl.unpause uuid -- wait for bootup services to complete if using sentinel maybe (return()) (\p -> liftIO . void . timeout (10^6 * 60) . xsWaitFor p $ ((\v -> isJust v && v /= Just "") `fmap` xsRead p) ) sentinel applyVmBackendShift uuid return () sentinelPath = do domid <- getDomainID uuid case domid of Nothing -> return Nothing Just domid -> do s <- getVmBootSentinel uuid case s of Nothing -> return Nothing Just p -> return (Just $ domainXSPath domid ++ "/" ++ p) --FIXME: get rid of this when/if we remove dbusbouncer from ndvm twiddlePermissions :: Uuid -> Rpc () twiddlePermissions uuid = -- make the /local/domain/<n>/vm node readable by all -- make the snapshot node readable/writable by itself whenDomainID_ uuid $ \domid -> let domid' = fromIntegral domid in liftIO $ do xsSetPermissions ("/local/domain/" ++ show domid ++ "/vm") [Permission 0 [PermRead]] xsSetPermissions ("/vm/" ++ show uuid ++ "/uuid") [Permission 0 [PermRead]] have_path <- xsRead (vmSuspendImageStatePath uuid) when (have_path /= Nothing) $ xsSetPermissions (vmSuspendImageStatePath uuid) [Permission 0 [], Permission domid' [PermRead,PermWrite]] removeVmEnvIso :: Uuid -> IO () removeVmEnvIso uuid = whenM (doesFileExist p) (removeFile p) where p = envIsoPath uuid -- update the backend/frontend driver paths to point to new domains, -- needed after backend reboot applyVmBackendShift :: Uuid -> XM () applyVmBackendShift bkuuid = do target_ <- getDomainID bkuuid case target_ of Nothing -> warn $ printf "failed to move devices backend; domain %s does not exist" (show bkuuid) Just target -> do vms <- filter ((/=) bkuuid) <$> (filterM Xl.isRunning =<< getVms) devs <- mapM getdevs vms let devices = filter (uses bkuuid) (concat devs) when (not . null $ devices) $ do info $ printf "moving device backends for %s" (show bkuuid) mapM_ (liftRpc . move target) devices where getdevs uuid = whenDomainID [] uuid $ \domid -> do -- TODO: only supporting vif,vwif devices atm vifs <- liftIO $ getFrontDevices VIF domid vwifs <- liftIO $ getFrontDevices VWIF domid return $ zip (repeat uuid) (vifs ++ vwifs) uses bkuuid (_,d) = bkuuid == dmfBackUuid d move target (_,d) = moveBackend (dmfType d) (dmfDomid d) (dmfID d) target -- Reboot a VM rebootVm :: Uuid -> Rpc () rebootVm uuid = do info $ "rebooting VM " ++ show uuid -- Write XL configuration file writeXlConfig =<< getVmConfig uuid True --Let xl take care of bringing down the domain and updating our state --When xenmgr sees the 'Rebooted' state, it fires off a startVm call, --which performs all the normal guest boot tasks, while xl brings up the domain. liftIO $ Xl.reboot uuid shutdownVm :: Uuid -> Rpc () shutdownVm uuid = do info $ "shutting down VM " ++ show uuid acpi <- getVmAcpiState uuid use_agent <- RpcAgent.guestAgentRunning uuid -- if it is asleep, we need to wake it first when (acpi == 3) $ do info $ "resuming " ++ show uuid ++ " from S3 first.." resumeS3AndWaitS0 uuid info $ "resuming " ++ show uuid ++ " from S3 DONE." if use_agent then RpcAgent.shutdown uuid else liftIO $ Xl.shutdown uuid forceShutdownVm :: Uuid -> Rpc () forceShutdownVm uuid = do info $ "forcibly shutting down VM " ++ show uuid liftIO $ Xl.destroy uuid invokeShutdownVm :: Vm () invokeShutdownVm = liftRpc . shutdownVm =<< vmUuid invokeForceShutdownVm :: Vm () invokeForceShutdownVm = liftRpc . forceShutdownVm =<< vmUuid pauseVm :: Uuid -> Rpc () pauseVm uuid = do info $ "pausing VM " ++ show uuid liftIO $ Xl.pause uuid unpauseVm :: Uuid -> Rpc () unpauseVm uuid = do info $ "unpausing VM " ++ show uuid liftIO $ Xl.unpause uuid assertPvAddons :: Uuid -> Rpc () assertPvAddons uuid = getVmPvAddons uuid >>= \addons -> when (not addons) failActionRequiresPvAddons sleepVm :: Uuid -> Rpc () sleepVm uuid = do acpi <- getVmAcpiState uuid case acpi of 3 -> info $ show uuid ++ " is already in S3, not sending it into S3 again." _ -> do info $ "sending VM " ++ show uuid ++ " into S3" use_agent <- RpcAgent.guestAgentRunning uuid if use_agent then RpcAgent.sleep uuid else do assertPvAddons uuid liftIO $ Xl.sleep uuid hibernateVm :: Uuid -> Rpc () hibernateVm uuid = do info $ "sending VM " ++ show uuid ++ " into S4" running <- isRunning uuid when running $ do use_agent <- RpcAgent.guestAgentRunning uuid when (not use_agent) $ assertPvAddons uuid acpi <- getVmAcpiState uuid -- if it is asleep, we need to wake it first when (acpi == 3) $ resumeS3AndWaitS0 uuid if use_agent then RpcAgent.hibernate uuid else liftIO $ Xl.hibernate uuid saveConfigProperty uuid vmHibernated True resumeS3AndWaitS0 :: Uuid -> Rpc () resumeS3AndWaitS0 uuid = do acpi <- getVmAcpiState uuid when (acpi == 3) $ do liftIO $ Xl.resumeFromSleep uuid done <- liftIO $ Xl.waitForAcpiState uuid 0 (Just 30) when (not done) $ warn $ "timeout waiting for S0 for " ++ show uuid -- Execute action in parallel for each of given VM, returns results of actions. If any action -- fails, we report an error through exception parallelVmExec :: [Uuid] -> (Uuid -> Rpc a) -> Rpc [a] parallelVmExec uuids f = do mvars <- mapM handle uuids results <- mvars `seq` liftIO $ mapM takeMVar mvars mapM unwrap results where unwrap (Right v) = return v unwrap (Left err) = throwError err handle uuid = do context <- rpcGetContext liftIO $ do r <- newEmptyMVar forkIO $ do -- execute in rpc monad rpcStatus <- rpc context (f uuid) -- give result or error putMVar r rpcStatus return r -- Execute action in stages, for each vm type, each stage is done in parallel but the stages itself -- are sequential parallelVmExecByType :: [VmType] -> (Uuid -> Rpc a) -> Rpc [(Uuid, a)] parallelVmExecByType types f = concat <$> mapM run types where run t = getVmsByType t >>= \uuids -> parallelVmExec uuids f >>= \results -> return $ zip uuids results -- paralell execution in explicitly specified stages (as sets of uuids). Stages are sequential, actions -- in a stage are parallel parallelVmExecInStages :: [[Uuid]] -> (Uuid -> Rpc a) -> Rpc [(Uuid, a)] parallelVmExecInStages stages f = concat <$> mapM run stages where run uuids = parallelVmExec uuids f >>= \results -> return $ zip uuids results -- Switch to a VM switchVm :: MonadRpc e m => Uuid -> m Bool switchVm uuid = whenDomainID False uuid $ \domid -> do debug $ "Attempting to switch screen to domain " ++ show uuid -- ensure switcher is ready liftIO $ Xl.wakeIfS3 uuid success <- inputSwitchFocus domid when (not success) $ warn ("switchVm: failed for uuid " ++ show uuid) return success -- Switch to a VM, and repeat the attempts until it succeeds reallySwitchVm :: MonadRpc e m => Uuid -> Float -> m Bool reallySwitchVm uuid timeout_time = do t0 <- liftIO getCurrentTime loop t0 where loop t0 = do t1 <- liftIO getCurrentTime let d = realToFrac $ diffUTCTime t1 t0 if d >= timeout_time || d < 0 then return False else do r <- switchVm uuid if r then return True else liftIO (threadDelay (2*10^5)) >> loop t0 -- Switch to graphics fallback vm switchGraphicsFallback :: Rpc Bool switchGraphicsFallback = do vm <- getGraphicsFallbackVm case vm of Nothing -> return False Just vm -> switchVm vm -- This just sets authentication context on input daemon loginToVm :: Uuid -> Rpc () loginToVm uuid = do -- typically this is actually a HASH not a real user id user <- readConfigProperty uuid vmCryptoUser case user of Nothing -> return () Just (uid :: String) -> inputAuthSetContextFlags uid "" (auth_FLAG_REMOTE_USER .|. auth_FLAG_USER_HASH) allocateDiskID :: Uuid -> Rpc DiskID allocateDiskID uuid = do disks <- getDisks uuid return $ (maxID (M.keys disks)) + 1 where maxID [] = (-1) maxID xs = maximum xs allocateNicID :: Uuid -> Rpc NicID allocateNicID uuid = getNicIds uuid >>= \ids -> return (XbDeviceID $ (maxID ids) + 1) where maxID [] = (-1) maxID xs = maximum . map xbdevID $ xs modifyDBVmFirewallRules :: Uuid -> ([Firewall.Rule] -> [Firewall.Rule]) -> Rpc () modifyDBVmFirewallRules uuid f = do r <- getVmFirewallRules uuid let r' = nub $ f r when ( r /= r' ) $ saveConfigProperty uuid vmFirewallRules r' addVmFirewallRule :: Uuid -> Firewall.Rule -> Rpc () addVmFirewallRule uuid rule = modifyDBVmFirewallRules uuid (++ [rule]) deleteVmFirewallRule :: Uuid -> Firewall.Rule -> Rpc () deleteVmFirewallRule uuid rule = modifyDBVmFirewallRules uuid (filter (/= rule)) getEffectiveVmFirewallRules :: Uuid -> Rpc [Firewall.Rule] getEffectiveVmFirewallRules uuid = getVmFirewallRules uuid >>= \rules -> return $ nub (rules ++ map Firewall.inverse rules) doVmFirewallRules :: Rpc () -> Rpc ([Firewall.ActiveVm], [Firewall.ActiveVm]) -> Rpc () doVmFirewallRules message which = whenM appGetArgoFirewall $ do message (vms, vms') <- which seamlessVms <- getSeamlessVms info $ "firewall rule delta vms:" info $ "BEFORE: " ++ show vms info $ "NOW: " ++ show vms let reduce vms ((Firewall.ActiveVm _ _ vm _ _), rule) = Firewall.reduce (Firewall.ReduceContext vm seamlessVms vms) [rule] vm_rules = mapM (getEffectiveVmFirewallRules . Firewall.vmUuid) let makeRules vms = (concat . map (reduce vms) . concat . zipWith (\vm rs -> map (vm,) rs) vms) <$> vm_rules vms changeset <- Firewall.changeset <$> makeRules vms <*> makeRules vms' liftIO $ Firewall.applyChangeset changeset applyVmFirewallRules :: Uuid -> Rpc () applyVmFirewallRules uuid = doVmFirewallRules (info $ "applying argo firewall rules due to " ++ show uuid) $ do active <- activeVms return (filter (\vm -> Firewall.vmUuid vm /= uuid) active, active) unapplyVmFirewallRules :: Uuid -> Rpc () unapplyVmFirewallRules uuid = doVmFirewallRules (info $ "unapplying argo firewall rules due to " ++ show uuid) $ do active <- activeVms myself <- getActiveVm uuid return (nub $ active ++ maybeToList myself , filter (\vm -> Firewall.vmUuid vm /= uuid) active) getActiveVm :: Uuid -> Rpc (Maybe Firewall.ActiveVm) getActiveVm uuid = do maybe_domid <- liftIO . xsRead $ "/xenmgr/vms/" ++ show uuid ++ "/domid" stubdom <- getStubDomainID uuid typ <- typStr <$> getVmType uuid name <- getVmName uuid return . fmap (\domid -> Firewall.ActiveVm domid stubdom uuid typ name) . fmap read $ maybe_domid where typStr (ServiceVm tag) = tag typStr Svm = "svm" mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM op = liftM catMaybes . mapM op -- this resolves domid using xenstore as the domain might well be destroyed on xen level when this info is needed activeVms :: Rpc [Firewall.ActiveVm] activeVms = mapMaybeM getActiveVm =<< filterM isRunning =<< getVms addNicToVm :: Uuid -> NicDef -> Vm NicID addNicToVm uuid nic = withVmDbLock . liftRpc $ do info $ "adding virtual nic to VM " ++ show uuid nics <- getVmNicDefs uuid id <- allocateNicID uuid let nics' = M.insert id (nic { nicdefId = id }) nics saveConfigProperty uuid vmNics nics' return id addDefaultNicToVm :: Uuid -> Vm NicID addDefaultNicToVm uuid = addNicToVm uuid nic where nic = NicDef { nicdefId = XbDeviceID (-1) , nicdefNetwork = fallbackNetwork , nicdefWirelessDriver = False , nicdefBackendUuid = Nothing , nicdefBackendName = Nothing , nicdefBackendDomid = Nothing , nicdefEnable = True , nicdefMac = Nothing , nicdefModel = Nothing } addDiskToVm :: Uuid -> Disk -> Vm DiskID addDiskToVm uuid disk = withVmDbLock . liftRpc $ do info $ "adding virtual disk to VM " ++ show uuid disks <- getDisks uuid id <- allocateDiskID uuid let disks' = M.insert id disk disks saveConfigProperty uuid vmDisks disks' return id -- removeNicFromVm :: Uuid -> NicID -> Vm () removeNicFromVm uuid id = withVmDbLock . liftRpc $ do info $ "removing virtual nic " ++ show id ++ " from VM " ++ show uuid nics <- getVmNicDefs uuid saveConfigProperty uuid vmNics (M.delete id nics) addDefaultDiskToVm :: Uuid -> Vm DiskID addDefaultDiskToVm uuid = do virt_path <- pickDiskVirtPath uuid addDiskToVm uuid $ Disk { diskPath = "" , diskType = VirtualHardDisk , diskMode = Vm.Types.ReadWrite , diskDeviceType = DiskDeviceTypeDisk , diskDevice = virt_path , diskSnapshotMode = Nothing , diskSha1Sum = Nothing , diskManagedType = UnmanagedDisk , diskShared = False , diskEnabled = True } -- addVhdDiskToVm :: Uuid -> FilePath -> Vm DiskID addVhdDiskToVm uuid path = do virt_path <- pickDiskVirtPath uuid let disk = Disk { diskPath = path , diskType = VirtualHardDisk , diskMode = Vm.Types.ReadWrite , diskDeviceType = DiskDeviceTypeDisk , diskDevice = virt_path , diskSnapshotMode = Nothing , diskSha1Sum = Nothing , diskManagedType = UnmanagedDisk , diskShared = False , diskEnabled = True } addDiskToVm uuid disk -- addPhyDiskToVm :: Uuid -> FilePath -> Vm DiskID addPhyDiskToVm uuid path = do virt_path <- pickDiskVirtPath uuid let disk = Disk { diskPath = path , diskType = PhysicalDevice , diskMode = Vm.Types.ReadWrite , diskDeviceType = DiskDeviceTypeDisk , diskDevice = virt_path , diskSnapshotMode = Nothing , diskSha1Sum = Nothing , diskManagedType = UnmanagedDisk , diskShared = False , diskEnabled = True } addDiskToVm uuid disk -- removeDiskFromVm :: Uuid -> DiskID -> Vm () removeDiskFromVm uuid id = withVmDbLock . liftRpc $ do info $ "removing a virtual disk " ++ show id ++ " from VM " ++ show uuid disks <- getDisks uuid case M.lookup id disks of Nothing -> return () Just d -> do let disks' = M.delete id disks removeDiskFiles uuid d saveConfigProperty uuid vmDisks disks' removeDiskFiles :: Uuid -> Disk -> Rpc () removeDiskFiles uuid d = removeVhd d where removeVhd d | not (diskShared d), diskType d == VirtualHardDisk = do refs <- nub . map fst <$> getVhdReferences (diskPath d) -- only remove when only this vm references the vhd when (refs == [uuid]) $ do let p = diskPath d diskhaskey <- getDiskEncryptionKeySet d -- if the disk has a key, remove it first if diskhaskey then do keydir <- appGetPlatformCryptoKeyDirs keyfiles <- liftIO $ getDirectoryContents_nonDotted keydir removeKey keydir keyfiles p else return () -- remove the vhd liftIO . whenM (doesFileExist p) $ do info $ "Removing VHD file " ++ p removeLink p where removeKey keydir keyfiles p = let vhd_name = takeBaseName p in let key_matches = filter (\x -> vhd_name `isPrefixOf` x) keyfiles in case key_matches of [x] -> liftIO $ removeLink (keydir ++ "/" ++ x) [] -> liftIO $ info $ "Key not found for " ++ p _ -> liftIO $ info $ "Multiple keys found for " ++ p removeVhd _ = return () -- createAndAddDiskToVm :: Uuid -> Int -> Vm DiskID createAndAddDiskToVm uuid sizeGB = do let sizeMB = sizeGB * 1024 vhdPath <- liftIO $ createVhd sizeMB addVhdDiskToVm uuid vhdPath modifyVmNic :: Uuid -> NicID -> (NicDef -> NicDef) -> Vm () modifyVmNic uuid nicID modifyF = withVmDbLock . liftRpc $ do n <- getNic uuid nicID case n of Nothing -> failNoSuchNic Just nic -> let nic' = modifyF nic in saveConfigProperty uuid (vmNic nicID) nic' modifyVmDisk :: Uuid -> DiskID -> (Disk -> Disk) -> Vm () modifyVmDisk uuid diskID modifyF = withVmDbLock . liftRpc $ do p <- readConfigProperty uuid (vmDisk diskID) case p of Nothing -> failNoSuchDisk Just disk -> let disk' = modifyF disk in saveConfigProperty uuid (vmDisk diskID) disk' modifyVmPciPtRules :: Uuid -> (PciPtRuleMap -> PciPtRuleMap) -> Rpc () modifyVmPciPtRules uuid modifyF = do rules <- getPciPtRules uuid let rules' = modifyF rules saveConfigProperty uuid vmPcis rules' finally' = flip E.finally mountVmDisk :: Uuid -> DiskID -> Bool -> FilePath -> Rpc () mountVmDisk uuid diskID readonly path = do disk <- getDisk uuid diskID case disk of Nothing -> failNoSuchDisk Just disk -> case diskType disk of VirtualHardDisk -> mountVhd $ diskPath disk _ -> failIncorrectDiskType where mountVhd :: FilePath -> Rpc () mountVhd vhdpath = do keydirs <- concat . intersperse "," <$> getCryptoKeyLookupPaths uuid liftIO $ do dev <- tapCreate "vhd" [("TAPDISK2_CRYPTO_KEYDIR", keydirs), ("TAPDISK3_CRYPTO_KEYDIR", keydirs)] readonly vhdpath E.handle (\(e :: E.SomeException) -> removedev dev >> E.throw e) $ do xsWrite (xspath ++ "/dev") dev let mountopts = if readonly then ["-o", "ro"] else [] readProcessOrDie "mount" (mountopts ++ [dev, path]) "" xsWrite (xspath ++ "/path") path return () where removedev path = do tapDestroy path xsRm xspath xspath = "/xenmgr/mount/" ++ show uuid ++ "/" ++ show diskID unmountVmDisk :: Uuid -> DiskID -> Rpc () unmountVmDisk uuid diskID = do disk <- getDisk uuid diskID case disk of Nothing -> failNoSuchDisk Just disk -> case diskType disk of VirtualHardDisk -> unmountVhd $ diskPath disk _ -> failIncorrectDiskType where unmountVhd :: FilePath -> Rpc () unmountVhd vhdpath = liftIO $ do dev <- fromMaybe "" <$> xsRead (xspath ++ "/dev") mountpath <- xsRead (xspath ++ "/path") case mountpath of Nothing -> error $ "device not mounted " ++ show dev Just mountpath -> do readProcessOrDie "umount" [mountpath] "" tapDestroy vhdpath xsRm xspath return () where xspath = "/xenmgr/mount/" ++ show uuid ++ "/" ++ show diskID generateCryptoKeyIn :: Uuid -> DiskID -> Int -> FilePath -> Rpc () generateCryptoKeyIn vm diskID keybits dir = do when (not $ keybits `elem` [256, 512]) $ error "only supported key sizes: 256, 512" disk <- haveDisk =<< getDisk vm diskID checkFileEx disk checkKeySet disk liftIO (setKeyHash disk =<< mkRandomKeyFile disk) where checkFileEx d = whenM (liftIO $ doesFileExist $ keyfile d) $ failCryptoKeyAlreadyExists checkKeySet d = whenM ((/= "none") <$> liftIO (readKeyHash d)) $ failVhdKeyAlreadySet readKeyHash d = strip <$> readProcessOrDie "vhd-util" ["key", "-n", diskPath d, "-p"] [] setKeyHash d f = void $ readProcessOrDie "vhd-util" ["key", "-n", diskPath d, "-k", f, "-s"] [] mkRandomKeyFile d = let dst = keyfile d src = "/dev/random" in copy src dst (fromIntegral keysize_bytes) >> return dst copy s d n = BL.readFile s >>= return . BL.take n >>= BL.writeFile d keyfile d = dir </> diskUuid d ++ ",aes-xts-plain," ++ show keybits ++ ".key" -- 512 keysize by default (this means AES-256 as aes-xts uses keys split in half) keysize_bytes = keybits `div` 8 haveDisk Nothing = failNoSuchDisk haveDisk (Just d) = return d diskUuid = takeBaseName . diskPath generateCryptoKey :: Uuid -> DiskID -> Int -> Rpc () generateCryptoKey vm diskID keybits = into =<< ( split ',' <$> appGetPlatformCryptoKeyDirs ) where into [] = error "no platform crypto directories configured" into (p:_) = do liftIO $ whenM (not <$> doesDirectoryExist p) $ createDirectory p generateCryptoKeyIn vm diskID keybits p -- only computes hash for disk of id 0. TODO: make this more generic maybe addVmDiskHashes :: Vm () addVmDiskHashes = vmUuid >>= \uuid -> addTo uuid 0 where addTo uuid id = do Just primary <- M.lookup id <$> (liftRpc $ getDisks uuid) case diskSha1Sum primary of Just _ -> return () -- already have Nothing -> liftRpc (computeDiskSha1Sum uuid primary) >>= \sum -> modifyVmDisk uuid id $ \disk -> disk { diskSha1Sum = Just sum } checkVmDiskHashes :: Vm Bool checkVmDiskHashes = do bypass <- liftRpc appBypassSha1SumChecks if not bypass then do uuid <- vmUuid disks <- M.elems <$> liftRpc (getDisks uuid) all (==True) <$> mapM (validate uuid) disks else return True where validate uuid d | Just sh <- sha1 = liftRpc ( computeDiskSha1Sum uuid d ) >>= \sh' -> equalT sh sh' | otherwise = return True where sha1 = diskSha1Sum d path = diskPath d equalT sh sh' | sh == sh' = return True | otherwise = vmSubmit (VmMeasurementFailure path sh sh') >> return False getMeasureFailAction :: Rpc PMAction getMeasureFailAction = dbReadWithDefault ActionForcedShutdown "/xenmgr/measure-fail-action" setMeasureFailAction :: PMAction -> Rpc () setMeasureFailAction a = dbWrite "/xenmgr/measure-fail-action" a tapEnvForVm :: Uuid -> Rpc [(String,String)] tapEnvForVm uuid = do keydirs <- concat . intersperse "," <$> getCryptoKeyLookupPaths uuid return [("TAPDISK2_CRYPTO_KEYDIR", keydirs), ("TAPDISK3_CRYPTO_KEYDIR", keydirs)] tapCreateForVm :: Uuid -> Bool -> FilePath -> Rpc FilePath tapCreateForVm uuid ro path = do env <- tapEnvForVm uuid liftIO $ tapCreateVhd env ro path -- Computer sha1 sum for disk. Has to be through tap device because the vhd file changes -- even for completely readonly fs computeDiskSha1Sum :: Uuid -> Disk -> Rpc Integer computeDiskSha1Sum vm_uuid d | diskType d == VirtualHardDisk = do tapdev <- tapCreateForVm vm_uuid True (diskPath d) liftIO $ E.finally (fileSha1Sum tapdev) (spawnShell' $ "tap-ctl destroy -d " ++ tapdev) | diskType d == Aio = liftIO $ do tapdev <- fromMaybe (error $ "FAILED to create tap device for " ++ diskPath d ++ ", possibly in use?") . fmap chomp <$> (spawnShell' $ "tap-ctl create -a aio:" ++ (diskPath d)) E.finally (fileSha1Sum tapdev) (spawnShell' $ "tap-ctl destroy -d " ++ tapdev) | diskType d `elem` [PhysicalDevice, DiskImage] = liftIO $ fileSha1Sum (diskPath d) | otherwise = error "unsupported disk type, should be vhd or phy or file" parseKernelExtract :: String -> (Maybe DiskID, Maybe PartitionNum, FilePath) parseKernelExtract p = case split ':' p of [file] -> (Nothing, Nothing, file) [opts, file] -> case split ',' p of [diskS,partS] -> let diskNum = fromMaybe (error "bad disk number in kernel-extract") $ maybeRead diskS in let partNum = fromMaybe (error "bad partition number in kernel-extract") $ maybeRead partS in (Just diskNum, Just partNum, file) [diskS] -> let diskNum = fromMaybe (error "bad disk number in kernel-extract") $ maybeRead diskS in (Just diskNum, Nothing, file) _ -> error "incorrect disk & partition specification in kernel-extract" _ -> error "incorrect kernel-extract syntax" -- Assumes that kernel is stored in disk of id 0 for that vm extractKernelFromPvDomain :: Uuid -> Rpc () extractKernelFromPvDomain uuid = join $ extractFileFromPvDomain <$> getVmKernelPath uuid <*> getVmKernelExtract uuid <*> pure uuid extractInitrdFromPvDomain :: Uuid -> Rpc () extractInitrdFromPvDomain uuid = do initrd <- getVmInitrd uuid let initrd' = case initrd of "" -> Nothing _ -> Just initrd join $ extractFileFromPvDomain <$> pure initrd' <*> getVmInitrdExtract uuid <*> pure uuid extractFileFromPvDomain :: Maybe FilePath -> String -> Uuid -> Rpc () extractFileFromPvDomain Nothing _ _ = return () extractFileFromPvDomain (Just dst_path) ext_loc uuid = withKernelPath dst_path where withKernelPath dst_kernel_path = do let (diskid,partid,src_path) = parseKernelExtract ext_loc disk <- getDisk uuid (fromMaybe 0 diskid) keydirs <- concat . intersperse "," <$> getCryptoKeyLookupPaths uuid case (disk, dst_kernel_path) of (_, "") -> return () -- doesn't have a kernel, not a pv domain, ignore (Nothing, _) -> error "extract-kernel: domain does not have a disk with ID 0" (_, path) | null src_path -> return () -- no extraction (Just disk, path) -> do liftIO $ copyKernelFromDisk [("TAPDISK2_CRYPTO_KEYDIR", keydirs), ("TAPDISK3_CRYPTO_KEYDIR", keydirs)] disk path (partid,src_path) info $ "extracted pv kernel/initrd from " ++ src_path ++ " into " ++ path copyKernelFromDisk :: [ (String, String) ] -> Disk -> FilePath -> (Maybe PartitionNum,FilePath) -> IO () copyKernelFromDisk extraEnv disk dst_path src = copyFileFromDisk extraEnv (diskType disk) (diskMode disk == ReadOnly) (diskPath disk) src dst_path changeVmNicNetwork :: Uuid -> NicID -> Network -> XM () changeVmNicNetwork uuid nicid network = do -- Save in database xmRunVm uuid $ modifyVmNic uuid nicid $ \nic -> nic { nicdefNetwork = network } -- Hotswap network if VM is running whenM (isRunning uuid) $ do xmWithNetsyncLock . liftRpc $ do -- disconnect vif -- notify xenvm TODO: maybe won't be necessary sometime? -- notify network daemon -- resynchronise vif state info $ "====In ChangeVmNicNetwork=====" liftIO $ Xl.connectVif uuid nicid False liftIO $ Xl.changeNicNetwork uuid nicid network whenDomainID_ uuid $ \domid -> joinNetwork network domid nicid -- Property accessors --------------------- setVmWiredNetwork :: Uuid -> Network -> XM () setVmWiredNetwork uuid network = getVmWiredNics uuid >>= pure . take 1 >>= mapM_ (\n -> changeVmNicNetwork uuid (nicdefId n) network) setVmWirelessNetwork :: Uuid -> Network -> XM () setVmWirelessNetwork uuid network = getVmWirelessNics uuid >>= pure . take 1 >>= mapM_ (\n -> changeVmNicNetwork uuid (nicdefId n) network) setVmGpu :: Uuid -> String -> Rpc () setVmGpu uuid s = do availableGpus <- getGpuPlacements case filter (matchBdf s) availableGpus of [] -> return () -- No configured gpu-placement _ -> saveConfigProperty uuid vmGpu s where matchBdf s (gpu, placement) = isInfixOf s (gpuId gpu) setVmCd :: Uuid -> String -> Rpc () setVmCd uuid str = -- change all cdrom paths readConfigPropertyDef uuid vmDisks [] >>= mapM maybeChange >>= saveConfigProperty uuid vmDisks where maybeChange disk | not (isCdrom disk) = return disk | otherwise = do isos <- appIsoPath let path = isos ++ "/" ++ name -- hot swap cd whenVmRunning uuid (liftIO $ Xl.changeCd uuid path) return $ disk { diskPath = path } name | str == "" = "null.iso" | otherwise = str setVmType :: Uuid -> VmType -> Rpc () setVmType uuid typ = saveConfigProperty uuid vmType typ setVmAmtPt :: Uuid -> Bool -> Rpc () setVmAmtPt uuid amtpt = saveConfigProperty uuid vmAmtPt amtpt setVmSeamlessTraffic :: Uuid -> Bool -> Rpc () setVmSeamlessTraffic uuid view = saveConfigProperty uuid vmSeamlessTraffic view setVmStartOnBoot :: Uuid -> Bool -> Rpc () setVmStartOnBoot uuid start = do saveConfigProperty uuid vmStartOnBoot start setVmHiddenInSwitcher :: Uuid -> Bool -> Rpc () setVmHiddenInSwitcher uuid hidden = do saveConfigProperty uuid vmHidden hidden exportVmSwitcherInfo uuid setVmHiddenInUi :: Uuid -> Bool -> Rpc () setVmHiddenInUi uuid hidden = saveConfigProperty uuid vmHiddenInUi hidden -- in mebibytes setVmMemory :: Uuid -> Int -> Rpc () setVmMemory uuid mb = do saveConfigProperty uuid vmMemory mb -- running <- isRunning uuid -- when running $ Xenvm.setMemTarget uuid mb -- <= 0 == turned off setVmMemoryStaticMax :: Uuid -> Int -> Rpc () setVmMemoryStaticMax uuid mib = do saveOrRmConfigProperty uuid vmMemoryStaticMax (if mib <= 0 then Nothing else Just mib) -- <= 0 == turned off setVmMemoryMin :: Uuid -> Int -> Rpc () setVmMemoryMin uuid mib = do saveOrRmConfigProperty uuid vmMemoryMin (if mib <= 0 then Nothing else Just mib) setVmName :: Uuid -> String -> Rpc () setVmName uuid name = do saveConfigProperty uuid vmName (strip name) exportVmSwitcherInfo uuid notifyVmNameChanged uuid setVmImagePath :: Uuid -> FilePath -> Rpc () setVmImagePath uuid path = do saveConfigProperty uuid vmImagePath (strip path) exportVmSwitcherInfo uuid -- swaps slots as necessary, requires locking setVmSlot :: Uuid -> Int -> XM () setVmSlot uuid slot = xmWithVmSlotLock . liftRpc $ swap where swap = do there <- if slot < 0 then return Nothing else slotted slot case there of Nothing -> really_save uuid slot Just vm -> getVmSlot uuid >>= \prev -> when (prev>0) (really_save vm prev) >> really_save uuid slot slotted at = fmap listToMaybe $ filterM (\uuid -> (at ==) <$> getVmSlot uuid) =<< getVms really_save uuid slot = getDomainID uuid >>= set where set (Just domid) = inputSetSlot domid slot >> saveConfigProperty uuid vmSlot slot set _ = saveConfigProperty uuid vmSlot slot setVmPvAddons uuid adds = saveConfigProperty uuid vmPvAddons ( adds :: Bool ) setVmPvAddonsVersion uuid v = saveConfigProperty uuid vmPvAddonsVersion ( v :: String ) setVmTimeOffset uuid o = saveConfigProperty uuid vmTimeOffset ( o :: Int ) setVmCryptoUser uuid u = saveOrRmConfigProperty uuid vmCryptoUser (if u == "" then Nothing else Just u) setVmCryptoKeyDirs uuid d = saveConfigProperty uuid vmCryptoKeyDirs ( d :: String ) setVmAutoS3Wake uuid a = saveConfigProperty uuid vmAutoS3Wake ( a :: Bool ) setVmNotify uuid v = saveConfigProperty uuid vmNotify (v::String) setVmVirtType uuid v = saveConfigProperty uuid vmVirtType (v::VirtType) setVmPae uuid v = saveConfigProperty uuid vmPae (v::Bool) setVmApic uuid v = saveConfigProperty uuid vmApic (v::Bool) setVmAcpi uuid v = saveConfigProperty uuid vmAcpi (v::Bool) setVmViridian uuid v = saveConfigProperty uuid vmViridian (v::Bool) setVmNx uuid v = saveConfigProperty uuid vmNx (v::Bool) setVmSound uuid v = saveConfigProperty uuid vmSound (v::String) setVmDisplay uuid v = saveConfigProperty uuid vmDisplay (v::String) setVmBoot uuid v = saveConfigProperty uuid vmBoot (v::String) setVmCmdLine uuid v = saveConfigProperty uuid vmCmdLine (v::String) setVmKernel uuid v = saveConfigProperty uuid vmKernel (v::String) setVmKernelExtract uuid v = saveConfigProperty uuid vmKernelExtract (v::String) setVmInitrd uuid v = saveConfigProperty uuid vmInitrd (v::String) setVmInitrdExtract uuid v = saveConfigProperty uuid vmInitrdExtract (v::String) setVmAcpiTable uuid v = saveConfigProperty uuid vmAcpiTable (v::Bool) setVmVcpus uuid v = saveConfigProperty uuid vmVcpus (v::Int) setVmCoresPerSocket uuid v = saveConfigProperty uuid vmCoresPerSocket (v::Int) setVmVideoram uuid v = saveConfigProperty uuid vmVideoram (v::Int) setVmPassthroughMmio uuid v = saveConfigProperty uuid vmPassthroughMmio (v::String) setVmPassthroughIo uuid v = saveConfigProperty uuid vmPassthroughIo (v::String) setVmFlaskLabel uuid v = saveConfigProperty uuid vmFlaskLabel (v::String) setVmInitFlaskLabel uuid v = saveConfigProperty uuid vmInitFlaskLabel (v::String) setVmStubdomFlaskLabel uuid v = saveConfigProperty uuid vmStubdomFlaskLabel (v::String) setVmHap uuid v = saveConfigProperty uuid vmHap (v::Bool) setVmDescription uuid v = saveConfigProperty uuid vmDescription (v::String) setVmStartOnBootPriority uuid v = saveConfigProperty uuid vmStartOnBootPriority (v::Int) setVmKeepAlive uuid v = saveConfigProperty uuid vmKeepAlive (v::Bool) setVmProvidesNetworkBackend uuid v = saveConfigProperty uuid vmProvidesNetworkBackend (v::Bool) setVmProvidesDefaultNetworkBackend uuid v = saveConfigProperty uuid vmProvidesDefaultNetworkBackend (v::Bool) setVmProvidesGraphicsFallback uuid v = saveConfigProperty uuid vmProvidesGraphicsFallback (v::Bool) setVmShutdownPriority uuid v = saveConfigProperty uuid vmShutdownPriority (v::Int) setVmSeamlessId uuid v = saveConfigProperty uuid vmSeamlessId (v::String) setVmQemuDmPath uuid v = saveConfigProperty uuid vmQemuDmPath (v::String) setVmQemuDmTimeout uuid v = saveConfigProperty uuid vmQemuDmTimeout (v::Int) setVmControlPlatformPowerState uuid v = saveConfigProperty uuid vmControlPlatformPowerState (v::Bool) setVmExtraXenvm uuid str = saveConfigProperty uuid vmExtraXenvm (filter (not.null) . map strip . split ';' $ str) setVmExtraHvm uuid str = saveConfigProperty uuid vmExtraHvms (filter (not.null) . map strip . split ';' $ str) setVmStartFromSuspendImage uuid v = saveConfigProperty uuid vmStartFromSuspendImage (v::String) setVmTrackDependencies uuid v = saveConfigProperty uuid vmTrackDependencies (v::Bool) setVmSeamlessMouseLeft uuid v = do saveConfigProperty uuid vmSeamlessMouseLeft (v::String) inputUpdateSeamlessMouseSettings uuid setVmSeamlessMouseRight uuid v = do saveConfigProperty uuid vmSeamlessMouseRight (v::String) inputUpdateSeamlessMouseSettings uuid setVmOs uuid os = saveConfigProperty uuid vmOs (osToStr os) setVmOemAcpiFeatures uuid v = saveConfigProperty uuid vmOemAcpiFeatures (v::Bool) setVmUsbEnabled uuid v = saveConfigProperty uuid vmUsbEnabled (v::Bool) setVmUsbControl uuid v = do saveConfigProperty uuid vmUsbControl (v::Bool) -- TODO: surely this can be improved, for now SIGHUP to cause proxy daemon -- to reevaluate rules liftIO $ spawnShell' "killall -SIGHUP rpc-proxy" return () setVmUsbAutoPassthrough uuid v = saveConfigProperty uuid vmUsbAutoPassthrough (v::Bool) setVmStubdom uuid v = saveConfigProperty uuid vmStubdom (v::Bool) setVmStubdomMemory uuid v = saveConfigProperty uuid vmStubdomMemory (v::Int) setVmStubdomCmdline uuid v = saveConfigProperty uuid vmStubdomCmdline (v::String) setVmCpuid uuid v = saveConfigProperty uuid vmCpuid (v::String) setVmXciCpuidSignature uuid v = saveConfigProperty uuid vmXciCpuidSignature (v::Bool) setVmGreedyPcibackBind uuid v = saveConfigProperty uuid vmGreedyPcibackBind (v::Bool) setVmRunPostCreate uuid v = saveOrRmConfigProperty uuid vmRunPostCreate (v::Maybe String) setVmRunPreDelete uuid v = saveOrRmConfigProperty uuid vmRunPreDelete (v::Maybe String) setVmRunPreBoot uuid v = saveOrRmConfigProperty uuid vmRunPreBoot (v::Maybe String) setVmRunInsteadofStart uuid v = saveOrRmConfigProperty uuid vmRunInsteadofStart (v::Maybe String) setVmRunOnStateChange uuid v = saveOrRmConfigProperty uuid vmRunOnStateChange (v::Maybe String) setVmRunOnAcpiStateChange uuid v = saveOrRmConfigProperty uuid vmRunOnAcpiStateChange (v::Maybe String) setVmNativeExperience uuid v = do mapM_ clearSetting =<< getGuestVms saveConfigProperty uuid vmNativeExperience (v :: Bool) where clearSetting uuid = saveConfigProperty uuid vmNativeExperience False setVmShowSwitcher uuid v = saveConfigProperty uuid vmShowSwitcher (v :: Bool) setVmWirelessControl uuid v = saveConfigProperty uuid vmWirelessControl (v :: Bool) setVmUsbGrabDevices uuid v = saveConfigProperty uuid vmUsbGrabDevices (v::Bool) setVmS3Mode uuid v = saveConfigProperty uuid vmS3Mode (v::S3Mode) setVmS4Mode uuid v = saveConfigProperty uuid vmS4Mode (v::S4Mode) setVmVsnd uuid v = saveConfigProperty uuid vmVsnd (v::Bool) setVmRealm uuid v = saveConfigProperty uuid vmRealm (v::String) setVmSyncUuid uuid v = saveConfigProperty uuid vmSyncUuid (v::String) setVmIcbinnPath uuid v = saveConfigProperty uuid vmIcbinnPath (v::String) setVmOvfTransportIso uuid = saveConfigProperty uuid vmOvfTransportIso setVmDownloadProgress uuid v = do dbWrite ("/vm/"++show uuid++"/download-progress") (v::Int) notifyVmTransferChanged uuid setVmReady uuid v = saveConfigProperty uuid vmReady (v::Bool) setVmVkbd uuid v = saveConfigProperty uuid vmVkbd (v::Bool) setVmArgo uuid v = saveConfigProperty uuid vmArgo (v::Bool) setVmRestrictDisplayDepth uuid v = saveConfigProperty uuid vmRestrictDisplayDepth (v::Bool) setVmRestrictDisplayRes uuid v = saveConfigProperty uuid vmRestrictDisplayRes (v::Bool) setVmPreserveOnReboot uuid v = saveConfigProperty uuid vmPreserveOnReboot (v::Bool) setVmBootSentinel uuid v = saveOrRmConfigProperty uuid vmBootSentinel (v::Maybe String) setVmHpet uuid v = saveConfigProperty uuid vmHpet (v::Bool) setVmTimerMode uuid v = saveConfigProperty uuid vmTimerMode (v::String) setVmNestedHvm uuid v = saveConfigProperty uuid vmNestedHvm (v::Bool) setVmSerial uuid v = saveConfigProperty uuid vmSerial (v::String) setVmBios uuid v = saveConfigProperty uuid vmBios (v::String) setVmSecureboot uuid v = saveConfigProperty uuid vmSecureboot (v::Bool) setVmAuthenforce uuid v = saveConfigProperty uuid vmAuthenforce (v::Bool) setVmHdType uuid v = saveConfigProperty uuid vmHdType (v::String) setVmDisplayHandlerStrict uuid v = saveConfigProperty uuid vmDisplayHandlerStrict (v::Bool) setVmLongForm uuid v = saveConfigProperty uuid vmLongForm (v::String) setVmShortForm uuid v = saveConfigProperty uuid vmShortForm (v::String) setVmTextColor uuid v = saveConfigProperty uuid vmTextColor (v::String) setVmDomainColor uuid v = saveConfigProperty uuid vmDomainColor (v::String) setVmBorderWidth uuid v = saveConfigProperty uuid vmBorderWidth (v::Int) setVmBorderHeight uuid v = saveConfigProperty uuid vmBorderHeight (v::Int) setVmMosaicVmEnabled uuid v = saveConfigProperty uuid vmMosaicVmEnabled (v::Bool) setVmVglassEnabled uuid v = saveConfigProperty uuid vmVglassEnabled (v::Bool) setVmMosaicMode uuid v = saveConfigProperty uuid vmMosaicMode (v::Int) setVmWindowedX uuid v = saveConfigProperty uuid vmWindowedX (v::Int) setVmWindowedY uuid v = saveConfigProperty uuid vmWindowedY (v::Int) setVmWindowedW uuid v = saveConfigProperty uuid vmWindowedW (v::Int) setVmWindowedH uuid v = saveConfigProperty uuid vmWindowedH (v::Int) setVmPrimaryDomainColor uuid v = saveConfigProperty uuid vmPrimaryDomainColor (v::String) setVmSecondaryDomainColor uuid v = saveConfigProperty uuid vmSecondaryDomainColor (v::String) -- set autolock flag on the vm xenstore tree, per cd device -- cd devices which have sticky bit are not subject to autolock ever setVmAutolockCdDrives uuid v = whenDomainID_ uuid $ \domid -> mapM_ (set domid) =<< devs where devs = mapM (\d -> (,) <$> pure d <*> getCdDeviceStickyVm d) =<< liftIO getHostBSGDevices set domid (d,sticky_vm) = let sticky = sticky_vm /= Nothing in -- sticky somewhere liftIO $ xsWrite (autolockpath domid d) (f $ v && (not sticky)) where f True = "1" f _ = "0" autolockpath domid (BSGDevice a b c d) = printf "/local/domain/%d/bsgdev-req/%s/autolock" domid (printf "%d_%d_%d_%d" a b c d :: String) -- Create XenStore information used by switcher exportVmSwitcherInfo :: Uuid -> Rpc () exportVmSwitcherInfo uuid = do running <- isRunning uuid typ <- getVmType uuid typStr <- readConfigPropertyDef uuid vmType "svm" if (not running) then liftIO $ xsRm path else do name <- getVmName uuid slot <- getVmSlot uuid image <- getVmImagePath uuid hidden <- getVmHiddenInSwitcher uuid hide_switcher <- not <$> getVmShowSwitcher uuid domid <- fromMaybe (-1) <$> getDomainID uuid seamlessid <- getVmSeamlessId uuid liftIO $ do xsWrite "/xenmgr/vms" "" xsChmod "/xenmgr/vms" "r0" xsWrite path "" xsChmod path "r0" xsWrite (path ++ "/domid") (show domid) xsWriteUTF8 (path ++ "/name" ) name xsWrite (path ++ "/slot" ) (show slot) xsWrite (path ++ "/image") image xsWrite (path ++ "/type" ) typStr xsWrite (path ++ "/hidden") (if hidden then "1" else "0") xsWrite (path ++ "/hide-switcher" ) (if hide_switcher then "1" else "0") xsWrite (path ++ "/seamlessid") seamlessid case typ of ServiceVm tag -> xsWrite (path ++ "/" ++ tag) "1" _ -> return () where path = "/xenmgr/vms/" ++ show uuid
OpenXT/manager
xenmgr/Vm/Actions.hs
gpl-2.0
81,447
4
27
23,096
21,519
10,616
10,903
1,536
6
{-Copyright 2011 Ben Blackburne This file is part of MetAl. MetAl 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. MetAl 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 MetAl. If not, see <http://www.gnu.org/licenses/>. -} module Sequence.AminoAcid where { data Alphabet = A | R | N | D | C | Q | E | G | H | I | L | K | M | F | P | S | T | W | Y | V deriving (Read,Show) }
benb/MetAl
src/Sequence/AminoAcid.hs
gpl-3.0
863
0
6
218
84
55
29
2
0
module Lamdu.GUI.NominalPane ( make ) where import qualified GUI.Momentu as M import GUI.Momentu.Responsive (Responsive) import qualified GUI.Momentu.Responsive as Responsive import qualified GUI.Momentu.Responsive.Options as ResponsiveOptions import qualified GUI.Momentu.State as GuiState import qualified GUI.Momentu.Widget as Widget import qualified Lamdu.Config.Theme.TextColors as TextColors import qualified Lamdu.GUI.Expr.TagEdit as TagEdit import Lamdu.GUI.Monad (GuiM) import qualified Lamdu.GUI.Styled as Styled import qualified Lamdu.GUI.TypeView as TypeView import qualified Lamdu.GUI.WidgetIds as WidgetIds import qualified Lamdu.I18N.Code as Texts import qualified Lamdu.I18N.CodeUI as Texts import Lamdu.Name (Name) import qualified Lamdu.Sugar.Types as Sugar import Lamdu.Prelude make :: _ => Sugar.NominalPane Name i o -> GuiM env i o (Responsive o) make nom = do nameEdit <- TagEdit.makeBinderTagEdit TextColors.nomColor (nom ^. Sugar.npName) <&> Responsive.fromWithTextPos hbox <- ResponsiveOptions.boxSpaced ?? ResponsiveOptions.disambiguationNone paramEdits <- nom ^. Sugar.npParams & traverse (TagEdit.makeRecordTag . (^. Sugar.pName)) <&> map Responsive.fromWithTextPos equals <- Styled.grammar (Styled.label Texts.assign) <&> Responsive.fromTextView bodyEdit <- makeNominalPaneBody (nom ^. Sugar.npBody) hbox [hbox ((nameEdit : paramEdits) <> [equals]), bodyEdit] & pure & local (M.animIdPrefix .~ Widget.toAnimId myId) & GuiState.assignCursor myId nameEditId where myId = nom ^. Sugar.npEntityId & WidgetIds.fromEntityId nameEditId = nom ^. Sugar.npName . Sugar.oTag . Sugar.tagRefTag . Sugar.tagInstance & WidgetIds.fromEntityId makeNominalPaneBody :: _ => Maybe (Sugar.Scheme Name o) -> f (Responsive a) makeNominalPaneBody Nothing = Styled.grammar (Styled.focusableLabel Texts.opaque) <&> Responsive.fromWithTextPos makeNominalPaneBody (Just scheme) = TypeView.makeScheme scheme <&> Responsive.fromTextView
Peaker/lamdu
src/Lamdu/GUI/NominalPane.hs
gpl-3.0
2,168
0
16
443
563
317
246
-1
-1
module Data.ConstraintSystem.Example.Sudoku (SudokuSquare, Sudoku, initSudoku, sudokuToStr, testPuz, rowIdx, colIdx, blockIdx) where import Data.ConstraintSystem import Data.ConstraintSystem.Domain import Data.ConstraintSystem.Domain.Integer import Data.ConstraintSystem.Constraint import Data.ConstraintSystem.Constraint.Finite import Data.Maybe import qualified Data.TypeLevel as Typ sudokuIndices :: [(Int,Int)] sudokuIndices = concat colIdx rowIdx :: [[(Int,Int)]] rowIdx = map (\m -> map (\n -> (n,m)) [1..9]) [1..9] colIdx :: [[(Int,Int)]] colIdx = map (\m -> map (\n -> (m,n)) [1..9]) [1..9] blockIdx :: [[(Int,Int)]] blockIdx = map (\offset -> map (\s -> ((fst s) + (fst offset),(snd s) + (snd offset))) bloc) offsets where bloc = [ (i,j) | i <- [0..2], j <- [0..2] ] offsets = [ (n,m) | n <- [1,4,7], m <- [1,4,7] ] crossSections = rowIdx ++ colIdx ++ blockIdx type SudokuSquare = ModuloDomain Typ.D9 type Sudoku = ConstraintSystem (Int,Int) (Constraint SudokuSquare Int) (SudokuSquare Int) sudokuConstraints :: [([(Int,Int)],Constraint SudokuSquare Int)] sudokuConstraints = zip crossSections $ repeat uniqueConstraint initSudoku :: [[Int]] -> Sudoku initSudoku rows = constraintSystem (concat $ map build_row $ zip [1..9] rows) sudokuConstraints where build_row (i,r) = zip (map ((,)i) [1..9]) $ map build_sq r build_sq n = if n > 0 then single (n-1) else universe sudokuToStr :: Sudoku -> String sudokuToStr p = ( concat $ map (\(i,j) -> ( sqStr (i,j) ) ++ if j == 9 then "\n" else "" ) $ sudokuIndices ) ++ "\n" where sqStr ix = let md = getDomain p ix in if isNothing md then "?" else let d = fromJust md in if size d == 1 then show $ ((head $ elems d) + 1) else "-" testPuz = initSudoku [ [0, 0, 3, 0, 2, 0, 6, 0, 0], [9, 0, 0, 3, 0, 5, 0, 0, 1], [0, 0, 1, 8, 0, 6, 4, 0, 0], [0, 0, 8, 1, 0, 2, 9, 0, 0], [7, 0, 0, 0, 0, 0, 0, 0, 8], [0, 0, 6, 7, 0, 8, 2, 0, 0], [0, 0, 2, 6, 0, 9, 5, 0, 0], [8, 0, 0, 2, 0, 3, 0, 0, 9], [0, 0, 5, 0, 1, 0, 3, 0, 0] ] testPuz2 = initSudoku [ [0, 0, 3, 0, 2, 1, 6, 0, 0], [9, 0, 0, 3, 0, 5, 0, 0, 1], [0, 0, 1, 8, 0, 6, 4, 0, 0], [0, 0, 8, 1, 0, 2, 9, 0, 0], [7, 2, 0, 5, 0, 0, 0, 0, 8], [0, 0, 6, 7, 0, 8, 2, 0, 0], [0, 0, 2, 6, 0, 9, 5, 0, 0], [8, 0, 0, 2, 5, 3, 0, 0, 9], [0, 0, 5, 0, 1, 0, 3, 0, 0] ] testPuz3 = initSudoku [ [1, 0, 0, 0, 0, 0, 0, 0, 4], [2, 0, 0, 0, 0, 0, 0, 3, 0], [3, 0, 0, 0, 0, 0, 1, 0, 0], [4, 0, 0, 0, 0, 3, 0, 0, 0], [5, 0, 0, 0, 0, 5, 0, 0, 0], [6, 0, 0, 0, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0, 0, 0, 0], [8, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 3, 4, 5, 6, 7, 8, 9] ]
qhool/constraint
Data/ConstraintSystem/Example/Sudoku.hs
gpl-3.0
3,226
0
18
1,204
1,634
1,005
629
76
4
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} -- | -- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <beschmi@gmail.com> -- -- Standard substitutions (with free variables). module Term.Substitution.SubstVFree ( -- * General Substitutions Subst(..) -- * application of substitutions , applyVTerm , applyLit -- * smart constructors for substitutions , substFromList , substFromMap , emptySubst -- * Composition of substitutions , compose , applySubst -- * operations , restrict , mapRange -- * queries , varsRange , dom , range , imageOf -- * views , substToListOn , substToList -- *Apply class , Apply(..) -- * Pretty printing , prettySubst -- * Substitution of LVars , LSubst , LNSubst , prettyLNSubst ) where import Term.LTerm import Term.Rewriting.Definitions import Text.PrettyPrint.Highlight import Logic.Connectives import Utils.Misc import Data.Maybe import Data.Map ( Map ) import qualified Data.Map as M import qualified Data.Set as S import Data.List import Data.Binary import Data.Monoid (mempty) import Control.Applicative import Control.DeepSeq ---------------------------------------------------------------------- -- Substitutions ---------------------------------------------------------------------- -- | We use the data type @Subst c v@ of substitutions. @c@ is the type of constants -- and @v@ the type of variables. newtype Subst c v = Subst { sMap :: Map v (VTerm c v) } deriving ( Eq, Ord, NFData, Binary ) -- | A substitution for logical variables. type LSubst c = Subst c LVar -- | A substitution with names and logical variables. type LNSubst = Subst Name LVar -- Application ---------------------------------------------------------------------- -- | @applyLit subst l@ applies the substitution @subst@ to the literal @l@. applyLit :: IsVar v => Subst c v -> Lit c v -> VTerm c v applyLit subst v@(Var i) = fromMaybe (lit v) $ M.lookup i (sMap subst) applyLit _ c@(Con _) = lit c -- | @applyVTerm subst t@ applies the substitution @subst@ to the term @t@. applyVTerm :: (IsConst c, IsVar v, Ord c) => Subst c v -> VTerm c v -> VTerm c v applyVTerm subst t = case viewTerm t of Lit l -> applyLit subst l FApp (AC o) ts -> fAppAC o (map (applyVTerm subst) ts) FApp (C o) ts -> fAppC o (map (applyVTerm subst) ts) FApp (NoEq o) ts -> fAppNoEq o (map (applyVTerm subst) ts) FApp List ts -> fAppList (map (applyVTerm subst) ts) -- Construction ---------------------------------------------------------------------- -- | Convert a list to a substitution. The @x/x@ mappings are removed. substFromList :: IsVar v => [(v, VTerm c v)] -> Subst c v substFromList xs = Subst (M.fromList [ (v,t) | (v,t) <- xs, not (equalToVar t v) ]) -- | Returns @True@ if given term is equal to given variable. equalToVar :: IsVar v => VTerm c v -> v -> Bool equalToVar (viewTerm -> Lit (Var v')) v = v == v' equalToVar _ _ = False -- | Convert a map to a substitution. The @x/x@ mappings are removed. -- FIXME: implement directly, use substFromMap for substFromList. substFromMap :: IsVar v => Map v (VTerm c v) -> Subst c v substFromMap = Subst . M.filterWithKey (\v t -> not $ equalToVar t v) -- | @emptySubVFree@ is the substitution with empty domain. emptySubst :: Subst c v emptySubst = Subst M.empty -- Composition ---------------------------------------------------------------------- -- | @applySubst subst subst'@ applies the substitution @subst@ to the range of -- the substitution @subst'@. applySubst :: (IsConst c, IsVar v) => Subst c v -> Subst c v -> Subst c v applySubst subst subst' = mapRange (applyVTerm subst) subst' -- | @compose s1 s2@ composes the substitutions s1 and s2. The result is -- @s1.s2@, i.e., it has the same effect as @(t s2) s1 = s1(s2(t))@ -- when applied to a term @t@. compose :: (IsConst c, IsVar v) => Subst c v -> Subst c v -> Subst c v compose s1 s2 = Subst $ sMap (applySubst s1 s2) `M.union` sMap (restrict (dom s1 \\ dom s2) s1) -- Operations ---------------------------------------------------------------------- -- | @restrict vars subst@ restricts the domain of the substitution @subst@ to @vars@. restrict :: IsVar v => [v] -> Subst c v -> Subst c v restrict vs (Subst smap) = Subst (M.filterWithKey (\v _ -> v `elem` vs) smap) -- | @mapRange f subst@ maps the function @f@ over the range of the substitution @subst@. mapRange :: (IsConst c, IsVar v, IsConst c2) => (VTerm c v -> VTerm c2 v) -> Subst c v -> Subst c2 v mapRange f subst@(Subst _) = Subst $ M.mapMaybeWithKey (\i t -> filterRefl i (f t)) (sMap subst) where filterRefl i (viewTerm -> Lit (Var j)) | i == j = Nothing filterRefl _ t = Just t -- Queries ---------------------------------------------------------------------- -- | @dom subst@ returns the domain of the substitution @substs@. dom :: Subst c v -> [v] dom = M.keys . sMap -- | @range subst@ returns the range of the substitution @substs@. range :: Subst c v -> [VTerm c v] range = M.elems . sMap -- | @varsRange subst@ returns all variables in the range of the substitution. varsRange :: IsVar v => Subst c v -> [v] varsRange = varsVTerm . fAppList . range -- Views ---------------------------------------------------------------------- -- | Convert substitution to list. substToList :: Subst c v -> [(v,VTerm c v)] substToList = M.toList . sMap -- | @substToPairOn vs sigma@ converts the list of variables @[x1,..,xk]@ to -- @[sigma(x1),..,sigma(xk)]@. substToListOn :: (IsConst c, IsVar v) => [v] -> Subst c v -> [VTerm c v] substToListOn vs subst = map (applyLit subst) (map Var vs) -- | Returns the image of @i@ under @subst@ if @i@ is in the domain of @subst@. imageOf :: IsVar v => Subst c v -> v -> Maybe (VTerm c v) imageOf subst i = M.lookup i (sMap subst) ---------------------------------------------------------------------- -- Boilerplate instances ---------------------------------------------------------------------- instance (Show v, Show c) => Show (Subst c v) where show subst@(Subst _) = "{" ++ mappings ++"}" where mappings = intercalate ", " [ show t ++" <~ "++show v | (v,t) <- substToList subst ] instance Sized (Subst c v) where size = sum . map size . range -- Instances ------------ instance Ord c => HasFrees (LSubst c) where foldFrees f = foldFrees f . sMap foldFreesOcc = mempty -- we ignore occurences in substitutions for now mapFrees f = (substFromList <$>) . mapFrees f . substToList -- | Types that support the application of 'LSubst's. class Apply t where apply :: LNSubst -> t -> t instance Apply LVar where apply subst x = maybe x extractVar $ imageOf subst x where extractVar (viewTerm -> Lit (Var x')) = x' extractVar t = error $ "apply (LVar): variable '" ++ show x ++ "' substituted with term '" ++ show t ++ "'" instance Apply LNTerm where apply subst = applyVTerm subst instance Apply BLVar where apply _ x@(Bound _) = x apply subst x@(Free v) = maybe x extractVar $ imageOf subst v where extractVar (viewTerm -> Lit (Var v')) = Free v' extractVar _t = error $ "apply (BLVar): variable '" ++ show v ++ "' substituted with term '" -- ++ show _t ++ "'" instance Apply BLTerm where apply subst = (`bindTerm` applyBLLit) where applyBLLit :: Lit Name BLVar -> BLTerm applyBLLit l@(Var (Free v)) = maybe (lit l) (fmapTerm (fmap Free)) (imageOf subst v) applyBLLit l = lit l instance Apply () where apply _ = id instance Apply Char where apply _ = id instance Apply Int where apply _ = id instance Apply Bool where apply _ = id instance (Apply a, Apply b) => Apply (a, b) where apply subst (x,y) = (apply subst x, apply subst y) instance Apply a => Apply (Maybe a) where apply subst = fmap (apply subst) instance (Apply a, Apply b) => Apply (Either a b) where apply subst = either (Left . apply subst) (Right . apply subst) instance Apply a => Apply [a] where apply subst = fmap (apply subst) instance Apply a => Apply (Map k a) where apply subst = fmap (apply subst) instance Apply a => Apply (Conj a) where apply subst = fmap (apply subst) instance Apply a => Apply (Disj a) where apply subst = fmap (apply subst) instance (Ord a, Apply a) => Apply (S.Set a) where apply subst = S.map (apply subst) instance Apply t => Apply (Equal t) where apply subst = fmap (apply subst) ---------------------------------------------------------------------- -- Pretty Printing ---------------------------------------------------------------------- -- | Pretty print a substitution. prettySubst :: (Ord c, Ord v, HighlightDocument d, Show c, Show v) => (v -> d) -> (Lit c v -> d) -> Subst c v -> [d] prettySubst ppVar ppLit = map pp . M.toList . equivClasses . substToList where pp (t, vs) = prettyTerm ppLit t <-> operator_ " <~ {" <> (fsep $ punctuate comma $ map ppVar $ S.toList vs) <> operator_ "}" -- | Pretty print a substitution with logical variables. prettyLNSubst :: (Show (Lit c LVar), Ord c, HighlightDocument d, Show c) => LSubst c -> d prettyLNSubst = vcat . prettySubst (text . show) (text . show)
ekr/tamarin-prover
lib/term/src/Term/Substitution/SubstVFree.hs
gpl-3.0
9,846
0
13
2,345
2,815
1,466
1,349
161
5
module Language.Soi.Parser ( parseFile ) where import ClassyPrelude import Language.Soi.Internal.ParseMonad import Language.Soi.Internal.Parser parseFile :: String -> ByteString -> Either ParseError File parseFile = runParser parseFileP
HMPerson1/soi
src/Language/Soi/Parser.hs
gpl-3.0
279
0
7
67
55
33
22
7
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.LandingPages.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the list of landing pages for the specified campaign. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.landingPages.list@. module Network.Google.Resource.DFAReporting.LandingPages.List ( -- * REST Resource LandingPagesListResource -- * Creating a Request , landingPagesList , LandingPagesList -- * Request Lenses , lplCampaignId , lplProFileId ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.landingPages.list@ method which the -- 'LandingPagesList' request conforms to. type LandingPagesListResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "campaigns" :> Capture "campaignId" (Textual Int64) :> "landingPages" :> QueryParam "alt" AltJSON :> Get '[JSON] LandingPagesListResponse -- | Retrieves the list of landing pages for the specified campaign. -- -- /See:/ 'landingPagesList' smart constructor. data LandingPagesList = LandingPagesList' { _lplCampaignId :: !(Textual Int64) , _lplProFileId :: !(Textual Int64) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LandingPagesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lplCampaignId' -- -- * 'lplProFileId' landingPagesList :: Int64 -- ^ 'lplCampaignId' -> Int64 -- ^ 'lplProFileId' -> LandingPagesList landingPagesList pLplCampaignId_ pLplProFileId_ = LandingPagesList' { _lplCampaignId = _Coerce # pLplCampaignId_ , _lplProFileId = _Coerce # pLplProFileId_ } -- | Landing page campaign ID. lplCampaignId :: Lens' LandingPagesList Int64 lplCampaignId = lens _lplCampaignId (\ s a -> s{_lplCampaignId = a}) . _Coerce -- | User profile ID associated with this request. lplProFileId :: Lens' LandingPagesList Int64 lplProFileId = lens _lplProFileId (\ s a -> s{_lplProFileId = a}) . _Coerce instance GoogleRequest LandingPagesList where type Rs LandingPagesList = LandingPagesListResponse type Scopes LandingPagesList = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient LandingPagesList'{..} = go _lplProFileId _lplCampaignId (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy LandingPagesListResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/LandingPages/List.hs
mpl-2.0
3,490
0
15
811
425
251
174
67
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Run.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Run.Types.Product where import Network.Google.Prelude import Network.Google.Run.Types.Sum -- | (Optional) Only memory and CPU are supported. Note: The only supported -- values for CPU are \'1\' and \'2\'. Requests describes the minimum -- amount of compute resources required. If Requests is omitted for a -- container, it defaults to Limits if that is explicitly specified, -- otherwise to an implementation-defined value. The values of the map is -- string form of the \'quantity\' k8s type: -- https:\/\/github.com\/kubernetes\/kubernetes\/blob\/master\/staging\/src\/k8s.io\/apimachinery\/pkg\/api\/resource\/quantity.go -- -- /See:/ 'resourceRequirementsRequests' smart constructor. newtype ResourceRequirementsRequests = ResourceRequirementsRequests' { _rrrAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResourceRequirementsRequests' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrrAddtional' resourceRequirementsRequests :: HashMap Text Text -- ^ 'rrrAddtional' -> ResourceRequirementsRequests resourceRequirementsRequests pRrrAddtional_ = ResourceRequirementsRequests' {_rrrAddtional = _Coerce # pRrrAddtional_} rrrAddtional :: Lens' ResourceRequirementsRequests (HashMap Text Text) rrrAddtional = lens _rrrAddtional (\ s a -> s{_rrrAddtional = a}) . _Coerce instance FromJSON ResourceRequirementsRequests where parseJSON = withObject "ResourceRequirementsRequests" (\ o -> ResourceRequirementsRequests' <$> (parseJSONObject o)) instance ToJSON ResourceRequirementsRequests where toJSON = toJSON . _rrrAddtional -- | Not supported by Cloud Run Selects a key from a ConfigMap. -- -- /See:/ 'configMapKeySelector' smart constructor. data ConfigMapKeySelector = ConfigMapKeySelector' { _cmksKey :: !(Maybe Text) , _cmksName :: !(Maybe Text) , _cmksLocalObjectReference :: !(Maybe LocalObjectReference) , _cmksOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ConfigMapKeySelector' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmksKey' -- -- * 'cmksName' -- -- * 'cmksLocalObjectReference' -- -- * 'cmksOptional' configMapKeySelector :: ConfigMapKeySelector configMapKeySelector = ConfigMapKeySelector' { _cmksKey = Nothing , _cmksName = Nothing , _cmksLocalObjectReference = Nothing , _cmksOptional = Nothing } -- | The key to select. cmksKey :: Lens' ConfigMapKeySelector (Maybe Text) cmksKey = lens _cmksKey (\ s a -> s{_cmksKey = a}) -- | The ConfigMap to select from. cmksName :: Lens' ConfigMapKeySelector (Maybe Text) cmksName = lens _cmksName (\ s a -> s{_cmksName = a}) -- | This field should not be used directly as it is meant to be inlined -- directly into the message. Use the \"name\" field instead. cmksLocalObjectReference :: Lens' ConfigMapKeySelector (Maybe LocalObjectReference) cmksLocalObjectReference = lens _cmksLocalObjectReference (\ s a -> s{_cmksLocalObjectReference = a}) -- | (Optional) Specify whether the ConfigMap or its key must be defined cmksOptional :: Lens' ConfigMapKeySelector (Maybe Bool) cmksOptional = lens _cmksOptional (\ s a -> s{_cmksOptional = a}) instance FromJSON ConfigMapKeySelector where parseJSON = withObject "ConfigMapKeySelector" (\ o -> ConfigMapKeySelector' <$> (o .:? "key") <*> (o .:? "name") <*> (o .:? "localObjectReference") <*> (o .:? "optional")) instance ToJSON ConfigMapKeySelector where toJSON ConfigMapKeySelector'{..} = object (catMaybes [("key" .=) <$> _cmksKey, ("name" .=) <$> _cmksName, ("localObjectReference" .=) <$> _cmksLocalObjectReference, ("optional" .=) <$> _cmksOptional]) -- | SecretKeySelector selects a key of a Secret. -- -- /See:/ 'secretKeySelector' smart constructor. data SecretKeySelector = SecretKeySelector' { _sksKey :: !(Maybe Text) , _sksName :: !(Maybe Text) , _sksLocalObjectReference :: !(Maybe LocalObjectReference) , _sksOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecretKeySelector' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sksKey' -- -- * 'sksName' -- -- * 'sksLocalObjectReference' -- -- * 'sksOptional' secretKeySelector :: SecretKeySelector secretKeySelector = SecretKeySelector' { _sksKey = Nothing , _sksName = Nothing , _sksLocalObjectReference = Nothing , _sksOptional = Nothing } -- | A Cloud Secret Manager secret version. Must be \'latest\' for the latest -- version or an integer for a specific version. The key of the secret to -- select from. Must be a valid secret key. sksKey :: Lens' SecretKeySelector (Maybe Text) sksKey = lens _sksKey (\ s a -> s{_sksKey = a}) -- | The name of the secret in Cloud Secret Manager. By default, the secret -- is assumed to be in the same project. If the secret is in another -- project, you must define an alias. An alias definition has the form: -- :projects\/\/secrets\/. If multiple alias definitions are needed, they -- must be separated by commas. The alias definitions must be set on the -- run.googleapis.com\/secrets annotation. The name of the secret in the -- pod\'s namespace to select from. sksName :: Lens' SecretKeySelector (Maybe Text) sksName = lens _sksName (\ s a -> s{_sksName = a}) -- | This field should not be used directly as it is meant to be inlined -- directly into the message. Use the \"name\" field instead. sksLocalObjectReference :: Lens' SecretKeySelector (Maybe LocalObjectReference) sksLocalObjectReference = lens _sksLocalObjectReference (\ s a -> s{_sksLocalObjectReference = a}) -- | (Optional) Specify whether the Secret or its key must be defined sksOptional :: Lens' SecretKeySelector (Maybe Bool) sksOptional = lens _sksOptional (\ s a -> s{_sksOptional = a}) instance FromJSON SecretKeySelector where parseJSON = withObject "SecretKeySelector" (\ o -> SecretKeySelector' <$> (o .:? "key") <*> (o .:? "name") <*> (o .:? "localObjectReference") <*> (o .:? "optional")) instance ToJSON SecretKeySelector where toJSON SecretKeySelector'{..} = object (catMaybes [("key" .=) <$> _sksKey, ("name" .=) <$> _sksName, ("localObjectReference" .=) <$> _sksLocalObjectReference, ("optional" .=) <$> _sksOptional]) -- | Not supported by Cloud Run TCPSocketAction describes an action based on -- opening a socket -- -- /See:/ 'tcpSocketAction' smart constructor. data TCPSocketAction = TCPSocketAction' { _tsaHost :: !(Maybe Text) , _tsaPort :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TCPSocketAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsaHost' -- -- * 'tsaPort' tcpSocketAction :: TCPSocketAction tcpSocketAction = TCPSocketAction' {_tsaHost = Nothing, _tsaPort = Nothing} -- | (Optional) Optional: Host name to connect to, defaults to the pod IP. tsaHost :: Lens' TCPSocketAction (Maybe Text) tsaHost = lens _tsaHost (\ s a -> s{_tsaHost = a}) -- | Number or name of the port to access on the container. Number must be in -- the range 1 to 65535. Name must be an IANA_SVC_NAME. This field is -- currently limited to integer types only because of proto\'s inability to -- properly support the IntOrString golang type. tsaPort :: Lens' TCPSocketAction (Maybe Int32) tsaPort = lens _tsaPort (\ s a -> s{_tsaPort = a}) . mapping _Coerce instance FromJSON TCPSocketAction where parseJSON = withObject "TCPSocketAction" (\ o -> TCPSocketAction' <$> (o .:? "host") <*> (o .:? "port")) instance ToJSON TCPSocketAction where toJSON TCPSocketAction'{..} = object (catMaybes [("host" .=) <$> _tsaHost, ("port" .=) <$> _tsaPort]) -- | Status is a return value for calls that don\'t return other objects -- -- /See:/ 'status' smart constructor. data Status = Status' { _sStatus :: !(Maybe Text) , _sReason :: !(Maybe Text) , _sDetails :: !(Maybe StatusDetails) , _sMetadata :: !(Maybe ListMeta) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sStatus' -- -- * 'sReason' -- -- * 'sDetails' -- -- * 'sMetadata' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' { _sStatus = Nothing , _sReason = Nothing , _sDetails = Nothing , _sMetadata = Nothing , _sCode = Nothing , _sMessage = Nothing } -- | Status of the operation. One of: \"Success\" or \"Failure\". More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/sig-architecture\/api-conventions.md#spec-and-status -- +optional sStatus :: Lens' Status (Maybe Text) sStatus = lens _sStatus (\ s a -> s{_sStatus = a}) -- | A machine-readable description of why this operation is in the -- \"Failure\" status. If this value is empty there is no information -- available. A Reason clarifies an HTTP status code but does not override -- it. +optional sReason :: Lens' Status (Maybe Text) sReason = lens _sReason (\ s a -> s{_sReason = a}) -- | Extended data associated with the reason. Each reason may define its own -- extended details. This field is optional and the data returned is not -- guaranteed to conform to any schema except that defined by the reason -- type. +optional sDetails :: Lens' Status (Maybe StatusDetails) sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) -- | Standard list metadata. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/sig-architecture\/api-conventions.md#types-kinds -- +optional sMetadata :: Lens' Status (Maybe ListMeta) sMetadata = lens _sMetadata (\ s a -> s{_sMetadata = a}) -- | Suggested HTTP return code for this status, 0 if not set. +optional sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A human-readable description of the status of this operation. +optional sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "status") <*> (o .:? "reason") <*> (o .:? "details") <*> (o .:? "metadata") <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("status" .=) <$> _sStatus, ("reason" .=) <$> _sReason, ("details" .=) <$> _sDetails, ("metadata" .=) <$> _sMetadata, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | Information for connecting over HTTP(s). -- -- /See:/ 'addressable' smart constructor. newtype Addressable = Addressable' { _aURL :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Addressable' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aURL' addressable :: Addressable addressable = Addressable' {_aURL = Nothing} aURL :: Lens' Addressable (Maybe Text) aURL = lens _aURL (\ s a -> s{_aURL = a}) instance FromJSON Addressable where parseJSON = withObject "Addressable" (\ o -> Addressable' <$> (o .:? "url")) instance ToJSON Addressable where toJSON Addressable'{..} = object (catMaybes [("url" .=) <$> _aURL]) -- | (Optional) Annotations is an unstructured key value map stored with a -- resource that may be set by external tools to store and retrieve -- arbitrary metadata. They are not queryable and should be preserved when -- modifying objects. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/annotations -- -- /See:/ 'objectMetaAnnotations' smart constructor. newtype ObjectMetaAnnotations = ObjectMetaAnnotations' { _omaAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ObjectMetaAnnotations' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omaAddtional' objectMetaAnnotations :: HashMap Text Text -- ^ 'omaAddtional' -> ObjectMetaAnnotations objectMetaAnnotations pOmaAddtional_ = ObjectMetaAnnotations' {_omaAddtional = _Coerce # pOmaAddtional_} omaAddtional :: Lens' ObjectMetaAnnotations (HashMap Text Text) omaAddtional = lens _omaAddtional (\ s a -> s{_omaAddtional = a}) . _Coerce instance FromJSON ObjectMetaAnnotations where parseJSON = withObject "ObjectMetaAnnotations" (\ o -> ObjectMetaAnnotations' <$> (parseJSONObject o)) instance ToJSON ObjectMetaAnnotations where toJSON = toJSON . _omaAddtional -- | TrafficTarget holds a single entry of the routing table for a Route. -- -- /See:/ 'trafficTarget' smart constructor. data TrafficTarget = TrafficTarget' { _ttRevisionName :: !(Maybe Text) , _ttConfigurationName :: !(Maybe Text) , _ttTag :: !(Maybe Text) , _ttLatestRevision :: !(Maybe Bool) , _ttURL :: !(Maybe Text) , _ttPercent :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TrafficTarget' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ttRevisionName' -- -- * 'ttConfigurationName' -- -- * 'ttTag' -- -- * 'ttLatestRevision' -- -- * 'ttURL' -- -- * 'ttPercent' trafficTarget :: TrafficTarget trafficTarget = TrafficTarget' { _ttRevisionName = Nothing , _ttConfigurationName = Nothing , _ttTag = Nothing , _ttLatestRevision = Nothing , _ttURL = Nothing , _ttPercent = Nothing } -- | RevisionName of a specific revision to which to send this portion of -- traffic. This is mutually exclusive with ConfigurationName. Providing -- RevisionName in spec is not currently supported by Cloud Run. ttRevisionName :: Lens' TrafficTarget (Maybe Text) ttRevisionName = lens _ttRevisionName (\ s a -> s{_ttRevisionName = a}) -- | ConfigurationName of a configuration to whose latest revision we will -- send this portion of traffic. When the -- \"status.latestReadyRevisionName\" of the referenced configuration -- changes, we will automatically migrate traffic from the prior \"latest -- ready\" revision to the new one. This field is never set in Route\'s -- status, only its spec. This is mutually exclusive with RevisionName. -- Cloud Run currently supports a single ConfigurationName. ttConfigurationName :: Lens' TrafficTarget (Maybe Text) ttConfigurationName = lens _ttConfigurationName (\ s a -> s{_ttConfigurationName = a}) -- | Optional. Tag is used to expose a dedicated url for referencing this -- target exclusively. ttTag :: Lens' TrafficTarget (Maybe Text) ttTag = lens _ttTag (\ s a -> s{_ttTag = a}) -- | Optional. LatestRevision may be provided to indicate that the latest -- ready Revision of the Configuration should be used for this traffic -- target. When provided LatestRevision must be true if RevisionName is -- empty; it must be false when RevisionName is non-empty. ttLatestRevision :: Lens' TrafficTarget (Maybe Bool) ttLatestRevision = lens _ttLatestRevision (\ s a -> s{_ttLatestRevision = a}) -- | Output only. URL displays the URL for accessing tagged traffic targets. -- URL is displayed in status, and is disallowed on spec. URL must contain -- a scheme (e.g. http:\/\/) and a hostname, but may not contain anything -- else (e.g. basic auth, url path, etc.) ttURL :: Lens' TrafficTarget (Maybe Text) ttURL = lens _ttURL (\ s a -> s{_ttURL = a}) -- | Percent specifies percent of the traffic to this Revision or -- Configuration. This defaults to zero if unspecified. Cloud Run currently -- requires 100 percent for a single ConfigurationName TrafficTarget entry. ttPercent :: Lens' TrafficTarget (Maybe Int32) ttPercent = lens _ttPercent (\ s a -> s{_ttPercent = a}) . mapping _Coerce instance FromJSON TrafficTarget where parseJSON = withObject "TrafficTarget" (\ o -> TrafficTarget' <$> (o .:? "revisionName") <*> (o .:? "configurationName") <*> (o .:? "tag") <*> (o .:? "latestRevision") <*> (o .:? "url") <*> (o .:? "percent")) instance ToJSON TrafficTarget where toJSON TrafficTarget'{..} = object (catMaybes [("revisionName" .=) <$> _ttRevisionName, ("configurationName" .=) <$> _ttConfigurationName, ("tag" .=) <$> _ttTag, ("latestRevision" .=) <$> _ttLatestRevision, ("url" .=) <$> _ttURL, ("percent" .=) <$> _ttPercent]) -- | Specifies the audit configuration for a service. The configuration -- determines which permission types are logged, and what identities, if -- any, are exempted from logging. An AuditConfig must have one or more -- AuditLogConfigs. If there are AuditConfigs for both \`allServices\` and -- a specific service, the union of the two AuditConfigs is used for that -- service: the log_types specified in each AuditConfig are enabled, and -- the exempted_members in each AuditLogConfig are exempted. Example Policy -- with multiple AuditConfigs: { \"audit_configs\": [ { \"service\": -- \"allServices\", \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" }, { \"log_type\": \"ADMIN_READ\" } ] }, { \"service\": -- \"sampleservice.googleapis.com\", \"audit_log_configs\": [ { -- \"log_type\": \"DATA_READ\" }, { \"log_type\": \"DATA_WRITE\", -- \"exempted_members\": [ \"user:aliya\'example.com\" ] } ] } ] } For -- sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ -- logging. It also exempts jose\'example.com from DATA_READ logging, and -- aliya\'example.com from DATA_WRITE logging. -- -- /See:/ 'auditConfig' smart constructor. data AuditConfig = AuditConfig' { _acService :: !(Maybe Text) , _acAuditLogConfigs :: !(Maybe [AuditLogConfig]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acService' -- -- * 'acAuditLogConfigs' auditConfig :: AuditConfig auditConfig = AuditConfig' {_acService = Nothing, _acAuditLogConfigs = Nothing} -- | Specifies a service that will be enabled for audit logging. For example, -- \`storage.googleapis.com\`, \`cloudsql.googleapis.com\`. \`allServices\` -- is a special value that covers all services. acService :: Lens' AuditConfig (Maybe Text) acService = lens _acService (\ s a -> s{_acService = a}) -- | The configuration for logging of each type of permission. acAuditLogConfigs :: Lens' AuditConfig [AuditLogConfig] acAuditLogConfigs = lens _acAuditLogConfigs (\ s a -> s{_acAuditLogConfigs = a}) . _Default . _Coerce instance FromJSON AuditConfig where parseJSON = withObject "AuditConfig" (\ o -> AuditConfig' <$> (o .:? "service") <*> (o .:? "auditLogConfigs" .!= mempty)) instance ToJSON AuditConfig where toJSON AuditConfig'{..} = object (catMaybes [("service" .=) <$> _acService, ("auditLogConfigs" .=) <$> _acAuditLogConfigs]) -- | A domain that a user has been authorized to administer. To authorize use -- of a domain, verify ownership via [Webmaster -- Central](https:\/\/www.google.com\/webmasters\/verification\/home). -- -- /See:/ 'authorizedDomain' smart constructor. data AuthorizedDomain = AuthorizedDomain' { _adName :: !(Maybe Text) , _adId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuthorizedDomain' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adName' -- -- * 'adId' authorizedDomain :: AuthorizedDomain authorizedDomain = AuthorizedDomain' {_adName = Nothing, _adId = Nothing} -- | Deprecated Read only. Full path to the \`AuthorizedDomain\` resource in -- the API. Example: -- \`projects\/myproject\/authorizedDomains\/example.com\`. adName :: Lens' AuthorizedDomain (Maybe Text) adName = lens _adName (\ s a -> s{_adName = a}) -- | Relative name of the domain authorized for use. Example: -- \`example.com\`. adId :: Lens' AuthorizedDomain (Maybe Text) adId = lens _adId (\ s a -> s{_adId = a}) instance FromJSON AuthorizedDomain where parseJSON = withObject "AuthorizedDomain" (\ o -> AuthorizedDomain' <$> (o .:? "name") <*> (o .:? "id")) instance ToJSON AuthorizedDomain where toJSON AuthorizedDomain'{..} = object (catMaybes [("name" .=) <$> _adName, ("id" .=) <$> _adId]) -- | Not supported by Cloud Run HTTPHeader describes a custom header to be -- used in HTTP probes -- -- /See:/ 'hTTPHeader' smart constructor. data HTTPHeader = HTTPHeader' { _httphValue :: !(Maybe Text) , _httphName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPHeader' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httphValue' -- -- * 'httphName' hTTPHeader :: HTTPHeader hTTPHeader = HTTPHeader' {_httphValue = Nothing, _httphName = Nothing} -- | The header field value httphValue :: Lens' HTTPHeader (Maybe Text) httphValue = lens _httphValue (\ s a -> s{_httphValue = a}) -- | The header field name httphName :: Lens' HTTPHeader (Maybe Text) httphName = lens _httphName (\ s a -> s{_httphName = a}) instance FromJSON HTTPHeader where parseJSON = withObject "HTTPHeader" (\ o -> HTTPHeader' <$> (o .:? "value") <*> (o .:? "name")) instance ToJSON HTTPHeader where toJSON HTTPHeader'{..} = object (catMaybes [("value" .=) <$> _httphValue, ("name" .=) <$> _httphName]) -- | A list of Service resources. -- -- /See:/ 'listServicesResponse' smart constructor. data ListServicesResponse = ListServicesResponse' { _lsrAPIVersion :: !(Maybe Text) , _lsrKind :: !(Maybe Text) , _lsrItems :: !(Maybe [Service]) , _lsrUnreachable :: !(Maybe [Text]) , _lsrMetadata :: !(Maybe ListMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListServicesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsrAPIVersion' -- -- * 'lsrKind' -- -- * 'lsrItems' -- -- * 'lsrUnreachable' -- -- * 'lsrMetadata' listServicesResponse :: ListServicesResponse listServicesResponse = ListServicesResponse' { _lsrAPIVersion = Nothing , _lsrKind = Nothing , _lsrItems = Nothing , _lsrUnreachable = Nothing , _lsrMetadata = Nothing } -- | The API version for this call such as \"serving.knative.dev\/v1\". lsrAPIVersion :: Lens' ListServicesResponse (Maybe Text) lsrAPIVersion = lens _lsrAPIVersion (\ s a -> s{_lsrAPIVersion = a}) -- | The kind of this resource, in this case \"ServiceList\". lsrKind :: Lens' ListServicesResponse (Maybe Text) lsrKind = lens _lsrKind (\ s a -> s{_lsrKind = a}) -- | List of Services. lsrItems :: Lens' ListServicesResponse [Service] lsrItems = lens _lsrItems (\ s a -> s{_lsrItems = a}) . _Default . _Coerce -- | Locations that could not be reached. lsrUnreachable :: Lens' ListServicesResponse [Text] lsrUnreachable = lens _lsrUnreachable (\ s a -> s{_lsrUnreachable = a}) . _Default . _Coerce -- | Metadata associated with this Service list. lsrMetadata :: Lens' ListServicesResponse (Maybe ListMeta) lsrMetadata = lens _lsrMetadata (\ s a -> s{_lsrMetadata = a}) instance FromJSON ListServicesResponse where parseJSON = withObject "ListServicesResponse" (\ o -> ListServicesResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "unreachable" .!= mempty) <*> (o .:? "metadata")) instance ToJSON ListServicesResponse where toJSON ListServicesResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _lsrAPIVersion, ("kind" .=) <$> _lsrKind, ("items" .=) <$> _lsrItems, ("unreachable" .=) <$> _lsrUnreachable, ("metadata" .=) <$> _lsrMetadata]) -- | Represents a textual expression in the Common Expression Language (CEL) -- syntax. CEL is a C-like expression language. The syntax and semantics of -- CEL are documented at https:\/\/github.com\/google\/cel-spec. Example -- (Comparison): title: \"Summary size limit\" description: \"Determines if -- a summary is less than 100 chars\" expression: \"document.summary.size() -- \< 100\" Example (Equality): title: \"Requestor is owner\" description: -- \"Determines if requestor is the document owner\" expression: -- \"document.owner == request.auth.claims.email\" Example (Logic): title: -- \"Public documents\" description: \"Determine whether the document -- should be publicly visible\" expression: \"document.type != \'private\' -- && document.type != \'internal\'\" Example (Data Manipulation): title: -- \"Notification string\" description: \"Create a notification string with -- a timestamp.\" expression: \"\'New message received at \' + -- string(document.create_time)\" The exact variables and functions that -- may be referenced within an expression are determined by the service -- that evaluates it. See the service documentation for additional -- information. -- -- /See:/ 'expr' smart constructor. data Expr = Expr' { _eLocation :: !(Maybe Text) , _eExpression :: !(Maybe Text) , _eTitle :: !(Maybe Text) , _eDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Expr' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eLocation' -- -- * 'eExpression' -- -- * 'eTitle' -- -- * 'eDescription' expr :: Expr expr = Expr' { _eLocation = Nothing , _eExpression = Nothing , _eTitle = Nothing , _eDescription = Nothing } -- | Optional. String indicating the location of the expression for error -- reporting, e.g. a file name and a position in the file. eLocation :: Lens' Expr (Maybe Text) eLocation = lens _eLocation (\ s a -> s{_eLocation = a}) -- | Textual representation of an expression in Common Expression Language -- syntax. eExpression :: Lens' Expr (Maybe Text) eExpression = lens _eExpression (\ s a -> s{_eExpression = a}) -- | Optional. Title for the expression, i.e. a short string describing its -- purpose. This can be used e.g. in UIs which allow to enter the -- expression. eTitle :: Lens' Expr (Maybe Text) eTitle = lens _eTitle (\ s a -> s{_eTitle = a}) -- | Optional. Description of the expression. This is a longer text which -- describes the expression, e.g. when hovered over it in a UI. eDescription :: Lens' Expr (Maybe Text) eDescription = lens _eDescription (\ s a -> s{_eDescription = a}) instance FromJSON Expr where parseJSON = withObject "Expr" (\ o -> Expr' <$> (o .:? "location") <*> (o .:? "expression") <*> (o .:? "title") <*> (o .:? "description")) instance ToJSON Expr where toJSON Expr'{..} = object (catMaybes [("location" .=) <$> _eLocation, ("expression" .=) <$> _eExpression, ("title" .=) <$> _eTitle, ("description" .=) <$> _eDescription]) -- | A DNS resource record. -- -- /See:/ 'resourceRecord' smart constructor. data ResourceRecord = ResourceRecord' { _rrRrData :: !(Maybe Text) , _rrName :: !(Maybe Text) , _rrType :: !(Maybe ResourceRecordType) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResourceRecord' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrRrData' -- -- * 'rrName' -- -- * 'rrType' resourceRecord :: ResourceRecord resourceRecord = ResourceRecord' {_rrRrData = Nothing, _rrName = Nothing, _rrType = Nothing} -- | Data for this record. Values vary by record type, as defined in RFC 1035 -- (section 5) and RFC 1034 (section 3.6.1). rrRrData :: Lens' ResourceRecord (Maybe Text) rrRrData = lens _rrRrData (\ s a -> s{_rrRrData = a}) -- | Relative name of the object affected by this record. Only applicable for -- \`CNAME\` records. Example: \'www\'. rrName :: Lens' ResourceRecord (Maybe Text) rrName = lens _rrName (\ s a -> s{_rrName = a}) -- | Resource record type. Example: \`AAAA\`. rrType :: Lens' ResourceRecord (Maybe ResourceRecordType) rrType = lens _rrType (\ s a -> s{_rrType = a}) instance FromJSON ResourceRecord where parseJSON = withObject "ResourceRecord" (\ o -> ResourceRecord' <$> (o .:? "rrdata") <*> (o .:? "name") <*> (o .:? "type")) instance ToJSON ResourceRecord where toJSON ResourceRecord'{..} = object (catMaybes [("rrdata" .=) <$> _rrRrData, ("name" .=) <$> _rrName, ("type" .=) <$> _rrType]) -- | The response message for Locations.ListLocations. -- -- /See:/ 'listLocationsResponse' smart constructor. data ListLocationsResponse = ListLocationsResponse' { _llrNextPageToken :: !(Maybe Text) , _llrLocations :: !(Maybe [Location]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListLocationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llrNextPageToken' -- -- * 'llrLocations' listLocationsResponse :: ListLocationsResponse listLocationsResponse = ListLocationsResponse' {_llrNextPageToken = Nothing, _llrLocations = Nothing} -- | The standard List next-page token. llrNextPageToken :: Lens' ListLocationsResponse (Maybe Text) llrNextPageToken = lens _llrNextPageToken (\ s a -> s{_llrNextPageToken = a}) -- | A list of locations that matches the specified filter in the request. llrLocations :: Lens' ListLocationsResponse [Location] llrLocations = lens _llrLocations (\ s a -> s{_llrLocations = a}) . _Default . _Coerce instance FromJSON ListLocationsResponse where parseJSON = withObject "ListLocationsResponse" (\ o -> ListLocationsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "locations" .!= mempty)) instance ToJSON ListLocationsResponse where toJSON ListLocationsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _llrNextPageToken, ("locations" .=) <$> _llrLocations]) -- | Not supported by Cloud Run Probe describes a health check to be -- performed against a container to determine whether it is alive or ready -- to receive traffic. -- -- /See:/ 'probe' smart constructor. data Probe = Probe' { _pSuccessThreshold :: !(Maybe (Textual Int32)) , _pFailureThreshold :: !(Maybe (Textual Int32)) , _pExec :: !(Maybe ExecAction) , _pTCPSocket :: !(Maybe TCPSocketAction) , _pTimeoutSeconds :: !(Maybe (Textual Int32)) , _pInitialDelaySeconds :: !(Maybe (Textual Int32)) , _pHTTPGet :: !(Maybe HTTPGetAction) , _pPeriodSeconds :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Probe' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pSuccessThreshold' -- -- * 'pFailureThreshold' -- -- * 'pExec' -- -- * 'pTCPSocket' -- -- * 'pTimeoutSeconds' -- -- * 'pInitialDelaySeconds' -- -- * 'pHTTPGet' -- -- * 'pPeriodSeconds' probe :: Probe probe = Probe' { _pSuccessThreshold = Nothing , _pFailureThreshold = Nothing , _pExec = Nothing , _pTCPSocket = Nothing , _pTimeoutSeconds = Nothing , _pInitialDelaySeconds = Nothing , _pHTTPGet = Nothing , _pPeriodSeconds = Nothing } -- | (Optional) Minimum consecutive successes for the probe to be considered -- successful after having failed. Defaults to 1. Must be 1 for liveness. -- Minimum value is 1. pSuccessThreshold :: Lens' Probe (Maybe Int32) pSuccessThreshold = lens _pSuccessThreshold (\ s a -> s{_pSuccessThreshold = a}) . mapping _Coerce -- | (Optional) Minimum consecutive failures for the probe to be considered -- failed after having succeeded. Defaults to 3. Minimum value is 1. pFailureThreshold :: Lens' Probe (Maybe Int32) pFailureThreshold = lens _pFailureThreshold (\ s a -> s{_pFailureThreshold = a}) . mapping _Coerce -- | (Optional) One and only one of the following should be specified. Exec -- specifies the action to take. A field inlined from the Handler message. pExec :: Lens' Probe (Maybe ExecAction) pExec = lens _pExec (\ s a -> s{_pExec = a}) -- | (Optional) TCPSocket specifies an action involving a TCP port. TCP hooks -- not yet supported A field inlined from the Handler message. pTCPSocket :: Lens' Probe (Maybe TCPSocketAction) pTCPSocket = lens _pTCPSocket (\ s a -> s{_pTCPSocket = a}) -- | (Optional) Number of seconds after which the probe times out. Defaults -- to 1 second. Minimum value is 1. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/workloads\/pods\/pod-lifecycle#container-probes pTimeoutSeconds :: Lens' Probe (Maybe Int32) pTimeoutSeconds = lens _pTimeoutSeconds (\ s a -> s{_pTimeoutSeconds = a}) . mapping _Coerce -- | (Optional) Number of seconds after the container has started before -- liveness probes are initiated. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/workloads\/pods\/pod-lifecycle#container-probes pInitialDelaySeconds :: Lens' Probe (Maybe Int32) pInitialDelaySeconds = lens _pInitialDelaySeconds (\ s a -> s{_pInitialDelaySeconds = a}) . mapping _Coerce -- | (Optional) HTTPGet specifies the http request to perform. A field -- inlined from the Handler message. pHTTPGet :: Lens' Probe (Maybe HTTPGetAction) pHTTPGet = lens _pHTTPGet (\ s a -> s{_pHTTPGet = a}) -- | (Optional) How often (in seconds) to perform the probe. Default to 10 -- seconds. Minimum value is 1. pPeriodSeconds :: Lens' Probe (Maybe Int32) pPeriodSeconds = lens _pPeriodSeconds (\ s a -> s{_pPeriodSeconds = a}) . mapping _Coerce instance FromJSON Probe where parseJSON = withObject "Probe" (\ o -> Probe' <$> (o .:? "successThreshold") <*> (o .:? "failureThreshold") <*> (o .:? "exec") <*> (o .:? "tcpSocket") <*> (o .:? "timeoutSeconds") <*> (o .:? "initialDelaySeconds") <*> (o .:? "httpGet") <*> (o .:? "periodSeconds")) instance ToJSON Probe where toJSON Probe'{..} = object (catMaybes [("successThreshold" .=) <$> _pSuccessThreshold, ("failureThreshold" .=) <$> _pFailureThreshold, ("exec" .=) <$> _pExec, ("tcpSocket" .=) <$> _pTCPSocket, ("timeoutSeconds" .=) <$> _pTimeoutSeconds, ("initialDelaySeconds" .=) <$> _pInitialDelaySeconds, ("httpGet" .=) <$> _pHTTPGet, ("periodSeconds" .=) <$> _pPeriodSeconds]) -- | ListConfigurationsResponse is a list of Configuration resources. -- -- /See:/ 'listConfigurationsResponse' smart constructor. data ListConfigurationsResponse = ListConfigurationsResponse' { _lcrAPIVersion :: !(Maybe Text) , _lcrKind :: !(Maybe Text) , _lcrItems :: !(Maybe [Configuration]) , _lcrUnreachable :: !(Maybe [Text]) , _lcrMetadata :: !(Maybe ListMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListConfigurationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcrAPIVersion' -- -- * 'lcrKind' -- -- * 'lcrItems' -- -- * 'lcrUnreachable' -- -- * 'lcrMetadata' listConfigurationsResponse :: ListConfigurationsResponse listConfigurationsResponse = ListConfigurationsResponse' { _lcrAPIVersion = Nothing , _lcrKind = Nothing , _lcrItems = Nothing , _lcrUnreachable = Nothing , _lcrMetadata = Nothing } -- | The API version for this call such as \"serving.knative.dev\/v1\". lcrAPIVersion :: Lens' ListConfigurationsResponse (Maybe Text) lcrAPIVersion = lens _lcrAPIVersion (\ s a -> s{_lcrAPIVersion = a}) -- | The kind of this resource, in this case \"ConfigurationList\". lcrKind :: Lens' ListConfigurationsResponse (Maybe Text) lcrKind = lens _lcrKind (\ s a -> s{_lcrKind = a}) -- | List of Configurations. lcrItems :: Lens' ListConfigurationsResponse [Configuration] lcrItems = lens _lcrItems (\ s a -> s{_lcrItems = a}) . _Default . _Coerce -- | Locations that could not be reached. lcrUnreachable :: Lens' ListConfigurationsResponse [Text] lcrUnreachable = lens _lcrUnreachable (\ s a -> s{_lcrUnreachable = a}) . _Default . _Coerce -- | Metadata associated with this Configuration list. lcrMetadata :: Lens' ListConfigurationsResponse (Maybe ListMeta) lcrMetadata = lens _lcrMetadata (\ s a -> s{_lcrMetadata = a}) instance FromJSON ListConfigurationsResponse where parseJSON = withObject "ListConfigurationsResponse" (\ o -> ListConfigurationsResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "unreachable" .!= mempty) <*> (o .:? "metadata")) instance ToJSON ListConfigurationsResponse where toJSON ListConfigurationsResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _lcrAPIVersion, ("kind" .=) <$> _lcrKind, ("items" .=) <$> _lcrItems, ("unreachable" .=) <$> _lcrUnreachable, ("metadata" .=) <$> _lcrMetadata]) -- | EnvVarSource represents a source for the value of an EnvVar. -- -- /See:/ 'envVarSource' smart constructor. data EnvVarSource = EnvVarSource' { _evsConfigMapKeyRef :: !(Maybe ConfigMapKeySelector) , _evsSecretKeyRef :: !(Maybe SecretKeySelector) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EnvVarSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'evsConfigMapKeyRef' -- -- * 'evsSecretKeyRef' envVarSource :: EnvVarSource envVarSource = EnvVarSource' {_evsConfigMapKeyRef = Nothing, _evsSecretKeyRef = Nothing} -- | (Optional) Not supported by Cloud Run Selects a key of a ConfigMap. evsConfigMapKeyRef :: Lens' EnvVarSource (Maybe ConfigMapKeySelector) evsConfigMapKeyRef = lens _evsConfigMapKeyRef (\ s a -> s{_evsConfigMapKeyRef = a}) -- | (Optional) Selects a key (version) of a secret in Secret Manager. evsSecretKeyRef :: Lens' EnvVarSource (Maybe SecretKeySelector) evsSecretKeyRef = lens _evsSecretKeyRef (\ s a -> s{_evsSecretKeyRef = a}) instance FromJSON EnvVarSource where parseJSON = withObject "EnvVarSource" (\ o -> EnvVarSource' <$> (o .:? "configMapKeyRef") <*> (o .:? "secretKeyRef")) instance ToJSON EnvVarSource where toJSON EnvVarSource'{..} = object (catMaybes [("configMapKeyRef" .=) <$> _evsConfigMapKeyRef, ("secretKeyRef" .=) <$> _evsSecretKeyRef]) -- | Service acts as a top-level container that manages a set of Routes and -- Configurations which implement a network service. Service exists to -- provide a singular abstraction which can be access controlled, reasoned -- about, and which encapsulates software lifecycle decisions such as -- rollout policy and team resource ownership. Service acts only as an -- orchestrator of the underlying Routes and Configurations (much as a -- kubernetes Deployment orchestrates ReplicaSets). The Service\'s -- controller will track the statuses of its owned Configuration and Route, -- reflecting their statuses and conditions as its own. See also: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/spec\/overview.md#service -- -- /See:/ 'service' smart constructor. data Service = Service' { _serStatus :: !(Maybe ServiceStatus) , _serAPIVersion :: !(Maybe Text) , _serKind :: !(Maybe Text) , _serSpec :: !(Maybe ServiceSpec) , _serMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Service' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'serStatus' -- -- * 'serAPIVersion' -- -- * 'serKind' -- -- * 'serSpec' -- -- * 'serMetadata' service :: Service service = Service' { _serStatus = Nothing , _serAPIVersion = Nothing , _serKind = Nothing , _serSpec = Nothing , _serMetadata = Nothing } -- | Status communicates the observed state of the Service (from the -- controller). serStatus :: Lens' Service (Maybe ServiceStatus) serStatus = lens _serStatus (\ s a -> s{_serStatus = a}) -- | The API version for this call such as \"serving.knative.dev\/v1\". serAPIVersion :: Lens' Service (Maybe Text) serAPIVersion = lens _serAPIVersion (\ s a -> s{_serAPIVersion = a}) -- | The kind of resource, in this case \"Service\". serKind :: Lens' Service (Maybe Text) serKind = lens _serKind (\ s a -> s{_serKind = a}) -- | Spec holds the desired state of the Service (from the client). serSpec :: Lens' Service (Maybe ServiceSpec) serSpec = lens _serSpec (\ s a -> s{_serSpec = a}) -- | Metadata associated with this Service, including name, namespace, -- labels, and annotations. Cloud Run (fully managed) uses the following -- annotation keys to configure features on a Service: * -- \`run.googleapis.com\/ingress\` sets the ingress settings for the -- Service. See [the ingress settings -- documentation](\/run\/docs\/securing\/ingress) for details on -- configuring ingress settings. * \`run.googleapis.com\/ingress-status\` -- is output-only and contains the currently active ingress settings for -- the Service. \`run.googleapis.com\/ingress-status\` may differ from -- \`run.googleapis.com\/ingress\` while the system is processing a change -- to \`run.googleapis.com\/ingress\` or if the system failed to process a -- change to \`run.googleapis.com\/ingress\`. When the system has processed -- all changes successfully \`run.googleapis.com\/ingress-status\` and -- \`run.googleapis.com\/ingress\` are equal. serMetadata :: Lens' Service (Maybe ObjectMeta) serMetadata = lens _serMetadata (\ s a -> s{_serMetadata = a}) instance FromJSON Service where parseJSON = withObject "Service" (\ o -> Service' <$> (o .:? "status") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON Service where toJSON Service'{..} = object (catMaybes [("status" .=) <$> _serStatus, ("apiVersion" .=) <$> _serAPIVersion, ("kind" .=) <$> _serKind, ("spec" .=) <$> _serSpec, ("metadata" .=) <$> _serMetadata]) -- | A resource that represents Google Cloud Platform location. -- -- /See:/ 'location' smart constructor. data Location = Location' { _lName :: !(Maybe Text) , _lMetadata :: !(Maybe LocationMetadata) , _lDisplayName :: !(Maybe Text) , _lLabels :: !(Maybe LocationLabels) , _lLocationId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Location' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lName' -- -- * 'lMetadata' -- -- * 'lDisplayName' -- -- * 'lLabels' -- -- * 'lLocationId' location :: Location location = Location' { _lName = Nothing , _lMetadata = Nothing , _lDisplayName = Nothing , _lLabels = Nothing , _lLocationId = Nothing } -- | Resource name for the location, which may vary between implementations. -- For example: \`\"projects\/example-project\/locations\/us-east1\"\` lName :: Lens' Location (Maybe Text) lName = lens _lName (\ s a -> s{_lName = a}) -- | Service-specific metadata. For example the available capacity at the -- given location. lMetadata :: Lens' Location (Maybe LocationMetadata) lMetadata = lens _lMetadata (\ s a -> s{_lMetadata = a}) -- | The friendly name for this location, typically a nearby city name. For -- example, \"Tokyo\". lDisplayName :: Lens' Location (Maybe Text) lDisplayName = lens _lDisplayName (\ s a -> s{_lDisplayName = a}) -- | Cross-service attributes for the location. For example -- {\"cloud.googleapis.com\/region\": \"us-east1\"} lLabels :: Lens' Location (Maybe LocationLabels) lLabels = lens _lLabels (\ s a -> s{_lLabels = a}) -- | The canonical id for this location. For example: \`\"us-east1\"\`. lLocationId :: Lens' Location (Maybe Text) lLocationId = lens _lLocationId (\ s a -> s{_lLocationId = a}) instance FromJSON Location where parseJSON = withObject "Location" (\ o -> Location' <$> (o .:? "name") <*> (o .:? "metadata") <*> (o .:? "displayName") <*> (o .:? "labels") <*> (o .:? "locationId")) instance ToJSON Location where toJSON Location'{..} = object (catMaybes [("name" .=) <$> _lName, ("metadata" .=) <$> _lMetadata, ("displayName" .=) <$> _lDisplayName, ("labels" .=) <$> _lLabels, ("locationId" .=) <$> _lLocationId]) -- | StatusCause provides more information about an api.Status failure, -- including cases when multiple errors are encountered. -- -- /See:/ 'statusCause' smart constructor. data StatusCause = StatusCause' { _scField :: !(Maybe Text) , _scReason :: !(Maybe Text) , _scMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusCause' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scField' -- -- * 'scReason' -- -- * 'scMessage' statusCause :: StatusCause statusCause = StatusCause' {_scField = Nothing, _scReason = Nothing, _scMessage = Nothing} -- | The field of the resource that has caused this error, as named by its -- JSON serialization. May include dot and postfix notation for nested -- attributes. Arrays are zero-indexed. Fields may appear more than once in -- an array of causes due to fields having multiple errors. Optional. -- Examples: \"name\" - the field \"name\" on the current resource -- \"items[0].name\" - the field \"name\" on the first array entry in -- \"items\" +optional scField :: Lens' StatusCause (Maybe Text) scField = lens _scField (\ s a -> s{_scField = a}) -- | A machine-readable description of the cause of the error. If this value -- is empty there is no information available. +optional scReason :: Lens' StatusCause (Maybe Text) scReason = lens _scReason (\ s a -> s{_scReason = a}) -- | A human-readable description of the cause of the error. This field may -- be presented as-is to a reader. +optional scMessage :: Lens' StatusCause (Maybe Text) scMessage = lens _scMessage (\ s a -> s{_scMessage = a}) instance FromJSON StatusCause where parseJSON = withObject "StatusCause" (\ o -> StatusCause' <$> (o .:? "field") <*> (o .:? "reason") <*> (o .:? "message")) instance ToJSON StatusCause where toJSON StatusCause'{..} = object (catMaybes [("field" .=) <$> _scField, ("reason" .=) <$> _scReason, ("message" .=) <$> _scMessage]) -- | RouteStatus communicates the observed state of the Route (from the -- controller). -- -- /See:/ 'routeStatus' smart constructor. data RouteStatus = RouteStatus' { _rsObservedGeneration :: !(Maybe (Textual Int32)) , _rsURL :: !(Maybe Text) , _rsAddress :: !(Maybe Addressable) , _rsTraffic :: !(Maybe [TrafficTarget]) , _rsConditions :: !(Maybe [GoogleCloudRunV1Condition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RouteStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rsObservedGeneration' -- -- * 'rsURL' -- -- * 'rsAddress' -- -- * 'rsTraffic' -- -- * 'rsConditions' routeStatus :: RouteStatus routeStatus = RouteStatus' { _rsObservedGeneration = Nothing , _rsURL = Nothing , _rsAddress = Nothing , _rsTraffic = Nothing , _rsConditions = Nothing } -- | ObservedGeneration is the \'Generation\' of the Route that was last -- processed by the controller. Clients polling for completed -- reconciliation should poll until observedGeneration = -- metadata.generation and the Ready condition\'s status is True or False. -- Note that providing a trafficTarget that only has a configurationName -- will result in a Route that does not increment either its -- metadata.generation or its observedGeneration, as new \"latest ready\" -- revisions from the Configuration are processed without an update to the -- Route\'s spec. rsObservedGeneration :: Lens' RouteStatus (Maybe Int32) rsObservedGeneration = lens _rsObservedGeneration (\ s a -> s{_rsObservedGeneration = a}) . mapping _Coerce -- | URL holds the url that will distribute traffic over the provided traffic -- targets. It generally has the form: -- https:\/\/{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app rsURL :: Lens' RouteStatus (Maybe Text) rsURL = lens _rsURL (\ s a -> s{_rsURL = a}) -- | Similar to url, information on where the service is available on HTTP. rsAddress :: Lens' RouteStatus (Maybe Addressable) rsAddress = lens _rsAddress (\ s a -> s{_rsAddress = a}) -- | Traffic holds the configured traffic distribution. These entries will -- always contain RevisionName references. When ConfigurationName appears -- in the spec, this will hold the LatestReadyRevisionName that we last -- observed. rsTraffic :: Lens' RouteStatus [TrafficTarget] rsTraffic = lens _rsTraffic (\ s a -> s{_rsTraffic = a}) . _Default . _Coerce -- | Conditions communicates information about ongoing\/complete -- reconciliation processes that bring the \"spec\" inline with the -- observed state of the world. rsConditions :: Lens' RouteStatus [GoogleCloudRunV1Condition] rsConditions = lens _rsConditions (\ s a -> s{_rsConditions = a}) . _Default . _Coerce instance FromJSON RouteStatus where parseJSON = withObject "RouteStatus" (\ o -> RouteStatus' <$> (o .:? "observedGeneration") <*> (o .:? "url") <*> (o .:? "address") <*> (o .:? "traffic" .!= mempty) <*> (o .:? "conditions" .!= mempty)) instance ToJSON RouteStatus where toJSON RouteStatus'{..} = object (catMaybes [("observedGeneration" .=) <$> _rsObservedGeneration, ("url" .=) <$> _rsURL, ("address" .=) <$> _rsAddress, ("traffic" .=) <$> _rsTraffic, ("conditions" .=) <$> _rsConditions]) -- | ConfigurationSpec holds the desired state of the Configuration (from the -- client). -- -- /See:/ 'configurationSpec' smart constructor. newtype ConfigurationSpec = ConfigurationSpec' { _csTemplate :: Maybe RevisionTemplate } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ConfigurationSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csTemplate' configurationSpec :: ConfigurationSpec configurationSpec = ConfigurationSpec' {_csTemplate = Nothing} -- | Template holds the latest specification for the Revision to be stamped -- out. csTemplate :: Lens' ConfigurationSpec (Maybe RevisionTemplate) csTemplate = lens _csTemplate (\ s a -> s{_csTemplate = a}) instance FromJSON ConfigurationSpec where parseJSON = withObject "ConfigurationSpec" (\ o -> ConfigurationSpec' <$> (o .:? "template")) instance ToJSON ConfigurationSpec where toJSON ConfigurationSpec'{..} = object (catMaybes [("template" .=) <$> _csTemplate]) -- | Condition defines a generic condition for a Resource -- -- /See:/ 'googleCloudRunV1Condition' smart constructor. data GoogleCloudRunV1Condition = GoogleCloudRunV1Condition' { _gcrvcStatus :: !(Maybe Text) , _gcrvcSeverity :: !(Maybe Text) , _gcrvcReason :: !(Maybe Text) , _gcrvcLastTransitionTime :: !(Maybe DateTime') , _gcrvcType :: !(Maybe Text) , _gcrvcMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleCloudRunV1Condition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcrvcStatus' -- -- * 'gcrvcSeverity' -- -- * 'gcrvcReason' -- -- * 'gcrvcLastTransitionTime' -- -- * 'gcrvcType' -- -- * 'gcrvcMessage' googleCloudRunV1Condition :: GoogleCloudRunV1Condition googleCloudRunV1Condition = GoogleCloudRunV1Condition' { _gcrvcStatus = Nothing , _gcrvcSeverity = Nothing , _gcrvcReason = Nothing , _gcrvcLastTransitionTime = Nothing , _gcrvcType = Nothing , _gcrvcMessage = Nothing } -- | Status of the condition, one of True, False, Unknown. gcrvcStatus :: Lens' GoogleCloudRunV1Condition (Maybe Text) gcrvcStatus = lens _gcrvcStatus (\ s a -> s{_gcrvcStatus = a}) -- | Optional. How to interpret failures of this condition, one of Error, -- Warning, Info gcrvcSeverity :: Lens' GoogleCloudRunV1Condition (Maybe Text) gcrvcSeverity = lens _gcrvcSeverity (\ s a -> s{_gcrvcSeverity = a}) -- | Optional. One-word CamelCase reason for the condition\'s last -- transition. gcrvcReason :: Lens' GoogleCloudRunV1Condition (Maybe Text) gcrvcReason = lens _gcrvcReason (\ s a -> s{_gcrvcReason = a}) -- | Optional. Last time the condition transitioned from one status to -- another. gcrvcLastTransitionTime :: Lens' GoogleCloudRunV1Condition (Maybe UTCTime) gcrvcLastTransitionTime = lens _gcrvcLastTransitionTime (\ s a -> s{_gcrvcLastTransitionTime = a}) . mapping _DateTime -- | type is used to communicate the status of the reconciliation process. -- See also: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/spec\/errors.md#error-conditions-and-reporting -- Types common to all resources include: * \"Ready\": True when the -- Resource is ready. gcrvcType :: Lens' GoogleCloudRunV1Condition (Maybe Text) gcrvcType = lens _gcrvcType (\ s a -> s{_gcrvcType = a}) -- | Optional. Human readable message indicating details about the current -- status. gcrvcMessage :: Lens' GoogleCloudRunV1Condition (Maybe Text) gcrvcMessage = lens _gcrvcMessage (\ s a -> s{_gcrvcMessage = a}) instance FromJSON GoogleCloudRunV1Condition where parseJSON = withObject "GoogleCloudRunV1Condition" (\ o -> GoogleCloudRunV1Condition' <$> (o .:? "status") <*> (o .:? "severity") <*> (o .:? "reason") <*> (o .:? "lastTransitionTime") <*> (o .:? "type") <*> (o .:? "message")) instance ToJSON GoogleCloudRunV1Condition where toJSON GoogleCloudRunV1Condition'{..} = object (catMaybes [("status" .=) <$> _gcrvcStatus, ("severity" .=) <$> _gcrvcSeverity, ("reason" .=) <$> _gcrvcReason, ("lastTransitionTime" .=) <$> _gcrvcLastTransitionTime, ("type" .=) <$> _gcrvcType, ("message" .=) <$> _gcrvcMessage]) -- | A list of Authorized Domains. -- -- /See:/ 'listAuthorizedDomainsResponse' smart constructor. data ListAuthorizedDomainsResponse = ListAuthorizedDomainsResponse' { _ladrNextPageToken :: !(Maybe Text) , _ladrDomains :: !(Maybe [AuthorizedDomain]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListAuthorizedDomainsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ladrNextPageToken' -- -- * 'ladrDomains' listAuthorizedDomainsResponse :: ListAuthorizedDomainsResponse listAuthorizedDomainsResponse = ListAuthorizedDomainsResponse' {_ladrNextPageToken = Nothing, _ladrDomains = Nothing} -- | Continuation token for fetching the next page of results. ladrNextPageToken :: Lens' ListAuthorizedDomainsResponse (Maybe Text) ladrNextPageToken = lens _ladrNextPageToken (\ s a -> s{_ladrNextPageToken = a}) -- | The authorized domains belonging to the user. ladrDomains :: Lens' ListAuthorizedDomainsResponse [AuthorizedDomain] ladrDomains = lens _ladrDomains (\ s a -> s{_ladrDomains = a}) . _Default . _Coerce instance FromJSON ListAuthorizedDomainsResponse where parseJSON = withObject "ListAuthorizedDomainsResponse" (\ o -> ListAuthorizedDomainsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "domains" .!= mempty)) instance ToJSON ListAuthorizedDomainsResponse where toJSON ListAuthorizedDomainsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _ladrNextPageToken, ("domains" .=) <$> _ladrDomains]) -- | (Optional) Only memory and CPU are supported. Note: The only supported -- values for CPU are \'1\', \'2\', and \'4\'. Setting 4 CPU requires at -- least 2Gi of memory. Limits describes the maximum amount of compute -- resources allowed. The values of the map is string form of the -- \'quantity\' k8s type: -- https:\/\/github.com\/kubernetes\/kubernetes\/blob\/master\/staging\/src\/k8s.io\/apimachinery\/pkg\/api\/resource\/quantity.go -- -- /See:/ 'resourceRequirementsLimits' smart constructor. newtype ResourceRequirementsLimits = ResourceRequirementsLimits' { _rrlAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResourceRequirementsLimits' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrlAddtional' resourceRequirementsLimits :: HashMap Text Text -- ^ 'rrlAddtional' -> ResourceRequirementsLimits resourceRequirementsLimits pRrlAddtional_ = ResourceRequirementsLimits' {_rrlAddtional = _Coerce # pRrlAddtional_} rrlAddtional :: Lens' ResourceRequirementsLimits (HashMap Text Text) rrlAddtional = lens _rrlAddtional (\ s a -> s{_rrlAddtional = a}) . _Coerce instance FromJSON ResourceRequirementsLimits where parseJSON = withObject "ResourceRequirementsLimits" (\ o -> ResourceRequirementsLimits' <$> (parseJSONObject o)) instance ToJSON ResourceRequirementsLimits where toJSON = toJSON . _rrlAddtional -- | Not supported by Cloud Run Volume represents a named volume in a -- container. -- -- /See:/ 'volume' smart constructor. data Volume = Volume' { _vConfigMap :: !(Maybe ConfigMapVolumeSource) , _vSecret :: !(Maybe SecretVolumeSource) , _vName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Volume' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vConfigMap' -- -- * 'vSecret' -- -- * 'vName' volume :: Volume volume = Volume' {_vConfigMap = Nothing, _vSecret = Nothing, _vName = Nothing} vConfigMap :: Lens' Volume (Maybe ConfigMapVolumeSource) vConfigMap = lens _vConfigMap (\ s a -> s{_vConfigMap = a}) vSecret :: Lens' Volume (Maybe SecretVolumeSource) vSecret = lens _vSecret (\ s a -> s{_vSecret = a}) -- | Volume\'s name. vName :: Lens' Volume (Maybe Text) vName = lens _vName (\ s a -> s{_vName = a}) instance FromJSON Volume where parseJSON = withObject "Volume" (\ o -> Volume' <$> (o .:? "configMap") <*> (o .:? "secret") <*> (o .:? "name")) instance ToJSON Volume where toJSON Volume'{..} = object (catMaybes [("configMap" .=) <$> _vConfigMap, ("secret" .=) <$> _vSecret, ("name" .=) <$> _vName]) -- | k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta is metadata that all -- persisted resources must have, which includes all objects users must -- create. -- -- /See:/ 'objectMeta' smart constructor. data ObjectMeta = ObjectMeta' { _omGenerateName :: !(Maybe Text) , _omAnnotations :: !(Maybe ObjectMetaAnnotations) , _omDeletionTimestamp :: !(Maybe DateTime') , _omUid :: !(Maybe Text) , _omDeletionGracePeriodSeconds :: !(Maybe (Textual Int32)) , _omResourceVersion :: !(Maybe Text) , _omFinalizers :: !(Maybe [Text]) , _omNamespace :: !(Maybe Text) , _omOwnerReferences :: !(Maybe [OwnerReference]) , _omSelfLink :: !(Maybe Text) , _omName :: !(Maybe Text) , _omCreationTimestamp :: !(Maybe DateTime') , _omClusterName :: !(Maybe Text) , _omLabels :: !(Maybe ObjectMetaLabels) , _omGeneration :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ObjectMeta' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omGenerateName' -- -- * 'omAnnotations' -- -- * 'omDeletionTimestamp' -- -- * 'omUid' -- -- * 'omDeletionGracePeriodSeconds' -- -- * 'omResourceVersion' -- -- * 'omFinalizers' -- -- * 'omNamespace' -- -- * 'omOwnerReferences' -- -- * 'omSelfLink' -- -- * 'omName' -- -- * 'omCreationTimestamp' -- -- * 'omClusterName' -- -- * 'omLabels' -- -- * 'omGeneration' objectMeta :: ObjectMeta objectMeta = ObjectMeta' { _omGenerateName = Nothing , _omAnnotations = Nothing , _omDeletionTimestamp = Nothing , _omUid = Nothing , _omDeletionGracePeriodSeconds = Nothing , _omResourceVersion = Nothing , _omFinalizers = Nothing , _omNamespace = Nothing , _omOwnerReferences = Nothing , _omSelfLink = Nothing , _omName = Nothing , _omCreationTimestamp = Nothing , _omClusterName = Nothing , _omLabels = Nothing , _omGeneration = Nothing } -- | (Optional) Not supported by Cloud Run GenerateName is an optional -- prefix, used by the server, to generate a unique name ONLY IF the Name -- field has not been provided. If this field is used, the name returned to -- the client will be different than the name passed. This value will also -- be combined with a unique suffix. The provided value has the same -- validation rules as the Name field, and may be truncated by the length -- of the suffix required to make the value unique on the server. If this -- field is specified and the generated name exists, the server will NOT -- return a 409 - instead, it will either return 201 Created or 500 with -- Reason ServerTimeout indicating a unique name could not be found in the -- time allotted, and the client should retry (optionally after the time -- indicated in the Retry-After header). Applied only if Name is not -- specified. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/api-conventions.md#idempotency -- string generateName = 2; omGenerateName :: Lens' ObjectMeta (Maybe Text) omGenerateName = lens _omGenerateName (\ s a -> s{_omGenerateName = a}) -- | (Optional) Annotations is an unstructured key value map stored with a -- resource that may be set by external tools to store and retrieve -- arbitrary metadata. They are not queryable and should be preserved when -- modifying objects. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/annotations omAnnotations :: Lens' ObjectMeta (Maybe ObjectMetaAnnotations) omAnnotations = lens _omAnnotations (\ s a -> s{_omAnnotations = a}) -- | (Optional) Not supported by Cloud Run DeletionTimestamp is RFC 3339 date -- and time at which this resource will be deleted. This field is set by -- the server when a graceful deletion is requested by the user, and is not -- directly settable by a client. The resource is expected to be deleted -- (no longer visible from resource lists, and not reachable by name) after -- the time in this field, once the finalizers list is empty. As long as -- the finalizers list contains items, deletion is blocked. Once the -- deletionTimestamp is set, this value may not be unset or be set further -- into the future, although it may be shortened or the resource may be -- deleted prior to this time. For example, a user may request that a pod -- is deleted in 30 seconds. The Kubelet will react by sending a graceful -- termination signal to the containers in the pod. After that 30 seconds, -- the Kubelet will send a hard termination signal (SIGKILL) to the -- container and after cleanup, remove the pod from the API. In the -- presence of network partitions, this object may still exist after this -- timestamp, until an administrator or automated process can determine the -- resource is fully terminated. If not set, graceful deletion of the -- object has not been requested. Populated by the system when a graceful -- deletion is requested. Read-only. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/api-conventions.md#metadata omDeletionTimestamp :: Lens' ObjectMeta (Maybe UTCTime) omDeletionTimestamp = lens _omDeletionTimestamp (\ s a -> s{_omDeletionTimestamp = a}) . mapping _DateTime -- | (Optional) UID is the unique in time and space value for this object. It -- is typically generated by the server on successful creation of a -- resource and is not allowed to change on PUT operations. Populated by -- the system. Read-only. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/identifiers#uids omUid :: Lens' ObjectMeta (Maybe Text) omUid = lens _omUid (\ s a -> s{_omUid = a}) -- | (Optional) Not supported by Cloud Run Number of seconds allowed for this -- object to gracefully terminate before it will be removed from the -- system. Only set when deletionTimestamp is also set. May only be -- shortened. Read-only. omDeletionGracePeriodSeconds :: Lens' ObjectMeta (Maybe Int32) omDeletionGracePeriodSeconds = lens _omDeletionGracePeriodSeconds (\ s a -> s{_omDeletionGracePeriodSeconds = a}) . mapping _Coerce -- | Optional. An opaque value that represents the internal version of this -- object that can be used by clients to determine when objects have -- changed. May be used for optimistic concurrency, change detection, and -- the watch operation on a resource or set of resources. Clients must -- treat these values as opaque and passed unmodified back to the server or -- omit the value to disable conflict-detection. They may only be valid for -- a particular resource or set of resources. Populated by the system. -- Read-only. Value must be treated as opaque by clients or omitted. More -- info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/sig-architecture\/api-conventions.md#concurrency-control-and-consistency omResourceVersion :: Lens' ObjectMeta (Maybe Text) omResourceVersion = lens _omResourceVersion (\ s a -> s{_omResourceVersion = a}) -- | (Optional) Not supported by Cloud Run Must be empty before the object is -- deleted from the registry. Each entry is an identifier for the -- responsible component that will remove the entry from the list. If the -- deletionTimestamp of the object is non-nil, entries in this list can -- only be removed. +patchStrategy=merge omFinalizers :: Lens' ObjectMeta [Text] omFinalizers = lens _omFinalizers (\ s a -> s{_omFinalizers = a}) . _Default . _Coerce -- | Namespace defines the space within each name must be unique, within a -- Cloud Run region. In Cloud Run the namespace must be equal to either the -- project ID or project number. omNamespace :: Lens' ObjectMeta (Maybe Text) omNamespace = lens _omNamespace (\ s a -> s{_omNamespace = a}) -- | (Optional) Not supported by Cloud Run List of objects that own this -- object. If ALL objects in the list have been deleted, this object will -- be garbage collected. omOwnerReferences :: Lens' ObjectMeta [OwnerReference] omOwnerReferences = lens _omOwnerReferences (\ s a -> s{_omOwnerReferences = a}) . _Default . _Coerce -- | (Optional) SelfLink is a URL representing this object. Populated by the -- system. Read-only. string selfLink = 4; omSelfLink :: Lens' ObjectMeta (Maybe Text) omSelfLink = lens _omSelfLink (\ s a -> s{_omSelfLink = a}) -- | Name must be unique within a namespace, within a Cloud Run region. Is -- required when creating resources, although some resources may allow a -- client to request the generation of an appropriate name automatically. -- Name is primarily intended for creation idempotence and configuration -- definition. Cannot be updated. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/identifiers#names +optional omName :: Lens' ObjectMeta (Maybe Text) omName = lens _omName (\ s a -> s{_omName = a}) -- | (Optional) CreationTimestamp is a timestamp representing the server time -- when this object was created. It is not guaranteed to be set in -- happens-before order across separate operations. Clients may not set -- this value. It is represented in RFC3339 form and is in UTC. Populated -- by the system. Read-only. Null for lists. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/api-conventions.md#metadata omCreationTimestamp :: Lens' ObjectMeta (Maybe UTCTime) omCreationTimestamp = lens _omCreationTimestamp (\ s a -> s{_omCreationTimestamp = a}) . mapping _DateTime -- | (Optional) Not supported by Cloud Run The name of the cluster which the -- object belongs to. This is used to distinguish resources with same name -- and namespace in different clusters. This field is not set anywhere -- right now and apiserver is going to ignore it if set in create or update -- request. omClusterName :: Lens' ObjectMeta (Maybe Text) omClusterName = lens _omClusterName (\ s a -> s{_omClusterName = a}) -- | (Optional) Map of string keys and values that can be used to organize -- and categorize (scope and select) objects. May match selectors of -- replication controllers and routes. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/labels omLabels :: Lens' ObjectMeta (Maybe ObjectMetaLabels) omLabels = lens _omLabels (\ s a -> s{_omLabels = a}) -- | (Optional) A sequence number representing a specific generation of the -- desired state. Populated by the system. Read-only. omGeneration :: Lens' ObjectMeta (Maybe Int32) omGeneration = lens _omGeneration (\ s a -> s{_omGeneration = a}) . mapping _Coerce instance FromJSON ObjectMeta where parseJSON = withObject "ObjectMeta" (\ o -> ObjectMeta' <$> (o .:? "generateName") <*> (o .:? "annotations") <*> (o .:? "deletionTimestamp") <*> (o .:? "uid") <*> (o .:? "deletionGracePeriodSeconds") <*> (o .:? "resourceVersion") <*> (o .:? "finalizers" .!= mempty) <*> (o .:? "namespace") <*> (o .:? "ownerReferences" .!= mempty) <*> (o .:? "selfLink") <*> (o .:? "name") <*> (o .:? "creationTimestamp") <*> (o .:? "clusterName") <*> (o .:? "labels") <*> (o .:? "generation")) instance ToJSON ObjectMeta where toJSON ObjectMeta'{..} = object (catMaybes [("generateName" .=) <$> _omGenerateName, ("annotations" .=) <$> _omAnnotations, ("deletionTimestamp" .=) <$> _omDeletionTimestamp, ("uid" .=) <$> _omUid, ("deletionGracePeriodSeconds" .=) <$> _omDeletionGracePeriodSeconds, ("resourceVersion" .=) <$> _omResourceVersion, ("finalizers" .=) <$> _omFinalizers, ("namespace" .=) <$> _omNamespace, ("ownerReferences" .=) <$> _omOwnerReferences, ("selfLink" .=) <$> _omSelfLink, ("name" .=) <$> _omName, ("creationTimestamp" .=) <$> _omCreationTimestamp, ("clusterName" .=) <$> _omClusterName, ("labels" .=) <$> _omLabels, ("generation" .=) <$> _omGeneration]) -- | Not supported by Cloud Run Adapts a ConfigMap into a volume. The -- contents of the target ConfigMap\'s Data field will be presented in a -- volume as files using the keys in the Data field as the file names, -- unless the items element is populated with specific mappings of keys to -- paths. -- -- /See:/ 'configMapVolumeSource' smart constructor. data ConfigMapVolumeSource = ConfigMapVolumeSource' { _cmvsDefaultMode :: !(Maybe (Textual Int32)) , _cmvsItems :: !(Maybe [KeyToPath]) , _cmvsName :: !(Maybe Text) , _cmvsOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ConfigMapVolumeSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmvsDefaultMode' -- -- * 'cmvsItems' -- -- * 'cmvsName' -- -- * 'cmvsOptional' configMapVolumeSource :: ConfigMapVolumeSource configMapVolumeSource = ConfigMapVolumeSource' { _cmvsDefaultMode = Nothing , _cmvsItems = Nothing , _cmvsName = Nothing , _cmvsOptional = Nothing } -- | (Optional) Mode bits to use on created files by default. Must be a value -- between 0 and 0777. Defaults to 0644. Directories within the path are -- not affected by this setting. This might be in conflict with other -- options that affect the file mode, like fsGroup, and the result can be -- other mode bits set. cmvsDefaultMode :: Lens' ConfigMapVolumeSource (Maybe Int32) cmvsDefaultMode = lens _cmvsDefaultMode (\ s a -> s{_cmvsDefaultMode = a}) . mapping _Coerce -- | (Optional) If unspecified, each key-value pair in the Data field of the -- referenced Secret will be projected into the volume as a file whose name -- is the key and content is the value. If specified, the listed keys will -- be projected into the specified paths, and unlisted keys will not be -- present. If a key is specified that is not present in the Secret, the -- volume setup will error unless it is marked optional. cmvsItems :: Lens' ConfigMapVolumeSource [KeyToPath] cmvsItems = lens _cmvsItems (\ s a -> s{_cmvsItems = a}) . _Default . _Coerce -- | Name of the config. cmvsName :: Lens' ConfigMapVolumeSource (Maybe Text) cmvsName = lens _cmvsName (\ s a -> s{_cmvsName = a}) -- | (Optional) Specify whether the Secret or its keys must be defined. cmvsOptional :: Lens' ConfigMapVolumeSource (Maybe Bool) cmvsOptional = lens _cmvsOptional (\ s a -> s{_cmvsOptional = a}) instance FromJSON ConfigMapVolumeSource where parseJSON = withObject "ConfigMapVolumeSource" (\ o -> ConfigMapVolumeSource' <$> (o .:? "defaultMode") <*> (o .:? "items" .!= mempty) <*> (o .:? "name") <*> (o .:? "optional")) instance ToJSON ConfigMapVolumeSource where toJSON ConfigMapVolumeSource'{..} = object (catMaybes [("defaultMode" .=) <$> _cmvsDefaultMode, ("items" .=) <$> _cmvsItems, ("name" .=) <$> _cmvsName, ("optional" .=) <$> _cmvsOptional]) -- | The secret\'s value will be presented as the content of a file whose -- name is defined in the item path. If no items are defined, the name of -- the file is the secret_name. The contents of the target Secret\'s Data -- field will be presented in a volume as files using the keys in the Data -- field as the file names. -- -- /See:/ 'secretVolumeSource' smart constructor. data SecretVolumeSource = SecretVolumeSource' { _svsDefaultMode :: !(Maybe (Textual Int32)) , _svsItems :: !(Maybe [KeyToPath]) , _svsSecretName :: !(Maybe Text) , _svsOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecretVolumeSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'svsDefaultMode' -- -- * 'svsItems' -- -- * 'svsSecretName' -- -- * 'svsOptional' secretVolumeSource :: SecretVolumeSource secretVolumeSource = SecretVolumeSource' { _svsDefaultMode = Nothing , _svsItems = Nothing , _svsSecretName = Nothing , _svsOptional = Nothing } -- | (Optional) Mode bits to use on created files by default. Must be a value -- between 0000 and 0777. Defaults to 0644. Directories within the path are -- not affected by this setting. This might be in conflict with other -- options that affect the file mode, like fsGroup, and the result can be -- other mode bits set. NOTE: This is an integer representation of the mode -- bits. So, the integer value should look exactly as the chmod numeric -- notation, i.e. Unix chmod \"777\" (a=rwx) should have the integer value -- 777. svsDefaultMode :: Lens' SecretVolumeSource (Maybe Int32) svsDefaultMode = lens _svsDefaultMode (\ s a -> s{_svsDefaultMode = a}) . mapping _Coerce -- | (Optional) If unspecified, the volume will expose a file whose name is -- the secret_name. If specified, the key will be used as the version to -- fetch from Cloud Secret Manager and the path will be the name of the -- file exposed in the volume. When items are defined, they must specify a -- key and a path. If unspecified, each key-value pair in the Data field of -- the referenced Secret will be projected into the volume as a file whose -- name is the key and content is the value. If specified, the listed keys -- will be projected into the specified paths, and unlisted keys will not -- be present. If a key is specified that is not present in the Secret, the -- volume setup will error unless it is marked optional. svsItems :: Lens' SecretVolumeSource [KeyToPath] svsItems = lens _svsItems (\ s a -> s{_svsItems = a}) . _Default . _Coerce -- | The name of the secret in Cloud Secret Manager. By default, the secret -- is assumed to be in the same project. If the secret is in another -- project, you must define an alias. An alias definition has the form: -- :projects\/\/secrets\/. If multiple alias definitions are needed, they -- must be separated by commas. The alias definitions must be set on the -- run.googleapis.com\/secrets annotation. Name of the secret in the -- container\'s namespace to use. svsSecretName :: Lens' SecretVolumeSource (Maybe Text) svsSecretName = lens _svsSecretName (\ s a -> s{_svsSecretName = a}) -- | (Optional) Specify whether the Secret or its keys must be defined. svsOptional :: Lens' SecretVolumeSource (Maybe Bool) svsOptional = lens _svsOptional (\ s a -> s{_svsOptional = a}) instance FromJSON SecretVolumeSource where parseJSON = withObject "SecretVolumeSource" (\ o -> SecretVolumeSource' <$> (o .:? "defaultMode") <*> (o .:? "items" .!= mempty) <*> (o .:? "secretName") <*> (o .:? "optional")) instance ToJSON SecretVolumeSource where toJSON SecretVolumeSource'{..} = object (catMaybes [("defaultMode" .=) <$> _svsDefaultMode, ("items" .=) <$> _svsItems, ("secretName" .=) <$> _svsSecretName, ("optional" .=) <$> _svsOptional]) -- | ListRoutesResponse is a list of Route resources. -- -- /See:/ 'listRoutesResponse' smart constructor. data ListRoutesResponse = ListRoutesResponse' { _lrrAPIVersion :: !(Maybe Text) , _lrrKind :: !(Maybe Text) , _lrrItems :: !(Maybe [Route]) , _lrrUnreachable :: !(Maybe [Text]) , _lrrMetadata :: !(Maybe ListMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListRoutesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lrrAPIVersion' -- -- * 'lrrKind' -- -- * 'lrrItems' -- -- * 'lrrUnreachable' -- -- * 'lrrMetadata' listRoutesResponse :: ListRoutesResponse listRoutesResponse = ListRoutesResponse' { _lrrAPIVersion = Nothing , _lrrKind = Nothing , _lrrItems = Nothing , _lrrUnreachable = Nothing , _lrrMetadata = Nothing } -- | The API version for this call such as \"serving.knative.dev\/v1\". lrrAPIVersion :: Lens' ListRoutesResponse (Maybe Text) lrrAPIVersion = lens _lrrAPIVersion (\ s a -> s{_lrrAPIVersion = a}) -- | The kind of this resource, in this case always \"RouteList\". lrrKind :: Lens' ListRoutesResponse (Maybe Text) lrrKind = lens _lrrKind (\ s a -> s{_lrrKind = a}) -- | List of Routes. lrrItems :: Lens' ListRoutesResponse [Route] lrrItems = lens _lrrItems (\ s a -> s{_lrrItems = a}) . _Default . _Coerce -- | Locations that could not be reached. lrrUnreachable :: Lens' ListRoutesResponse [Text] lrrUnreachable = lens _lrrUnreachable (\ s a -> s{_lrrUnreachable = a}) . _Default . _Coerce -- | Metadata associated with this Route list. lrrMetadata :: Lens' ListRoutesResponse (Maybe ListMeta) lrrMetadata = lens _lrrMetadata (\ s a -> s{_lrrMetadata = a}) instance FromJSON ListRoutesResponse where parseJSON = withObject "ListRoutesResponse" (\ o -> ListRoutesResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "unreachable" .!= mempty) <*> (o .:? "metadata")) instance ToJSON ListRoutesResponse where toJSON ListRoutesResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _lrrAPIVersion, ("kind" .=) <$> _lrrKind, ("items" .=) <$> _lrrItems, ("unreachable" .=) <$> _lrrUnreachable, ("metadata" .=) <$> _lrrMetadata]) -- | RevisionTemplateSpec describes the data a revision should have when -- created from a template. Based on: -- https:\/\/github.com\/kubernetes\/api\/blob\/e771f807\/core\/v1\/types.go#L3179-L3190 -- -- /See:/ 'revisionTemplate' smart constructor. data RevisionTemplate = RevisionTemplate' { _rtSpec :: !(Maybe RevisionSpec) , _rtMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RevisionTemplate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rtSpec' -- -- * 'rtMetadata' revisionTemplate :: RevisionTemplate revisionTemplate = RevisionTemplate' {_rtSpec = Nothing, _rtMetadata = Nothing} -- | RevisionSpec holds the desired state of the Revision (from the client). rtSpec :: Lens' RevisionTemplate (Maybe RevisionSpec) rtSpec = lens _rtSpec (\ s a -> s{_rtSpec = a}) -- | Optional metadata for this Revision, including labels and annotations. -- Name will be generated by the Configuration. The following annotation -- keys set properties of the created revision: * -- \`autoscaling.knative.dev\/minScale\` sets the minimum number of -- instances. * \`autoscaling.knative.dev\/maxScale\` sets the maximum -- number of instances. * \`run.googleapis.com\/cloudsql-instances\` sets -- Cloud SQL connections. Multiple values should be comma separated. * -- \`run.googleapis.com\/vpc-access-connector\` sets a Serverless VPC -- Access connector. * \`run.googleapis.com\/vpc-access-egress\` sets VPC -- egress. Supported values are \`all-traffic\`, \`all\` (deprecated), and -- \`private-ranges-only\`. \`all-traffic\` and \`all\` provide the same -- functionality. \`all\` is deprecated but will continue to be supported. -- Prefer \`all-traffic\`. rtMetadata :: Lens' RevisionTemplate (Maybe ObjectMeta) rtMetadata = lens _rtMetadata (\ s a -> s{_rtMetadata = a}) instance FromJSON RevisionTemplate where parseJSON = withObject "RevisionTemplate" (\ o -> RevisionTemplate' <$> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON RevisionTemplate where toJSON RevisionTemplate'{..} = object (catMaybes [("spec" .=) <$> _rtSpec, ("metadata" .=) <$> _rtMetadata]) -- | StatusDetails is a set of additional properties that MAY be set by the -- server to provide additional information about a response. The Reason -- field of a Status object defines what attributes will be set. Clients -- must ignore fields that do not match the defined type of each attribute, -- and should assume that any attribute may be empty, invalid, or under -- defined. -- -- /See:/ 'statusDetails' smart constructor. data StatusDetails = StatusDetails' { _sdGroup :: !(Maybe Text) , _sdCauses :: !(Maybe [StatusCause]) , _sdKind :: !(Maybe Text) , _sdUid :: !(Maybe Text) , _sdRetryAfterSeconds :: !(Maybe (Textual Int32)) , _sdName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdGroup' -- -- * 'sdCauses' -- -- * 'sdKind' -- -- * 'sdUid' -- -- * 'sdRetryAfterSeconds' -- -- * 'sdName' statusDetails :: StatusDetails statusDetails = StatusDetails' { _sdGroup = Nothing , _sdCauses = Nothing , _sdKind = Nothing , _sdUid = Nothing , _sdRetryAfterSeconds = Nothing , _sdName = Nothing } -- | The group attribute of the resource associated with the status -- StatusReason. +optional sdGroup :: Lens' StatusDetails (Maybe Text) sdGroup = lens _sdGroup (\ s a -> s{_sdGroup = a}) -- | The Causes array includes more details associated with the StatusReason -- failure. Not all StatusReasons may provide detailed causes. +optional sdCauses :: Lens' StatusDetails [StatusCause] sdCauses = lens _sdCauses (\ s a -> s{_sdCauses = a}) . _Default . _Coerce -- | The kind attribute of the resource associated with the status -- StatusReason. On some operations may differ from the requested resource -- Kind. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/sig-architecture\/api-conventions.md#types-kinds -- +optional sdKind :: Lens' StatusDetails (Maybe Text) sdKind = lens _sdKind (\ s a -> s{_sdKind = a}) -- | UID of the resource. (when there is a single resource which can be -- described). More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/identifiers#uids +optional sdUid :: Lens' StatusDetails (Maybe Text) sdUid = lens _sdUid (\ s a -> s{_sdUid = a}) -- | If specified, the time in seconds before the operation should be -- retried. Some errors may indicate the client must take an alternate -- action - for those errors this field may indicate how long to wait -- before taking the alternate action. +optional sdRetryAfterSeconds :: Lens' StatusDetails (Maybe Int32) sdRetryAfterSeconds = lens _sdRetryAfterSeconds (\ s a -> s{_sdRetryAfterSeconds = a}) . mapping _Coerce -- | The name attribute of the resource associated with the status -- StatusReason (when there is a single name which can be described). -- +optional sdName :: Lens' StatusDetails (Maybe Text) sdName = lens _sdName (\ s a -> s{_sdName = a}) instance FromJSON StatusDetails where parseJSON = withObject "StatusDetails" (\ o -> StatusDetails' <$> (o .:? "group") <*> (o .:? "causes" .!= mempty) <*> (o .:? "kind") <*> (o .:? "uid") <*> (o .:? "retryAfterSeconds") <*> (o .:? "name")) instance ToJSON StatusDetails where toJSON StatusDetails'{..} = object (catMaybes [("group" .=) <$> _sdGroup, ("causes" .=) <$> _sdCauses, ("kind" .=) <$> _sdKind, ("uid" .=) <$> _sdUid, ("retryAfterSeconds" .=) <$> _sdRetryAfterSeconds, ("name" .=) <$> _sdName]) -- | ResourceRequirements describes the compute resource requirements. -- -- /See:/ 'resourceRequirements' smart constructor. data ResourceRequirements = ResourceRequirements' { _rrLimits :: !(Maybe ResourceRequirementsLimits) , _rrRequests :: !(Maybe ResourceRequirementsRequests) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResourceRequirements' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrLimits' -- -- * 'rrRequests' resourceRequirements :: ResourceRequirements resourceRequirements = ResourceRequirements' {_rrLimits = Nothing, _rrRequests = Nothing} -- | (Optional) Only memory and CPU are supported. Note: The only supported -- values for CPU are \'1\', \'2\', and \'4\'. Setting 4 CPU requires at -- least 2Gi of memory. Limits describes the maximum amount of compute -- resources allowed. The values of the map is string form of the -- \'quantity\' k8s type: -- https:\/\/github.com\/kubernetes\/kubernetes\/blob\/master\/staging\/src\/k8s.io\/apimachinery\/pkg\/api\/resource\/quantity.go rrLimits :: Lens' ResourceRequirements (Maybe ResourceRequirementsLimits) rrLimits = lens _rrLimits (\ s a -> s{_rrLimits = a}) -- | (Optional) Only memory and CPU are supported. Note: The only supported -- values for CPU are \'1\' and \'2\'. Requests describes the minimum -- amount of compute resources required. If Requests is omitted for a -- container, it defaults to Limits if that is explicitly specified, -- otherwise to an implementation-defined value. The values of the map is -- string form of the \'quantity\' k8s type: -- https:\/\/github.com\/kubernetes\/kubernetes\/blob\/master\/staging\/src\/k8s.io\/apimachinery\/pkg\/api\/resource\/quantity.go rrRequests :: Lens' ResourceRequirements (Maybe ResourceRequirementsRequests) rrRequests = lens _rrRequests (\ s a -> s{_rrRequests = a}) instance FromJSON ResourceRequirements where parseJSON = withObject "ResourceRequirements" (\ o -> ResourceRequirements' <$> (o .:? "limits") <*> (o .:? "requests")) instance ToJSON ResourceRequirements where toJSON ResourceRequirements'{..} = object (catMaybes [("limits" .=) <$> _rrLimits, ("requests" .=) <$> _rrRequests]) -- | Request message for \`SetIamPolicy\` method. -- -- /See:/ 'setIAMPolicyRequest' smart constructor. data SetIAMPolicyRequest = SetIAMPolicyRequest' { _siprUpdateMask :: !(Maybe GFieldMask) , _siprPolicy :: !(Maybe Policy) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SetIAMPolicyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siprUpdateMask' -- -- * 'siprPolicy' setIAMPolicyRequest :: SetIAMPolicyRequest setIAMPolicyRequest = SetIAMPolicyRequest' {_siprUpdateMask = Nothing, _siprPolicy = Nothing} -- | OPTIONAL: A FieldMask specifying which fields of the policy to modify. -- Only the fields in the mask will be modified. If no mask is provided, -- the following default mask is used: \`paths: \"bindings, etag\"\` siprUpdateMask :: Lens' SetIAMPolicyRequest (Maybe GFieldMask) siprUpdateMask = lens _siprUpdateMask (\ s a -> s{_siprUpdateMask = a}) -- | REQUIRED: The complete policy to be applied to the \`resource\`. The -- size of the policy is limited to a few 10s of KB. An empty policy is a -- valid policy but certain Cloud Platform services (such as Projects) -- might reject them. siprPolicy :: Lens' SetIAMPolicyRequest (Maybe Policy) siprPolicy = lens _siprPolicy (\ s a -> s{_siprPolicy = a}) instance FromJSON SetIAMPolicyRequest where parseJSON = withObject "SetIAMPolicyRequest" (\ o -> SetIAMPolicyRequest' <$> (o .:? "updateMask") <*> (o .:? "policy")) instance ToJSON SetIAMPolicyRequest where toJSON SetIAMPolicyRequest'{..} = object (catMaybes [("updateMask" .=) <$> _siprUpdateMask, ("policy" .=) <$> _siprPolicy]) -- | The desired state of the Domain Mapping. -- -- /See:/ 'domainMAppingSpec' smart constructor. data DomainMAppingSpec = DomainMAppingSpec' { _dmasRouteName :: !(Maybe Text) , _dmasCertificateMode :: !(Maybe DomainMAppingSpecCertificateMode) , _dmasForceOverride :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DomainMAppingSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dmasRouteName' -- -- * 'dmasCertificateMode' -- -- * 'dmasForceOverride' domainMAppingSpec :: DomainMAppingSpec domainMAppingSpec = DomainMAppingSpec' { _dmasRouteName = Nothing , _dmasCertificateMode = Nothing , _dmasForceOverride = Nothing } -- | The name of the Knative Route that this DomainMapping applies to. The -- route must exist. dmasRouteName :: Lens' DomainMAppingSpec (Maybe Text) dmasRouteName = lens _dmasRouteName (\ s a -> s{_dmasRouteName = a}) -- | The mode of the certificate. dmasCertificateMode :: Lens' DomainMAppingSpec (Maybe DomainMAppingSpecCertificateMode) dmasCertificateMode = lens _dmasCertificateMode (\ s a -> s{_dmasCertificateMode = a}) -- | If set, the mapping will override any mapping set before this spec was -- set. It is recommended that the user leaves this empty to receive an -- error warning about a potential conflict and only set it once the -- respective UI has given such a warning. dmasForceOverride :: Lens' DomainMAppingSpec (Maybe Bool) dmasForceOverride = lens _dmasForceOverride (\ s a -> s{_dmasForceOverride = a}) instance FromJSON DomainMAppingSpec where parseJSON = withObject "DomainMAppingSpec" (\ o -> DomainMAppingSpec' <$> (o .:? "routeName") <*> (o .:? "certificateMode") <*> (o .:? "forceOverride")) instance ToJSON DomainMAppingSpec where toJSON DomainMAppingSpec'{..} = object (catMaybes [("routeName" .=) <$> _dmasRouteName, ("certificateMode" .=) <$> _dmasCertificateMode, ("forceOverride" .=) <$> _dmasForceOverride]) -- | Route is responsible for configuring ingress over a collection of -- Revisions. Some of the Revisions a Route distributes traffic over may be -- specified by referencing the Configuration responsible for creating -- them; in these cases the Route is additionally responsible for -- monitoring the Configuration for \"latest ready\" revision changes, and -- smoothly rolling out latest revisions. See also: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/spec\/overview.md#route -- Cloud Run currently supports referencing a single Configuration to -- automatically deploy the \"latest ready\" Revision from that -- Configuration. -- -- /See:/ 'route' smart constructor. data Route = Route' { _rStatus :: !(Maybe RouteStatus) , _rAPIVersion :: !(Maybe Text) , _rKind :: !(Maybe Text) , _rSpec :: !(Maybe RouteSpec) , _rMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Route' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rStatus' -- -- * 'rAPIVersion' -- -- * 'rKind' -- -- * 'rSpec' -- -- * 'rMetadata' route :: Route route = Route' { _rStatus = Nothing , _rAPIVersion = Nothing , _rKind = Nothing , _rSpec = Nothing , _rMetadata = Nothing } -- | Status communicates the observed state of the Route (from the -- controller). rStatus :: Lens' Route (Maybe RouteStatus) rStatus = lens _rStatus (\ s a -> s{_rStatus = a}) -- | The API version for this call such as \"serving.knative.dev\/v1\". rAPIVersion :: Lens' Route (Maybe Text) rAPIVersion = lens _rAPIVersion (\ s a -> s{_rAPIVersion = a}) -- | The kind of this resource, in this case always \"Route\". rKind :: Lens' Route (Maybe Text) rKind = lens _rKind (\ s a -> s{_rKind = a}) -- | Spec holds the desired state of the Route (from the client). rSpec :: Lens' Route (Maybe RouteSpec) rSpec = lens _rSpec (\ s a -> s{_rSpec = a}) -- | Metadata associated with this Route, including name, namespace, labels, -- and annotations. rMetadata :: Lens' Route (Maybe ObjectMeta) rMetadata = lens _rMetadata (\ s a -> s{_rMetadata = a}) instance FromJSON Route where parseJSON = withObject "Route" (\ o -> Route' <$> (o .:? "status") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON Route where toJSON Route'{..} = object (catMaybes [("status" .=) <$> _rStatus, ("apiVersion" .=) <$> _rAPIVersion, ("kind" .=) <$> _rKind, ("spec" .=) <$> _rSpec, ("metadata" .=) <$> _rMetadata]) -- | Not supported by Cloud Run SecurityContext holds security configuration -- that will be applied to a container. Some fields are present in both -- SecurityContext and PodSecurityContext. When both are set, the values in -- SecurityContext take precedence. -- -- /See:/ 'securityContext' smart constructor. newtype SecurityContext = SecurityContext' { _scRunAsUser :: Maybe (Textual Int32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecurityContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scRunAsUser' securityContext :: SecurityContext securityContext = SecurityContext' {_scRunAsUser = Nothing} -- | (Optional) The UID to run the entrypoint of the container process. -- Defaults to user specified in image metadata if unspecified. May also be -- set in PodSecurityContext. If set in both SecurityContext and -- PodSecurityContext, the value specified in SecurityContext takes -- precedence. scRunAsUser :: Lens' SecurityContext (Maybe Int32) scRunAsUser = lens _scRunAsUser (\ s a -> s{_scRunAsUser = a}) . mapping _Coerce instance FromJSON SecurityContext where parseJSON = withObject "SecurityContext" (\ o -> SecurityContext' <$> (o .:? "runAsUser")) instance ToJSON SecurityContext where toJSON SecurityContext'{..} = object (catMaybes [("runAsUser" .=) <$> _scRunAsUser]) -- | The current state of the Service. Output only. -- -- /See:/ 'serviceStatus' smart constructor. data ServiceStatus = ServiceStatus' { _ssLatestCreatedRevisionName :: !(Maybe Text) , _ssObservedGeneration :: !(Maybe (Textual Int32)) , _ssURL :: !(Maybe Text) , _ssAddress :: !(Maybe Addressable) , _ssLatestReadyRevisionName :: !(Maybe Text) , _ssTraffic :: !(Maybe [TrafficTarget]) , _ssConditions :: !(Maybe [GoogleCloudRunV1Condition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssLatestCreatedRevisionName' -- -- * 'ssObservedGeneration' -- -- * 'ssURL' -- -- * 'ssAddress' -- -- * 'ssLatestReadyRevisionName' -- -- * 'ssTraffic' -- -- * 'ssConditions' serviceStatus :: ServiceStatus serviceStatus = ServiceStatus' { _ssLatestCreatedRevisionName = Nothing , _ssObservedGeneration = Nothing , _ssURL = Nothing , _ssAddress = Nothing , _ssLatestReadyRevisionName = Nothing , _ssTraffic = Nothing , _ssConditions = Nothing } -- | From ConfigurationStatus. LatestCreatedRevisionName is the last revision -- that was created from this Service\'s Configuration. It might not be -- ready yet, for that use LatestReadyRevisionName. ssLatestCreatedRevisionName :: Lens' ServiceStatus (Maybe Text) ssLatestCreatedRevisionName = lens _ssLatestCreatedRevisionName (\ s a -> s{_ssLatestCreatedRevisionName = a}) -- | ObservedGeneration is the \'Generation\' of the Route that was last -- processed by the controller. Clients polling for completed -- reconciliation should poll until observedGeneration = -- metadata.generation and the Ready condition\'s status is True or False. ssObservedGeneration :: Lens' ServiceStatus (Maybe Int32) ssObservedGeneration = lens _ssObservedGeneration (\ s a -> s{_ssObservedGeneration = a}) . mapping _Coerce -- | From RouteStatus. URL holds the url that will distribute traffic over -- the provided traffic targets. It generally has the form -- https:\/\/{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app ssURL :: Lens' ServiceStatus (Maybe Text) ssURL = lens _ssURL (\ s a -> s{_ssURL = a}) -- | From RouteStatus. Similar to url, information on where the service is -- available on HTTP. ssAddress :: Lens' ServiceStatus (Maybe Addressable) ssAddress = lens _ssAddress (\ s a -> s{_ssAddress = a}) -- | From ConfigurationStatus. LatestReadyRevisionName holds the name of the -- latest Revision stamped out from this Service\'s Configuration that has -- had its \"Ready\" condition become \"True\". ssLatestReadyRevisionName :: Lens' ServiceStatus (Maybe Text) ssLatestReadyRevisionName = lens _ssLatestReadyRevisionName (\ s a -> s{_ssLatestReadyRevisionName = a}) -- | From RouteStatus. Traffic holds the configured traffic distribution. -- These entries will always contain RevisionName references. When -- ConfigurationName appears in the spec, this will hold the -- LatestReadyRevisionName that we last observed. ssTraffic :: Lens' ServiceStatus [TrafficTarget] ssTraffic = lens _ssTraffic (\ s a -> s{_ssTraffic = a}) . _Default . _Coerce -- | Conditions communicates information about ongoing\/complete -- reconciliation processes that bring the \"spec\" inline with the -- observed state of the world. Service-specific conditions include: * -- \"ConfigurationsReady\": true when the underlying Configuration is -- ready. * \"RoutesReady\": true when the underlying Route is ready. * -- \"Ready\": true when both the underlying Route and Configuration are -- ready. ssConditions :: Lens' ServiceStatus [GoogleCloudRunV1Condition] ssConditions = lens _ssConditions (\ s a -> s{_ssConditions = a}) . _Default . _Coerce instance FromJSON ServiceStatus where parseJSON = withObject "ServiceStatus" (\ o -> ServiceStatus' <$> (o .:? "latestCreatedRevisionName") <*> (o .:? "observedGeneration") <*> (o .:? "url") <*> (o .:? "address") <*> (o .:? "latestReadyRevisionName") <*> (o .:? "traffic" .!= mempty) <*> (o .:? "conditions" .!= mempty)) instance ToJSON ServiceStatus where toJSON ServiceStatus'{..} = object (catMaybes [("latestCreatedRevisionName" .=) <$> _ssLatestCreatedRevisionName, ("observedGeneration" .=) <$> _ssObservedGeneration, ("url" .=) <$> _ssURL, ("address" .=) <$> _ssAddress, ("latestReadyRevisionName" .=) <$> _ssLatestReadyRevisionName, ("traffic" .=) <$> _ssTraffic, ("conditions" .=) <$> _ssConditions]) -- | Resource to hold the state and status of a user\'s domain mapping. NOTE: -- This resource is currently in Beta. -- -- /See:/ 'domainMApping' smart constructor. data DomainMApping = DomainMApping' { _dmaStatus :: !(Maybe DomainMAppingStatus) , _dmaAPIVersion :: !(Maybe Text) , _dmaKind :: !(Maybe Text) , _dmaSpec :: !(Maybe DomainMAppingSpec) , _dmaMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DomainMApping' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dmaStatus' -- -- * 'dmaAPIVersion' -- -- * 'dmaKind' -- -- * 'dmaSpec' -- -- * 'dmaMetadata' domainMApping :: DomainMApping domainMApping = DomainMApping' { _dmaStatus = Nothing , _dmaAPIVersion = Nothing , _dmaKind = Nothing , _dmaSpec = Nothing , _dmaMetadata = Nothing } -- | The current status of the DomainMapping. dmaStatus :: Lens' DomainMApping (Maybe DomainMAppingStatus) dmaStatus = lens _dmaStatus (\ s a -> s{_dmaStatus = a}) -- | The API version for this call such as \"domains.cloudrun.com\/v1\". dmaAPIVersion :: Lens' DomainMApping (Maybe Text) dmaAPIVersion = lens _dmaAPIVersion (\ s a -> s{_dmaAPIVersion = a}) -- | The kind of resource, in this case \"DomainMapping\". dmaKind :: Lens' DomainMApping (Maybe Text) dmaKind = lens _dmaKind (\ s a -> s{_dmaKind = a}) -- | The spec for this DomainMapping. dmaSpec :: Lens' DomainMApping (Maybe DomainMAppingSpec) dmaSpec = lens _dmaSpec (\ s a -> s{_dmaSpec = a}) -- | Metadata associated with this BuildTemplate. dmaMetadata :: Lens' DomainMApping (Maybe ObjectMeta) dmaMetadata = lens _dmaMetadata (\ s a -> s{_dmaMetadata = a}) instance FromJSON DomainMApping where parseJSON = withObject "DomainMApping" (\ o -> DomainMApping' <$> (o .:? "status") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON DomainMApping where toJSON DomainMApping'{..} = object (catMaybes [("status" .=) <$> _dmaStatus, ("apiVersion" .=) <$> _dmaAPIVersion, ("kind" .=) <$> _dmaKind, ("spec" .=) <$> _dmaSpec, ("metadata" .=) <$> _dmaMetadata]) -- | ConfigurationStatus communicates the observed state of the Configuration -- (from the controller). -- -- /See:/ 'configurationStatus' smart constructor. data ConfigurationStatus = ConfigurationStatus' { _csLatestCreatedRevisionName :: !(Maybe Text) , _csObservedGeneration :: !(Maybe (Textual Int32)) , _csLatestReadyRevisionName :: !(Maybe Text) , _csConditions :: !(Maybe [GoogleCloudRunV1Condition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ConfigurationStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csLatestCreatedRevisionName' -- -- * 'csObservedGeneration' -- -- * 'csLatestReadyRevisionName' -- -- * 'csConditions' configurationStatus :: ConfigurationStatus configurationStatus = ConfigurationStatus' { _csLatestCreatedRevisionName = Nothing , _csObservedGeneration = Nothing , _csLatestReadyRevisionName = Nothing , _csConditions = Nothing } -- | LatestCreatedRevisionName is the last revision that was created from -- this Configuration. It might not be ready yet, for that use -- LatestReadyRevisionName. csLatestCreatedRevisionName :: Lens' ConfigurationStatus (Maybe Text) csLatestCreatedRevisionName = lens _csLatestCreatedRevisionName (\ s a -> s{_csLatestCreatedRevisionName = a}) -- | ObservedGeneration is the \'Generation\' of the Configuration that was -- last processed by the controller. The observed generation is updated -- even if the controller failed to process the spec and create the -- Revision. Clients polling for completed reconciliation should poll until -- observedGeneration = metadata.generation, and the Ready condition\'s -- status is True or False. csObservedGeneration :: Lens' ConfigurationStatus (Maybe Int32) csObservedGeneration = lens _csObservedGeneration (\ s a -> s{_csObservedGeneration = a}) . mapping _Coerce -- | LatestReadyRevisionName holds the name of the latest Revision stamped -- out from this Configuration that has had its \"Ready\" condition become -- \"True\". csLatestReadyRevisionName :: Lens' ConfigurationStatus (Maybe Text) csLatestReadyRevisionName = lens _csLatestReadyRevisionName (\ s a -> s{_csLatestReadyRevisionName = a}) -- | Conditions communicates information about ongoing\/complete -- reconciliation processes that bring the \"spec\" inline with the -- observed state of the world. csConditions :: Lens' ConfigurationStatus [GoogleCloudRunV1Condition] csConditions = lens _csConditions (\ s a -> s{_csConditions = a}) . _Default . _Coerce instance FromJSON ConfigurationStatus where parseJSON = withObject "ConfigurationStatus" (\ o -> ConfigurationStatus' <$> (o .:? "latestCreatedRevisionName") <*> (o .:? "observedGeneration") <*> (o .:? "latestReadyRevisionName") <*> (o .:? "conditions" .!= mempty)) instance ToJSON ConfigurationStatus where toJSON ConfigurationStatus'{..} = object (catMaybes [("latestCreatedRevisionName" .=) <$> _csLatestCreatedRevisionName, ("observedGeneration" .=) <$> _csObservedGeneration, ("latestReadyRevisionName" .=) <$> _csLatestReadyRevisionName, ("conditions" .=) <$> _csConditions]) -- | RouteSpec holds the desired state of the Route (from the client). -- -- /See:/ 'routeSpec' smart constructor. newtype RouteSpec = RouteSpec' { _rTraffic :: Maybe [TrafficTarget] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RouteSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rTraffic' routeSpec :: RouteSpec routeSpec = RouteSpec' {_rTraffic = Nothing} -- | Traffic specifies how to distribute traffic over a collection of Knative -- Revisions and Configurations. Cloud Run currently supports a single -- configurationName. rTraffic :: Lens' RouteSpec [TrafficTarget] rTraffic = lens _rTraffic (\ s a -> s{_rTraffic = a}) . _Default . _Coerce instance FromJSON RouteSpec where parseJSON = withObject "RouteSpec" (\ o -> RouteSpec' <$> (o .:? "traffic" .!= mempty)) instance ToJSON RouteSpec where toJSON RouteSpec'{..} = object (catMaybes [("traffic" .=) <$> _rTraffic]) -- | RevisionStatus communicates the observed state of the Revision (from the -- controller). -- -- /See:/ 'revisionStatus' smart constructor. data RevisionStatus = RevisionStatus' { _rLogURL :: !(Maybe Text) , _rObservedGeneration :: !(Maybe (Textual Int32)) , _rImageDigest :: !(Maybe Text) , _rServiceName :: !(Maybe Text) , _rConditions :: !(Maybe [GoogleCloudRunV1Condition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RevisionStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rLogURL' -- -- * 'rObservedGeneration' -- -- * 'rImageDigest' -- -- * 'rServiceName' -- -- * 'rConditions' revisionStatus :: RevisionStatus revisionStatus = RevisionStatus' { _rLogURL = Nothing , _rObservedGeneration = Nothing , _rImageDigest = Nothing , _rServiceName = Nothing , _rConditions = Nothing } -- | Optional. Specifies the generated logging url for this particular -- revision based on the revision url template specified in the -- controller\'s config. rLogURL :: Lens' RevisionStatus (Maybe Text) rLogURL = lens _rLogURL (\ s a -> s{_rLogURL = a}) -- | ObservedGeneration is the \'Generation\' of the Revision that was last -- processed by the controller. Clients polling for completed -- reconciliation should poll until observedGeneration = -- metadata.generation, and the Ready condition\'s status is True or False. rObservedGeneration :: Lens' RevisionStatus (Maybe Int32) rObservedGeneration = lens _rObservedGeneration (\ s a -> s{_rObservedGeneration = a}) . mapping _Coerce -- | ImageDigest holds the resolved digest for the image specified within -- .Spec.Container.Image. The digest is resolved during the creation of -- Revision. This field holds the digest value regardless of whether a tag -- or digest was originally specified in the Container object. rImageDigest :: Lens' RevisionStatus (Maybe Text) rImageDigest = lens _rImageDigest (\ s a -> s{_rImageDigest = a}) -- | Not currently used by Cloud Run. rServiceName :: Lens' RevisionStatus (Maybe Text) rServiceName = lens _rServiceName (\ s a -> s{_rServiceName = a}) -- | Conditions communicates information about ongoing\/complete -- reconciliation processes that bring the \"spec\" inline with the -- observed state of the world. As a Revision is being prepared, it will -- incrementally update conditions. Revision-specific conditions include: * -- \"ResourcesAvailable\": True when underlying resources have been -- provisioned. * \"ContainerHealthy\": True when the Revision readiness -- check completes. * \"Active\": True when the Revision may receive -- traffic. rConditions :: Lens' RevisionStatus [GoogleCloudRunV1Condition] rConditions = lens _rConditions (\ s a -> s{_rConditions = a}) . _Default . _Coerce instance FromJSON RevisionStatus where parseJSON = withObject "RevisionStatus" (\ o -> RevisionStatus' <$> (o .:? "logUrl") <*> (o .:? "observedGeneration") <*> (o .:? "imageDigest") <*> (o .:? "serviceName") <*> (o .:? "conditions" .!= mempty)) instance ToJSON RevisionStatus where toJSON RevisionStatus'{..} = object (catMaybes [("logUrl" .=) <$> _rLogURL, ("observedGeneration" .=) <$> _rObservedGeneration, ("imageDigest" .=) <$> _rImageDigest, ("serviceName" .=) <$> _rServiceName, ("conditions" .=) <$> _rConditions]) -- | A single application container. This specifies both the container to -- run, the command to run in the container and the arguments to supply to -- it. Note that additional arguments may be supplied by the system to the -- container at runtime. -- -- /See:/ 'container' smart constructor. data Container = Container' { _cLivenessProbe :: !(Maybe Probe) , _cImage :: !(Maybe Text) , _cTerminationMessagePolicy :: !(Maybe Text) , _cCommand :: !(Maybe [Text]) , _cArgs :: !(Maybe [Text]) , _cImagePullPolicy :: !(Maybe Text) , _cReadinessProbe :: !(Maybe Probe) , _cEnv :: !(Maybe [EnvVar]) , _cVolumeMounts :: !(Maybe [VolumeMount]) , _cWorkingDir :: !(Maybe Text) , _cSecurityContext :: !(Maybe SecurityContext) , _cResources :: !(Maybe ResourceRequirements) , _cName :: !(Maybe Text) , _cStartupProbe :: !(Maybe Probe) , _cTerminationMessagePath :: !(Maybe Text) , _cPorts :: !(Maybe [ContainerPort]) , _cEnvFrom :: !(Maybe [EnvFromSource]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Container' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cLivenessProbe' -- -- * 'cImage' -- -- * 'cTerminationMessagePolicy' -- -- * 'cCommand' -- -- * 'cArgs' -- -- * 'cImagePullPolicy' -- -- * 'cReadinessProbe' -- -- * 'cEnv' -- -- * 'cVolumeMounts' -- -- * 'cWorkingDir' -- -- * 'cSecurityContext' -- -- * 'cResources' -- -- * 'cName' -- -- * 'cStartupProbe' -- -- * 'cTerminationMessagePath' -- -- * 'cPorts' -- -- * 'cEnvFrom' container :: Container container = Container' { _cLivenessProbe = Nothing , _cImage = Nothing , _cTerminationMessagePolicy = Nothing , _cCommand = Nothing , _cArgs = Nothing , _cImagePullPolicy = Nothing , _cReadinessProbe = Nothing , _cEnv = Nothing , _cVolumeMounts = Nothing , _cWorkingDir = Nothing , _cSecurityContext = Nothing , _cResources = Nothing , _cName = Nothing , _cStartupProbe = Nothing , _cTerminationMessagePath = Nothing , _cPorts = Nothing , _cEnvFrom = Nothing } -- | (Optional) Periodic probe of container liveness. Container will be -- restarted if the probe fails. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/workloads\/pods\/pod-lifecycle#container-probes cLivenessProbe :: Lens' Container (Maybe Probe) cLivenessProbe = lens _cLivenessProbe (\ s a -> s{_cLivenessProbe = a}) -- | Only supports containers from Google Container Registry or Artifact -- Registry URL of the Container image. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/containers\/images cImage :: Lens' Container (Maybe Text) cImage = lens _cImage (\ s a -> s{_cImage = a}) -- | (Optional) Indicate how the termination message should be populated. -- File will use the contents of terminationMessagePath to populate the -- container status message on both success and failure. -- FallbackToLogsOnError will use the last chunk of container log output if -- the termination message file is empty and the container exited with an -- error. The log output is limited to 2048 bytes or 80 lines, whichever is -- smaller. Defaults to File. Cannot be updated. cTerminationMessagePolicy :: Lens' Container (Maybe Text) cTerminationMessagePolicy = lens _cTerminationMessagePolicy (\ s a -> s{_cTerminationMessagePolicy = a}) cCommand :: Lens' Container [Text] cCommand = lens _cCommand (\ s a -> s{_cCommand = a}) . _Default . _Coerce -- | (Optional) Arguments to the entrypoint. The docker image\'s CMD is used -- if this is not provided. Variable references $(VAR_NAME) are expanded -- using the container\'s environment. If a variable cannot be resolved, -- the reference in the input string will be unchanged. The $(VAR_NAME) -- syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped -- references will never be expanded, regardless of whether the variable -- exists or not. More info: -- https:\/\/kubernetes.io\/docs\/tasks\/inject-data-application\/define-command-argument-container\/#running-a-command-in-a-shell cArgs :: Lens' Container [Text] cArgs = lens _cArgs (\ s a -> s{_cArgs = a}) . _Default . _Coerce -- | (Optional) Image pull policy. One of Always, Never, IfNotPresent. -- Defaults to Always if :latest tag is specified, or IfNotPresent -- otherwise. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/containers\/images#updating-images cImagePullPolicy :: Lens' Container (Maybe Text) cImagePullPolicy = lens _cImagePullPolicy (\ s a -> s{_cImagePullPolicy = a}) -- | (Optional) Periodic probe of container service readiness. Container will -- be removed from service endpoints if the probe fails. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/workloads\/pods\/pod-lifecycle#container-probes cReadinessProbe :: Lens' Container (Maybe Probe) cReadinessProbe = lens _cReadinessProbe (\ s a -> s{_cReadinessProbe = a}) -- | (Optional) List of environment variables to set in the container. cEnv :: Lens' Container [EnvVar] cEnv = lens _cEnv (\ s a -> s{_cEnv = a}) . _Default . _Coerce -- | (Optional) Volume to mount into the container\'s filesystem. Only -- supports SecretVolumeSources. Pod volumes to mount into the container\'s -- filesystem. cVolumeMounts :: Lens' Container [VolumeMount] cVolumeMounts = lens _cVolumeMounts (\ s a -> s{_cVolumeMounts = a}) . _Default . _Coerce -- | (Optional) Container\'s working directory. If not specified, the -- container runtime\'s default will be used, which might be configured in -- the container image. cWorkingDir :: Lens' Container (Maybe Text) cWorkingDir = lens _cWorkingDir (\ s a -> s{_cWorkingDir = a}) -- | (Optional) Security options the pod should run with. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/policy\/security-context\/ More -- info: -- https:\/\/kubernetes.io\/docs\/tasks\/configure-pod-container\/security-context\/ cSecurityContext :: Lens' Container (Maybe SecurityContext) cSecurityContext = lens _cSecurityContext (\ s a -> s{_cSecurityContext = a}) -- | (Optional) Compute Resources required by this container. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/storage\/persistent-volumes#resources cResources :: Lens' Container (Maybe ResourceRequirements) cResources = lens _cResources (\ s a -> s{_cResources = a}) -- | (Optional) Name of the container specified as a DNS_LABEL. Currently -- unused in Cloud Run. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/overview\/working-with-objects\/names\/#dns-label-names cName :: Lens' Container (Maybe Text) cName = lens _cName (\ s a -> s{_cName = a}) -- | (Optional) Startup probe of application within the container. All other -- probes are disabled if a startup probe is provided, until it succeeds. -- Container will not be added to service endpoints if the probe fails. -- More info: -- https:\/\/kubernetes.io\/docs\/concepts\/workloads\/pods\/pod-lifecycle#container-probes cStartupProbe :: Lens' Container (Maybe Probe) cStartupProbe = lens _cStartupProbe (\ s a -> s{_cStartupProbe = a}) -- | (Optional) Path at which the file to which the container\'s termination -- message will be written is mounted into the container\'s filesystem. -- Message written is intended to be brief final status, such as an -- assertion failure message. Will be truncated by the node if greater than -- 4096 bytes. The total message length across all containers will be -- limited to 12kb. Defaults to \/dev\/termination-log. cTerminationMessagePath :: Lens' Container (Maybe Text) cTerminationMessagePath = lens _cTerminationMessagePath (\ s a -> s{_cTerminationMessagePath = a}) -- | (Optional) List of ports to expose from the container. Only a single -- port can be specified. The specified ports must be listening on all -- interfaces (0.0.0.0) within the container to be accessible. If omitted, -- a port number will be chosen and passed to the container through the -- PORT environment variable for the container to listen on. cPorts :: Lens' Container [ContainerPort] cPorts = lens _cPorts (\ s a -> s{_cPorts = a}) . _Default . _Coerce -- | (Optional) List of sources to populate environment variables in the -- container. The keys defined within a source must be a C_IDENTIFIER. All -- invalid keys will be reported as an event when the container is -- starting. When a key exists in multiple sources, the value associated -- with the last source will take precedence. Values defined by an Env with -- a duplicate key will take precedence. Cannot be updated. cEnvFrom :: Lens' Container [EnvFromSource] cEnvFrom = lens _cEnvFrom (\ s a -> s{_cEnvFrom = a}) . _Default . _Coerce instance FromJSON Container where parseJSON = withObject "Container" (\ o -> Container' <$> (o .:? "livenessProbe") <*> (o .:? "image") <*> (o .:? "terminationMessagePolicy") <*> (o .:? "command" .!= mempty) <*> (o .:? "args" .!= mempty) <*> (o .:? "imagePullPolicy") <*> (o .:? "readinessProbe") <*> (o .:? "env" .!= mempty) <*> (o .:? "volumeMounts" .!= mempty) <*> (o .:? "workingDir") <*> (o .:? "securityContext") <*> (o .:? "resources") <*> (o .:? "name") <*> (o .:? "startupProbe") <*> (o .:? "terminationMessagePath") <*> (o .:? "ports" .!= mempty) <*> (o .:? "envFrom" .!= mempty)) instance ToJSON Container where toJSON Container'{..} = object (catMaybes [("livenessProbe" .=) <$> _cLivenessProbe, ("image" .=) <$> _cImage, ("terminationMessagePolicy" .=) <$> _cTerminationMessagePolicy, ("command" .=) <$> _cCommand, ("args" .=) <$> _cArgs, ("imagePullPolicy" .=) <$> _cImagePullPolicy, ("readinessProbe" .=) <$> _cReadinessProbe, ("env" .=) <$> _cEnv, ("volumeMounts" .=) <$> _cVolumeMounts, ("workingDir" .=) <$> _cWorkingDir, ("securityContext" .=) <$> _cSecurityContext, ("resources" .=) <$> _cResources, ("name" .=) <$> _cName, ("startupProbe" .=) <$> _cStartupProbe, ("terminationMessagePath" .=) <$> _cTerminationMessagePath, ("ports" .=) <$> _cPorts, ("envFrom" .=) <$> _cEnvFrom]) -- | ListMeta describes metadata that synthetic resources must have, -- including lists and various status objects. A resource may have only one -- of {ObjectMeta, ListMeta}. -- -- /See:/ 'listMeta' smart constructor. data ListMeta = ListMeta' { _lmResourceVersion :: !(Maybe Text) , _lmSelfLink :: !(Maybe Text) , _lmContinue :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListMeta' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmResourceVersion' -- -- * 'lmSelfLink' -- -- * 'lmContinue' listMeta :: ListMeta listMeta = ListMeta' {_lmResourceVersion = Nothing, _lmSelfLink = Nothing, _lmContinue = Nothing} -- | String that identifies the server\'s internal version of this object -- that can be used by clients to determine when objects have changed. -- Value must be treated as opaque by clients and passed unmodified back to -- the server. Populated by the system. Read-only. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/api-conventions.md#concurrency-control-and-consistency -- +optional lmResourceVersion :: Lens' ListMeta (Maybe Text) lmResourceVersion = lens _lmResourceVersion (\ s a -> s{_lmResourceVersion = a}) -- | SelfLink is a URL representing this object. Populated by the system. -- Read-only. +optional lmSelfLink :: Lens' ListMeta (Maybe Text) lmSelfLink = lens _lmSelfLink (\ s a -> s{_lmSelfLink = a}) -- | continue may be set if the user set a limit on the number of items -- returned, and indicates that the server has more data available. The -- value is opaque and may be used to issue another request to the endpoint -- that served this list to retrieve the next set of available objects. -- Continuing a list may not be possible if the server configuration has -- changed or more than a few minutes have passed. The resourceVersion -- field returned when using this continue value will be identical to the -- value in the first response. lmContinue :: Lens' ListMeta (Maybe Text) lmContinue = lens _lmContinue (\ s a -> s{_lmContinue = a}) instance FromJSON ListMeta where parseJSON = withObject "ListMeta" (\ o -> ListMeta' <$> (o .:? "resourceVersion") <*> (o .:? "selfLink") <*> (o .:? "continue")) instance ToJSON ListMeta where toJSON ListMeta'{..} = object (catMaybes [("resourceVersion" .=) <$> _lmResourceVersion, ("selfLink" .=) <$> _lmSelfLink, ("continue" .=) <$> _lmContinue]) -- | OwnerReference contains enough information to let you identify an owning -- object. Currently, an owning object must be in the same namespace, so -- there is no namespace field. -- -- /See:/ 'ownerReference' smart constructor. data OwnerReference = OwnerReference' { _orController :: !(Maybe Bool) , _orAPIVersion :: !(Maybe Text) , _orKind :: !(Maybe Text) , _orUid :: !(Maybe Text) , _orBlockOwnerDeletion :: !(Maybe Bool) , _orName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OwnerReference' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orController' -- -- * 'orAPIVersion' -- -- * 'orKind' -- -- * 'orUid' -- -- * 'orBlockOwnerDeletion' -- -- * 'orName' ownerReference :: OwnerReference ownerReference = OwnerReference' { _orController = Nothing , _orAPIVersion = Nothing , _orKind = Nothing , _orUid = Nothing , _orBlockOwnerDeletion = Nothing , _orName = Nothing } -- | If true, this reference points to the managing controller. +optional orController :: Lens' OwnerReference (Maybe Bool) orController = lens _orController (\ s a -> s{_orController = a}) -- | API version of the referent. orAPIVersion :: Lens' OwnerReference (Maybe Text) orAPIVersion = lens _orAPIVersion (\ s a -> s{_orAPIVersion = a}) -- | Kind of the referent. More info: -- https:\/\/git.k8s.io\/community\/contributors\/devel\/sig-architecture\/api-conventions.md#types-kinds orKind :: Lens' OwnerReference (Maybe Text) orKind = lens _orKind (\ s a -> s{_orKind = a}) -- | UID of the referent. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/identifiers#uids orUid :: Lens' OwnerReference (Maybe Text) orUid = lens _orUid (\ s a -> s{_orUid = a}) -- | If true, AND if the owner has the \"foregroundDeletion\" finalizer, then -- the owner cannot be deleted from the key-value store until this -- reference is removed. Defaults to false. To set this field, a user needs -- \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) -- will be returned. +optional orBlockOwnerDeletion :: Lens' OwnerReference (Maybe Bool) orBlockOwnerDeletion = lens _orBlockOwnerDeletion (\ s a -> s{_orBlockOwnerDeletion = a}) -- | Name of the referent. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/identifiers#names orName :: Lens' OwnerReference (Maybe Text) orName = lens _orName (\ s a -> s{_orName = a}) instance FromJSON OwnerReference where parseJSON = withObject "OwnerReference" (\ o -> OwnerReference' <$> (o .:? "controller") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "uid") <*> (o .:? "blockOwnerDeletion") <*> (o .:? "name")) instance ToJSON OwnerReference where toJSON OwnerReference'{..} = object (catMaybes [("controller" .=) <$> _orController, ("apiVersion" .=) <$> _orAPIVersion, ("kind" .=) <$> _orKind, ("uid" .=) <$> _orUid, ("blockOwnerDeletion" .=) <$> _orBlockOwnerDeletion, ("name" .=) <$> _orName]) -- | Request message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsRequest' smart constructor. newtype TestIAMPermissionsRequest = TestIAMPermissionsRequest' { _tiprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiprPermissions' testIAMPermissionsRequest :: TestIAMPermissionsRequest testIAMPermissionsRequest = TestIAMPermissionsRequest' {_tiprPermissions = Nothing} -- | The set of permissions to check for the \`resource\`. Permissions with -- wildcards (such as \'*\' or \'storage.*\') are not allowed. For more -- information see [IAM -- Overview](https:\/\/cloud.google.com\/iam\/docs\/overview#permissions). tiprPermissions :: Lens' TestIAMPermissionsRequest [Text] tiprPermissions = lens _tiprPermissions (\ s a -> s{_tiprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsRequest where parseJSON = withObject "TestIAMPermissionsRequest" (\ o -> TestIAMPermissionsRequest' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsRequest where toJSON TestIAMPermissionsRequest'{..} = object (catMaybes [("permissions" .=) <$> _tiprPermissions]) -- | Not supported by Cloud Run ExecAction describes a \"run in container\" -- action. -- -- /See:/ 'execAction' smart constructor. newtype ExecAction = ExecAction' { _eaCommand :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExecAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eaCommand' execAction :: ExecAction execAction = ExecAction' {_eaCommand = Nothing} -- | (Optional) Command is the command line to execute inside the container, -- the working directory for the command is root (\'\/\') in the -- container\'s filesystem. The command is simply exec\'d, it is not run -- inside a shell, so traditional shell instructions (\'|\', etc) won\'t -- work. To use a shell, you need to explicitly call out to that shell. -- Exit status of 0 is treated as live\/healthy and non-zero is unhealthy. eaCommand :: Lens' ExecAction [Text] eaCommand = lens _eaCommand (\ s a -> s{_eaCommand = a}) . _Default . _Coerce instance FromJSON ExecAction where parseJSON = withObject "ExecAction" (\ o -> ExecAction' <$> (o .:? "command" .!= mempty)) instance ToJSON ExecAction where toJSON ExecAction'{..} = object (catMaybes [("command" .=) <$> _eaCommand]) -- | (Optional) Map of string keys and values that can be used to organize -- and categorize (scope and select) objects. May match selectors of -- replication controllers and routes. More info: -- http:\/\/kubernetes.io\/docs\/user-guide\/labels -- -- /See:/ 'objectMetaLabels' smart constructor. newtype ObjectMetaLabels = ObjectMetaLabels' { _omlAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ObjectMetaLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omlAddtional' objectMetaLabels :: HashMap Text Text -- ^ 'omlAddtional' -> ObjectMetaLabels objectMetaLabels pOmlAddtional_ = ObjectMetaLabels' {_omlAddtional = _Coerce # pOmlAddtional_} omlAddtional :: Lens' ObjectMetaLabels (HashMap Text Text) omlAddtional = lens _omlAddtional (\ s a -> s{_omlAddtional = a}) . _Coerce instance FromJSON ObjectMetaLabels where parseJSON = withObject "ObjectMetaLabels" (\ o -> ObjectMetaLabels' <$> (parseJSONObject o)) instance ToJSON ObjectMetaLabels where toJSON = toJSON . _omlAddtional -- | Not supported by Cloud Run VolumeMount describes a mounting of a Volume -- within a container. -- -- /See:/ 'volumeMount' smart constructor. data VolumeMount = VolumeMount' { _vmSubPath :: !(Maybe Text) , _vmName :: !(Maybe Text) , _vmMountPath :: !(Maybe Text) , _vmReadOnly :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'VolumeMount' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vmSubPath' -- -- * 'vmName' -- -- * 'vmMountPath' -- -- * 'vmReadOnly' volumeMount :: VolumeMount volumeMount = VolumeMount' { _vmSubPath = Nothing , _vmName = Nothing , _vmMountPath = Nothing , _vmReadOnly = Nothing } -- | (Optional) Path within the volume from which the container\'s volume -- should be mounted. Defaults to \"\" (volume\'s root). vmSubPath :: Lens' VolumeMount (Maybe Text) vmSubPath = lens _vmSubPath (\ s a -> s{_vmSubPath = a}) -- | This must match the Name of a Volume. vmName :: Lens' VolumeMount (Maybe Text) vmName = lens _vmName (\ s a -> s{_vmName = a}) -- | Path within the container at which the volume should be mounted. Must -- not contain \':\'. vmMountPath :: Lens' VolumeMount (Maybe Text) vmMountPath = lens _vmMountPath (\ s a -> s{_vmMountPath = a}) -- | (Optional) Only true is accepted. Defaults to true. vmReadOnly :: Lens' VolumeMount (Maybe Bool) vmReadOnly = lens _vmReadOnly (\ s a -> s{_vmReadOnly = a}) instance FromJSON VolumeMount where parseJSON = withObject "VolumeMount" (\ o -> VolumeMount' <$> (o .:? "subPath") <*> (o .:? "name") <*> (o .:? "mountPath") <*> (o .:? "readOnly")) instance ToJSON VolumeMount where toJSON VolumeMount'{..} = object (catMaybes [("subPath" .=) <$> _vmSubPath, ("name" .=) <$> _vmName, ("mountPath" .=) <$> _vmMountPath, ("readOnly" .=) <$> _vmReadOnly]) -- | Response message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsResponse' smart constructor. newtype TestIAMPermissionsResponse = TestIAMPermissionsResponse' { _tiamprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiamprPermissions' testIAMPermissionsResponse :: TestIAMPermissionsResponse testIAMPermissionsResponse = TestIAMPermissionsResponse' {_tiamprPermissions = Nothing} -- | A subset of \`TestPermissionsRequest.permissions\` that the caller is -- allowed. tiamprPermissions :: Lens' TestIAMPermissionsResponse [Text] tiamprPermissions = lens _tiamprPermissions (\ s a -> s{_tiamprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsResponse where parseJSON = withObject "TestIAMPermissionsResponse" (\ o -> TestIAMPermissionsResponse' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsResponse where toJSON TestIAMPermissionsResponse'{..} = object (catMaybes [("permissions" .=) <$> _tiamprPermissions]) -- | The current state of the Domain Mapping. -- -- /See:/ 'domainMAppingStatus' smart constructor. data DomainMAppingStatus = DomainMAppingStatus' { _dmasResourceRecords :: !(Maybe [ResourceRecord]) , _dmasObservedGeneration :: !(Maybe (Textual Int32)) , _dmasMAppedRouteName :: !(Maybe Text) , _dmasURL :: !(Maybe Text) , _dmasConditions :: !(Maybe [GoogleCloudRunV1Condition]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DomainMAppingStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dmasResourceRecords' -- -- * 'dmasObservedGeneration' -- -- * 'dmasMAppedRouteName' -- -- * 'dmasURL' -- -- * 'dmasConditions' domainMAppingStatus :: DomainMAppingStatus domainMAppingStatus = DomainMAppingStatus' { _dmasResourceRecords = Nothing , _dmasObservedGeneration = Nothing , _dmasMAppedRouteName = Nothing , _dmasURL = Nothing , _dmasConditions = Nothing } -- | The resource records required to configure this domain mapping. These -- records must be added to the domain\'s DNS configuration in order to -- serve the application via this domain mapping. dmasResourceRecords :: Lens' DomainMAppingStatus [ResourceRecord] dmasResourceRecords = lens _dmasResourceRecords (\ s a -> s{_dmasResourceRecords = a}) . _Default . _Coerce -- | ObservedGeneration is the \'Generation\' of the DomainMapping that was -- last processed by the controller. Clients polling for completed -- reconciliation should poll until observedGeneration = -- metadata.generation and the Ready condition\'s status is True or False. dmasObservedGeneration :: Lens' DomainMAppingStatus (Maybe Int32) dmasObservedGeneration = lens _dmasObservedGeneration (\ s a -> s{_dmasObservedGeneration = a}) . mapping _Coerce -- | The name of the route that the mapping currently points to. dmasMAppedRouteName :: Lens' DomainMAppingStatus (Maybe Text) dmasMAppedRouteName = lens _dmasMAppedRouteName (\ s a -> s{_dmasMAppedRouteName = a}) -- | Optional. Cloud Run fully managed: not supported Cloud Run on GKE: -- supported Holds the URL that will serve the traffic of the -- DomainMapping. dmasURL :: Lens' DomainMAppingStatus (Maybe Text) dmasURL = lens _dmasURL (\ s a -> s{_dmasURL = a}) -- | Array of observed DomainMappingConditions, indicating the current state -- of the DomainMapping. dmasConditions :: Lens' DomainMAppingStatus [GoogleCloudRunV1Condition] dmasConditions = lens _dmasConditions (\ s a -> s{_dmasConditions = a}) . _Default . _Coerce instance FromJSON DomainMAppingStatus where parseJSON = withObject "DomainMAppingStatus" (\ o -> DomainMAppingStatus' <$> (o .:? "resourceRecords" .!= mempty) <*> (o .:? "observedGeneration") <*> (o .:? "mappedRouteName") <*> (o .:? "url") <*> (o .:? "conditions" .!= mempty)) instance ToJSON DomainMAppingStatus where toJSON DomainMAppingStatus'{..} = object (catMaybes [("resourceRecords" .=) <$> _dmasResourceRecords, ("observedGeneration" .=) <$> _dmasObservedGeneration, ("mappedRouteName" .=) <$> _dmasMAppedRouteName, ("url" .=) <$> _dmasURL, ("conditions" .=) <$> _dmasConditions]) -- | EnvVar represents an environment variable present in a Container. -- -- /See:/ 'envVar' smart constructor. data EnvVar = EnvVar' { _evValue :: !(Maybe Text) , _evName :: !(Maybe Text) , _evValueFrom :: !(Maybe EnvVarSource) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EnvVar' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'evValue' -- -- * 'evName' -- -- * 'evValueFrom' envVar :: EnvVar envVar = EnvVar' {_evValue = Nothing, _evName = Nothing, _evValueFrom = Nothing} -- | (Optional) Variable references $(VAR_NAME) are expanded using the -- previous defined environment variables in the container and any route -- environment variables. If a variable cannot be resolved, the reference -- in the input string will be unchanged. The $(VAR_NAME) syntax can be -- escaped with a double $$, ie: $$(VAR_NAME). Escaped references will -- never be expanded, regardless of whether the variable exists or not. -- Defaults to \"\". evValue :: Lens' EnvVar (Maybe Text) evValue = lens _evValue (\ s a -> s{_evValue = a}) -- | Name of the environment variable. Must be a C_IDENTIFIER. evName :: Lens' EnvVar (Maybe Text) evName = lens _evName (\ s a -> s{_evName = a}) -- | (Optional) Source for the environment variable\'s value. Only supports -- secret_key_ref. Source for the environment variable\'s value. Cannot be -- used if value is not empty. evValueFrom :: Lens' EnvVar (Maybe EnvVarSource) evValueFrom = lens _evValueFrom (\ s a -> s{_evValueFrom = a}) instance FromJSON EnvVar where parseJSON = withObject "EnvVar" (\ o -> EnvVar' <$> (o .:? "value") <*> (o .:? "name") <*> (o .:? "valueFrom")) instance ToJSON EnvVar where toJSON EnvVar'{..} = object (catMaybes [("value" .=) <$> _evValue, ("name" .=) <$> _evName, ("valueFrom" .=) <$> _evValueFrom]) -- | ServiceSpec holds the desired state of the Route (from the client), -- which is used to manipulate the underlying Route and Configuration(s). -- -- /See:/ 'serviceSpec' smart constructor. data ServiceSpec = ServiceSpec' { _sTraffic :: !(Maybe [TrafficTarget]) , _sTemplate :: !(Maybe RevisionTemplate) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sTraffic' -- -- * 'sTemplate' serviceSpec :: ServiceSpec serviceSpec = ServiceSpec' {_sTraffic = Nothing, _sTemplate = Nothing} -- | Traffic specifies how to distribute traffic over a collection of Knative -- Revisions and Configurations. sTraffic :: Lens' ServiceSpec [TrafficTarget] sTraffic = lens _sTraffic (\ s a -> s{_sTraffic = a}) . _Default . _Coerce -- | Template holds the latest specification for the Revision to be stamped -- out. sTemplate :: Lens' ServiceSpec (Maybe RevisionTemplate) sTemplate = lens _sTemplate (\ s a -> s{_sTemplate = a}) instance FromJSON ServiceSpec where parseJSON = withObject "ServiceSpec" (\ o -> ServiceSpec' <$> (o .:? "traffic" .!= mempty) <*> (o .:? "template")) instance ToJSON ServiceSpec where toJSON ServiceSpec'{..} = object (catMaybes [("traffic" .=) <$> _sTraffic, ("template" .=) <$> _sTemplate]) -- | An Identity and Access Management (IAM) policy, which specifies access -- controls for Google Cloud resources. A \`Policy\` is a collection of -- \`bindings\`. A \`binding\` binds one or more \`members\` to a single -- \`role\`. Members can be user accounts, service accounts, Google groups, -- and domains (such as G Suite). A \`role\` is a named list of -- permissions; each \`role\` can be an IAM predefined role or a -- user-created custom role. For some types of Google Cloud resources, a -- \`binding\` can also specify a \`condition\`, which is a logical -- expression that allows access to a resource only if the expression -- evaluates to \`true\`. A condition can add constraints based on -- attributes of the request, the resource, or both. To learn which -- resources support conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). -- **JSON example:** { \"bindings\": [ { \"role\": -- \"roles\/resourcemanager.organizationAdmin\", \"members\": [ -- \"user:mike\'example.com\", \"group:admins\'example.com\", -- \"domain:google.com\", -- \"serviceAccount:my-project-id\'appspot.gserviceaccount.com\" ] }, { -- \"role\": \"roles\/resourcemanager.organizationViewer\", \"members\": [ -- \"user:eve\'example.com\" ], \"condition\": { \"title\": \"expirable -- access\", \"description\": \"Does not grant access after Sep 2020\", -- \"expression\": \"request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\')\", } } ], \"etag\": -- \"BwWWja0YfJA=\", \"version\": 3 } **YAML example:** bindings: - -- members: - user:mike\'example.com - group:admins\'example.com - -- domain:google.com - -- serviceAccount:my-project-id\'appspot.gserviceaccount.com role: -- roles\/resourcemanager.organizationAdmin - members: - -- user:eve\'example.com role: roles\/resourcemanager.organizationViewer -- condition: title: expirable access description: Does not grant access -- after Sep 2020 expression: request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\') - etag: BwWWja0YfJA= - version: -- 3 For a description of IAM and its features, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/docs\/). -- -- /See:/ 'policy' smart constructor. data Policy = Policy' { _pAuditConfigs :: !(Maybe [AuditConfig]) , _pEtag :: !(Maybe Bytes) , _pVersion :: !(Maybe (Textual Int32)) , _pBindings :: !(Maybe [Binding]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Policy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pAuditConfigs' -- -- * 'pEtag' -- -- * 'pVersion' -- -- * 'pBindings' policy :: Policy policy = Policy' { _pAuditConfigs = Nothing , _pEtag = Nothing , _pVersion = Nothing , _pBindings = Nothing } -- | Specifies cloud audit logging configuration for this policy. pAuditConfigs :: Lens' Policy [AuditConfig] pAuditConfigs = lens _pAuditConfigs (\ s a -> s{_pAuditConfigs = a}) . _Default . _Coerce -- | \`etag\` is used for optimistic concurrency control as a way to help -- prevent simultaneous updates of a policy from overwriting each other. It -- is strongly suggested that systems make use of the \`etag\` in the -- read-modify-write cycle to perform policy updates in order to avoid race -- conditions: An \`etag\` is returned in the response to \`getIamPolicy\`, -- and systems are expected to put that etag in the request to -- \`setIamPolicy\` to ensure that their change will be applied to the same -- version of the policy. **Important:** If you use IAM Conditions, you -- must include the \`etag\` field whenever you call \`setIamPolicy\`. If -- you omit this field, then IAM allows you to overwrite a version \`3\` -- policy with a version \`1\` policy, and all of the conditions in the -- version \`3\` policy are lost. pEtag :: Lens' Policy (Maybe ByteString) pEtag = lens _pEtag (\ s a -> s{_pEtag = a}) . mapping _Bytes -- | Specifies the format of the policy. Valid values are \`0\`, \`1\`, and -- \`3\`. Requests that specify an invalid value are rejected. Any -- operation that affects conditional role bindings must specify version -- \`3\`. This requirement applies to the following operations: * Getting a -- policy that includes a conditional role binding * Adding a conditional -- role binding to a policy * Changing a conditional role binding in a -- policy * Removing any role binding, with or without a condition, from a -- policy that includes conditions **Important:** If you use IAM -- Conditions, you must include the \`etag\` field whenever you call -- \`setIamPolicy\`. If you omit this field, then IAM allows you to -- overwrite a version \`3\` policy with a version \`1\` policy, and all of -- the conditions in the version \`3\` policy are lost. If a policy does -- not include any conditions, operations on that policy may specify any -- valid version or leave the field unset. To learn which resources support -- conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). pVersion :: Lens' Policy (Maybe Int32) pVersion = lens _pVersion (\ s a -> s{_pVersion = a}) . mapping _Coerce -- | Associates a list of \`members\` to a \`role\`. Optionally, may specify -- a \`condition\` that determines how and when the \`bindings\` are -- applied. Each of the \`bindings\` must contain at least one member. pBindings :: Lens' Policy [Binding] pBindings = lens _pBindings (\ s a -> s{_pBindings = a}) . _Default . _Coerce instance FromJSON Policy where parseJSON = withObject "Policy" (\ o -> Policy' <$> (o .:? "auditConfigs" .!= mempty) <*> (o .:? "etag") <*> (o .:? "version") <*> (o .:? "bindings" .!= mempty)) instance ToJSON Policy where toJSON Policy'{..} = object (catMaybes [("auditConfigs" .=) <$> _pAuditConfigs, ("etag" .=) <$> _pEtag, ("version" .=) <$> _pVersion, ("bindings" .=) <$> _pBindings]) -- | Cross-service attributes for the location. For example -- {\"cloud.googleapis.com\/region\": \"us-east1\"} -- -- /See:/ 'locationLabels' smart constructor. newtype LocationLabels = LocationLabels' { _llAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LocationLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llAddtional' locationLabels :: HashMap Text Text -- ^ 'llAddtional' -> LocationLabels locationLabels pLlAddtional_ = LocationLabels' {_llAddtional = _Coerce # pLlAddtional_} llAddtional :: Lens' LocationLabels (HashMap Text Text) llAddtional = lens _llAddtional (\ s a -> s{_llAddtional = a}) . _Coerce instance FromJSON LocationLabels where parseJSON = withObject "LocationLabels" (\ o -> LocationLabels' <$> (parseJSONObject o)) instance ToJSON LocationLabels where toJSON = toJSON . _llAddtional -- | Not supported by Cloud Run HTTPGetAction describes an action based on -- HTTP Get requests. -- -- /See:/ 'hTTPGetAction' smart constructor. data HTTPGetAction = HTTPGetAction' { _httpgaHTTPHeaders :: !(Maybe [HTTPHeader]) , _httpgaPath :: !(Maybe Text) , _httpgaScheme :: !(Maybe Text) , _httpgaHost :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPGetAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpgaHTTPHeaders' -- -- * 'httpgaPath' -- -- * 'httpgaScheme' -- -- * 'httpgaHost' hTTPGetAction :: HTTPGetAction hTTPGetAction = HTTPGetAction' { _httpgaHTTPHeaders = Nothing , _httpgaPath = Nothing , _httpgaScheme = Nothing , _httpgaHost = Nothing } -- | (Optional) Custom headers to set in the request. HTTP allows repeated -- headers. httpgaHTTPHeaders :: Lens' HTTPGetAction [HTTPHeader] httpgaHTTPHeaders = lens _httpgaHTTPHeaders (\ s a -> s{_httpgaHTTPHeaders = a}) . _Default . _Coerce -- | (Optional) Path to access on the HTTP server. httpgaPath :: Lens' HTTPGetAction (Maybe Text) httpgaPath = lens _httpgaPath (\ s a -> s{_httpgaPath = a}) -- | (Optional) Scheme to use for connecting to the host. Defaults to HTTP. httpgaScheme :: Lens' HTTPGetAction (Maybe Text) httpgaScheme = lens _httpgaScheme (\ s a -> s{_httpgaScheme = a}) -- | (Optional) Host name to connect to, defaults to the pod IP. You probably -- want to set \"Host\" in httpHeaders instead. httpgaHost :: Lens' HTTPGetAction (Maybe Text) httpgaHost = lens _httpgaHost (\ s a -> s{_httpgaHost = a}) instance FromJSON HTTPGetAction where parseJSON = withObject "HTTPGetAction" (\ o -> HTTPGetAction' <$> (o .:? "httpHeaders" .!= mempty) <*> (o .:? "path") <*> (o .:? "scheme") <*> (o .:? "host")) instance ToJSON HTTPGetAction where toJSON HTTPGetAction'{..} = object (catMaybes [("httpHeaders" .=) <$> _httpgaHTTPHeaders, ("path" .=) <$> _httpgaPath, ("scheme" .=) <$> _httpgaScheme, ("host" .=) <$> _httpgaHost]) -- | Configuration represents the \"floating HEAD\" of a linear history of -- Revisions, and optionally how the containers those revisions reference -- are built. Users create new Revisions by updating the Configuration\'s -- spec. The \"latest created\" revision\'s name is available under status, -- as is the \"latest ready\" revision\'s name. See also: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/spec\/overview.md#configuration -- -- /See:/ 'configuration' smart constructor. data Configuration = Configuration' { _cStatus :: !(Maybe ConfigurationStatus) , _cAPIVersion :: !(Maybe Text) , _cKind :: !(Maybe Text) , _cSpec :: !(Maybe ConfigurationSpec) , _cMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Configuration' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cStatus' -- -- * 'cAPIVersion' -- -- * 'cKind' -- -- * 'cSpec' -- -- * 'cMetadata' configuration :: Configuration configuration = Configuration' { _cStatus = Nothing , _cAPIVersion = Nothing , _cKind = Nothing , _cSpec = Nothing , _cMetadata = Nothing } -- | Status communicates the observed state of the Configuration (from the -- controller). cStatus :: Lens' Configuration (Maybe ConfigurationStatus) cStatus = lens _cStatus (\ s a -> s{_cStatus = a}) -- | The API version for this call such as \"serving.knative.dev\/v1\". cAPIVersion :: Lens' Configuration (Maybe Text) cAPIVersion = lens _cAPIVersion (\ s a -> s{_cAPIVersion = a}) -- | The kind of resource, in this case always \"Configuration\". cKind :: Lens' Configuration (Maybe Text) cKind = lens _cKind (\ s a -> s{_cKind = a}) -- | Spec holds the desired state of the Configuration (from the client). cSpec :: Lens' Configuration (Maybe ConfigurationSpec) cSpec = lens _cSpec (\ s a -> s{_cSpec = a}) -- | Metadata associated with this Configuration, including name, namespace, -- labels, and annotations. cMetadata :: Lens' Configuration (Maybe ObjectMeta) cMetadata = lens _cMetadata (\ s a -> s{_cMetadata = a}) instance FromJSON Configuration where parseJSON = withObject "Configuration" (\ o -> Configuration' <$> (o .:? "status") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON Configuration where toJSON Configuration'{..} = object (catMaybes [("status" .=) <$> _cStatus, ("apiVersion" .=) <$> _cAPIVersion, ("kind" .=) <$> _cKind, ("spec" .=) <$> _cSpec, ("metadata" .=) <$> _cMetadata]) -- | Service-specific metadata. For example the available capacity at the -- given location. -- -- /See:/ 'locationMetadata' smart constructor. newtype LocationMetadata = LocationMetadata' { _lmAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LocationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmAddtional' locationMetadata :: HashMap Text JSONValue -- ^ 'lmAddtional' -> LocationMetadata locationMetadata pLmAddtional_ = LocationMetadata' {_lmAddtional = _Coerce # pLmAddtional_} -- | Properties of the object. Contains field \'type with type URL. lmAddtional :: Lens' LocationMetadata (HashMap Text JSONValue) lmAddtional = lens _lmAddtional (\ s a -> s{_lmAddtional = a}) . _Coerce instance FromJSON LocationMetadata where parseJSON = withObject "LocationMetadata" (\ o -> LocationMetadata' <$> (parseJSONObject o)) instance ToJSON LocationMetadata where toJSON = toJSON . _lmAddtional -- | Provides the configuration for logging a type of permissions. Example: { -- \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" } ] } This enables \'DATA_READ\' and \'DATA_WRITE\' -- logging, while exempting jose\'example.com from DATA_READ logging. -- -- /See:/ 'auditLogConfig' smart constructor. data AuditLogConfig = AuditLogConfig' { _alcLogType :: !(Maybe AuditLogConfigLogType) , _alcExemptedMembers :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditLogConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alcLogType' -- -- * 'alcExemptedMembers' auditLogConfig :: AuditLogConfig auditLogConfig = AuditLogConfig' {_alcLogType = Nothing, _alcExemptedMembers = Nothing} -- | The log type that this config enables. alcLogType :: Lens' AuditLogConfig (Maybe AuditLogConfigLogType) alcLogType = lens _alcLogType (\ s a -> s{_alcLogType = a}) -- | Specifies the identities that do not cause logging for this type of -- permission. Follows the same format of Binding.members. alcExemptedMembers :: Lens' AuditLogConfig [Text] alcExemptedMembers = lens _alcExemptedMembers (\ s a -> s{_alcExemptedMembers = a}) . _Default . _Coerce instance FromJSON AuditLogConfig where parseJSON = withObject "AuditLogConfig" (\ o -> AuditLogConfig' <$> (o .:? "logType") <*> (o .:? "exemptedMembers" .!= mempty)) instance ToJSON AuditLogConfig where toJSON AuditLogConfig'{..} = object (catMaybes [("logType" .=) <$> _alcLogType, ("exemptedMembers" .=) <$> _alcExemptedMembers]) -- | Not supported by Cloud Run LocalObjectReference contains enough -- information to let you locate the referenced object inside the same -- namespace. -- -- /See:/ 'localObjectReference' smart constructor. newtype LocalObjectReference = LocalObjectReference' { _lorName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LocalObjectReference' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lorName' localObjectReference :: LocalObjectReference localObjectReference = LocalObjectReference' {_lorName = Nothing} -- | (Optional) Name of the referent. More info: -- https:\/\/kubernetes.io\/docs\/concepts\/overview\/working-with-objects\/names\/#names lorName :: Lens' LocalObjectReference (Maybe Text) lorName = lens _lorName (\ s a -> s{_lorName = a}) instance FromJSON LocalObjectReference where parseJSON = withObject "LocalObjectReference" (\ o -> LocalObjectReference' <$> (o .:? "name")) instance ToJSON LocalObjectReference where toJSON LocalObjectReference'{..} = object (catMaybes [("name" .=) <$> _lorName]) -- | Revision is an immutable snapshot of code and configuration. A revision -- references a container image. Revisions are created by updates to a -- Configuration. See also: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/spec\/overview.md#revision -- -- /See:/ 'revision' smart constructor. data Revision = Revision' { _revStatus :: !(Maybe RevisionStatus) , _revAPIVersion :: !(Maybe Text) , _revKind :: !(Maybe Text) , _revSpec :: !(Maybe RevisionSpec) , _revMetadata :: !(Maybe ObjectMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Revision' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'revStatus' -- -- * 'revAPIVersion' -- -- * 'revKind' -- -- * 'revSpec' -- -- * 'revMetadata' revision :: Revision revision = Revision' { _revStatus = Nothing , _revAPIVersion = Nothing , _revKind = Nothing , _revSpec = Nothing , _revMetadata = Nothing } -- | Status communicates the observed state of the Revision (from the -- controller). revStatus :: Lens' Revision (Maybe RevisionStatus) revStatus = lens _revStatus (\ s a -> s{_revStatus = a}) -- | The API version for this call such as \"serving.knative.dev\/v1\". revAPIVersion :: Lens' Revision (Maybe Text) revAPIVersion = lens _revAPIVersion (\ s a -> s{_revAPIVersion = a}) -- | The kind of this resource, in this case \"Revision\". revKind :: Lens' Revision (Maybe Text) revKind = lens _revKind (\ s a -> s{_revKind = a}) -- | Spec holds the desired state of the Revision (from the client). revSpec :: Lens' Revision (Maybe RevisionSpec) revSpec = lens _revSpec (\ s a -> s{_revSpec = a}) -- | Metadata associated with this Revision, including name, namespace, -- labels, and annotations. revMetadata :: Lens' Revision (Maybe ObjectMeta) revMetadata = lens _revMetadata (\ s a -> s{_revMetadata = a}) instance FromJSON Revision where parseJSON = withObject "Revision" (\ o -> Revision' <$> (o .:? "status") <*> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON Revision where toJSON Revision'{..} = object (catMaybes [("status" .=) <$> _revStatus, ("apiVersion" .=) <$> _revAPIVersion, ("kind" .=) <$> _revKind, ("spec" .=) <$> _revSpec, ("metadata" .=) <$> _revMetadata]) -- | Not supported by Cloud Run EnvFromSource represents the source of a set -- of ConfigMaps -- -- /See:/ 'envFromSource' smart constructor. data EnvFromSource = EnvFromSource' { _efsConfigMapRef :: !(Maybe ConfigMapEnvSource) , _efsSecretRef :: !(Maybe SecretEnvSource) , _efsPrefix :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EnvFromSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'efsConfigMapRef' -- -- * 'efsSecretRef' -- -- * 'efsPrefix' envFromSource :: EnvFromSource envFromSource = EnvFromSource' {_efsConfigMapRef = Nothing, _efsSecretRef = Nothing, _efsPrefix = Nothing} -- | (Optional) The ConfigMap to select from efsConfigMapRef :: Lens' EnvFromSource (Maybe ConfigMapEnvSource) efsConfigMapRef = lens _efsConfigMapRef (\ s a -> s{_efsConfigMapRef = a}) -- | (Optional) The Secret to select from efsSecretRef :: Lens' EnvFromSource (Maybe SecretEnvSource) efsSecretRef = lens _efsSecretRef (\ s a -> s{_efsSecretRef = a}) -- | (Optional) An optional identifier to prepend to each key in the -- ConfigMap. Must be a C_IDENTIFIER. efsPrefix :: Lens' EnvFromSource (Maybe Text) efsPrefix = lens _efsPrefix (\ s a -> s{_efsPrefix = a}) instance FromJSON EnvFromSource where parseJSON = withObject "EnvFromSource" (\ o -> EnvFromSource' <$> (o .:? "configMapRef") <*> (o .:? "secretRef") <*> (o .:? "prefix")) instance ToJSON EnvFromSource where toJSON EnvFromSource'{..} = object (catMaybes [("configMapRef" .=) <$> _efsConfigMapRef, ("secretRef" .=) <$> _efsSecretRef, ("prefix" .=) <$> _efsPrefix]) -- | RevisionSpec holds the desired state of the Revision (from the client). -- -- /See:/ 'revisionSpec' smart constructor. data RevisionSpec = RevisionSpec' { _rsServiceAccountName :: !(Maybe Text) , _rsContainers :: !(Maybe [Container]) , _rsContainerConcurrency :: !(Maybe (Textual Int32)) , _rsTimeoutSeconds :: !(Maybe (Textual Int32)) , _rsVolumes :: !(Maybe [Volume]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RevisionSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rsServiceAccountName' -- -- * 'rsContainers' -- -- * 'rsContainerConcurrency' -- -- * 'rsTimeoutSeconds' -- -- * 'rsVolumes' revisionSpec :: RevisionSpec revisionSpec = RevisionSpec' { _rsServiceAccountName = Nothing , _rsContainers = Nothing , _rsContainerConcurrency = Nothing , _rsTimeoutSeconds = Nothing , _rsVolumes = Nothing } -- | Email address of the IAM service account associated with the revision of -- the service. The service account represents the identity of the running -- revision, and determines what permissions the revision has. If not -- provided, the revision will use the project\'s default service account. rsServiceAccountName :: Lens' RevisionSpec (Maybe Text) rsServiceAccountName = lens _rsServiceAccountName (\ s a -> s{_rsServiceAccountName = a}) -- | Containers holds the single container that defines the unit of execution -- for this Revision. In the context of a Revision, we disallow a number of -- fields on this Container, including: name and lifecycle. In Cloud Run, -- only a single container may be provided. The runtime contract is -- documented here: -- https:\/\/github.com\/knative\/serving\/blob\/master\/docs\/runtime-contract.md rsContainers :: Lens' RevisionSpec [Container] rsContainers = lens _rsContainers (\ s a -> s{_rsContainers = a}) . _Default . _Coerce -- | Optional. ContainerConcurrency specifies the maximum allowed in-flight -- (concurrent) requests per container instance of the Revision. Cloud Run -- fully managed: supported, defaults to 80 Cloud Run for Anthos: -- supported, defaults to 0, which means concurrency to the application is -- not limited, and the system decides the target concurrency for the -- autoscaler. rsContainerConcurrency :: Lens' RevisionSpec (Maybe Int32) rsContainerConcurrency = lens _rsContainerConcurrency (\ s a -> s{_rsContainerConcurrency = a}) . mapping _Coerce -- | TimeoutSeconds holds the max duration the instance is allowed for -- responding to a request. Cloud Run fully managed: defaults to 300 -- seconds (5 minutes). Maximum allowed value is 900 seconds (15 minutes). -- Cloud Run for Anthos: defaults to 300 seconds (5 minutes). Maximum -- allowed value is configurable by the cluster operator. rsTimeoutSeconds :: Lens' RevisionSpec (Maybe Int32) rsTimeoutSeconds = lens _rsTimeoutSeconds (\ s a -> s{_rsTimeoutSeconds = a}) . mapping _Coerce rsVolumes :: Lens' RevisionSpec [Volume] rsVolumes = lens _rsVolumes (\ s a -> s{_rsVolumes = a}) . _Default . _Coerce instance FromJSON RevisionSpec where parseJSON = withObject "RevisionSpec" (\ o -> RevisionSpec' <$> (o .:? "serviceAccountName") <*> (o .:? "containers" .!= mempty) <*> (o .:? "containerConcurrency") <*> (o .:? "timeoutSeconds") <*> (o .:? "volumes" .!= mempty)) instance ToJSON RevisionSpec where toJSON RevisionSpec'{..} = object (catMaybes [("serviceAccountName" .=) <$> _rsServiceAccountName, ("containers" .=) <$> _rsContainers, ("containerConcurrency" .=) <$> _rsContainerConcurrency, ("timeoutSeconds" .=) <$> _rsTimeoutSeconds, ("volumes" .=) <$> _rsVolumes]) -- | Not supported by Cloud Run ConfigMapEnvSource selects a ConfigMap to -- populate the environment variables with. The contents of the target -- ConfigMap\'s Data field will represent the key-value pairs as -- environment variables. -- -- /See:/ 'configMapEnvSource' smart constructor. data ConfigMapEnvSource = ConfigMapEnvSource' { _cmesName :: !(Maybe Text) , _cmesLocalObjectReference :: !(Maybe LocalObjectReference) , _cmesOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ConfigMapEnvSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmesName' -- -- * 'cmesLocalObjectReference' -- -- * 'cmesOptional' configMapEnvSource :: ConfigMapEnvSource configMapEnvSource = ConfigMapEnvSource' { _cmesName = Nothing , _cmesLocalObjectReference = Nothing , _cmesOptional = Nothing } -- | The ConfigMap to select from. cmesName :: Lens' ConfigMapEnvSource (Maybe Text) cmesName = lens _cmesName (\ s a -> s{_cmesName = a}) -- | This field should not be used directly as it is meant to be inlined -- directly into the message. Use the \"name\" field instead. cmesLocalObjectReference :: Lens' ConfigMapEnvSource (Maybe LocalObjectReference) cmesLocalObjectReference = lens _cmesLocalObjectReference (\ s a -> s{_cmesLocalObjectReference = a}) -- | (Optional) Specify whether the ConfigMap must be defined cmesOptional :: Lens' ConfigMapEnvSource (Maybe Bool) cmesOptional = lens _cmesOptional (\ s a -> s{_cmesOptional = a}) instance FromJSON ConfigMapEnvSource where parseJSON = withObject "ConfigMapEnvSource" (\ o -> ConfigMapEnvSource' <$> (o .:? "name") <*> (o .:? "localObjectReference") <*> (o .:? "optional")) instance ToJSON ConfigMapEnvSource where toJSON ConfigMapEnvSource'{..} = object (catMaybes [("name" .=) <$> _cmesName, ("localObjectReference" .=) <$> _cmesLocalObjectReference, ("optional" .=) <$> _cmesOptional]) -- | Not supported by Cloud Run SecretEnvSource selects a Secret to populate -- the environment variables with. The contents of the target Secret\'s -- Data field will represent the key-value pairs as environment variables. -- -- /See:/ 'secretEnvSource' smart constructor. data SecretEnvSource = SecretEnvSource' { _sesName :: !(Maybe Text) , _sesLocalObjectReference :: !(Maybe LocalObjectReference) , _sesOptional :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecretEnvSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sesName' -- -- * 'sesLocalObjectReference' -- -- * 'sesOptional' secretEnvSource :: SecretEnvSource secretEnvSource = SecretEnvSource' { _sesName = Nothing , _sesLocalObjectReference = Nothing , _sesOptional = Nothing } -- | The Secret to select from. sesName :: Lens' SecretEnvSource (Maybe Text) sesName = lens _sesName (\ s a -> s{_sesName = a}) -- | This field should not be used directly as it is meant to be inlined -- directly into the message. Use the \"name\" field instead. sesLocalObjectReference :: Lens' SecretEnvSource (Maybe LocalObjectReference) sesLocalObjectReference = lens _sesLocalObjectReference (\ s a -> s{_sesLocalObjectReference = a}) -- | (Optional) Specify whether the Secret must be defined sesOptional :: Lens' SecretEnvSource (Maybe Bool) sesOptional = lens _sesOptional (\ s a -> s{_sesOptional = a}) instance FromJSON SecretEnvSource where parseJSON = withObject "SecretEnvSource" (\ o -> SecretEnvSource' <$> (o .:? "name") <*> (o .:? "localObjectReference") <*> (o .:? "optional")) instance ToJSON SecretEnvSource where toJSON SecretEnvSource'{..} = object (catMaybes [("name" .=) <$> _sesName, ("localObjectReference" .=) <$> _sesLocalObjectReference, ("optional" .=) <$> _sesOptional]) -- | ListDomainMappingsResponse is a list of DomainMapping resources. -- -- /See:/ 'listDomainMAppingsResponse' smart constructor. data ListDomainMAppingsResponse = ListDomainMAppingsResponse' { _ldmarAPIVersion :: !(Maybe Text) , _ldmarKind :: !(Maybe Text) , _ldmarItems :: !(Maybe [DomainMApping]) , _ldmarUnreachable :: !(Maybe [Text]) , _ldmarMetadata :: !(Maybe ListMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListDomainMAppingsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ldmarAPIVersion' -- -- * 'ldmarKind' -- -- * 'ldmarItems' -- -- * 'ldmarUnreachable' -- -- * 'ldmarMetadata' listDomainMAppingsResponse :: ListDomainMAppingsResponse listDomainMAppingsResponse = ListDomainMAppingsResponse' { _ldmarAPIVersion = Nothing , _ldmarKind = Nothing , _ldmarItems = Nothing , _ldmarUnreachable = Nothing , _ldmarMetadata = Nothing } -- | The API version for this call such as \"domains.cloudrun.com\/v1\". ldmarAPIVersion :: Lens' ListDomainMAppingsResponse (Maybe Text) ldmarAPIVersion = lens _ldmarAPIVersion (\ s a -> s{_ldmarAPIVersion = a}) -- | The kind of this resource, in this case \"DomainMappingList\". ldmarKind :: Lens' ListDomainMAppingsResponse (Maybe Text) ldmarKind = lens _ldmarKind (\ s a -> s{_ldmarKind = a}) -- | List of DomainMappings. ldmarItems :: Lens' ListDomainMAppingsResponse [DomainMApping] ldmarItems = lens _ldmarItems (\ s a -> s{_ldmarItems = a}) . _Default . _Coerce -- | Locations that could not be reached. ldmarUnreachable :: Lens' ListDomainMAppingsResponse [Text] ldmarUnreachable = lens _ldmarUnreachable (\ s a -> s{_ldmarUnreachable = a}) . _Default . _Coerce -- | Metadata associated with this DomainMapping list. ldmarMetadata :: Lens' ListDomainMAppingsResponse (Maybe ListMeta) ldmarMetadata = lens _ldmarMetadata (\ s a -> s{_ldmarMetadata = a}) instance FromJSON ListDomainMAppingsResponse where parseJSON = withObject "ListDomainMAppingsResponse" (\ o -> ListDomainMAppingsResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "unreachable" .!= mempty) <*> (o .:? "metadata")) instance ToJSON ListDomainMAppingsResponse where toJSON ListDomainMAppingsResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _ldmarAPIVersion, ("kind" .=) <$> _ldmarKind, ("items" .=) <$> _ldmarItems, ("unreachable" .=) <$> _ldmarUnreachable, ("metadata" .=) <$> _ldmarMetadata]) -- | ContainerPort represents a network port in a single container. -- -- /See:/ 'containerPort' smart constructor. data ContainerPort = ContainerPort' { _cpProtocol :: !(Maybe Text) , _cpName :: !(Maybe Text) , _cpContainerPort :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ContainerPort' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpProtocol' -- -- * 'cpName' -- -- * 'cpContainerPort' containerPort :: ContainerPort containerPort = ContainerPort' {_cpProtocol = Nothing, _cpName = Nothing, _cpContainerPort = Nothing} -- | (Optional) Protocol for port. Must be \"TCP\". Defaults to \"TCP\". cpProtocol :: Lens' ContainerPort (Maybe Text) cpProtocol = lens _cpProtocol (\ s a -> s{_cpProtocol = a}) -- | (Optional) If specified, used to specify which protocol to use. Allowed -- values are \"http1\" and \"h2c\". cpName :: Lens' ContainerPort (Maybe Text) cpName = lens _cpName (\ s a -> s{_cpName = a}) -- | (Optional) Port number the container listens on. This must be a valid -- port number, 0 \< x \< 65536. cpContainerPort :: Lens' ContainerPort (Maybe Int32) cpContainerPort = lens _cpContainerPort (\ s a -> s{_cpContainerPort = a}) . mapping _Coerce instance FromJSON ContainerPort where parseJSON = withObject "ContainerPort" (\ o -> ContainerPort' <$> (o .:? "protocol") <*> (o .:? "name") <*> (o .:? "containerPort")) instance ToJSON ContainerPort where toJSON ContainerPort'{..} = object (catMaybes [("protocol" .=) <$> _cpProtocol, ("name" .=) <$> _cpName, ("containerPort" .=) <$> _cpContainerPort]) -- | ListRevisionsResponse is a list of Revision resources. -- -- /See:/ 'listRevisionsResponse' smart constructor. data ListRevisionsResponse = ListRevisionsResponse' { _lisAPIVersion :: !(Maybe Text) , _lisKind :: !(Maybe Text) , _lisItems :: !(Maybe [Revision]) , _lisUnreachable :: !(Maybe [Text]) , _lisMetadata :: !(Maybe ListMeta) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListRevisionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lisAPIVersion' -- -- * 'lisKind' -- -- * 'lisItems' -- -- * 'lisUnreachable' -- -- * 'lisMetadata' listRevisionsResponse :: ListRevisionsResponse listRevisionsResponse = ListRevisionsResponse' { _lisAPIVersion = Nothing , _lisKind = Nothing , _lisItems = Nothing , _lisUnreachable = Nothing , _lisMetadata = Nothing } -- | The API version for this call such as \"serving.knative.dev\/v1\". lisAPIVersion :: Lens' ListRevisionsResponse (Maybe Text) lisAPIVersion = lens _lisAPIVersion (\ s a -> s{_lisAPIVersion = a}) -- | The kind of this resource, in this case \"RevisionList\". lisKind :: Lens' ListRevisionsResponse (Maybe Text) lisKind = lens _lisKind (\ s a -> s{_lisKind = a}) -- | List of Revisions. lisItems :: Lens' ListRevisionsResponse [Revision] lisItems = lens _lisItems (\ s a -> s{_lisItems = a}) . _Default . _Coerce -- | Locations that could not be reached. lisUnreachable :: Lens' ListRevisionsResponse [Text] lisUnreachable = lens _lisUnreachable (\ s a -> s{_lisUnreachable = a}) . _Default . _Coerce -- | Metadata associated with this revision list. lisMetadata :: Lens' ListRevisionsResponse (Maybe ListMeta) lisMetadata = lens _lisMetadata (\ s a -> s{_lisMetadata = a}) instance FromJSON ListRevisionsResponse where parseJSON = withObject "ListRevisionsResponse" (\ o -> ListRevisionsResponse' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "items" .!= mempty) <*> (o .:? "unreachable" .!= mempty) <*> (o .:? "metadata")) instance ToJSON ListRevisionsResponse where toJSON ListRevisionsResponse'{..} = object (catMaybes [("apiVersion" .=) <$> _lisAPIVersion, ("kind" .=) <$> _lisKind, ("items" .=) <$> _lisItems, ("unreachable" .=) <$> _lisUnreachable, ("metadata" .=) <$> _lisMetadata]) -- | Associates \`members\` with a \`role\`. -- -- /See:/ 'binding' smart constructor. data Binding = Binding' { _bMembers :: !(Maybe [Text]) , _bRole :: !(Maybe Text) , _bCondition :: !(Maybe Expr) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Binding' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bMembers' -- -- * 'bRole' -- -- * 'bCondition' binding :: Binding binding = Binding' {_bMembers = Nothing, _bRole = Nothing, _bCondition = Nothing} -- | Specifies the identities requesting access for a Cloud Platform -- resource. \`members\` can have the following values: * \`allUsers\`: A -- special identifier that represents anyone who is on the internet; with -- or without a Google account. * \`allAuthenticatedUsers\`: A special -- identifier that represents anyone who is authenticated with a Google -- account or a service account. * \`user:{emailid}\`: An email address -- that represents a specific Google account. For example, -- \`alice\'example.com\` . * \`serviceAccount:{emailid}\`: An email -- address that represents a service account. For example, -- \`my-other-app\'appspot.gserviceaccount.com\`. * \`group:{emailid}\`: An -- email address that represents a Google group. For example, -- \`admins\'example.com\`. * \`deleted:user:{emailid}?uid={uniqueid}\`: An -- email address (plus unique identifier) representing a user that has been -- recently deleted. For example, -- \`alice\'example.com?uid=123456789012345678901\`. If the user is -- recovered, this value reverts to \`user:{emailid}\` and the recovered -- user retains the role in the binding. * -- \`deleted:serviceAccount:{emailid}?uid={uniqueid}\`: An email address -- (plus unique identifier) representing a service account that has been -- recently deleted. For example, -- \`my-other-app\'appspot.gserviceaccount.com?uid=123456789012345678901\`. -- If the service account is undeleted, this value reverts to -- \`serviceAccount:{emailid}\` and the undeleted service account retains -- the role in the binding. * \`deleted:group:{emailid}?uid={uniqueid}\`: -- An email address (plus unique identifier) representing a Google group -- that has been recently deleted. For example, -- \`admins\'example.com?uid=123456789012345678901\`. If the group is -- recovered, this value reverts to \`group:{emailid}\` and the recovered -- group retains the role in the binding. * \`domain:{domain}\`: The G -- Suite domain (primary) that represents all the users of that domain. For -- example, \`google.com\` or \`example.com\`. bMembers :: Lens' Binding [Text] bMembers = lens _bMembers (\ s a -> s{_bMembers = a}) . _Default . _Coerce -- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`, -- \`roles\/editor\`, or \`roles\/owner\`. bRole :: Lens' Binding (Maybe Text) bRole = lens _bRole (\ s a -> s{_bRole = a}) -- | The condition that is associated with this binding. If the condition -- evaluates to \`true\`, then this binding applies to the current request. -- If the condition evaluates to \`false\`, then this binding does not -- apply to the current request. However, a different role binding might -- grant the same role to one or more of the members in this binding. To -- learn which resources support conditions in their IAM policies, see the -- [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). bCondition :: Lens' Binding (Maybe Expr) bCondition = lens _bCondition (\ s a -> s{_bCondition = a}) instance FromJSON Binding where parseJSON = withObject "Binding" (\ o -> Binding' <$> (o .:? "members" .!= mempty) <*> (o .:? "role") <*> (o .:? "condition")) instance ToJSON Binding where toJSON Binding'{..} = object (catMaybes [("members" .=) <$> _bMembers, ("role" .=) <$> _bRole, ("condition" .=) <$> _bCondition]) -- | Maps a string key to a path within a volume. -- -- /See:/ 'keyToPath' smart constructor. data KeyToPath = KeyToPath' { _ktpPath :: !(Maybe Text) , _ktpMode :: !(Maybe (Textual Int32)) , _ktpKey :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'KeyToPath' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ktpPath' -- -- * 'ktpMode' -- -- * 'ktpKey' keyToPath :: KeyToPath keyToPath = KeyToPath' {_ktpPath = Nothing, _ktpMode = Nothing, _ktpKey = Nothing} -- | The relative path of the file to map the key to. May not be an absolute -- path. May not contain the path element \'..\'. May not start with the -- string \'..\'. ktpPath :: Lens' KeyToPath (Maybe Text) ktpPath = lens _ktpPath (\ s a -> s{_ktpPath = a}) -- | (Optional) Mode bits to use on this file, must be a value between 0000 -- and 0777. If not specified, the volume defaultMode will be used. This -- might be in conflict with other options that affect the file mode, like -- fsGroup, and the result can be other mode bits set. ktpMode :: Lens' KeyToPath (Maybe Int32) ktpMode = lens _ktpMode (\ s a -> s{_ktpMode = a}) . mapping _Coerce -- | The Cloud Secret Manager secret version. Can be \'latest\' for the -- latest value or an integer for a specific version. The key to project. ktpKey :: Lens' KeyToPath (Maybe Text) ktpKey = lens _ktpKey (\ s a -> s{_ktpKey = a}) instance FromJSON KeyToPath where parseJSON = withObject "KeyToPath" (\ o -> KeyToPath' <$> (o .:? "path") <*> (o .:? "mode") <*> (o .:? "key")) instance ToJSON KeyToPath where toJSON KeyToPath'{..} = object (catMaybes [("path" .=) <$> _ktpPath, ("mode" .=) <$> _ktpMode, ("key" .=) <$> _ktpKey])
brendanhay/gogol
gogol-run/gen/Network/Google/Run/Types/Product.hs
mpl-2.0
193,876
0
27
44,565
32,149
18,687
13,462
3,429
1
module Tables.A301851 where import Helpers.DistinctDistances (distinctDistances) import Helpers.Table (tableByAntidiagonals) a301851 :: Integer -> Int a301851 n = distinctDistances (n' + 1) (k' + 1) where (n', k') = tableByAntidiagonals (n - 1)
peterokagey/haskellOEIS
src/Tables/A301851.hs
apache-2.0
250
0
9
37
86
48
38
6
1
data Info = Info { infoPath :: FilePath , infoPerms :: Maybe Permissions , infoSize :: Maybe Integer , infoModTime :: Maybe ClockTime } deriving (Eq, Ord, Show) getInfo :: FilePath -> IO Info getInfo = undefined traverse :: ([Info] -> [Info]) -> FilePath -> IO [Info] traverse order path = do names <- getUsefulContents path contents <- mapM getInfo (path : map (path </>) names) liftM concat $ forM (order contents) $ \info -> do if isDirectory info && infoPath info /= path then traverse order $ infoPath info else return [info] getUsefulContents :: FilePath -> IO [String] getUsefulContents path = do names <- getDirecotryContents path return $ filter (`notElem` [".", ".."]) names isDirectory :: Info -> Bool isDirectory = maybe False searchable . infoPerms maybeIO :: IO a -> IO (Maybe a) maybeIO act = handle (\_ -> return Nothing) (Just `liftM` act) getInfo path = do perms <- maybeIO $ getPermissions path size <- maybeIO (bracket (openFile path ReadMode) hclose hFileSize) modified <- maybeIO $ getModificationTime path return $ Info path perms size modified
EricYT/Haskell
src/real_haskell/chapter-9/ControlledVisit.hs
apache-2.0
1,187
0
14
296
438
220
218
29
2
import Data.IORef data Expr = EVar String | ELam String Expr | EApp Expr Expr | EBool Bool | EInt Integer | EFix Expr deriving (Show) data Value = VBool Bool | VInt Integer | VClosure (Thunk -> IO Value) instance Show Value where show (VBool b) = show b show (VInt n) = show n show (VClosure _) = "<<closure>>" type Env = [(String, IORef Thunk)] type Thunk = () -> IO Value update :: IORef Thunk -> Value -> IO () update ref v = do writeIORef ref (\() -> return v) return () lookupEnv :: Env -> String -> IO (IORef Thunk) lookupEnv [] y = error $ "Unbound Variable" ++ y lookupEnv ((x, v) : xs) n = if x == n then return v else lookupEnv xs n force :: IORef Thunk -> IO Value force ref = do th <- readIORef ref v <- th () update ref v return v mkThunk :: Env -> String -> Expr -> (Thunk -> IO Value) mkThunk env x body a = do a' <- newIORef a eval ((x, a') : env) body eval :: Env -> Expr -> IO Value eval env ex = case ex of EVar n -> do th <- lookupEnv env n force th ELam x e -> return $ VClosure (mkThunk env x e) EApp a b -> do VClosure c <- eval env a c (\() -> eval env b) EBool b -> return $ VBool b EInt n -> return $ VInt n EFix e -> eval env (EApp e (EFix e)) omega :: Expr omega = EApp (ELam "x" (EApp (EVar "x") (EVar "x"))) (ELam "x" (EApp (EVar "x") (EVar "x"))) test1 :: IO Value test1 = eval [] $ EApp (ELam "y" (EInt 42)) omega main = undefined
toonn/wyah
src/CbNdInterpreter.hs
bsd-2-clause
1,621
8
13
559
767
370
397
57
6
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} import qualified Data.ByteString.Char8 as C import qualified Data.Set as Set import qualified Data.IntSet as IntSet import qualified Data.IntMap.Strict as IntMap import Data.IntSet(IntSet) import Data.IntMap.Strict(IntMap) import Data.Set(Set) import Control.Monad import Data.Array.Unboxed import Data.Array.ST import Control.Monad.ST import Data.Array.IO import Data.Array.Unsafe import Data.Maybe import Data.Int import Data.Ord import Data.List import Debug.Trace type Node = Int type Weight = Int type LNode = (Node, Weight) type Graph = Array Int [(Int, Int)] data WP = WP { currWeight :: {-# UNPACK #-} !Weight , currNnode :: {-# UNPACK #-} !Node , prevWeight :: {-# UNPACK #-} !Weight , prevNode :: {-# UNPACK #-} !Node } instance Show WP where show (WP w1 n1 w2 n2) = show n1 ++ "(" ++ show w1 ++ ")" ++ " <-- " ++ show n2 ++ "(" ++ show w2 ++ ")" instance Eq WP where (WP cw1 cn1 pw1 pn1) == (WP cw2 cn2 pw2 pn2) = cw1 == cw2 && cn1 == cn2 instance Ord WP where compare (WP cw1 cn1 pw1 pn1) (WP cw2 cn2 pw2 pn2) = compare (cw1, cn1) (cw2, cn2) data Work = Work { _done :: [WP] , _visited :: !IntSet , _minHeap :: !(Set WP) , _adjustedNodes :: !(IntMap WP) } deriving Show {-# INLINE adjustHeap #-} {-# INLINE insertHeap #-} adjustHeap old new heap = Set.insert new . Set.delete old $ heap insertHeap new = Set.insert new {-# INLINE mkWP #-} mkWP w n pw pn = WP w n pw pn adjust heap adjusted from@(WP w1 n1 pw1 pn1) (!to, !weight) = case IntMap.lookup to adjusted of Nothing -> ((insertHeap (mkWP newWeight to w1 n1) heap), (IntMap.insert to (mkWP newWeight to w1 n1) adjusted)) Just wpold@(WP oldWeight oldn oldw1 oldn1) -> case compare newWeight oldWeight of GT -> (heap, adjusted) EQ -> if weight >= (w1 - pw1) then (heap, adjusted) else ((adjustHeap wpold (mkWP newWeight to w1 n1) heap), (IntMap.insert to (mkWP newWeight to w1 n1) adjusted)) LT -> ((adjustHeap wpold (mkWP newWeight to w1 n1) heap), (IntMap.insert to (mkWP newWeight to w1 n1) adjusted)) where !newWeight = w1 + weight {-# INLINE expand #-} expand (!heap, !adjusted) (!latest, !to) = r --trace ("expand" ++ show (latest, to, r)) $ r where !r = adjust heap adjusted latest to {-# INLINE mkSource #-} mkSource srcs = Work done (IntSet.fromList srcs) Set.empty IntMap.empty where done = map (\s -> WP 0 s 0 s) srcs sp work@(Work ( (latest@(WP startW startN prevW prevN)) : done) visited heap adjusted) graph = let !adjs = filter (\(to, toW) -> to `IntSet.notMember` visited ) (graph ! startN) !(!heap', !adjusted') = foldl expand (heap, adjusted) (zip (repeat latest) adjs) in case Set.minView heap' of Nothing -> (latest:done) Just (!wpnew@(WP minW minN prevMinW prevMinN), !heap'') -> let !visited' = IntSet.insert minN visited !done' = wpnew : latest : done in sp (Work done' visited' heap'' adjusted') graph dijkstra source graph = sp (mkSource [source]) graph lnode (WP w n w1 n1) = (n, w) {-# INLINE lnode #-} cntall fwd rsd lo hi = foldl go 0 [succ lo .. hi] where go r k = r + fwd ! k + rsd ! k mkUArr lo hi l = array (lo, hi) l :: UArray Node Weight incards graph graph' = cntall fwd rsd start end where (start, end) = bounds graph fwd = mkUArr start end . map lnode . dijkstra start $ graph rsd = mkUArr start end . map lnode . dijkstra start $ graph' {-# INLINE readP2 #-} {-# INLINE readP3 #-} readP2 s = fromJust $ C.readInt s >>= \(x, s1) -> (C.readInt . C.tail) s1 >>= \(y, _) -> return $! (x, y) readP3 s = fromJust $ C.readInt s >>= \(x, s1) -> (C.readInt . C.tail) s1 >>= \(y, s2) -> (C.readInt . C.tail) s2 >>= \(z, _) -> return $! (x, y, (fromIntegral z)) mkGraph :: Node -> Node -> [(Int, Int, Int)] -> Graph mkGraph begin end directed = runST $ do iou <- newArray (begin, end) [] :: ST s (STArray s Int [(Int, Int)]) mapM_ (\(from, to, weight) -> readArray iou from >>= \dir -> writeArray iou from ( (to, weight):dir) ) directed unsafeFreeze iou mkGraphR :: Node -> Node -> [(Int, Int, Int)] -> Graph mkGraphR begin end directed = runST $ do iou <- newArray (begin, end) [] :: ST s (STArray s Int [(Int, Int)]) mapM_ (\(from, to, weight) -> readArray iou to >>= \dir -> writeArray iou to ( (from, weight):dir) ) directed unsafeFreeze iou readint = fst . fromJust . C.readInt process (s1:ss) = (gr, gr', rest) where (numNodes, numEdges) = readP2 s1 (es, rest) = splitAt numEdges ss edges = map readP3 es !gr = mkGraph 1 numNodes edges !gr' = mkGraphR 1 numNodes edges processinputs 0 _ = return () processinputs k lines = print (incards gr grr) >> processinputs (pred k) rest where (gr, grr, rest) = process lines processall inputs = processinputs (readint nt) lines where (nt:lines) = C.lines inputs main = C.getContents >>= processall --- ex1 = C.pack . unlines $ [ "2" , "2 2" , "1 2 13" , "2 1 33" , "4 6" , "1 2 10" , "2 1 60" , "1 3 20" , "3 4 10" , "2 4 5" , "4 1 50" ]
wangbj/haskell
incards.hs
bsd-2-clause
5,143
7
16
1,191
2,187
1,163
1,024
134
5
{-# LANGUAGE RecordWildCards #-} module Halive.Args ( Args(..) , FileType , parseArgs , usage) where type FileType = String data Args = Args { mainFileName :: String , includeDirs :: [String] , fileTypes :: [FileType] , targetArgs :: [String] , shouldCompile :: Bool } data PartialArgs = PartialArgs { mainFileName' :: Maybe String , includeDirs' :: [String] , fileTypes' :: [FileType] , targetArgs' :: [String] , shouldCompile' :: Bool } usage :: String usage = "Usage: halive <main.hs> [<include dir>] [-f|--file-type <file type>] [-c|--compiled] [-- <args to myapp>]\n\ \\n\ \Available options:\n\ \ -f, --file-type <file type> Custom file type to watch for changes (e.g. \"-f html\")\n\ \ -c, --compiled Faster code (but slower compilation)" parseArgs :: [String] -> Maybe Args parseArgs args = go args (PartialArgs Nothing [] [] [] False) >>= fromPartial where go :: [String] -> PartialArgs -> Maybe PartialArgs go [] partial = Just partial go (x : xs) partial | x == "--" = Just partial { targetArgs' = xs } | x == "-f" || x == "--file-type" = case xs of [] -> Nothing ("--" : _) -> Nothing (fileType : xs') -> go xs' $ partial { fileTypes' = fileType : fileTypes' partial } | x == "-c" || x == "--compiled" = go xs $ partial { shouldCompile' = True } | otherwise = case mainFileName' partial of Nothing -> go xs $ partial { mainFileName' = Just x } Just _ -> go xs $ partial { includeDirs' = x : includeDirs' partial} fromPartial :: PartialArgs -> Maybe Args fromPartial PartialArgs {..} = case mainFileName' of Nothing -> Nothing Just mfn -> Just Args { mainFileName = mfn , includeDirs = includeDirs' , fileTypes = fileTypes' , targetArgs = targetArgs' , shouldCompile = shouldCompile' }
lukexi/halive
src/Halive/Args.hs
bsd-2-clause
2,288
0
15
885
534
290
244
48
5
module Data.Geo.OSM.Lens( module Data.Geo.OSM.Lens.PublicL , module Data.Geo.OSM.Lens.OriginL , module Data.Geo.OSM.Lens.PerPageL , module Data.Geo.OSM.Lens.MaxlonL , module Data.Geo.OSM.Lens.AreaL , module Data.Geo.OSM.Lens.GeneratorL , module Data.Geo.OSM.Lens.RefL , module Data.Geo.OSM.Lens.TracepointsL , module Data.Geo.OSM.Lens.UidL , module Data.Geo.OSM.Lens.MinlonL , module Data.Geo.OSM.Lens.VL , module Data.Geo.OSM.Lens.ChildrenL , module Data.Geo.OSM.Lens.IdL , module Data.Geo.OSM.Lens.MaxlatL , module Data.Geo.OSM.Lens.MinlatL , module Data.Geo.OSM.Lens.NdL , module Data.Geo.OSM.Lens.MinimumL , module Data.Geo.OSM.Lens.MaximumL , module Data.Geo.OSM.Lens.HomeL , module Data.Geo.OSM.Lens.AccountCreatedL , module Data.Geo.OSM.Lens.BoundsL , module Data.Geo.OSM.Lens.KL , module Data.Geo.OSM.Lens.MemberL , module Data.Geo.OSM.Lens.LatL , module Data.Geo.OSM.Lens.VersionL , module Data.Geo.OSM.Lens.WaynodesL , module Data.Geo.OSM.Lens.TimestampL , module Data.Geo.OSM.Lens.PendingL , module Data.Geo.OSM.Lens.DisplayNameL , module Data.Geo.OSM.Lens.VisibleL , module Data.Geo.OSM.Lens.UserL , module Data.Geo.OSM.Lens.LonL , module Data.Geo.OSM.Lens.BoxL , module Data.Geo.OSM.Lens.TagsL , module Data.Geo.OSM.Lens.NameL , module Data.Geo.OSM.Lens.ZoomL , module Data.Geo.OSM.Lens.RoleL , module Data.Geo.OSM.Lens.ChangesetL , module Data.Geo.OSM.Lens.TypeL ) where import Data.Geo.OSM.Lens.PublicL import Data.Geo.OSM.Lens.OriginL import Data.Geo.OSM.Lens.PerPageL import Data.Geo.OSM.Lens.MaxlonL import Data.Geo.OSM.Lens.AreaL import Data.Geo.OSM.Lens.GeneratorL import Data.Geo.OSM.Lens.RefL import Data.Geo.OSM.Lens.TracepointsL import Data.Geo.OSM.Lens.UidL import Data.Geo.OSM.Lens.MinlonL import Data.Geo.OSM.Lens.VL import Data.Geo.OSM.Lens.ChildrenL import Data.Geo.OSM.Lens.IdL import Data.Geo.OSM.Lens.MaxlatL import Data.Geo.OSM.Lens.MinlatL import Data.Geo.OSM.Lens.NdL import Data.Geo.OSM.Lens.MinimumL import Data.Geo.OSM.Lens.MaximumL import Data.Geo.OSM.Lens.HomeL import Data.Geo.OSM.Lens.AccountCreatedL import Data.Geo.OSM.Lens.BoundsL import Data.Geo.OSM.Lens.KL import Data.Geo.OSM.Lens.MemberL import Data.Geo.OSM.Lens.LatL import Data.Geo.OSM.Lens.VersionL import Data.Geo.OSM.Lens.WaynodesL import Data.Geo.OSM.Lens.TimestampL import Data.Geo.OSM.Lens.PendingL import Data.Geo.OSM.Lens.DisplayNameL import Data.Geo.OSM.Lens.VisibleL import Data.Geo.OSM.Lens.UserL import Data.Geo.OSM.Lens.LonL import Data.Geo.OSM.Lens.BoxL import Data.Geo.OSM.Lens.TagsL import Data.Geo.OSM.Lens.NameL import Data.Geo.OSM.Lens.ZoomL import Data.Geo.OSM.Lens.RoleL import Data.Geo.OSM.Lens.ChangesetL import Data.Geo.OSM.Lens.TypeL
tonymorris/geo-osm
src/Data/Geo/OSM/Lens.hs
bsd-3-clause
2,664
0
5
202
673
514
159
79
0
{-# LANGUAGE BangPatterns, CPP #-} -- | A CSV parser. The parser defined here is RFC 4180 compliant, with -- the following extensions: -- -- * Empty lines are ignored. -- -- * Non-escaped fields may contain any characters except -- double-quotes, commas, carriage returns, and newlines. -- -- * Escaped fields may contain any characters (but double-quotes -- need to be escaped). -- -- The functions in this module can be used to implement e.g. a -- resumable parser that is fed input incrementally. module Data.Csv.Parser ( DecodeOptions(..) , defaultDecodeOptions , csv , csvWithHeader , header , record , name , field ) where import Blaze.ByteString.Builder (fromByteString, toByteString) import Blaze.ByteString.Builder.Char.Utf8 (fromChar) import Control.Applicative ((*>), (<$>), (<*), optional, pure) import Data.Attoparsec.Char8 (char, endOfInput) import qualified Data.Attoparsec as A import qualified Data.Attoparsec.Lazy as AL import qualified Data.Attoparsec.Zepto as Z import qualified Data.ByteString as S import qualified Data.ByteString.Unsafe as S import Data.Monoid (mappend, mempty) import qualified Data.Vector as V import Data.Word (Word8) import Data.Csv.Types import Data.Csv.Util ((<$!>), blankLine, endOfLine, liftM2', cr, newline, doubleQuote) -- | Options that controls how data is decoded. These options can be -- used to e.g. decode tab-separated data instead of comma-separated -- data. -- -- To avoid having your program stop compiling when new fields are -- added to 'DecodeOptions', create option records by overriding -- values in 'defaultDecodeOptions'. Example: -- -- > myOptions = defaultDecodeOptions { -- > decDelimiter = fromIntegral (ord '\t') -- > } data DecodeOptions = DecodeOptions { -- | Field delimiter. decDelimiter :: {-# UNPACK #-} !Word8 } deriving (Eq, Show) -- | Decoding options for parsing CSV files. defaultDecodeOptions :: DecodeOptions defaultDecodeOptions = DecodeOptions { decDelimiter = 44 -- comma } -- | Parse a CSV file that does not include a header. csv :: DecodeOptions -> AL.Parser Csv csv !opts = do vals <- sepByEndOfLine1' (record (decDelimiter opts)) _ <- optional endOfLine endOfInput let nonEmpty = removeBlankLines vals return $! V.fromList nonEmpty {-# INLINE csv #-} -- | Specialized version of 'sepBy1'' which is faster due to not -- accepting an arbitrary separator. sepByDelim1' :: AL.Parser a -> Word8 -- ^ Field delimiter -> AL.Parser [a] sepByDelim1' p !delim = liftM2' (:) p loop where loop = do mb <- A.peekWord8 case mb of Just b | b == delim -> liftM2' (:) (A.anyWord8 *> p) loop _ -> pure [] {-# INLINe sepByDelim1' #-} -- | Specialized version of 'sepBy1'' which is faster due to not -- accepting an arbitrary separator. sepByEndOfLine1' :: AL.Parser a -> AL.Parser [a] sepByEndOfLine1' p = liftM2' (:) p loop where loop = do mb <- A.peekWord8 case mb of Just b | b == cr -> liftM2' (:) (A.anyWord8 *> A.word8 newline *> p) loop | b == newline -> liftM2' (:) (A.anyWord8 *> p) loop _ -> pure [] {-# INLINe sepByEndOfLine1' #-} -- | Parse a CSV file that includes a header. csvWithHeader :: DecodeOptions -> AL.Parser (Header, V.Vector NamedRecord) csvWithHeader !opts = do !hdr <- header (decDelimiter opts) vals <- map (toNamedRecord hdr) . removeBlankLines <$> sepByEndOfLine1' (record (decDelimiter opts)) _ <- optional endOfLine endOfInput let !v = V.fromList vals return (hdr, v) -- | Parse a header, including the terminating line separator. header :: Word8 -- ^ Field delimiter -> AL.Parser Header header !delim = V.fromList <$!> name delim `sepByDelim1'` delim <* endOfLine -- | Parse a header name. Header names have the same format as regular -- 'field's. name :: Word8 -> AL.Parser Name name !delim = field delim removeBlankLines :: [Record] -> [Record] removeBlankLines = filter (not . blankLine) -- | Parse a record, not including the terminating line separator. The -- terminating line separate is not included as the last record in a -- CSV file is allowed to not have a terminating line separator. You -- most likely want to use the 'endOfLine' parser in combination with -- this parser. record :: Word8 -- ^ Field delimiter -> AL.Parser Record record !delim = V.fromList <$!> field delim `sepByDelim1'` delim {-# INLINE record #-} -- | Parse a field. The field may be in either the escaped or -- non-escaped format. The return value is unescaped. field :: Word8 -> AL.Parser Field field !delim = do mb <- A.peekWord8 -- We purposely don't use <|> as we want to commit to the first -- choice if we see a double quote. case mb of Just b | b == doubleQuote -> escapedField _ -> unescapedField delim {-# INLINE field #-} escapedField :: AL.Parser S.ByteString escapedField = do _ <- dquote -- The scan state is 'True' if the previous character was a double -- quote. We need to drop a trailing double quote left by scan. s <- S.init <$> (A.scan False $ \s c -> if c == doubleQuote then Just (not s) else if s then Nothing else Just False) if doubleQuote `S.elem` s then case Z.parse unescape s of Right r -> return r Left err -> fail err else return s unescapedField :: Word8 -> AL.Parser S.ByteString unescapedField !delim = A.takeWhile (\ c -> c /= doubleQuote && c /= newline && c /= delim && c /= cr) dquote :: AL.Parser Char dquote = char '"' unescape :: Z.Parser S.ByteString unescape = toByteString <$!> go mempty where go acc = do h <- Z.takeWhile (/= doubleQuote) let rest = do start <- Z.take 2 if (S.unsafeHead start == doubleQuote && S.unsafeIndex start 1 == doubleQuote) then go (acc `mappend` fromByteString h `mappend` fromChar '"') else fail "invalid CSV escape sequence" done <- Z.atEnd if done then return (acc `mappend` fromByteString h) else rest
howell/cassava
Data/Csv/Parser.hs
bsd-3-clause
6,522
0
20
1,785
1,402
757
645
120
5
import Data.Array.MArray import Data.Array.IO import Control.Monad (foldM, mapM_) import Common.Utils (isqrt, if') type IntArray = IOArray Int Int limit = 1500000 :: Int limit' = isqrt $ limit `div` 2 candidate = [ (m, n) | m <- [1 .. limit'], n <- [1 .. m - 1], gcd m n == 1, odd (m + n) ] incArray :: IntArray -> Int -> IO () incArray arr index = (readArray arr index) >>= ((writeArray arr index) . succ) update :: Int -> Int -> IntArray -> IO () update m n arr = do let a = m^2 - n^2 let b = 2*m*n let c = m^2 + n^2 let p = a + b + c let xs = takeWhile (\x -> x <= limit) [p, p + p .. ] mapM_ (\x -> incArray arr x) xs main = do arr <- newArray (0, limit) 0 :: IO IntArray mapM (\(m ,n) -> update m n arr) candidate (foldM helper (0, arr) [0 .. limit]) >>= (print . fst) where helper (s, arr) index = do val <- readArray arr index return $ if' (val == 1) (s + 1, arr) (s, arr)
foreverbell/project-euler-solutions
src/75.hs
bsd-3-clause
952
0
13
269
530
280
250
25
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} -- | -- Module : Crypto.Classical.Types -- Copyright : (c) Colin Woodbury, 2015 - 2020 -- License : BSD3 -- Maintainer: Colin Woodbury <colin@fosskers.ca> module Crypto.Classical.Types ( -- * Cipher Cipher(..) -- * Keys , Key(..) -- * Enigma Types , EnigmaKey(..) , Rotor(..) , Reflector , Plugboard , plugFrom ) where import Crypto.Classical.Shuffle import Crypto.Classical.Util import Crypto.Number.Generate import Crypto.Random (CPRG) import Data.ByteString.Lazy (ByteString) import Data.Char (isUpper) import Data.List ((\\)) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Modular import Data.Text (Text) --- -- | A Cipher must be able to encrypt and decrypt. The Cipher type -- determines the Key type. class Key k => Cipher k a | a -> k where encrypt :: k -> ByteString -> a ByteString decrypt :: k -> ByteString -> a ByteString -- | Keys can appear in a number of different forms. -- E.g. a single number, a tuple, a mapping, etc. -- Each needs to be interpreted uniquely by a Cipher's -- `encrypt` and `decrypt` algorithms. class Key a where -- | Randomly generate a Key. key :: CPRG g => g -> a instance Key (ℤ/26) where key g = toMod . fst $ generateBetween g 1 25 -- | For Affine Ciphers. -- `a` must be coprime with 26, or else a^-1 won't exist and -- and we can't decrypt. instance Key (ℤ/26,ℤ/26) where key g = (a, b) where a = toMod . head $ shuffle g ([1,3..25] \\ [13]) 12 b = key g -- | Key for Substitution Cipher. The Key is the Mapping itself. instance Key (Map Char Char) where key g = M.fromList $ zip ['A'..'Z'] $ shuffle g ['A'..'Z'] 26 -- | Key for Stream/Vigenère Cipher. instance Key [ℤ/26] where key g = toMod n : key g' where (n,g') = generateMax g 26 --- -- | A Rotor (German: Walze) is a wheel labelled A to Z, with internal wirings -- from each entry point to exit point. There is also a turnover point, upon -- which a Rotor would turn its left neighbour as well. Typically said turnover -- point is thought of in terms of letters (e.g. Q->R for Rotor I). Here, we -- represent the turnover point as a distance from A (or 0, the first entry -- point). As the Rotor rotates, this value decrements. When it rolls back to 25 -- (modular arithmetic), we rotate the next Rotor. -- -- Our Rotors are letter-agnostic. That is, they only map numeric entry points -- to exit points. data Rotor = Rotor { _name :: Text , _turnover :: ℤ/26 , _circuit :: Map (ℤ/26) (ℤ/26) } deriving (Eq, Show) -- | Rotor I: Turnover from Q to R. rI :: Rotor rI = Rotor "I" (int 'Q') . M.fromList $ map (both int) pairs where pairs :: [(Char, Char)] pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "EKMFLGDQVZNTOWYHXUSPAIBRCJ" -- | Rotor II: Turnover from E to F. rII :: Rotor rII = Rotor "II" (int 'E') . M.fromList $ map (both int) pairs where pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "AJDKSIRUXBLHWTMCQGZNPYFVOE" -- | Rotor III: Turnover from V to W. rIII :: Rotor rIII = Rotor "III" (int 'V') . M.fromList $ map (both int) pairs where pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "BDFHJLCPRTXVZNYEIWGAKMUSQO" -- | Rotor IV: Turnover from J to K. rIV :: Rotor rIV = Rotor "IV" (int 'J') . M.fromList $ map (both int) pairs where pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "ESOVPZJAYQUIRHXLNFTGKDCMWB" -- | Rotor V: Turnover from Z to A. rV :: Rotor rV = Rotor "V" (int 'Z') . M.fromList $ map (both int) pairs where pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "VZBRGITYUPSDNHLXAWMJQOFECK" -- | A unmoving map, similar to the Rotors, which feeds the electrical -- current back into Rotors. This would never feed the left Rotor's letter -- back to itself, meaning a plaintext character would never encrypt -- to itself. This was a major weakness in scheme which allowed the Allies -- to make Known Plaintext Attacks against the machine. type Reflector = Map (ℤ/26) (ℤ/26) ukwB :: Reflector ukwB = M.fromList $ map (both int) pairs where pairs = zip "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "YRUHQSLDPXNGOKMIEBFZCWVJAT" -- | A set of 10 pairs of connected letters which would map letters -- to other ones both before and after being put through the Rotors. -- The remaining six unpaired letters can be thought of mapping to themselves. type Plugboard = Map (ℤ/26) (ℤ/26) -- | Essentially the machine itself. It is made up of: -- 1. Three rotor choices from five, in a random placement. -- 2. Initial settings of those Rotors. -- 3. The Reflector model in use. -- 4. Plugboard settings (pairs of characters). data EnigmaKey = EnigmaKey { _rotors :: [Rotor] , _settings :: String , _reflector :: Reflector , _plugboard :: Plugboard } deriving (Eq, Show) -- | Note that the randomly generated initial Rotor positions are not -- applied to the Rotors when the key is generated. They have to -- be applied before first use. instance Key EnigmaKey where key g = EnigmaKey rs ss ukwB $ randPlug g where rn = 3 -- Number of Rotors to use. rs = take rn $ shuffle g [rI,rII,rIII,rIV,rV] 5 ss = randChars g rn -- | Generate random start positions for the Rotors. randChars :: CPRG g => g -> Int -> String randChars _ 0 = [] randChars g n = letter (toMod c) : randChars g' (n-1) where (c,g') = generateBetween g 0 25 -- | Generate settings for the Plugboard. Ten pairs of characters will -- be mapped to each other, and the remaining six characters will map -- to themselves. randPlug :: CPRG g => g -> Plugboard randPlug g = M.fromList (pairs <> singles) where shuffled = shuffle g [0..25] 26 (ps,ss) = (take 20 shuffled, drop 20 shuffled) pairs = foldr (\(k,v) acc -> (k,v) : (v,k) : acc) [] $ uniZip ps singles = map (\v -> (v,v)) ss -- | Given a list of letter pairs, generates a Plugboard. -- Any letters left out of the pair list will be mapped to themselves. plugFrom :: [(Char,Char)] -> Plugboard plugFrom = f [] where f acc [] = let rest = stretch (['A'..'Z'] \\ acc) in M.fromList . uniZip . map int $ acc ++ rest f acc ((a,b):ps) | a `notElem` acc && b `notElem` acc && isUpper a && isUpper b = f (a : b : b : a : acc) ps | otherwise = f acc ps
fosskers/crypto-classical
lib/Crypto/Classical/Types.hs
bsd-3-clause
6,562
0
14
1,518
1,514
842
672
-1
-1
module Main(main) where import Codec.Base85.Internal hiding(fromString) import Control.Exception import Data.Char import Data.Word import qualified Data.ByteString.Lazy as BS import Test.Framework(Test, defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2(testProperty) import Test.Framework.Providers.HUnit(testCase) import Test.HUnit hiding(Test) main :: IO () main = defaultMain tests tests :: [Test] tests = [ rfc1924Tests , ascii85Tests , word32Tests , encodingTests , wordConversions , encoderDecoderTests] toChar :: Word8 -> Char toChar = chr . fromIntegral fromChar :: Integral a => Char -> a fromChar = fromIntegral . ord fromString :: String -> BS.ByteString fromString = BS.pack . map fromChar rfc1924String :: String rfc1924String = map toChar rfc1924Alphabet rfc1924Tests :: Test rfc1924Tests = testGroup "rfc1924" [ testCase "length(TT)" $ assertEqual "length" 85 $ length rfc1924Alphabet , testCase "printable" $ assertBool "alphabet is not printable" (all isPrint rfc1924String) , testCase "ascii" $ assertBool "alphabet contains non-ascii chars" (all isAscii rfc1924String)] ascii85String :: String ascii85String = map toChar ascii85Alphabet ascii85Tests :: Test ascii85Tests = testGroup "ascii85" [ testCase "length(TT)" $ assertEqual "length" 85 $ length ascii85Alphabet , testCase "printable" $ assertBool "alphabet is not printable" (all isPrint ascii85String) , testCase "ascii" $ assertBool "alphabet contains non-ascii chars" (all isAscii ascii85String) ] chunk :: BS.ByteString chunk = BS.pack [0x12, 0x34, 0x56, 0x78, 0x9A] word32Tests :: Test word32Tests = testGroup "word32 encoding" [ testProperty "Word32 encodes to 5 bytes with rfc1924" (\w32 -> BS.length (encodeWord32 (encoding rfc1924) w32) == 5) , testProperty "Word32 encodes to 5 bytes with ascii85" (\w32 -> BS.length (encodeWord32 (encoding ascii85) w32) == 5) , testCase "w32 encoder" $ assertEqual "encodeW32" (fromString "&i<X6") (encodeWord32 (encoding ascii85) 305419896) , testCase "w32 encoder" $ assertEqual "encodeW32" (fromString "RK*<f") (encodeWord32 (encoding ascii85) 2583691264) , testCase "chunkToW32" $ assertEqual "chunkToW32BE" 305419896 $ chunkToWord32BE chunk , testCase "w32 encode chunk" $ assertEqual "encode chunk" (fromString "&i<X6") (encodeChunkBE ascii85 chunk)] encodingTests :: Test encodingTests = testGroup "encoding bytestrings" [ testCase "bs encoder" $ assertEqual "encode bs" (fromString "&i<X6RK") (encode (encodeChunkBE ascii85) chunk) , testProperty "should not fail for any BS" (\bs -> (evaluate $ encodeBE rfc1924 (fromString bs)) `seq` True) , testProperty "should not fail for any BS" (\bs -> (evaluate $ encodeBE ascii85 (fromString bs)) `seq` True) , testProperty "should not fail for any BS (LE)" (\bs -> (evaluate $ encodeLE rfc1924 (fromString bs)) `seq` True) , testProperty "should not fail for any BS (LE)" (\bs -> (evaluate $ encodeLE ascii85 (fromString bs)) `seq` True) ] wordConversions :: Test wordConversions = testGroup "Conversions from Word32 to Word8 and back" [ testProperty "should be reversible (BE)" (\w32 -> w32 == (toWord32BE $ unWord32BE w32)) , testProperty "should be reversible (LE)" (\w32 -> w32 == (toWord32LE $ unWord32LE w32))] mkEncodeDecode :: Base85 -> BS.ByteString -> Bool mkEncodeDecode alpha bs = bs == (decodeBE alpha $ encodeBE alpha bs) mkEncodeDecodeLE :: Base85 -> BS.ByteString -> Bool mkEncodeDecodeLE alpha bs = bs == (decodeLE alpha $ encodeLE alpha bs) encoderDecoderTests :: Test encoderDecoderTests = testGroup "Conversions to base85 and back" [ testProperty "should be reversible (BE, rfc1924)" $ \bl -> mkEncodeDecode rfc1924 $ BS.pack bl , testProperty "should be reversible (BE, ascii85)" $ \bl -> mkEncodeDecode ascii85 $ BS.pack bl -- , testProperty "should be reversible for (LE, rfc1924)" $ -- \bl -> mkEncodeDecodeLE rfc1924 $ BS.pack bl -- , testProperty "should be reversible for (LE, ascii85)" $ -- \bl -> mkEncodeDecodeLE ascii85 $ BS.pack bl ]
kaaveland/haskell-base85
tests/RunTests.hs
bsd-3-clause
4,154
0
15
742
1,109
588
521
87
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Ivory.Opts.CSE (cseFold) where import Control.Applicative import qualified Data.DList as D import Data.Foldable import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet import Data.List (sort) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Monoid import Data.Reify import Data.Traversable import Ivory.Language.Array (ixRep) import qualified Ivory.Language.Syntax as AST import MonadLib (WriterT, StateT, Id, get, set, sets, sets_, put, collect, lift, runM) import Prelude hiding (foldr, mapM, mapM_) import System.IO.Unsafe (unsafePerformIO) -- | Find each common sub-expression and extract it to a new variable, -- making any sharing explicit. However, this function should never move -- evaluation of an expression earlier than it would have occurred in -- the source program, which means that sometimes an expression must be -- re-computed on each of several execution paths. cseFold :: AST.Proc -> AST.Proc cseFold def = def { AST.procBody = reconstruct $ unsafePerformIO $ reifyGraph $ AST.procBody def } -- | Variable assignments emitted so far. data Bindings = Bindings { availableBindings :: (Map (Unique, AST.Type) Int) , unusedBindings :: IntSet , totalBindings :: Int } -- | A monad for emitting both source-level statements as well as -- assignments that capture common subexpressions. -- -- Note that the StateT is outside the WriterT so that we can first run -- the StateT, getting a set of expressions which shouldn't be assigned -- to fresh names, and only then decide whether to write out Assign -- statements. See the comment in `updateFacts`. type BlockM a = StateT Bindings (WriterT (D.DList AST.Stmt) Id) a -- | We perform CSE on expressions but also across all the blocks in a -- procedure. data CSE t = CSEExpr (ExprF t) | CSEBlock (BlockF t) deriving (Show, Eq, Ord, Functor) -- | During CSE, we replace recursive references to an expression with a -- unique ID for that expression. data ExprF t = ExpSimpleF AST.Expr -- ^ For expressions that cannot contain any expressions recursively. | ExpLabelF AST.Type t String | ExpIndexF AST.Type t AST.Type t | ExpToIxF t Integer | ExpSafeCastF AST.Type t | ExpOpF AST.ExpOp [t] deriving (Show, Eq, Ord, Foldable, Functor, Traversable) instance MuRef AST.Expr where type DeRef AST.Expr = CSE mapDeRef child e = CSEExpr <$> case e of AST.ExpSym{} -> pure $ ExpSimpleF e AST.ExpExtern{} -> pure $ ExpSimpleF e AST.ExpVar{} -> pure $ ExpSimpleF e AST.ExpLit{} -> pure $ ExpSimpleF e AST.ExpLabel ty ex nm -> ExpLabelF <$> pure ty <*> child ex <*> pure nm AST.ExpIndex ty1 ex1 ty2 ex2 -> ExpIndexF <$> pure ty1 <*> child ex1 <*> pure ty2 <*> child ex2 AST.ExpToIx ex bound -> ExpToIxF <$> child ex <*> pure bound AST.ExpSafeCast ty ex -> ExpSafeCastF ty <$> child ex AST.ExpOp op args -> ExpOpF op <$> traverse child args AST.ExpAddrOfGlobal{} -> pure $ ExpSimpleF e AST.ExpMaxMin{} -> pure $ ExpSimpleF e AST.ExpSizeOf{} -> pure $ ExpSimpleF e -- | Convert a flattened expression back to a real expression. toExpr :: ExprF AST.Expr -> AST.Expr toExpr (ExpSimpleF ex) = ex toExpr (ExpLabelF ty ex nm) = AST.ExpLabel ty ex nm toExpr (ExpIndexF ty1 ex1 ty2 ex2) = AST.ExpIndex ty1 ex1 ty2 ex2 toExpr (ExpToIxF ex bound) = AST.ExpToIx ex bound toExpr (ExpSafeCastF ty ex) = AST.ExpSafeCast ty ex toExpr (ExpOpF op args) = AST.ExpOp op args -- | Wrap the second type in either TyRef or TyConstRef, according to -- whether the first argument was a constant ref. copyConst :: AST.Type -> AST.Type -> AST.Type copyConst (AST.TyRef _) ty = AST.TyRef ty copyConst (AST.TyConstRef _) ty = AST.TyConstRef ty copyConst ty _ = error $ "Ivory.Opts.CSE.copyConst: expected a Ref type but got " ++ show ty -- | Label all sub-expressions with the type at which they're used, -- assuming that this expression is used at the given type. labelTypes :: AST.Type -> ExprF k -> ExprF (k, AST.Type) labelTypes _ (ExpSimpleF e) = ExpSimpleF e labelTypes resty (ExpLabelF ty ex nm) = ExpLabelF ty (ex, copyConst resty ty) nm labelTypes resty (ExpIndexF ty1 ex1 ty2 ex2) = ExpIndexF ty1 (ex1, copyConst resty ty1) ty2 (ex2, ty2) labelTypes _ (ExpToIxF ex bd) = ExpToIxF (ex, ixRep) bd labelTypes _ (ExpSafeCastF ty ex) = ExpSafeCastF ty (ex, ty) labelTypes ty (ExpOpF op args) = ExpOpF op $ case op of AST.ExpEq t -> map (`atType` t) args AST.ExpNeq t -> map (`atType` t) args AST.ExpCond -> let (cond, rest) = splitAt 1 args in map (`atType` AST.TyBool) cond ++ map (`atType` ty) rest AST.ExpGt _ t -> map (`atType` t) args AST.ExpLt _ t -> map (`atType` t) args AST.ExpIsNan t -> map (`atType` t) args AST.ExpIsInf t -> map (`atType` t) args _ -> map (`atType` ty) args where atType = (,) -- | Like ExprF, we replace recursive references to -- blocks/statements/expressions with unique IDs. -- -- Note that we treat statements as a kind of block, because extracting -- assignments for the common subexpressions in a statement can result -- in multiple statements, which looks much like a block. data BlockF t = StmtSimple AST.Stmt -- ^ For statements that cannot contain any other statements or expressions. | StmtIfTE t t t | StmtAssert t | StmtCompilerAssert t | StmtAssume t | StmtReturn (AST.Typed t) | StmtDeref AST.Type AST.Var t | StmtStore AST.Type t t | StmtAssign AST.Type AST.Var t | StmtCall AST.Type (Maybe AST.Var) AST.Name [AST.Typed t] | StmtLocal AST.Type AST.Var (InitF t) | StmtRefCopy AST.Type t t | StmtLoop AST.Var t (LoopIncrF t) t | StmtForever t | Block [t] deriving (Show, Eq, Ord, Functor) data LoopIncrF t = IncrTo t | DecrTo t deriving (Show, Eq, Ord, Functor) data InitF t = InitZero | InitExpr AST.Type t | InitStruct [(String, InitF t)] | InitArray [InitF t] deriving (Show, Eq, Ord, Functor) instance MuRef AST.Stmt where type DeRef AST.Stmt = CSE mapDeRef child stmt = CSEBlock <$> case stmt of AST.IfTE cond tb fb -> StmtIfTE <$> child cond <*> child tb <*> child fb AST.Assert cond -> StmtAssert <$> child cond AST.CompilerAssert cond -> StmtCompilerAssert <$> child cond AST.Assume cond -> StmtAssume <$> child cond AST.Return (AST.Typed ty ex) -> StmtReturn <$> (AST.Typed ty <$> child ex) AST.Deref ty var ex -> StmtDeref ty var <$> child ex AST.Store ty lhs rhs -> StmtStore ty <$> child lhs <*> child rhs AST.Assign ty var ex -> StmtAssign ty var <$> child ex AST.Call ty mv nm args -> StmtCall ty mv nm <$> traverse (\ (AST.Typed argTy argEx) -> AST.Typed argTy <$> child argEx) args AST.Local ty var initex -> StmtLocal ty var <$> mapInit initex AST.RefCopy ty dst src -> StmtRefCopy ty <$> child dst <*> child src AST.Loop var ex incr lb -> StmtLoop var <$> child ex <*> mapIncr incr <*> child lb AST.Forever lb -> StmtForever <$> child lb -- These kinds of statements can't contain other statements or expressions. AST.ReturnVoid -> pure $ StmtSimple stmt AST.AllocRef{} -> pure $ StmtSimple stmt AST.Break -> pure $ StmtSimple stmt AST.Comment{} -> pure $ StmtSimple stmt where mapInit AST.InitZero = pure InitZero mapInit (AST.InitExpr ty ex) = InitExpr ty <$> child ex mapInit (AST.InitStruct fields) = InitStruct <$> traverse (\ (nm, i) -> (,) nm <$> mapInit i) fields mapInit (AST.InitArray elements) = InitArray <$> traverse mapInit elements mapIncr (AST.IncrTo ex) = IncrTo <$> child ex mapIncr (AST.DecrTo ex) = DecrTo <$> child ex instance (MuRef a, DeRef [a] ~ DeRef a) => MuRef [a] where type DeRef [a] = CSE mapDeRef child xs = CSEBlock <$> Block <$> traverse child xs -- | Convert a flattened statement or block back to a real block. toBlock :: (k -> AST.Type -> BlockM AST.Expr) -> (k -> BlockM ()) -> BlockF k -> BlockM () toBlock expr block b = case b of StmtSimple s -> stmt $ return s StmtIfTE ex tb fb -> stmt $ AST.IfTE <$> expr ex AST.TyBool <*> genBlock (block tb) <*> genBlock (block fb) StmtAssert cond -> stmt $ AST.Assert <$> expr cond AST.TyBool StmtCompilerAssert cond -> stmt $ AST.CompilerAssert <$> expr cond AST.TyBool StmtAssume cond -> stmt $ AST.Assume <$> expr cond AST.TyBool StmtReturn (AST.Typed ty ex) -> stmt $ AST.Return <$> (AST.Typed ty <$> expr ex ty) -- XXX: The AST does not preserve whether the RHS of a deref was for a -- const ref, but it's safe to assume it's const. StmtDeref ty var ex -> stmt $ AST.Deref ty var <$> expr ex (AST.TyConstRef ty) -- XXX: The LHS of a store must not have been const. StmtStore ty lhs rhs -> stmt $ AST.Store ty <$> expr lhs (AST.TyRef ty) <*> expr rhs ty StmtAssign ty var ex -> stmt $ AST.Assign ty var <$> expr ex ty StmtCall ty mv nm args -> stmt $ AST.Call ty mv nm <$> mapM (\ (AST.Typed argTy argEx) -> AST.Typed argTy <$> expr argEx argTy) args StmtLocal ty var initex -> stmt $ AST.Local ty var <$> toInit initex -- XXX: See deref and store comments above. StmtRefCopy ty dst src -> stmt $ AST.RefCopy ty <$> expr dst (AST.TyRef ty) <*> expr src (AST.TyConstRef ty) StmtLoop var ex incr lb -> stmt $ AST.Loop var <$> expr ex ixRep <*> toIncr incr <*> genBlock (block lb) StmtForever lb -> stmt $ AST.Forever <$> genBlock (block lb) Block stmts -> mapM_ block stmts where stmt stmtM = fmap D.singleton stmtM >>= put toInit InitZero = pure AST.InitZero toInit (InitExpr ty ex) = AST.InitExpr ty <$> expr ex ty toInit (InitStruct fields) = AST.InitStruct <$> traverse (\ (nm, i) -> (,) nm <$> toInit i) fields toInit (InitArray elements) = AST.InitArray <$> traverse toInit elements toIncr (IncrTo ex) = AST.IncrTo <$> expr ex ixRep toIncr (DecrTo ex) = AST.DecrTo <$> expr ex ixRep -- | When a statement contains a block, we need to propagate the -- available expressions into that block. However, on exit from that -- block, the expressions it made newly-available go out of scope, so we -- remove them from the available set for subsequent statements. genBlock :: BlockM () -> BlockM AST.Block genBlock gen = do oldBindings <- get ((), stmts) <- collect gen sets_ $ \ newBindings -> newBindings { availableBindings = availableBindings oldBindings } return $ D.toList stmts -- | Data to accumulate as we analyze each expression and each -- block/statement. type Facts = (IntMap (AST.Type -> BlockM AST.Expr), IntMap (BlockM ())) -- | We can only generate code from a DAG, so this function calls -- `error` if the reified graph has cycles. Because we walk the AST in -- topo-sorted order, if we haven't already computed the desired fact, -- then we're trying to follow a back-edge in the graph, and that means -- the graph has cycles. getFact :: IntMap v -> Unique -> v getFact m k = case IntMap.lookup k m of Nothing -> error "IvoryCSE: cycle detected in expression graph" Just v -> v -- | Walk a reified AST in topo-sorted order, accumulating analysis -- results. -- -- `usedOnce` must be the final value of `unusedBindings` after analysis -- is complete. updateFacts :: IntSet -> (Unique, CSE Unique) -> Facts -> Facts updateFacts _ (ident, CSEBlock block) (exprFacts, blockFacts) = (exprFacts, IntMap.insert ident (toBlock (getFact exprFacts) (getFact blockFacts) block) blockFacts) updateFacts usedOnce (ident, CSEExpr expr) (exprFacts, blockFacts) = (IntMap.insert ident fact exprFacts, blockFacts) where nameOf var = AST.VarName $ "cse" ++ show var fact = case expr of ExpSimpleF e -> const $ return e ex -> \ ty -> do bindings <- get case Map.lookup (ident, ty) $ availableBindings bindings of Just var -> do set $ bindings { unusedBindings = IntSet.delete var $ unusedBindings bindings } return $ AST.ExpVar $ nameOf var Nothing -> do ex' <- fmap toExpr $ mapM (uncurry $ getFact exprFacts) $ labelTypes ty ex var <- sets $ \ (Bindings { availableBindings = avail, unusedBindings = unused, totalBindings = maxId}) -> (maxId, Bindings { availableBindings = Map.insert (ident, ty) maxId avail , unusedBindings = IntSet.insert maxId unused , totalBindings = maxId + 1 }) -- Defer a final decision on whether to inline this expression -- or allocate a variable for it until we've finished running -- the State monad and can extract the unusedBindings set from -- there. After that the Writer monad can make decisions based -- on usedOnce without throwing a <<loop>> exception. lift $ if var `IntSet.member` usedOnce then return ex' else do put $ D.singleton $ AST.Assign ty (nameOf var) ex' return $ AST.ExpVar $ nameOf var -- | Values that we may generate by simplification rules on the reified -- representation of the graph. data Constant = ConstFalse | ConstTrue | ConstZero | ConstTwo deriving (Bounded, Enum) -- | AST implementation for each constant value. constExpr :: Constant -> CSE Unique constExpr ConstFalse = CSEExpr $ ExpSimpleF $ AST.ExpLit $ AST.LitBool False constExpr ConstTrue = CSEExpr $ ExpSimpleF $ AST.ExpLit $ AST.LitBool True constExpr ConstZero = CSEExpr $ ExpSimpleF $ AST.ExpLit $ AST.LitInteger 0 constExpr ConstTwo = CSEExpr $ ExpSimpleF $ AST.ExpLit $ AST.LitInteger 2 -- | Generate a unique integer for each constant which doesn't collide -- with any IDs that reifyGraph may generate. constUnique :: Constant -> Unique constUnique c = negate $ 1 + fromEnum c -- | Wrapper around Facts to track unshared duplicates. type Dupes = (Map (CSE Unique) Unique, IntMap Unique, Facts) -- | Wrapper around updateFacts to remove unshared duplicates. Also, -- checking for equality of statements or expressions is constant-time -- in this representation, so apply any simplifications that rely on -- equality of subtrees here. dedup :: IntSet -> (Unique, CSE Unique) -> Dupes -> Dupes dedup usedOnce (ident, expr) (seen, remap, facts) = case expr' of -- If this operator yields a constant on equal operands, we can -- rewrite it to that constant. CSEExpr (ExpOpF (AST.ExpEq ty) [a, b]) | not (isFloat ty) && a == b -> remapTo $ constUnique ConstTrue CSEExpr (ExpOpF (AST.ExpNeq ty) [a, b]) | not (isFloat ty) && a == b -> remapTo $ constUnique ConstFalse CSEExpr (ExpOpF (AST.ExpGt isEq ty) [a, b]) | not (isFloat ty) && a == b -> remapTo $ if isEq then constUnique ConstTrue else constUnique ConstFalse CSEExpr (ExpOpF (AST.ExpLt isEq ty) [a, b]) | not (isFloat ty) && a == b -> remapTo $ if isEq then constUnique ConstTrue else constUnique ConstFalse CSEExpr (ExpOpF AST.ExpBitXor [a, b]) | a == b -> remapTo $ constUnique ConstZero -- NOTE: This transformation is not safe for ExpSub on floating-point -- values, which could be NaN. -- If this operator is idempotent and its operands are equal, we can -- replace it with either operand without changing its meaning. CSEExpr (ExpOpF AST.ExpAnd [a, b]) | a == b -> remapTo a CSEExpr (ExpOpF AST.ExpOr [a, b]) | a == b -> remapTo a CSEExpr (ExpOpF AST.ExpBitAnd [a, b]) | a == b -> remapTo a CSEExpr (ExpOpF AST.ExpBitOr [a, b]) | a == b -> remapTo a -- If both branches of a conditional expression or statement have the -- same effect, then we don't need to evaluate the condition; we can -- just replace it with either branch. This is not safe in C because -- the condition might have side effects, but Ivory expressions never -- have side effects. CSEExpr (ExpOpF AST.ExpCond [_, t, f]) | t == f -> remapTo t -- NOTE: This results in inserting a Block directly into another -- Block, which can't happen any other way. CSEBlock (StmtIfTE _ t f) | t == f -> remapTo t -- Single-statement blocks generate the same code as the statement. CSEBlock (Block [s]) -> remapTo s -- No equal subtrees, so run with it. _ -> case Map.lookup expr' seen of Just ident' -> remapTo ident' Nothing -> (Map.insert expr' ident seen, remap, updateFacts usedOnce (ident, expr') facts) where remapTo ident' = (seen, IntMap.insert ident ident' remap, facts) expr' = case fmap (\ k -> IntMap.findWithDefault k k remap) expr of -- Perhaps this operator can be replaced by a simpler one when its -- operands are equal. CSEExpr (ExpOpF AST.ExpAdd [a, b]) | a == b -> CSEExpr $ ExpOpF AST.ExpMul $ sort [constUnique ConstTwo, a] -- If this operator is commutative, we can put its arguments in any -- order we want. If we choose the same order every time, more -- semantically equivalent subexpressions will be factored out. CSEExpr (ExpOpF op args) | isCommutative op -> CSEExpr $ ExpOpF op $ sort args asis -> asis isFloat AST.TyFloat = True isFloat AST.TyDouble = True isFloat _ = False isCommutative (AST.ExpEq _) = True isCommutative (AST.ExpNeq _) = True isCommutative AST.ExpMul = True isCommutative AST.ExpAdd = True isCommutative AST.ExpBitAnd = True isCommutative AST.ExpBitOr = True isCommutative AST.ExpBitXor = True isCommutative _ = False -- | Given a reified AST, reconstruct an Ivory AST with all sharing made -- explicit. reconstruct :: Graph CSE -> AST.Block reconstruct (Graph subexprs root) = D.toList rootBlock where -- NOTE: `dedup` needs to merge the constants in first, which means -- that as long as this is a `foldr`, they need to be appended after -- `subexprs`. Don't try to optimize this by re-ordering the list. (_, remap, (_, blockFacts)) = foldr (dedup usedOnce) mempty $ subexprs ++ [ (constUnique c, constExpr c) | c <- [minBound..maxBound] ] Just rootGen = IntMap.lookup (IntMap.findWithDefault root root remap) blockFacts (((), Bindings { unusedBindings = usedOnce }), rootBlock) = runM rootGen $ Bindings Map.empty IntSet.empty 0
Hodapp87/ivory
ivory-opts/src/Ivory/Opts/CSE.hs
bsd-3-clause
18,145
0
25
3,723
5,450
2,782
2,668
255
27
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Stg to C-- code generation: the binding environment -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmEnv ( CgIdInfo, litIdInfo, lneIdInfo, rhsIdInfo, mkRhsInit, idInfoToAmode, addBindC, addBindsC, bindArgsToRegs, bindToReg, rebindToReg, bindArgToReg, idToReg, getArgAmode, getNonVoidArgAmodes, getCgIdInfo, maybeLetNoEscape, ) where #include "HsVersions.h" import TyCon import StgCmmMonad import StgCmmUtils import StgCmmClosure import StgSyn (StgArg) import CLabel import BlockId import CmmExpr import CmmUtils import DynFlags import Id import MkGraph import Name import Outputable import StgSyn import UniqFM import VarEnv ------------------------------------- -- Manipulating CgIdInfo ------------------------------------- mkCgIdInfo :: Id -> LambdaFormInfo -> CmmExpr -> CgIdInfo mkCgIdInfo id lf expr = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = CmmLoc expr } litIdInfo :: DynFlags -> Id -> LambdaFormInfo -> CmmLit -> CgIdInfo litIdInfo dflags id lf lit = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = CmmLoc (addDynTag dflags (CmmLit lit) tag) } where tag = lfDynTag dflags lf lneIdInfo :: DynFlags -> Id -> [NonVoid Id] -> CgIdInfo lneIdInfo dflags id regs = CgIdInfo { cg_id = id, cg_lf = lf , cg_loc = LneLoc blk_id (map (idToReg dflags) regs) } where lf = mkLFLetNoEscape blk_id = mkBlockId (idUnique id) rhsIdInfo :: Id -> LambdaFormInfo -> FCode (CgIdInfo, LocalReg) rhsIdInfo id lf_info = do dflags <- getDynFlags reg <- newTemp (gcWord dflags) return (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg)), reg) mkRhsInit :: DynFlags -> LocalReg -> LambdaFormInfo -> CmmExpr -> CmmAGraph mkRhsInit dflags reg lf_info expr = mkAssign (CmmLocal reg) (addDynTag dflags expr (lfDynTag dflags lf_info)) idInfoToAmode :: CgIdInfo -> CmmExpr -- Returns a CmmExpr for the *tagged* pointer idInfoToAmode (CgIdInfo { cg_loc = CmmLoc e }) = e idInfoToAmode cg_info = pprPanic "idInfoToAmode" (ppr (cg_id cg_info)) -- LneLoc addDynTag :: DynFlags -> CmmExpr -> DynTag -> CmmExpr -- A tag adds a byte offset to the pointer addDynTag dflags expr tag = cmmOffsetB dflags expr tag maybeLetNoEscape :: CgIdInfo -> Maybe (BlockId, [LocalReg]) maybeLetNoEscape (CgIdInfo { cg_loc = LneLoc blk_id args}) = Just (blk_id, args) maybeLetNoEscape _other = Nothing --------------------------------------------------------- -- The binding environment -- -- There are three basic routines, for adding (addBindC), -- modifying(modifyBindC) and looking up (getCgIdInfo) bindings. --------------------------------------------------------- addBindC :: CgIdInfo -> FCode () addBindC stuff_to_bind = do binds <- getBinds setBinds $ extendVarEnv binds (cg_id stuff_to_bind) stuff_to_bind addBindsC :: [CgIdInfo] -> FCode () addBindsC new_bindings = do binds <- getBinds let new_binds = foldl (\ binds info -> extendVarEnv binds (cg_id info) info) binds new_bindings setBinds new_binds getCgIdInfo :: Id -> FCode CgIdInfo getCgIdInfo id = do { dflags <- getDynFlags ; local_binds <- getBinds -- Try local bindings first ; case lookupVarEnv local_binds id of { Just info -> return info ; Nothing -> do { -- Should be imported; make up a CgIdInfo for it let name = idName id ; if isExternalName name then let ext_lbl = CmmLabel (mkClosureLabel name $ idCafInfo id) in return (litIdInfo dflags id (mkLFImported id) ext_lbl) else cgLookupPanic id -- Bug }}} cgLookupPanic :: Id -> FCode a cgLookupPanic id = do local_binds <- getBinds pprPanic "StgCmmEnv: variable not found" (vcat [ppr id, text "local binds for:", pprUFM local_binds $ \infos -> vcat [ ppr (cg_id info) | info <- infos ] ]) -------------------- getArgAmode :: NonVoid StgArg -> FCode CmmExpr getArgAmode (NonVoid (StgVarArg var)) = idInfoToAmode <$> getCgIdInfo var getArgAmode (NonVoid (StgLitArg lit)) = CmmLit <$> cgLit lit getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr] -- NB: Filters out void args, -- so the result list may be shorter than the argument list getNonVoidArgAmodes [] = return [] getNonVoidArgAmodes (arg:args) | isVoidRep (argPrimRep arg) = getNonVoidArgAmodes args | otherwise = do { amode <- getArgAmode (NonVoid arg) ; amodes <- getNonVoidArgAmodes args ; return ( amode : amodes ) } ------------------------------------------------------------------------ -- Interface functions for binding and re-binding names ------------------------------------------------------------------------ bindToReg :: NonVoid Id -> LambdaFormInfo -> FCode LocalReg -- Bind an Id to a fresh LocalReg bindToReg nvid@(NonVoid id) lf_info = do dflags <- getDynFlags let reg = idToReg dflags nvid addBindC (mkCgIdInfo id lf_info (CmmReg (CmmLocal reg))) return reg rebindToReg :: NonVoid Id -> FCode LocalReg -- Like bindToReg, but the Id is already in scope, so -- get its LF info from the envt rebindToReg nvid@(NonVoid id) = do { info <- getCgIdInfo id ; bindToReg nvid (cg_lf info) } bindArgToReg :: NonVoid Id -> FCode LocalReg bindArgToReg nvid@(NonVoid id) = bindToReg nvid (mkLFArgument id) bindArgsToRegs :: [NonVoid Id] -> FCode [LocalReg] bindArgsToRegs args = mapM bindArgToReg args idToReg :: DynFlags -> NonVoid Id -> LocalReg -- Make a register from an Id, typically a function argument, -- free variable, or case binder -- -- We re-use the Unique from the Id to make it easier to see what is going on -- -- By now the Ids should be uniquely named; else one would worry -- about accidental collision idToReg dflags (NonVoid id) = LocalReg (idUnique id) (case idPrimRep id of VoidRep -> pprPanic "idToReg" (ppr id) _ -> primRepCmmType dflags (idPrimRep id))
snoyberg/ghc
compiler/codeGen/StgCmmEnv.hs
bsd-3-clause
6,466
0
20
1,589
1,564
817
747
120
3
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.SGIX.TextureScaleBias -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/SGIX/texture_scale_bias.txt SGIX_texture_scale_bias> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.SGIX.TextureScaleBias ( -- * Enums gl_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX, gl_POST_TEXTURE_FILTER_BIAS_SGIX, gl_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX, gl_POST_TEXTURE_FILTER_SCALE_SGIX ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/SGIX/TextureScaleBias.hs
bsd-3-clause
805
0
4
87
46
37
9
6
0
module Main where import Lexer import Syntax import Test.Hspec import Test.Hspec.QuickCheck main :: IO () main = do testWhiteSpace testBrackets testArithmicOperators testCompareOperators testListOperators testBoolean testNumbers testKeywords testComments testArithmics testTypes testIdentifiers numbersWithUnits -- testLists -- Test that whitespace is removed testWhiteSpace = hspec $ do describe "Testing if whitespace is remvod properly" $ do it "Nothing at all" $ lexer "" `shouldBe` Right [] it "Space" $ lexer " " `shouldBe` Right [] it "New line" $ lexer "\n" `shouldBe` Right [] it "Tab" $ lexer "\t" `shouldBe` Right [] -- Test that brackets are lexer corretly testBrackets = hspec $ do describe "Testing Brackets and paren" $ do it "Parent" $ lexer "( )" `shouldBe` Right [Bracket LeftParen, Bracket RightParen] it "Brackets" $ lexer "{}" `shouldBe` Right [Bracket LeftBracket, Bracket RightBracket] it "Square brackets" $ lexer "[]" `shouldBe` Right [Bracket LeftSquareBracket, Bracket RightSquareBracket] -- Test that the arithmic operators are represented correctly testArithmicOperators = hspec $ do describe "Testing the different arithmic operators:" $ do it "Addition" $ lexer "+" `shouldBe` Right [Operator Add] it "Subtraction" $ lexer "-" `shouldBe` Right [Operator Sub] it "Multiplcation" $ lexer "*" `shouldBe` Right [Operator Mul] it "Divition" $ lexer "/" `shouldBe` Right [Operator Div] it "Reminder" $ lexer "%" `shouldBe` Right [Operator Mod] it "Power" $ lexer "^" `shouldBe` Right [Operator Pow] it "Assignment" $ lexer "=" `shouldBe` Right [Operator Assignment] it "Type Assignment" $ lexer "::" `shouldBe` Right [Operator TypeAssignment] it "Type arrow" $ lexer "->" `shouldBe` Right [Operator TypeArrow] -- Test comparation operators testCompareOperators = hspec $ do describe "Testing the comparator operators:" $ do it "Equality " $ lexer "==" `shouldBe` Right [Operator Eq] it "Not equal " $ lexer "!=" `shouldBe` Right [Operator Ne] it "Less than " $ lexer "<" `shouldBe` Right [Operator Lt] it "Greater than " $ lexer ">" `shouldBe` Right [Operator Gt] it "Less than or equal " $ lexer "<=" `shouldBe` Right [Operator Le] it "Greater than or equal " $ lexer ">=" `shouldBe` Right [Operator Ge] -- Testing list operators testListOperators = hspec $ do describe "Testing list operators:" $ do it "Head" $ lexer "head" `shouldBe` Right [Operator Head] it "Tail" $ lexer "tail" `shouldBe` Right [Operator Tail] it "ListCons" $ lexer ":" `shouldBe` Right [Operator ListCons] it "Comma" $ lexer "," `shouldBe` Right [Operator Comma] it "isEmpty" $ lexer "isEmpty" `shouldBe` Right [Operator IsEmpty] -- Testing Boolean operators testBoolean = hspec $ do describe "Testing boolean constants" $ do it "True" $ lexer "True" `shouldBe` Right [Booly True] it "False" $ lexer "False" `shouldBe` Right [Booly False] describe "Testing the booloan operators:" $ do it "And" $ lexer "&&" `shouldBe` Right [Operator And] it "Or" $ lexer "||" `shouldBe` Right [Operator Or] it "Not" $ lexer "!" `shouldBe` Right [Operator Not] describe "Testing boolean expression lexing" $ do it "True and True" $ lexer "True && True" `shouldBe` Right [Booly True, Operator And, Booly True] it "True or False" $ lexer "True || False" `shouldBe` Right [Booly True, Operator Or, Booly False] it "Not True" $ lexer "!True" `shouldBe` Right [Operator Not, Booly True] it "Not False" $ lexer "!False" `shouldBe` Right [Operator Not, Booly False] -- Test that numbers are being converted correctly testNumbers = hspec $ do describe "Testing number conversions" $ do it "Integers" $ do lexer "10" `shouldBe` Right [Num 10] lexer "123456" `shouldBe` Right [Num 123456] it "Floating points" $ do lexer "12.34" `shouldBe` Right [Num 12.34] lexer "12.84" `shouldBe` Right [Num 12.84] -- it "Floating points with mulitipul '.'. Should throw an error (Left)" $ do -- -- lexer "12.34.5" `shouldBe` Left "Could not parse: number contains too many '.'" -- lexer "12.34.5" `shouldThrow` anyException -- Test that the keywords are represented correctly testKeywords = hspec $ do describe "Conveting simple keywords" $ do it "Convert each keyword into its tokenized version" $ do lexer "if" `shouldBe` Right [Keyword If] lexer "then" `shouldBe` Right [Keyword Then] lexer "else" `shouldBe` Right [Keyword Else] -- This should maybe not fail later on, if the lexer should catch these errors lexer "if then else" `shouldBe` Right [Keyword If, Keyword Then, Keyword Else] lexer "where" `shouldBe` Right [Keyword Where] lexer "case of" `shouldBe` Right [Keyword Case, Keyword Of] lexer "let in" `shouldBe` Right [Keyword Let, Keyword In] lexer "abc" `shouldBe` Right [Identifier "abc"] lexer "a = 10" `shouldBe` Right [Identifier "a", Operator Assignment, Num 10] lexer "$" `shouldBe` Left (LexingError "Unexpected character: \t$\n \t^") it "Valid expressions" $ do lexer "let x = 1 in x" `shouldBe` Right [Keyword Let, Identifier "x", Operator Assignment, Num 1, Keyword In, Identifier "x"] -- Test that comments are removed testComments = hspec $ do describe "Testing that comments are removed" $ do it "Should only return the code, not the comment" $ do lexer "-- This is a comment * + \n" `shouldBe` Right [] lexer "-- This is a comment * + \n3" `shouldBe` Right [Num 3] -- Test that arithmics are lexed correctly testArithmics = hspec $ do describe "Testing the lexing of arithmic strings" $ do it "Testing each operator with numbers" $ do lexer "2 + 3" `shouldBe` Right [Num 2, Operator Add, Num 3] lexer "1 - 2" `shouldBe` Right [Num 1, Operator Sub, Num 2] lexer "1 * 2" `shouldBe` Right [Num 1, Operator Mul, Num 2] lexer "1 / 2" `shouldBe` Right [Num 1, Operator Div, Num 2] lexer "2 ^ 2" `shouldBe` Right [Num 2, Operator Pow, Num 2] it "Test cases with interleaving operators" $ do lexer "1 + 2 * 3" `shouldBe` Right [Num 1, Operator Add, Num 2, Operator Mul, Num 3] lexer "1 * 2 + 3" `shouldBe` Right [Num 1, Operator Mul, Num 2, Operator Add, Num 3] lexer "1 / 2 - 3" `shouldBe` Right [Num 1, Operator Div, Num 2, Operator Sub, Num 3] lexer "1 - 2 / 3" `shouldBe` Right [Num 1, Operator Sub, Num 2, Operator Div, Num 3] it "Test cases with floating point numbers" $ do lexer "1.2 + 3" `shouldBe` Right [Num 1.2, Operator Add, Num 3] lexer "1 + 2.3" `shouldBe` Right [Num 1, Operator Add, Num 2.3] lexer "1.2 + 3.4" `shouldBe` Right [Num 1.2, Operator Add, Num 3.4] lexer "1.2 * 3.4" `shouldBe` Right [Num 1.2, Operator Mul, Num 3.4] testTypes = hspec $ do describe "Testing types" $ do it "Int" $ lexer "Int" `shouldBe` Right [BType Int] it "Float" $ lexer "Float" `shouldBe` Right [BType Float] it "Bool" $ lexer "Bool" `shouldBe` Right [BType Bool] it "Unit" $ lexer "()" `shouldBe` Right [BType UnitType] it "Int -> Int" $ lexer "Int -> Int" `shouldBe` Right [BType Int, Operator TypeArrow, BType Int] testIdentifiers = hspec $ do describe "Finding identifiers -" $ do it "a" $ lexer "a" `shouldBe` Right [Identifier "a"] it "abc" $ lexer "abc" `shouldBe` Right [Identifier "abc"] it "a1a" $ lexer "a1a" `shouldBe` Right [Identifier "a1a"] -- testLists = hspec $ do -- describe "Testing basic list construction:" $ do -- -- it "The empty list" $ lexer "[]" `shouldBe` Right [] -- it -- Testing the lexing of numbers with units numbersWithUnits = hspec $ do describe "Testing lexing of numbers with units" $ do it "1 #" $ lexer "1 <<m>>" `shouldBe` Right [Num 1, Units "m"] it "1 # m s A #" $ lexer "1 <<m s A>>" `shouldBe` Right [Num 1, Units "m s A"]
OliverFlecke/Funci
tests/LexerTests.hs
bsd-3-clause
8,010
0
17
1,789
2,688
1,274
1,414
132
1
-- | This is just to be able to produce a Haddock documentation on a Linux system module System.Midi.Placeholder ( module System.Midi.Base , Source , Destination , Connection , enumerateSources , enumerateDestinations , MidiHasName , getName , getModel , getManufacturer , openSource , openDestination , close , send , sendSysEx , start , stop , getNextEvent , getEvents , currentTime ) where import System.Midi.Base data Source = Source deriving (Eq, Ord, Show) data Destination = Destination deriving (Eq, Ord, Show) data Connection = Connection deriving (Eq, Ord, Show) enumerateSources = noImpl enumerateDestinations = noImpl class MidiHasName a where getName = noImpl getManufacturer = noImpl getModel = noImpl openSource = noImpl openDestination = noImpl close = noImpl send = noImpl sendSysEx = noImpl start = noImpl stop = noImpl getNextEvent = noImpl getEvents = noImpl currentTime = noImpl noImpl = error "Not implemented"
hanshoglund/hamid
src/System/Midi/Placeholder.hs
bsd-3-clause
1,347
0
6
555
238
143
95
-1
-1
-- | Monadic combinators missing from the standard library module Control.Monad.TM ( (.=<<.) , (.>>=.) , anyM , allM , findM ) where import Control.Applicative import Data.Traversable import Control.Monad -- | Lifting bind into a monad. Often denoted /concatMapM/. (.=<<.) :: (Applicative q, Monad m, Traversable m) => (a -> q (m b)) -> m a -> q (m b) (.=<<.) f = fmap join . traverse f -- | Lifting bind into a monad. Often denoted /concatMapM/. (.>>=.) :: (Applicative q, Monad m, Traversable m) => m a -> (a -> q (m b)) -> q (m b) (.>>=.) = flip (.=<<.) -- | Existential quantification. anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool anyM _ [] = return False anyM f (a:as) = do z <- f a if z then return True else anyM f as -- | Universal quantification. allM :: Monad m => (a -> m Bool) -> [a] -> m Bool allM _ [] = return True allM f (a:as) = do z <- f a if z then allM f as else return False -- | Find an element satisfying a predicate findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a) findM _ [] = return Nothing findM f (x:xs) = do b <- f x if b then return (Just x) else findM f xs
tonymorris/utility-tm
src/Control/Monad/TM.hs
bsd-3-clause
1,248
0
12
383
512
266
246
60
2
module AAPL.Main ( module AAPL.Main ) where import AAPL.Types import AAPL.RD import AAPL.Leases import AAPL.Options terminalYear :: Year terminalYear = 2027 revenue :: Val revenue 2016 = 218118 revenue t | t > 2016 = (1 + revenueGrowthRate t) * revenue (t-1) | otherwise = throwError "invalid year" revenueGrowthRate :: Val revenueGrowthRate t | 2017 <= t && t <= 2021 = 0.015 | 2022 <= t = linear revenueGrowthRate 2021 2026 0.01 t operatingMargin :: Val operatingMargin 2016 = operatingIncome 2016 / revenue 2016 operatingMargin t = linear operatingMargin 2016 2026 0.25 t operatingIncome :: Val operatingIncome 2016 = 59212 + leaseCommittments 2016 - depreciationOperatingLease 2016 + rdExpenses 2016 - rdAmortization 2016 operatingIncome t = revenue t * operatingMargin t taxRate :: Val taxRate t | 2016 <= t && t <= 2021 = 0.2601 | 2022 <= t = linear taxRate 2021 2026 0.3 t marginalTaxRate :: Val marginalTaxRate 2016 = 0.3 noplat :: Val noplat t = (1 - taxRate t) * operatingIncome t salesToCapitalRatio :: Val salesToCapitalRatio _ = 1.6 reinvestment :: Val reinvestment t | t < 2027 = (revenue t - revenue (t-1)) / salesToCapitalRatio t | otherwise = revenueGrowthRate t * noplat t / wacc t fcff :: Val fcff t = noplat t - reinvestment t terminalValue :: Val terminalValue t | t == terminalYear = fcff t * (1 + wacc t) / (wacc t - revenueGrowthRate t) | otherwise = 0 cashFlow :: Val cashFlow t | t <= 2016 = 0 | t < terminalYear = fcff t | t == terminalYear = terminalValue t | otherwise = throwError "invalid year" wacc :: Val wacc t | 2017 <= t && t <= 2021 = 0.0908 | 2022 <= t = linear wacc 2021 2026 0.0697 t valueOperatingAssets :: Val valueOperatingAssets = npv wacc cashFlow debt :: Val debt 2016 = 87549 + debtValueOfLeases 2016 cash :: Val cash 2016 = 245090 - 150000 * (marginalTaxRate 2016 - 0.1) distressProceeds :: Val distressProceeds _ = 0.5 equity :: Val equity t = valueOperatingAssets t - debt t + cash t equityInCommonShares :: Val equityInCommonShares t = equity t - outstandingOptionsValue t value :: Val value t = equityInCommonShares t / pure shares
sboehler/haskell-valuation
src/AAPL/Main.hs
bsd-3-clause
2,298
0
11
587
820
397
423
68
1
{-# LANGUAGE RankNTypes, TupleSections, NoMonomorphismRestriction #-} module LensPatch ( -- * Applying JSON Patches <http://jsonpatch.com> patch, -- * Helpers -- ** Misc toLens, setj, remove, add, -- ** Unsafe traversals findAtPath, fAtPath, addAtPath, setAtPath, -- ** Unsafe Applicative Traversals fAtPathA, addAtPathA, setAtPathA, -- ** Safe Traversals safeFAtPath, safeAddAtPath, safeSetAtPath ) where import Prelude hiding (foldr, foldl, foldr1, foldl1) import Control.Applicative import Control.Lens import Data.Aeson import Data.Aeson.Lens import Data.Foldable import Data.HashMap.Strict (insert, delete) import Data.Monoid import qualified Data.Vector as V import ParsePatch -- |Converts an Ix value to a JSON lens -- -- > toLens (N n) = nth n -- > toLens (K k) = key k toLens :: (AsValue t) => Ix -> Traversal' t Value toLens (N n) = nth n toLens (K k) = key k navPath :: (Foldable t, Applicative f) => t Ix -> (Value -> f Value) -> Value -> f Value navPath = foldl' (\acc p -> acc . toLens p) id -- |Converts an Ix value to a setter lens -- -- > setj = set ∘ toLens setj :: Ix -> Value -> Value -> Value setj = set . toLens -- |Removes the value at an Ix from a value, deleting nothing if the value isn't indexable -- -- > remove (K k) (Object h) = Object $ delete k h -- > remove (N i) (Array v) = Array $ ifilter (const ∘ (≢ i)) v -- > remove _ v = v remove :: Ix -> Value -> Value remove (K k) (Object h) = Object $ delete k h remove (N i) (Array v) = Array $ V.ifilter (const . (/= i)) v remove _ v = v -- |Adds a Value to an Ix within another Value, replacing whatever was already there add :: Value -> Ix -> Value -> Value add v (K k) (Object o) = Object $ insert k v o add v (N i) (Array a) = if V.length a >= i then Array $ V.concat [first, V.fromList [v], rest] else error "Index out of bounds error" where (first, rest) = V.splitAt i a -- |Traverses through a hierarchy of JSON values and returns what it finds findAtPath :: [Ix] -> Value -> Maybe Value findAtPath ps j = j ^? navPath ps -- |Applies an applicative operation and stores the new value in the old context fAtPathA :: Applicative f => (Value -> f Value) -> [Ix] -> Value -> f Value fAtPathA f ps = navPath ps %%~ f -- |Inserts an applicative value and returns the new value in the old context setAtPathA :: Applicative f => f Value -> [Ix] -> Value -> f Value setAtPathA v = fAtPathA $ const v -- |Adds an applicative value at a given path, adding a key if there wasn't one already addAtPathA :: Applicative f => [Ix] -> f Value -> Value -> f Value addAtPathA [p] v j = add <$> v <*> pure p <*> pure j addAtPathA (p:ps) v j = toLens p %%~ addAtPathA ps v $ j addAtPathA [] v _ = v -- |Applies a normal function to the value at a given path fAtPath :: (Value -> Value) -> [Ix] -> Value -> Value fAtPath f ps = runIdentity . fAtPathA (Identity . f) ps -- |Inserts a normal value to a given path setAtPath :: Value -> [Ix] -> Value -> Value setAtPath v = fAtPath $ const v -- |Adds a normal value at the given path addAtPath :: [Ix] -> Value -> Value -> Value addAtPath ps v = runIdentity . addAtPathA ps (Identity v) -- |Only returns if it can make the full traversal --safeFAtPath :: (Foldable t, Applicative f) => (Value -> Value) -> t Ix -> Value -> f Value safeFAtPath f = foldr (traverseOf . toLens) (pure . f) -- |Only returns if it can make the full traversal safeAddAtPath :: Applicative f => [Ix] -> Value -> Value -> f Value safeAddAtPath [p] v = pure . add v p safeAddAtPath (p:ps) v = toLens p %%~ safeAddAtPath ps v safeAddAtPath [] v = pure . const v -- |Only returns if it can make the full traversal safeSetAtPath :: Applicative f => Value -> [Ix] -> Value -> f Value safeSetAtPath v = safeFAtPath $ const v infixl 0 <$$> (<$$>) = (<$>) findAndDelete :: [Ix] -> Value -> Maybe (Value,Value) findAndDelete [p] o = (,remove p o) <$> o ^? toLens p findAndDelete (p:ps) o = _2 %~ setj p o <$$> o ^? toLens p >>= findAndDelete ps findAndDelete [] _ = Nothing deleteAtPath :: [Ix] -> Value -> Maybe Value deleteAtPath [p] = Just . remove p deleteAtPath (p:ps) = toLens p %%~ deleteAtPath ps -- |Applies a single JSON patch patch :: Operation -> Value -> Either String Value patch (Add p v) obj = case safeAddAtPath p v obj of (Just a) -> Right a Nothing -> Left $ "Nothing to remove at " <> fromPath p patch (Rem p) obj = case snd <$> findAndDelete p obj of (Just a) -> Right a Nothing -> Left $ "Nothing to remove at " <> fromPath p patch (Cop p1 p2) obj = case findAtPath p1 obj of (Just old) -> patch (Add p2 old) obj Nothing -> Left $ "Couldn't find value at " <> fromPath p1 patch (Mov p1 p2) obj = case findAndDelete p1 obj of (Just (old,new)) -> patch (Add p2 old) new Nothing -> Left $ "Can't find value at path " <> fromPath p1 patch (Rep p v) obj = case safeSetAtPath v p obj of (Just a) -> Right a Nothing -> Left $ "Can't find value at path " <> fromPath p patch (Tes p t) obj = case findAtPath p obj of (Just v) -> if t == v then return obj else Left $ "Value at path " <> fromPath p <> " is " <> show v <> " not " <> show t Nothing -> Left $ "Couldn't find value at path " <> fromPath p fromPath :: (Functor f, Foldable f, Show b) => f b -> String fromPath = foldr1 (<>) . fmap (cons '/' . show)
GallagherCommaJack/Haskell-JSON-Patch
LensPatch.hs
bsd-3-clause
5,487
0
14
1,321
1,816
942
874
100
8
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Exception import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Short as SBS import Data.Digest.Keccak import Data.Either import Data.Foldable import Data.Int import Data.List import qualified Data.Map as M import Data.Maybe import Data.Model hiding ( Name ) import qualified Data.Sequence as S import qualified Data.Text as T import Data.Word import Debug.Trace import Info import System.Exit ( exitFailure ) import System.TimeIt import Test.Data hiding ( Cons , Unit ) import Test.Data.Flat hiding ( Cons , Unit ) import Test.Data.Model import qualified Test.Data2 as Data2 import qualified Test.Data3 as Data3 import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck as QC import qualified Test.ZM.ADT.Bool.K306f1981b41c as Z import qualified Test.ZM.ADT.TypedBLOB.K614edd84c8bd as Z import qualified Test.ZM.ADT.Word.Kf92e8339908a as Z import qualified Test.ZM.ADT.Word7.Kf4c946334a7e as Z import qualified Test.ZM.ADT.Word8.Kb1f46a49c8f8 as Z import Text.PrettyPrint import ZM import ZM.To.Decoder import ZM.AsValue -- import Data.Timeless t = main main = mainTest -- main = mainMakeTests -- main = mainPerformance -- main = mainShow mainMakeTests = do let code = concat ["codes = [", intercalate "\n," $ map (show . typeName) models, "]"] putStrLn code exitFailure mainPerformance = do print "Calculate codes" mapM_ (timeIt . evaluate . typeName) models print "Again" mapM_ (timeIt . evaluate . typeName) models exitFailure mainShow = do -- prt (Proxy::Proxy Char) -- prt (Proxy::Proxy String) prt (Proxy :: Proxy T.Text) prt (Proxy :: Proxy (BLOB UTF8Encoding)) -- prt (Proxy::Proxy (Array Word8)) -- prtH (Proxy::Proxy (Bool,())) -- prt (Proxy::Proxy L.ByteString) -- prt (Proxy::Proxy T.Text) -- print $ tstDec (Proxy::Proxy L.ByteString) [2,11,22,0,1] -- print $ tstDec (Proxy::Proxy (Bool,Bool,Bool)) [128+32] -- print $ tstDec (Proxy::Proxy (List Bool)) [72] -- print . B.length . flat . timelessSimple $ True -- print . B.length . flat . timelessHash $ True -- print . B.length . flat . timelessExplicit $ True -- print "OK" -- prt $ tst (Proxy :: Proxy (List (Data2.List (Bool)))) exitFailure where prt = putStrLn . prettyShow . CompactPretty . absTypeModel -- pshort = putStrLn . take 1000 . prettyShow mainTest = defaultMain tests tests :: TestTree tests = testGroup "Tests" [ sha3DigestTests , shakeDigestTests , codesTests , consistentModelTests , mutuallyRecursiveTests , transformTests , identifiersTests --, timelessTests -- BUG: These tests lock up with --fast compilation -- stack clean;stack test zm --file-watch --fast , customEncodingTests , encodingTests ] sha3DigestTests = testGroup "SHA3 Digest Tests" [tst [] [0xa7, 0xff, 0xc6], tst [48, 49, 50, 51] [0x33, 0xbc, 0xc2]] where tst inp out = testCase (unwords ["SHA3", show inp]) $ B.pack out @?= sha3_256 3 (B.pack inp) shakeDigestTests = testGroup "Shake Digest Tests" [tst [] [0x7f, 0x9c, 0x2b], tst [48, 49, 50, 51] [0x30, 0xc5, 0x1c]] where tst inp out = testCase (unwords ["Shake128", show inp]) $ shake_128 3 (B.pack inp) @?= B.pack out codesTests = testGroup "Absolute Types Codes Tests" (map tst $ zip models codes) where --tst (model,code) = testCase (unwords ["Code",prettyShow model]) $ code @?= typeName model tst (model, code) = testCase (unwords ["Code", let (TypeModel t e) = model in prettyShow (e, t)]) $ code @?= typeName model consistentModelTests = testGroup "TypeModel Consistency Tests" $ map tst models where tst tm = testCase (unwords ["Consistency"]) $ internalConsistency tm && externalConsistency tm @?= True internalConsistency = noErrors . map prettyShow . refErrors . typeEnv -- |Check external consistency of absolute environment -- the key of every ADT in the env is correct (same as calculated directly on the ADT) externalConsistency = all (\(r, adt) -> absRef adt == r) . M.toList . typeEnv mutuallyRecursiveTests = testGroup "Mutually Recursion Detection Tests" $ [ tst (Proxy :: Proxy A0) , tst (Proxy :: Proxy B0) , tst (Proxy :: Proxy (Forest Bool)) ] where tst :: forall a . (Model a) => Proxy a -> TestTree tst proxy = let r = absTypeModelMaybe proxy in testCase (unwords ["Mutual Recursion", show r]) $ --isLeft r && (let Left es = r in all (isInfixOf "mutually recursive") es) @?= True isLeft r && (all isMutuallyRecursive . fromLeft2 $ r) @?= True fromLeft2 (Left l) = l isMutuallyRecursive (MutuallyRecursive _) = True isMutuallyRecursive _ = False -- |Test all custom flat instances for conformity to their model customEncodingTests = testGroup "Typed Unit Tests" [ om (Proxy :: Proxy Z.Bool) False , om (Proxy :: Proxy Z.Word8) (255 :: Word8) , om (Proxy :: Proxy Z.Word) (930123123 :: Word) , om (Proxy :: Proxy Z.TypedBLOB) (typedBLOB False) , em (Proxy :: Proxy T.Text) (Proxy :: Proxy (BLOB UTF8Encoding)) , em (Proxy :: Proxy UTF8Text) (Proxy :: Proxy (BLOB UTF8Encoding)) , em (Proxy :: Proxy UTF16Text) (Proxy :: Proxy (BLOB UTF16LEEncoding)) , e () , e False , e (Just True) , e (Left True :: Either Bool Char) , e (Right () :: Either Bool ()) , e (False, 'g') , e [(False, 'g')] , e (M.fromList ([] :: [(Bool, Bool)])) , e (M.fromList [(False, 'g')]) , e (M.fromList [(33 :: Int, "abc")]) , e (M.fromList [(33 :: Int, 57 :: Word8), (44, 77)]) , e $ B.pack [] , e $ B.pack [11, 22] , e $ L.pack [] , e $ L.pack (replicate 11 77) , e $ SBS.pack [] , e $ SBS.pack [11, 22] , e an , e aw , e ab , e $ seq an , e $ seq ab , e $ seq aw , e $ seq ac , e 'a' , e 'k' -- ,e "\n" , e "ab\ncd" , e ac , e $ blob NoEncoding [11 :: Word8, 22, 33] , e $ blob UTF8Encoding [97 :: Word8, 98, 99] , e $ blob UTF16LEEncoding ([0x24, 0x00, 0xAC, 0x20, 0x01, 0xD8, 0x37, 0xDC] :: [Word8]) -- $€𐐷 --,e $ typedBLOB True , e (T.pack "abc$€𐐷") , e (UTF8Text $ T.pack "abc$€𐐷") , e (UTF16Text $ T.pack "abc$€𐐷") , e (False, True) , e (False, True, 44 :: Word8) , e (False, True, 44 :: Word8, True) -- , e (False, True, 44 :: Word8, True, False) -- , e (False, True, 44 :: Word8, True, False, False) -- , e (False, True, 44 :: Word8, True, False, False, 44 :: Word8) -- , e (False, True, 44 :: Word8, True, False, False, 44 :: Word8, ()) -- , e (False, True, 44 :: Word8, True, False, False, 44 :: Word8, (), 'a') , e (33 :: Word) , e (0 :: Word8) , e (33 :: Word8) , e (255 :: Word8) , e (3333 :: Word16) , e (333333 :: Word32) , e (33333333 :: Word64) , e (maxBound :: Word64) , e (-11111111 :: Int) , e (11111111 :: Int) , e (88 :: Int8) , e (1616 :: Int16) , e (32323232 :: Int32) , e (6464646464 :: Int64) , e (minBound :: Int32) , e (maxBound :: Int32) , e (minBound :: Int64) , e (maxBound :: Int64) , e (-88 :: Int8) , e (-1616 :: Int16) , e (-32323232 :: Int32) , e (-6464646464 :: Int64) , e (44323232123 :: Integer) , e (-4323232123 :: Integer) , e (12.123 :: Float) , e (-57.238E-11 :: Float) , e (12.123 :: Double) , e (-57.238E-11 :: Double) ] where seq = S.fromList an = [] :: [()] aw = [0, 128, 127, 255 :: Word8] ab = [False, True, False] ac = ['v', 'i', 'c'] e :: forall a . (AsValue a, Pretty a, Flat a, Show a, Model a, Eq a) => a -> TestTree e x = --testCase (unwords ["Custom Encoding", show x, prettyShow x, dynamicShow x]) $ dynamicShow x @?= prettyShow x -- prettierShow x testCase (unwords ["Custom Encoding", show x, prettyShow x]) $ unValue (value x) @?= x em p1 p2 = testCase (unwords ["Model Mapping"]) $ absType p1 @?= absType p2 om :: forall a m . (Flat a, Show a, Eq a, Flat m) => Proxy m -> a -> TestTree om p v = testCase (unwords ["Original Model Mapping"]) $ (let Right (vm :: m) = unflat (flat v) in unflat (flat vm)) @?= Right v -- As previous test but using Arbitrary values encodingTests = testGroup "Encoding Tests" [ ce "()" (prop_encoding :: RT ()) , ce "Bool" (prop_encoding :: RT Bool) , ce "Maybe Bool" (prop_encoding :: RT (Maybe Bool)) , ce "Word" (prop_encoding :: RT Word) , ce "Word8" (prop_encoding :: RT Word8) , ce "Word16" (prop_encoding :: RT Word16) , ce "Word32" (prop_encoding :: RT Word32) , ce "Word64" (prop_encoding :: RT Word64) , ce "Int" (prop_encoding :: RT Int) , ce "Int16" (prop_encoding :: RT Int16) , ce "Int16" (prop_encoding :: RT Int16) , ce "Int32" (prop_encoding :: RT Int32) , ce "Int64" (prop_encoding :: RT Int64) , ce "Integer" (prop_encoding :: RT Integer) , ce "Char" (prop_encoding :: RT Char) , ce "String" (prop_encoding :: RT String) -- too slow , ce "[Maybe (Bool,Char)]" (prop_encoding :: RT ([Maybe (Bool, Char)])) ] where ce n = QC.testProperty (unwords ["Encoding", n]) identifiersTests = testGroup "Identifier Tests" $ concat [ testId "Tuple2" $ Name (UnicodeLetter 'T') [ UnicodeLetterOrNumberOrLine 'u' , UnicodeLetterOrNumberOrLine 'p' , UnicodeLetterOrNumberOrLine 'l' , UnicodeLetterOrNumberOrLine 'e' , UnicodeLetterOrNumberOrLine '2' ] , testId "abc" $ Name (UnicodeLetter 'a') [UnicodeLetterOrNumberOrLine 'b', UnicodeLetterOrNumberOrLine 'c'] , testId "<>" $ Symbol (Cons (UnicodeSymbol '<') (Elem (UnicodeSymbol '>'))) ] where testId s i = [ testCase (unwords ["identifier parse", s]) $ convert s @?= i , testCase (unwords ["identifier roundtrip", s]) $ convert (convert s :: Identifier) @?= s ] transformTests = testGroup "Transform Tests" [ testRecDeps (Proxy :: Proxy Bool) 1 , testRecDeps (Proxy :: Proxy (Bool, [Bool])) 3 ] where testRecDeps proxy len = let tm = absTypeModel proxy in let Right deps = typeDefinition (typeEnv tm) (typeName tm) -- $ length (typeDefinition (typeEnv tm) (typeName tm)) @?= len in testCase (unwords ["recursiveDependencies", prettyShow $ typeName tm]) $ length deps @?= len -- prop_encoding x = dynamicShow x == prettierShow x -- prop_encoding :: forall a . (Pretty a, Flat a, Model a) => RT a prop_encoding :: forall a . (AsValue a, Flat a, Model a, Eq a) => RT a -- prop_encoding x = dynamicShow x == prettyShow x prop_encoding x = unValue (value x) == x -- dynamicShow :: forall a . (Flat a, Model a,Pretty a ) => a -> String -- dynamicShow a = -- case decodeAbsTypeModel (absTypeModel (Proxy :: Proxy a)) (flat a) of -- Left e -> error (show e) -- Right v -> prettyShow v type RT a = a -> Bool -- timelessTests = t True -- where -- t n = testGroup (unwords ["Timeless",show n]) [ -- testCase "simple" (untimeless (timelessSimple n) @?= Right n) -- ,testCase "hash" (untimeless (timelessHash n) @?= Right n) -- ,testCase "explicit" (untimeless (timelessExplicit n) @?= Right n) -- ]
tittoassini/typed
test/Spec.hs
bsd-3-clause
12,558
0
18
3,833
3,464
1,911
1,553
268
1
{- Copyright (c) 2013, Markus Barenhoff <alios@alios.org> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 DeriveDataTypeable #-} module Data.DEVS.Simulation.Processor(SimMsg (..)) where import Data.Typeable (Typeable) import Data.DEVS.Devs import Data.Binary data SimMsg y = Sync Int T | Done T | Out y T deriving (Typeable) instance (Binary y) => Binary (SimMsg y) where put (Sync c t) = do putWord8 0x01; put c ; put t put (Done t) = do putWord8 0x02 ; put t put (Out y t) = do putWord8 0x03 ; put y ; put t get = do m <- getWord8 case m of 0x01 -> do c <- get t <- get return $ Sync c t 0x02 -> do t <- get return $ Done t 0x03 -> do y <- get t <- get return $ Out y t t -> fail $ "Unexpected SimMsg t" ++ show t
alios/lambda-devs
Data/DEVS/Simulation/Processor.hs
bsd-3-clause
2,356
0
14
606
316
156
160
25
0
{-# LANGUAGE OverloadedStrings, DeriveGeneric, RecordWildCards #-} module VimGif (serveRandomVimGif) where import qualified Data.ByteString.Lazy as L import qualified Network.HTTP.Simple as S import Data.Text (Text, pack) import Data.Maybe (fromMaybe) import Control.Monad.Random (MonadRandom, getRandomR) import GHC.Generics (Generic) import Data.Vector (Vector(..), (!), fromList) import Data.Aeson -- | wrapping Text in a newtype -- this will get us the encoding/decoding JSON features -- and the wrapper disappears at runtime newtype GifTitle = GifTitle Text deriving (Show, Generic) instance ToJSON GifTitle instance FromJSON GifTitle where parseJSON (String t) = pure $ GifTitle t parseJSON (Number n) = pure (GifTitle $ pack (show n)) parseJSON _ = mempty data Gif = Gif { title :: GifTitle , url :: Text , awslink :: Text } deriving (Show, Generic) instance FromJSON Gif instance ToJSON Gif type GifList = Vector Gif serveRandomVimGif :: IO Value serveRandomVimGif = gifToSlack <$> (getGifs >>= chooseRandom) getGifs :: IO GifList getGifs = fromMaybe (fromList [Gif (GifTitle "") "" ""]) . decode . S.getResponseBody <$> S.httpLbs "https://vimgifs.com/gifs.json" chooseRandom :: (MonadRandom m) => Vector a -> m a chooseRandom gifs = do idx <- getRandomR (0, length gifs - 1) return $ gifs ! idx gifToSlack :: Gif -> Value gifToSlack Gif{..} = object [ "response_type" .= pack "in_channel" , "attachments" .= [ object [ "text" .= title , "image_url" .= awslink ] ] ]
clarkenciel/slackers
src/VimGif.hs
bsd-3-clause
1,602
0
14
347
472
259
213
39
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Anatomy.Atomo where import Data.Dynamic import Data.Text.Encoding import Prelude hiding (div, span) import System.Directory import System.FilePath import Text.Blaze.Html5 hiding (p, string) import Text.Blaze.Html5.Attributes hiding (name, span) import Text.Blaze.Renderer.String import Text.Highlighter.Formatters.Html import Text.Highlighter.Lexers.Atomo (lexer) import qualified Data.ByteString as BS import qualified Data.Text as T import qualified Text.Highlighter as HL import Atomo import Atomo.Load import Anatomy.Builder import Anatomy.Parser import Anatomy.Scanner import Anatomy.Types import Paths_anatomy load :: VM () load = do ([$p|A|] =::) =<< eval [$e|Object clone|] liftIO (getDataFileName "lib/core.atomo") >>= loadFile [$p|(a: A) new: (fn: String)|] =: do fn <- getString [$e|fn|] path <- fmap takeDirectory . liftIO $ canonicalizePath fn liftIO (putStrLn ("path: " ++ path)) ast <- parseFile fn sec <- scan 0 1 path ast [$p|a state|] =:: Haskell (toDyn sec) here "a" [$p|(a: A) url-for: (e: Expression)|] =: do Expression ae <- here "e" >>= findExpression Haskell ds <- eval [$e|a state|] let st = fromDyn ds (error "hotlink A is invalid") :: Section find <- case ae of EDispatch { eMessage = Single { mName = n } } -> runAVM' (findBinding (SingleKey n) st) st EDispatch { eMessage = Keyword { mNames = ns } } -> runAVM' (findBinding (KeywordKey ns) st) st EParticle { eParticle = Single { mName = n } } -> runAVM' (findBinding (SingleKey n) st) st EParticle { eParticle = Keyword { mNames = ns } } -> runAVM' (findBinding (KeywordKey ns) st) st EPrimitive { eValue = Particle (Single { mName = n }) } -> runAVM' (findBinding (SingleKey n) st) st EPrimitive { eValue = Particle (Keyword { mNames = ns }) } -> runAVM' (findBinding (KeywordKey ns) st) st _ -> raise ["no-url-for"] [Expression ae] case find of Nothing -> return (particle "none") Just u -> return (keyParticle ["ok"] [Nothing, Just (string u)]) [$p|(a: A) reference: (s: String)|] =: do n <- getString [$e|s|] Haskell ds <- eval [$e|a state|] let st = fromDyn ds (error "hotlink A is invalid") :: Section flip runAVM' st $ do ms <- findSection n st case ms of Nothing -> return (string n) Just s -> do url <- sectionURL s name <- buildForString' (titleText (sectionTitle s)) return (string $ "<a href=\"" ++ url ++ "\">" ++ name ++ "</a>") [$p|(a: A) atomo: (s: String)|] =: do s <- getText [$e|s|] Haskell ds <- eval [$e|a state|] let st = fromDyn ds (error "hotlink A is invalid") :: Section case HL.runLexer lexer (encodeUtf8 s) of Left err -> error ("lexing of Atomo source failed: " ++ show (s, err)) Right ts -> liftM (string . renderHtml . (div ! class_ (stringValue "highlight")) . pre) (runAVM' (autoLink ts) st) [$p|(a: A) highlight: (s: String) &auto-link|] =: do s <- getText [$e|s|] Haskell ds <- eval [$e|a state|] Boolean auto <- here "auto-link" >>= findBoolean let st = fromDyn ds (error "hotlink A is invalid") :: Section case HL.runLexer lexer (encodeUtf8 s) of Left err -> error ("@highlight: - lexing failed: " ++ show (s, err)) Right ts | auto -> liftM (string . renderHtml) (runAVM' (autoLink ts) st) Right ts -> return (string (renderHtml (formatInline ts))) [$p|(a: A) highlight: (s: String) as: (lang: String)|] =: do s <- getText [$e|s|] l <- getString [$e|lang|] >>= \n -> case HL.lexerFromFilename ("." ++ n) of Nothing -> raise ["unknown-lexer"] [string n] Just l -> return l case HL.runLexer l (encodeUtf8 s) of Left err -> error ("@highlight:as: - lexing failed: " ++ show (s, err)) Right ts -> return (string (renderHtml (formatInline ts))) -- Format lexed source, auto-linking dispatches to their definitions. autoLink :: [HL.Token] -> AVM Html autoLink = autoLink' ([], "") where autoLink' _ [] = return (return ()) autoLink' cks (HL.Token HL.Name s:ts) = do st <- get mu <- findBinding (SingleKey (fromBS s)) st case mu of Nothing -> do rest <- autoLink' cks ts return $ (span ! class_ (stringValue "n") $ bs s) >> rest Just u -> do rest <- autoLink' cks ts return $ (span ! class_ (stringValue "n") $ a ! href (stringValue u) $ bs s) >> rest autoLink' cks (HL.Token HL.Operator s:ts) = do st <- get mu <- findBinding (KeywordKey [fromBS s]) st case mu of Nothing -> do rest <- autoLink' cks ts return $ (span ! class_ (stringValue "o") $ bs s) >> rest Just u -> do rest <- autoLink' cks ts return $ (span ! class_ (stringValue "o") $ a ! href (stringValue u) $ bs s) >> rest autoLink' ([], _) (HL.Token (HL.Name HL.:. HL.Function) s:ts) = do st <- get let full = init (fromBS s) : restOf ts mu <- findBinding (KeywordKey full) st case mu of Nothing -> do rest <- autoLink' (tail full, "") ts return $ (span ! class_ "nf" $ bs s) >> rest Just u -> do rest <- autoLink' (tail full, u) ts return $ (span ! class_ "nf" $ a ! href (stringValue u) $ bs s) >> rest autoLink' (cks, u) (HL.Token (HL.Name HL.:. HL.Function) s:ts) = do rest <- autoLink' (tail cks, u) ts if not (null u) then return $ (span ! class_ "nf" $ a ! href (stringValue u) $ bs s) >> rest else return $ (span ! class_ "nf" $ bs s) >> rest autoLink' cks (HL.Token t s:ts) = do rest <- autoLink' cks ts return $ (span ! class_ (stringValue $ HL.shortName t) $ bs s) >> rest -- Retrieve the rest of a keyword message name from a list of tokens. restOf :: [HL.Token] -> [String] restOf [] = [] restOf (HL.Token _ "(":ts) = restOf (drop 1 $ dropWhile ((/= "(") . HL.tText) $ ts) restOf (HL.Token _ "{":ts) = restOf (drop 1 $ dropWhile ((/= "}") . HL.tText) $ ts) restOf (HL.Token _ "[":ts) = restOf (drop 1 $ dropWhile ((/= "]") . HL.tText) $ ts) restOf (HL.Token _ ")":_) = [] restOf (HL.Token _ "}":_) = [] restOf (HL.Token _ "]":_) = [] restOf (HL.Token (HL.Name HL.:. HL.Function) n:ts) = init (fromBS n) : restOf ts restOf (HL.Token HL.Text x:_) | toEnum (fromEnum '\n') `BS.elem` x = [] restOf (_:ts) = restOf ts bs :: BS.ByteString -> Html bs = text . decodeUtf8 fromBS :: BS.ByteString -> String fromBS = T.unpack . decodeUtf8
vito/atomo-anatomy
src/Anatomy/Atomo.hs
bsd-3-clause
7,346
118
25
2,419
3,016
1,512
1,504
163
14
module Network.Sock.Types.Protocol ( Protocol(..) , ProtocolControl(..) ) where ------------------------------------------------------------------------------ import qualified Data.ByteString.Lazy as BL (ByteString) ------------------------------------------------------------------------------ -- | Data type representing the protocol used to encode outgoing messages. data Protocol = Message BL.ByteString -- ^ Interpreted as an element of a FrameMessages. Public. | Control ProtocolControl -- ^ Interpreted case by case. | Raw BL.ByteString -- ^ Interpreted as is. Used to contain encoded FrameClose, FrameOpen, FrameHeartbeat and some other stuff. -- | Data type to represend control messages. data ProtocolControl = Close -- ^ Signifies that we wish to close the session. Enables the Application to close the session.
Palmik/wai-sockjs
src/Network/Sock/Types/Protocol.hs
bsd-3-clause
862
0
7
139
76
52
24
8
0
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE MultiParamTypeClasses,TypeFamilies,FlexibleInstances #-} module QuickWeave.Runtime.Applyable where class Applyable a b where type Result a b fromApp :: a -> b -> Result a b instance (a~a') => Applyable (a->b) a' where type Result (a->b) a' = b fromApp f x = f x
shayan-najd/QuickWeave
QuickWeave/Runtime/Applyable.hs
bsd-3-clause
315
0
9
62
102
56
46
9
0
{-# Language ScopedTypeVariables, CPP #-} module FindSymbol ( findSymbol ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) import qualified UniqFM #else import GHC.PackageDb (exposedName) import GhcMonad (liftIO) #endif import Control.Monad (filterM) import Control.Exception import Data.List (find, nub) import Data.Maybe (catMaybes, isJust) import qualified GHC import qualified Packages as PKG import qualified Name import Exception (ghandle) type SymbolName = String type ModuleName = String findSymbol :: SymbolName -> GHC.Ghc [ModuleName] findSymbol symbol = do fileMods <- findSymbolInFile symbol pkgsMods <- findSymbolInPackages symbol return . nub . map (GHC.moduleNameString . GHC.moduleName) $ fileMods ++ pkgsMods findSymbolInFile :: SymbolName -> GHC.Ghc [GHC.Module] findSymbolInFile symbol = filterM (containsSymbol symbol) =<< map GHC.ms_mod <$> GHC.getModuleGraph findSymbolInPackages :: SymbolName -> GHC.Ghc [GHC.Module] findSymbolInPackages symbol = filterM (containsSymbol symbol) =<< allExposedModules where allExposedModules :: GHC.Ghc [GHC.Module] allExposedModules = do modNames <- exposedModuleNames catMaybes <$> mapM findModule modNames where exposedModuleNames :: GHC.Ghc [GHC.ModuleName] #if __GLASGOW_HASKELL__ < 710 exposedModuleNames = concatMap exposedModules . UniqFM.eltsUFM . PKG.pkgIdMap . GHC.pkgState <$> GHC.getSessionDynFlags #elif __GLASGOW_HASKELL__ >= 800 exposedModuleNames = do dynFlags <- GHC.getSessionDynFlags pkgConfigs <- liftIO $ fmap concat . (fmap . fmap) snd . PKG.readPackageConfigs $ dynFlags return $ map exposedName (concatMap exposedModules pkgConfigs) #else exposedModuleNames = do dynFlags <- GHC.getSessionDynFlags pkgConfigs <- liftIO $ PKG.readPackageConfigs dynFlags return $ map exposedName (concatMap exposedModules pkgConfigs) #endif exposedModules pkg = if PKG.exposed pkg then PKG.exposedModules pkg else [] findModule :: GHC.ModuleName -> GHC.Ghc (Maybe GHC.Module) findModule moduleName = ghandle (\(_ :: SomeException) -> return Nothing) (Just <$> GHC.findModule moduleName Nothing) containsSymbol :: SymbolName -> GHC.Module -> GHC.Ghc Bool containsSymbol symbol module_ = isJust . find (== symbol) <$> allExportedSymbols where allExportedSymbols = ghandle (\(_ :: SomeException) -> return []) (do info <- GHC.getModuleInfo module_ return $ maybe [] (map Name.getOccString . GHC.modInfoExports) info)
pacak/hdevtools
src/FindSymbol.hs
mit
2,680
23
13
571
559
303
256
49
2
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : ./Comorphisms/CASL2CspCASL.hs Copyright : (c) Till Mossakowski and Uni Bremen 2003 License : GPLv2 or higher, see LICENSE.txt Maintainer : M.Roggenbach@swansea.ac.uk Stability : provisional Portability : non-portable (imports Logic.Logic) The embedding comorphism from CASL to CspCASL. -} module Comorphisms.CASL2CspCASL where import Logic.Logic import Logic.Comorphism import Common.ProofTree -- CASL import CASL.AS_Basic_CASL import CASL.Logic_CASL import CASL.Morphism import CASL.Sign import CASL.Sublogic as SL -- CspCASL import CspCASL.Logic_CspCASL import CspCASL.StatAnaCSP (CspBasicSpec) import CspCASL.SignCSP import CspCASL.Morphism (CspCASLMorphism, emptyCspAddMorphism) import CspCASL.SymbItems import CspCASL.Symbol import qualified Data.Set as Set -- | The identity of the comorphism data CASL2CspCASL = CASL2CspCASL deriving (Show) instance Language CASL2CspCASL -- default definition is okay instance Comorphism CASL2CspCASL CASL CASL_Sublogics CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS CASLSign CASLMor Symbol RawSymbol ProofTree CspCASL () CspBasicSpec CspCASLSen CspSymbItems CspSymbMapItems CspCASLSign CspCASLMorphism CspSymbol CspRawSymbol () where sourceLogic CASL2CspCASL = CASL sourceSublogic CASL2CspCASL = SL.top targetLogic CASL2CspCASL = cspCASL mapSublogic CASL2CspCASL _ = Just () map_theory CASL2CspCASL = return . embedCASLTheory emptyCspSign map_symbol CASL2CspCASL _ = Set.singleton . caslToCspSymbol map_morphism CASL2CspCASL = return . mapCASLMor emptyCspSign emptyCspAddMorphism map_sentence CASL2CspCASL _sig = return . mapFORMULA has_model_expansion CASL2CspCASL = True is_weakly_amalgamable CASL2CspCASL = True isInclusionComorphism CASL2CspCASL = True
spechub/Hets
Comorphisms/CASL2CspCASL.hs
gpl-2.0
1,909
0
7
307
309
169
140
37
0
-- | -- Module : Aura.Pkgbuild.Records -- Copyright : (c) Colin Woodbury, 2012 - 2020 -- License : GPL3 -- Maintainer: Colin Woodbury <colin@fosskers.ca> -- -- Handle the storing of PKGBUILDs. module Aura.Pkgbuild.Records ( hasPkgbuildStored , storePkgbuilds , pkgbuildPath ) where import Aura.Types import RIO import RIO.Directory import RIO.FilePath import qualified RIO.Text as T --- -- | The default location: \/var\/cache\/aura\/pkgbuilds\/ pkgbuildCache :: FilePath pkgbuildCache = "/var/cache/aura/pkgbuilds/" -- | The expected path to a stored PKGBUILD, given some package name. pkgbuildPath :: PkgName -> FilePath pkgbuildPath (PkgName p) = pkgbuildCache </> T.unpack p <.> "pb" -- | Does a given package has a PKGBUILD stored? -- This is `True` when a package has been built successfully once before. hasPkgbuildStored :: PkgName -> IO Bool hasPkgbuildStored = doesFileExist . pkgbuildPath -- | Write the PKGBUILDs of some `Buildable`s to disk. storePkgbuilds :: NonEmpty Buildable -> IO () storePkgbuilds bs = do createDirectoryIfMissing True pkgbuildCache traverse_ (\p -> writePkgbuild (bName p) (bPkgbuild p)) bs writePkgbuild :: PkgName -> Pkgbuild -> IO () writePkgbuild pn (Pkgbuild pb) = writeFileBinary (pkgbuildPath pn) pb
bb010g/aura
aura/lib/Aura/Pkgbuild/Records.hs
gpl-3.0
1,308
0
12
244
235
130
105
21
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} module Hledger.Web.Handler.AddR ( getAddR , postAddR , putAddR ) where import Data.Aeson.Types (Result(..)) import qualified Data.Text as T import Network.HTTP.Types.Status (status400) import Text.Blaze.Html (preEscapedToHtml) import Yesod import Hledger import Hledger.Cli.Commands.Add (appendToJournalFileOrStdout, journalAddTransaction) import Hledger.Web.Import import Hledger.Web.WebOptions (WebOpts(..)) import Hledger.Web.Widget.AddForm (addForm) getAddR :: Handler () getAddR = do checkServerSideUiEnabled postAddR postAddR :: Handler () postAddR = do checkServerSideUiEnabled VD{caps, j, today} <- getViewData when (CapAdd `notElem` caps) (permissionDenied "Missing the 'add' capability") ((res, view), enctype) <- runFormPost $ addForm j today case res of FormSuccess res' -> do let t = txnTieKnot res' -- XXX(?) move into balanceTransaction liftIO $ ensureJournalFileExists (journalFilePath j) -- XXX why not journalAddTransaction ? liftIO $ appendToJournalFileOrStdout (journalFilePath j) (showTransaction t) setMessage "Transaction added." redirect JournalR FormMissing -> showForm view enctype FormFailure errs -> do mapM_ (setMessage . preEscapedToHtml . T.replace "\n" "<br>") errs showForm view enctype where showForm view enctype = sendResponse =<< defaultLayout [whamlet| <h2>Add transaction <div .row style="margin-top:1em"> <form#addform.form.col-xs-12.col-md-8 method=post enctype=#{enctype}> ^{view} |] -- Add a single new transaction, send as JSON via PUT, to the journal. -- The web form handler above should probably use PUT as well. putAddR :: Handler RepJson putAddR = do VD{caps, j, opts} <- getViewData when (CapAdd `notElem` caps) (permissionDenied "Missing the 'add' capability") (r :: Result Transaction) <- parseCheckJsonBody case r of Error err -> sendStatusJSON status400 ("could not parse json: " ++ err ::String) Success t -> do void $ liftIO $ journalAddTransaction j (cliopts_ opts) t sendResponseCreated TransactionsR
adept/hledger
hledger-web/Hledger/Web/Handler/AddR.hs
gpl-3.0
2,306
0
16
444
536
285
251
52
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} ------------------------------------------------------------------------------ -- | -- Module : Database.PostgreSQL.Simple.Ok -- Copyright : (c) 2012 Leon P Smith -- License : BSD3 -- -- Maintainer : leon@melding-monads.com -- Stability : experimental -- -- The 'Ok' type is a simple error handler, basically equivalent to -- @Either [SomeException]@. This type (without the list) was used to -- handle conversion errors in early versions of postgresql-simple. -- -- One of the primary reasons why this type was introduced is that -- @Either SomeException@ had not been provided an instance for 'Alternative', -- and it would have been a bad idea to provide an orphaned instance for a -- commonly-used type and typeclass included in @base@. -- -- Extending the failure case to a list of 'SomeException's enables a -- more sensible 'Alternative' instance definitions: '<|>' concatinates -- the list of exceptions when both cases fail, and 'empty' is defined as -- 'Errors []'. Though '<|>' one could pick one of two exceptions, and -- throw away the other, and have 'empty' provide a generic exception, -- this avoids cases where 'empty' overrides a more informative exception -- and allows you to see all the different ways your computation has failed. -- ------------------------------------------------------------------------------ module Database.PostgreSQL.Simple.Ok where import Control.Applicative import Control.Exception import Control.Monad(MonadPlus(..)) import Data.Typeable -- FIXME: [SomeException] should probably be something else, maybe -- a difference list (or a tree?) data Ok a = Errors [SomeException] | Ok !a deriving(Show, Typeable, Functor) -- | Two 'Errors' cases are considered equal, regardless of what the -- list of exceptions looks like. instance Eq a => Eq (Ok a) where Errors _ == Errors _ = True Ok a == Ok b = a == b _ == _ = False instance Applicative Ok where pure = Ok Errors es <*> _ = Errors es _ <*> Errors es = Errors es Ok f <*> Ok a = Ok (f a) instance Alternative Ok where empty = Errors [] a@(Ok _) <|> _ = a Errors _ <|> b@(Ok _) = b Errors as <|> Errors bs = Errors (as ++ bs) instance MonadPlus Ok where mzero = empty mplus = (<|>) instance Monad Ok where return = Ok Errors es >>= _ = Errors es Ok a >>= f = f a fail str = Errors [SomeException (ErrorCall str)] -- | a way to reify a list of exceptions into a single exception newtype ManyErrors = ManyErrors [SomeException] deriving (Show, Typeable) instance Exception ManyErrors
avieth/postgresql-simple
src/Database/PostgreSQL/Simple/Ok.hs
bsd-3-clause
2,731
0
10
599
455
242
213
36
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MonadComprehensions #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} -- | TPC-H Q13 module Queries.TPCH.Standard.Q13 ( q13 , q13Default ) where import qualified Data.Text as T import Database.DSH import Queries.TPCH.BuildingBlocks import Schema.TPCH -- TPC-H Q13. Note that we replace the LEFT OUTER JOIN and grouping -- with a nestjoin, to include those customers with an empty list of -- (relevant) orders. -- | Compute number of orders per customer, including those that have -- not placed any orders. ordersPerCustomer :: Text -> Q [(Integer, Integer)] ordersPerCustomer pat = [ tup2 (c_custkeyQ c) (length $ filter (\o -> o_commentQ o `notLike` (toQ pat)) $ custOrders c) | c <- customers ] -- | TPC-H Query Q13 with standard validation parameters q13Default :: Q [(Integer, Integer)] q13Default = q13 "special" "requests" -- | TPC-H Q13: Distribution of orders per customer, including -- customers without orders. q13 :: Text -> Text -> Q [(Integer, Integer)] q13 w1 w2 = sortWith (\(view -> (c_count, custdist)) -> pair (custdist * (-1)) (c_count * (-1))) $ groupAggr snd id length (ordersPerCustomer pat) where pat = foldr T.append "" ["%", w1, "%", w2, "%"]
ulricha/dsh-example-queries
Queries/TPCH/Standard/Q13.hs
bsd-3-clause
1,616
0
15
402
315
185
130
31
1
{-# LANGUAGE CPP, FlexibleInstances, IncoherentInstances, NamedFieldPuns, NoImplicitPrelude, OverlappingInstances, TemplateHaskell, UndecidableInstances #-} {-| Module: Data.Aeson.TH Copyright: (c) 2011-2015 Bryan O'Sullivan (c) 2011 MailRank, Inc. License: Apache Stability: experimental Portability: portable Functions to mechanically derive 'ToJSON' and 'FromJSON' instances. Note that you need to enable the @TemplateHaskell@ language extension in order to use this module. An example shows how instances are generated for arbitrary data types. First we define a data type: @ data D a = Nullary | Unary Int | Product String Char a | Record { testOne :: Double , testTwo :: Bool , testThree :: D a } deriving Eq @ Next we derive the necessary instances. Note that we make use of the feature to change record field names. In this case we drop the first 4 characters of every field name. We also modify constructor names by lower-casing them: @ $('deriveJSON' 'defaultOptions'{'fieldLabelModifier' = 'drop' 4, 'constructorTagModifier' = map toLower} ''D) @ Now we can use the newly created instances. @ d :: D 'Int' d = Record { testOne = 3.14159 , testTwo = 'True' , testThree = Product \"test\" \'A\' 123 } @ >>> fromJSON (toJSON d) == Success d > True Please note that you can derive instances for tuples using the following syntax: @ -- FromJSON and ToJSON instances for 4-tuples. $('deriveJSON' 'defaultOptions' ''(,,,)) @ -} module Data.Aeson.TH ( -- * Encoding configuration Options(..), SumEncoding(..), defaultOptions, defaultTaggedObject -- * FromJSON and ToJSON derivation , deriveJSON , deriveToJSON , deriveFromJSON , mkToJSON , mkParseJSON ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from aeson: import Data.Aeson ( toJSON, Object, object, (.=), (.:), (.:?) , ToJSON, toJSON , FromJSON, parseJSON ) import Data.Aeson.Types ( Value(..), Parser , Options(..) , SumEncoding(..) , defaultOptions , defaultTaggedObject ) -- from base: import Control.Applicative ( pure, (<$>), (<*>) ) import Control.Monad ( return, mapM, liftM2, fail ) import Data.Bool ( Bool(False, True), otherwise, (&&) ) import Data.Eq ( (==) ) import Data.Function ( ($), (.) ) import Data.Functor ( fmap ) import Data.Int ( Int ) import Data.Either ( Either(Left, Right) ) import Data.List ( (++), foldl, foldl', intercalate , length, map, zip, genericLength, all, partition ) import Data.Maybe ( Maybe(Nothing, Just), catMaybes ) import Prelude ( String, (-), Integer, fromIntegral, error ) import Text.Printf ( printf ) import Text.Show ( show ) -- from unordered-containers: import qualified Data.HashMap.Strict as H ( lookup, toList ) -- from template-haskell: import Language.Haskell.TH import Language.Haskell.TH.Syntax ( VarStrictType ) -- from text: import qualified Data.Text as T ( Text, pack, unpack ) -- from vector: import qualified Data.Vector as V ( unsafeIndex, null, length, create, fromList ) import qualified Data.Vector.Mutable as VM ( unsafeNew, unsafeWrite ) -------------------------------------------------------------------------------- -- Convenience -------------------------------------------------------------------------------- -- | Generates both 'ToJSON' and 'FromJSON' instance declarations for the given -- data type. -- -- This is a convienience function which is equivalent to calling both -- 'deriveToJSON' and 'deriveFromJSON'. deriveJSON :: Options -- ^ Encoding options. -> Name -- ^ Name of the type for which to generate 'ToJSON' and 'FromJSON' -- instances. -> Q [Dec] deriveJSON opts name = liftM2 (++) (deriveToJSON opts name) (deriveFromJSON opts name) -------------------------------------------------------------------------------- -- ToJSON -------------------------------------------------------------------------------- {- TODO: Don't constrain phantom type variables. data Foo a = Foo Int instance (ToJSON a) ⇒ ToJSON Foo where ... The above (ToJSON a) constraint is not necessary and perhaps undesirable. -} -- | Generates a 'ToJSON' instance declaration for the given data type. deriveToJSON :: Options -- ^ Encoding options. -> Name -- ^ Name of the type for which to generate a 'ToJSON' instance -- declaration. -> Q [Dec] deriveToJSON opts name = withType name $ \tvbs cons -> fmap (:[]) $ fromCons tvbs cons where fromCons :: [TyVarBndr] -> [Con] -> Q Dec fromCons tvbs cons = instanceD (applyCon ''ToJSON typeNames) (classType `appT` instanceType) [ funD 'toJSON [ clause [] (normalB $ consToJSON opts cons) [] ] ] where classType = conT ''ToJSON typeNames = map tvbName tvbs instanceType = foldl' appT (conT name) $ map varT typeNames -- | Generates a lambda expression which encodes the given data type as JSON. mkToJSON :: Options -- ^ Encoding options. -> Name -- ^ Name of the type to encode. -> Q Exp mkToJSON opts name = withType name (\_ cons -> consToJSON opts cons) -- | Helper function used by both 'deriveToJSON' and 'mkToJSON'. Generates code -- to generate the JSON encoding of a number of constructors. All constructors -- must be from the same type. consToJSON :: Options -- ^ Encoding options. -> [Con] -- ^ Constructors for which to generate JSON generating code. -> Q Exp consToJSON _ [] = error $ "Data.Aeson.TH.consToJSON: " ++ "Not a single constructor given!" -- A single constructor is directly encoded. The constructor itself may be -- forgotten. consToJSON opts [con] = do value <- newName "value" lam1E (varP value) $ caseE (varE value) [encodeArgs opts False con] consToJSON opts cons = do value <- newName "value" lam1E (varP value) $ caseE (varE value) matches where matches | allNullaryToStringTag opts && all isNullary cons = [ match (conP conName []) (normalB $ conStr opts conName) [] | con <- cons , let conName = getConName con ] | otherwise = [encodeArgs opts True con | con <- cons] conStr :: Options -> Name -> Q Exp conStr opts = appE [|String|] . conTxt opts conTxt :: Options -> Name -> Q Exp conTxt opts = appE [|T.pack|] . conStringE opts conStringE :: Options -> Name -> Q Exp conStringE opts = stringE . constructorTagModifier opts . nameBase -- | If constructor is nullary. isNullary :: Con -> Bool isNullary (NormalC _ []) = True isNullary _ = False encodeSum :: Options -> Bool -> Name -> Q Exp -> Q Exp encodeSum opts multiCons conName exp | multiCons = case sumEncoding opts of TwoElemArray -> [|Array|] `appE` ([|V.fromList|] `appE` listE [conStr opts conName, exp]) TaggedObject{tagFieldName, contentsFieldName} -> [|object|] `appE` listE [ infixApp [|T.pack tagFieldName|] [|(.=)|] (conStr opts conName) , infixApp [|T.pack contentsFieldName|] [|(.=)|] exp ] ObjectWithSingleField -> [|object|] `appE` listE [ infixApp (conTxt opts conName) [|(.=)|] exp ] | otherwise = exp -- | Generates code to generate the JSON encoding of a single constructor. encodeArgs :: Options -> Bool -> Con -> Q Match -- Nullary constructors. Generates code that explicitly matches against the -- constructor even though it doesn't contain data. This is useful to prevent -- type errors. encodeArgs opts multiCons (NormalC conName []) = match (conP conName []) (normalB (encodeSum opts multiCons conName [e|toJSON ([] :: [()])|])) [] -- Polyadic constructors with special case for unary constructors. encodeArgs opts multiCons (NormalC conName ts) = do let len = length ts args <- mapM newName ["arg" ++ show n | n <- [1..len]] js <- case [[|toJSON|] `appE` varE arg | arg <- args] of -- Single argument is directly converted. [e] -> return e -- Multiple arguments are converted to a JSON array. es -> do mv <- newName "mv" let newMV = bindS (varP mv) ([|VM.unsafeNew|] `appE` litE (integerL $ fromIntegral len)) stmts = [ noBindS $ [|VM.unsafeWrite|] `appE` (varE mv) `appE` litE (integerL ix) `appE` e | (ix, e) <- zip [(0::Integer)..] es ] ret = noBindS $ [|return|] `appE` varE mv return $ [|Array|] `appE` (varE 'V.create `appE` doE (newMV:stmts++[ret])) match (conP conName $ map varP args) (normalB $ encodeSum opts multiCons conName js) [] -- Records. encodeArgs opts multiCons (RecC conName ts) = do args <- mapM newName ["arg" ++ show n | (_, n) <- zip ts [1 :: Integer ..]] let exp = [|object|] `appE` pairs pairs | omitNothingFields opts = infixApp maybeFields [|(++)|] restFields | otherwise = listE $ map toPair argCons argCons = zip args ts maybeFields = [|catMaybes|] `appE` listE (map maybeToPair maybes) restFields = listE $ map toPair rest (maybes, rest) = partition isMaybe argCons isMaybe (_, (_, _, AppT (ConT t) _)) = t == ''Maybe isMaybe _ = False maybeToPair (arg, (field, _, _)) = infixApp (infixE (Just $ toFieldName field) [|(.=)|] Nothing) [|(<$>)|] (varE arg) toPair (arg, (field, _, _)) = infixApp (toFieldName field) [|(.=)|] (varE arg) toFieldName field = [|T.pack|] `appE` fieldLabelExp opts field match (conP conName $ map varP args) ( normalB $ if multiCons then case sumEncoding opts of TwoElemArray -> [|toJSON|] `appE` tupE [conStr opts conName, exp] TaggedObject{tagFieldName} -> [|object|] `appE` -- TODO: Maybe throw an error in case -- tagFieldName overwrites a field in pairs. infixApp (infixApp [|T.pack tagFieldName|] [|(.=)|] (conStr opts conName)) [|(:)|] pairs ObjectWithSingleField -> [|object|] `appE` listE [ infixApp (conTxt opts conName) [|(.=)|] exp ] else exp ) [] -- Infix constructors. encodeArgs opts multiCons (InfixC _ conName _) = do al <- newName "argL" ar <- newName "argR" match (infixP (varP al) conName (varP ar)) ( normalB $ encodeSum opts multiCons conName $ [|toJSON|] `appE` listE [ [|toJSON|] `appE` varE a | a <- [al,ar] ] ) [] -- Existentially quantified constructors. encodeArgs opts multiCons (ForallC _ _ con) = encodeArgs opts multiCons con -------------------------------------------------------------------------------- -- FromJSON -------------------------------------------------------------------------------- -- | Generates a 'FromJSON' instance declaration for the given data type. deriveFromJSON :: Options -- ^ Encoding options. -> Name -- ^ Name of the type for which to generate a 'FromJSON' instance -- declaration. -> Q [Dec] deriveFromJSON opts name = withType name $ \tvbs cons -> fmap (:[]) $ fromCons tvbs cons where fromCons :: [TyVarBndr] -> [Con] -> Q Dec fromCons tvbs cons = instanceD (applyCon ''FromJSON typeNames) (classType `appT` instanceType) [ funD 'parseJSON [ clause [] (normalB $ consFromJSON name opts cons) [] ] ] where classType = conT ''FromJSON typeNames = map tvbName tvbs instanceType = foldl' appT (conT name) $ map varT typeNames -- | Generates a lambda expression which parses the JSON encoding of the given -- data type. mkParseJSON :: Options -- ^ Encoding options. -> Name -- ^ Name of the encoded type. -> Q Exp mkParseJSON opts name = withType name (\_ cons -> consFromJSON name opts cons) -- | Helper function used by both 'deriveFromJSON' and 'mkParseJSON'. Generates -- code to parse the JSON encoding of a number of constructors. All constructors -- must be from the same type. consFromJSON :: Name -- ^ Name of the type to which the constructors belong. -> Options -- ^ Encoding options -> [Con] -- ^ Constructors for which to generate JSON parsing code. -> Q Exp consFromJSON _ _ [] = error $ "Data.Aeson.TH.consFromJSON: " ++ "Not a single constructor given!" consFromJSON tName opts [con] = do value <- newName "value" lam1E (varP value) (parseArgs tName opts con (Right value)) consFromJSON tName opts cons = do value <- newName "value" lam1E (varP value) $ caseE (varE value) $ if allNullaryToStringTag opts && all isNullary cons then allNullaryMatches else mixedMatches where allNullaryMatches = [ do txt <- newName "txt" match (conP 'String [varP txt]) (guardedB $ [ liftM2 (,) (normalG $ infixApp (varE txt) [|(==)|] ([|T.pack|] `appE` conStringE opts conName) ) ([|pure|] `appE` conE conName) | con <- cons , let conName = getConName con ] ++ [ liftM2 (,) (normalG [|otherwise|]) ( [|noMatchFail|] `appE` (litE $ stringL $ show tName) `appE` ([|T.unpack|] `appE` varE txt) ) ] ) [] , do other <- newName "other" match (varP other) (normalB $ [|noStringFail|] `appE` (litE $ stringL $ show tName) `appE` ([|valueConName|] `appE` varE other) ) [] ] mixedMatches = case sumEncoding opts of TaggedObject {tagFieldName, contentsFieldName} -> parseObject $ parseTaggedObject tagFieldName contentsFieldName ObjectWithSingleField -> parseObject $ parseObjectWithSingleField TwoElemArray -> [ do arr <- newName "array" match (conP 'Array [varP arr]) (guardedB $ [ liftM2 (,) (normalG $ infixApp ([|V.length|] `appE` varE arr) [|(==)|] (litE $ integerL 2)) (parse2ElemArray arr) , liftM2 (,) (normalG [|otherwise|]) (([|not2ElemArray|] `appE` (litE $ stringL $ show tName) `appE` ([|V.length|] `appE` varE arr))) ] ) [] , do other <- newName "other" match (varP other) ( normalB $ [|noArrayFail|] `appE` (litE $ stringL $ show tName) `appE` ([|valueConName|] `appE` varE other) ) [] ] parseObject f = [ do obj <- newName "obj" match (conP 'Object [varP obj]) (normalB $ f obj) [] , do other <- newName "other" match (varP other) ( normalB $ [|noObjectFail|] `appE` (litE $ stringL $ show tName) `appE` ([|valueConName|] `appE` varE other) ) [] ] parseTaggedObject typFieldName valFieldName obj = do conKey <- newName "conKey" doE [ bindS (varP conKey) (infixApp (varE obj) [|(.:)|] ([|T.pack|] `appE` stringE typFieldName)) , noBindS $ parseContents conKey (Left (valFieldName, obj)) 'conNotFoundFailTaggedObject ] parse2ElemArray arr = do conKey <- newName "conKey" conVal <- newName "conVal" let letIx n ix = valD (varP n) (normalB ([|V.unsafeIndex|] `appE` varE arr `appE` litE (integerL ix))) [] letE [ letIx conKey 0 , letIx conVal 1 ] (caseE (varE conKey) [ do txt <- newName "txt" match (conP 'String [varP txt]) (normalB $ parseContents txt (Right conVal) 'conNotFoundFail2ElemArray ) [] , do other <- newName "other" match (varP other) ( normalB $ [|firstElemNoStringFail|] `appE` (litE $ stringL $ show tName) `appE` ([|valueConName|] `appE` varE other) ) [] ] ) parseObjectWithSingleField obj = do conKey <- newName "conKey" conVal <- newName "conVal" caseE ([e|H.toList|] `appE` varE obj) [ match (listP [tupP [varP conKey, varP conVal]]) (normalB $ parseContents conKey (Right conVal) 'conNotFoundFailObjectSingleField) [] , do other <- newName "other" match (varP other) (normalB $ [|wrongPairCountFail|] `appE` (litE $ stringL $ show tName) `appE` ([|show . length|] `appE` varE other) ) [] ] parseContents conKey contents errorFun = caseE (varE conKey) [ match wildP ( guardedB $ [ do g <- normalG $ infixApp (varE conKey) [|(==)|] ([|T.pack|] `appE` conNameExp opts con) e <- parseArgs tName opts con contents return (g, e) | con <- cons ] ++ [ liftM2 (,) (normalG [e|otherwise|]) ( varE errorFun `appE` (litE $ stringL $ show tName) `appE` listE (map ( litE . stringL . constructorTagModifier opts . nameBase . getConName ) cons ) `appE` ([|T.unpack|] `appE` varE conKey) ) ] ) [] ] parseNullaryMatches :: Name -> Name -> [Q Match] parseNullaryMatches tName conName = [ do arr <- newName "arr" match (conP 'Array [varP arr]) (guardedB $ [ liftM2 (,) (normalG $ [|V.null|] `appE` varE arr) ([|pure|] `appE` conE conName) , liftM2 (,) (normalG [|otherwise|]) (parseTypeMismatch tName conName (litE $ stringL "an empty Array") (infixApp (litE $ stringL $ "Array of length ") [|(++)|] ([|show . V.length|] `appE` varE arr) ) ) ] ) [] , matchFailed tName conName "Array" ] parseUnaryMatches :: Name -> [Q Match] parseUnaryMatches conName = [ do arg <- newName "arg" match (varP arg) ( normalB $ infixApp (conE conName) [|(<$>)|] ([|parseJSON|] `appE` varE arg) ) [] ] parseRecord :: Options -> Name -> Name -> [VarStrictType] -> Name -> ExpQ parseRecord opts tName conName ts obj = foldl' (\a b -> infixApp a [|(<*>)|] b) (infixApp (conE conName) [|(<$>)|] x) xs where x:xs = [ [|lookupField|] `appE` (litE $ stringL $ show tName) `appE` (litE $ stringL $ constructorTagModifier opts $ nameBase conName) `appE` (varE obj) `appE` ( [|T.pack|] `appE` fieldLabelExp opts field ) | (field, _, _) <- ts ] getValField :: Name -> String -> [MatchQ] -> Q Exp getValField obj valFieldName matches = do val <- newName "val" doE [ bindS (varP val) $ infixApp (varE obj) [|(.:)|] ([|T.pack|] `appE` (litE $ stringL valFieldName)) , noBindS $ caseE (varE val) matches ] -- | Generates code to parse the JSON encoding of a single constructor. parseArgs :: Name -- ^ Name of the type to which the constructor belongs. -> Options -- ^ Encoding options. -> Con -- ^ Constructor for which to generate JSON parsing code. -> Either (String, Name) Name -- ^ Left (valFieldName, objName) or -- Right valName -> Q Exp -- Nullary constructors. parseArgs tName _ (NormalC conName []) (Left (valFieldName, obj)) = getValField obj valFieldName $ parseNullaryMatches tName conName parseArgs tName _ (NormalC conName []) (Right valName) = caseE (varE valName) $ parseNullaryMatches tName conName -- Unary constructors. parseArgs _ _ (NormalC conName [_]) (Left (valFieldName, obj)) = getValField obj valFieldName $ parseUnaryMatches conName parseArgs _ _ (NormalC conName [_]) (Right valName) = caseE (varE valName) $ parseUnaryMatches conName -- Polyadic constructors. parseArgs tName _ (NormalC conName ts) (Left (valFieldName, obj)) = getValField obj valFieldName $ parseProduct tName conName $ genericLength ts parseArgs tName _ (NormalC conName ts) (Right valName) = caseE (varE valName) $ parseProduct tName conName $ genericLength ts -- Records. parseArgs tName opts (RecC conName ts) (Left (_, obj)) = parseRecord opts tName conName ts obj parseArgs tName opts (RecC conName ts) (Right valName) = do obj <- newName "recObj" caseE (varE valName) [ match (conP 'Object [varP obj]) (normalB $ parseRecord opts tName conName ts obj) [] , matchFailed tName conName "Object" ] -- Infix constructors. Apart from syntax these are the same as -- polyadic constructors. parseArgs tName _ (InfixC _ conName _) (Left (valFieldName, obj)) = getValField obj valFieldName $ parseProduct tName conName 2 parseArgs tName _ (InfixC _ conName _) (Right valName) = caseE (varE valName) $ parseProduct tName conName 2 -- Existentially quantified constructors. We ignore the quantifiers -- and proceed with the contained constructor. parseArgs tName opts (ForallC _ _ con) contents = parseArgs tName opts con contents -- | Generates code to parse the JSON encoding of an n-ary -- constructor. parseProduct :: Name -- ^ Name of the type to which the constructor belongs. -> Name -- ^ 'Con'structor name. -> Integer -- ^ 'Con'structor arity. -> [Q Match] parseProduct tName conName numArgs = [ do arr <- newName "arr" -- List of: "parseJSON (arr `V.unsafeIndex` <IX>)" let x:xs = [ [|parseJSON|] `appE` infixApp (varE arr) [|V.unsafeIndex|] (litE $ integerL ix) | ix <- [0 .. numArgs - 1] ] match (conP 'Array [varP arr]) (normalB $ condE ( infixApp ([|V.length|] `appE` varE arr) [|(==)|] (litE $ integerL numArgs) ) ( foldl' (\a b -> infixApp a [|(<*>)|] b) (infixApp (conE conName) [|(<$>)|] x) xs ) ( parseTypeMismatch tName conName (litE $ stringL $ "Array of length " ++ show numArgs) ( infixApp (litE $ stringL $ "Array of length ") [|(++)|] ([|show . V.length|] `appE` varE arr) ) ) ) [] , matchFailed tName conName "Array" ] -------------------------------------------------------------------------------- -- Parsing errors -------------------------------------------------------------------------------- matchFailed :: Name -> Name -> String -> MatchQ matchFailed tName conName expected = do other <- newName "other" match (varP other) ( normalB $ parseTypeMismatch tName conName (litE $ stringL expected) ([|valueConName|] `appE` varE other) ) [] parseTypeMismatch :: Name -> Name -> ExpQ -> ExpQ -> ExpQ parseTypeMismatch tName conName expected actual = foldl appE [|parseTypeMismatch'|] [ litE $ stringL $ nameBase conName , litE $ stringL $ show tName , expected , actual ] class (FromJSON a) => LookupField a where lookupField :: String -> String -> Object -> T.Text -> Parser a instance (FromJSON a) => LookupField a where lookupField tName rec obj key = case H.lookup key obj of Nothing -> unknownFieldFail tName rec (T.unpack key) Just v -> parseJSON v instance (FromJSON a) => LookupField (Maybe a) where lookupField _ _ = (.:?) unknownFieldFail :: String -> String -> String -> Parser fail unknownFieldFail tName rec key = fail $ printf "When parsing the record %s of type %s the key %s was not present." rec tName key noArrayFail :: String -> String -> Parser fail noArrayFail t o = fail $ printf "When parsing %s expected Array but got %s." t o noObjectFail :: String -> String -> Parser fail noObjectFail t o = fail $ printf "When parsing %s expected Object but got %s." t o firstElemNoStringFail :: String -> String -> Parser fail firstElemNoStringFail t o = fail $ printf "When parsing %s expected an Array of 2 elements where the first element is a String but got %s at the first element." t o wrongPairCountFail :: String -> String -> Parser fail wrongPairCountFail t n = fail $ printf "When parsing %s expected an Object with a single tag/contents pair but got %s pairs." t n noStringFail :: String -> String -> Parser fail noStringFail t o = fail $ printf "When parsing %s expected String but got %s." t o noMatchFail :: String -> String -> Parser fail noMatchFail t o = fail $ printf "When parsing %s expected a String with the tag of a constructor but got %s." t o not2ElemArray :: String -> Int -> Parser fail not2ElemArray t i = fail $ printf "When parsing %s expected an Array of 2 elements but got %i elements" t i conNotFoundFail2ElemArray :: String -> [String] -> String -> Parser fail conNotFoundFail2ElemArray t cs o = fail $ printf "When parsing %s expected a 2-element Array with a tag and contents element where the tag is one of [%s], but got %s." t (intercalate ", " cs) o conNotFoundFailObjectSingleField :: String -> [String] -> String -> Parser fail conNotFoundFailObjectSingleField t cs o = fail $ printf "When parsing %s expected an Object with a single tag/contents pair where the tag is one of [%s], but got %s." t (intercalate ", " cs) o conNotFoundFailTaggedObject :: String -> [String] -> String -> Parser fail conNotFoundFailTaggedObject t cs o = fail $ printf "When parsing %s expected an Object with a tag field where the value is one of [%s], but got %s." t (intercalate ", " cs) o parseTypeMismatch' :: String -> String -> String -> String -> Parser fail parseTypeMismatch' tName conName expected actual = fail $ printf "When parsing the constructor %s of type %s expected %s but got %s." conName tName expected actual -------------------------------------------------------------------------------- -- Utility functions -------------------------------------------------------------------------------- -- | Boilerplate for top level splices. -- -- The given 'Name' must be from a type constructor. Furthermore, the -- type constructor must be either a data type or a newtype. Any other -- value will result in an exception. withType :: Name -> ([TyVarBndr] -> [Con] -> Q a) -- ^ Function that generates the actual code. Will be applied -- to the type variable binders and constructors extracted -- from the given 'Name'. -> Q a -- ^ Resulting value in the 'Q'uasi monad. withType name f = do info <- reify name case info of TyConI dec -> case dec of DataD _ _ tvbs cons _ -> f tvbs cons NewtypeD _ _ tvbs con _ -> f tvbs [con] other -> error $ "Data.Aeson.TH.withType: Unsupported type: " ++ show other _ -> error "Data.Aeson.TH.withType: I need the name of a type." -- | Extracts the name from a constructor. getConName :: Con -> Name getConName (NormalC name _) = name getConName (RecC name _) = name getConName (InfixC _ name _) = name getConName (ForallC _ _ con) = getConName con -- | Extracts the name from a type variable binder. tvbName :: TyVarBndr -> Name tvbName (PlainTV name ) = name tvbName (KindedTV name _) = name -- | Makes a string literal expression from a constructor's name. conNameExp :: Options -> Con -> Q Exp conNameExp opts = litE . stringL . constructorTagModifier opts . nameBase . getConName -- | Creates a string literal expression from a record field label. fieldLabelExp :: Options -- ^ Encoding options -> Name -> Q Exp fieldLabelExp opts = litE . stringL . fieldLabelModifier opts . nameBase -- | The name of the outermost 'Value' constructor. valueConName :: Value -> String valueConName (Object _) = "Object" valueConName (Array _) = "Array" valueConName (String _) = "String" valueConName (Number _) = "Number" valueConName (Bool _) = "Boolean" valueConName Null = "Null" applyCon :: Name -> [Name] -> Q [Pred] applyCon con typeNames = return (map apply typeNames) where apply t = #if MIN_VERSION_template_haskell(2,10,0) AppT (ConT con) (VarT t) #else ClassP con [VarT t] #endif
plaprade/aeson
Data/Aeson/TH.hs
bsd-3-clause
33,874
0
24
13,013
7,561
4,077
3,484
554
6
module Vimus.Command.Completion ( completeCommand , parseCommand , completeOptions , completeOptions_ ) where import Data.List import Data.Char import Vimus.Util import Vimus.Command.Type completeCommand :: [Command] -> CompletionFunction completeCommand commands input_ = (pre ++) `fmap` case parseCommand_ input of (c, "") -> completeCommandName c (c, args) -> -- the list of matches is reversed, so that completion is done for the last -- command in the list case reverse $ filter ((== c) . commandName) commands of x:_ -> (c ++) `fmap` completeArguments (commandArguments x) args [] -> Left [] where (pre, input) = span isSpace input_ -- a completion function for command names completeCommandName :: CompletionFunction completeCommandName = completeOptions (map commandName commands) completeArguments :: [ArgumentInfo] -> CompletionFunction completeArguments = go where go specs_ input_ = (pre ++) `fmap` case specs_ of [] -> Left [] spec:specs -> case break isSpace input of (arg, "") -> argumentInfoComplete spec arg (arg, args) -> (arg ++) `fmap` go specs args where (pre, input) = span isSpace input_ -- | Create a completion function from a list of possibilities. completeOptions :: [String] -> CompletionFunction completeOptions = completeOptions_ " " -- | Like `completeOptions`, but terminates completion with a given string -- instead of " ". completeOptions_ :: String -> [String] -> CompletionFunction completeOptions_ terminator options input = case filter (isPrefixOf input) options of [x] -> Right (x ++ terminator) xs -> case commonPrefix $ map (drop $ length input) xs of "" -> Left xs ys -> Right (input ++ ys) -- | Split given input into a command name and a rest (the arguments). -- -- Whitespace in front of the command name and the arguments is striped. parseCommand :: String -> (String, String) parseCommand input = (name, dropWhile isSpace args) where (name, args) = parseCommand_ (dropWhile isSpace input) -- | Like `parseCommand`, but assume that input starts with a non-whitespace -- character, and retain whitespace in front of the arguments. parseCommand_ :: String -> (String, String) parseCommand_ input = (name, args) where (name, args) = case input of '!':xs -> ("!", xs) xs -> break isSpace xs
haasn/vimus
src/Vimus/Command/Completion.hs
mit
2,422
0
15
531
634
349
285
43
3
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} module Axiomatize where import Language.Haskell.TH import Language.Haskell.TH.Quote import Debug.Trace import Control.Applicative import Data.List ((\\)) import Data.Maybe (fromMaybe) data Proof = Proof axiomatize :: Q [Dec] -> Q [Dec] axiomatize q = do d <- q let vts = [(x, t) | FunD x _ <- d, SigD y t <- d, x == y ] ds <- mapM (axiomatizeOne vts) d return $ trace (show d) $ concat ds axiomatizeOne :: [(Name, Type)] -> Dec -> Q [Dec] axiomatizeOne env f@(FunD name cs) = do axioms <- makeAxioms (lookup name env) name cs return $ f:axioms axiomatizeOne _ (SigD _ _) = return [] axiomatizeOne _ d = error $ "axiomatizeOne: Cannot axiomatize" ++ show d makeAxioms :: Maybe Type -> Name -> [Clause] -> Q [Dec] makeAxioms t f cs = concat <$> mapM go cs where go :: Clause -> Q [Dec] go (Clause ps (NormalB (CaseE e ms)) []) = mapM (makeAxiomMatch f ps e) ms go (Clause ps (NormalB _) []) = makeAxiomPattern t f ps go d = error $ "makeAxioms: Cannot axiomatize\n" ++ show d makeAxiomPattern :: Maybe Type -> Name -> [Pat] -> Q [Dec] makeAxiomPattern t g ps = do ifs <- mapM reify (fst <$> ds) ff <- makeFun f xs <$> axiom_body ft <- makeSigT t f ps return $ [ff] ++ ft where f = mkName $ makeNamePattern g (fst <$> ds) ds = [(n, dps) | ConP n dps <- ps] xs = [x | VarP x <- (ps ++ concat (snd <$> ds))] makeSigT Nothing _ _ = return [] makeSigT (Just t) f ps = do r <- [t|Proof|] ifs <- mapM reify (fst . snd <$> ds) let ts2 = concat $ zipWith makePTys ds ifs return $ [SigD f $ mkUnivArrow (as, ts1 ++ ts2, r)] where (as, ts, _) = bkUnivFun t ts1 = [t | (t, VarP _) <- zip ts ps] ds = [(t, (n, dps)) | (t, ConP n dps) <- zip ts ps] makePTys :: (Type, (Name, [Pat])) -> Info -> [Type] makePTys (tr, (n, dps)) (DataConI m t _ _) | n == m = (applySub θ <$> [t | (t, VarP _) <- zip ts dps]) where (as, ts, r) = bkUnivFun t θ = unify r tr makePTys _ _ = error "makePTys: on invalid arguments" unify (VarT n) t = [(n,t)] unify t (VarT n) = [(n,t)] unify (AppT t1 t2) (AppT t1' t2') = unify t1 t1' ++ unify t2 t2' unify (ForallT _ _ t1) t2 = unify t1 t2 unify t1 (ForallT _ _ t2) = unify t1 t2 unify _ _ = [] applySub :: [(Name, Type)] -> Type -> Type applySub θ t@(VarT v) = fromMaybe t (lookup v θ) applySub θ (AppT t1 t2) = AppT (applySub θ t1) (applySub θ t2) applySub θ (ForallT _ _ _) = error "applySub: TODO" applySub θ t = t bkUnivFun = go [] [] where go as xs (ForallT vs _ t) = go (as ++ vs) xs t go as xs (AppT (AppT ArrowT tx) t) = go as (tx:xs) t go as xs t = (as, reverse xs, t) mkUnivArrow (as, ts, r) = ForallT as [] $ mkArrow ts r where mkArrow [] r = r mkArrow (t:ts) r = AppT (AppT ArrowT t) $ mkArrow ts r makeAxiomMatch :: Name -> [Pat] -> Exp -> Match -> Q Dec makeAxiomMatch g ps (VarE x) (Match (ConP dc dps) bd decs) = makeFun f xs <$> axiom_body where f = mkName $ makeName g x dc xs = [p | VarP p <- ps ++ dps] \\ [x] makeFun :: Name -> [Name] -> Exp -> Dec makeFun f xs bd = FunD f [Clause (VarP <$> xs) (NormalB bd) []] axiom_body :: Q Exp axiom_body = [|Proof|] sep = "_" mkSep :: [String] -> String mkSep [] = [] mkSep [x] = x mkSep (x:xs) = x ++ sep ++ mkSep xs eq = "is" makeName fname x dc = mkSep ["axiom", nameBase fname, nameBase x, eq, nameBase dc] makeNamePattern fname dcs = mkSep $ ["axiom", nameBase fname] ++ (nameBase <$> dcs)
ssaavedra/liquidhaskell
tests/equationalproofs/neg/Axiomatize.hs
bsd-3-clause
3,612
0
14
979
1,864
960
904
90
3
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} module Language.Haskell.Refact.Refactoring.Simple(removeBracket) where import qualified Data.Generics as SYB import qualified GHC as GHC import qualified GhcMod as GM (Options(..)) import Language.Haskell.Refact.API -- To be moved into HaRe API import Language.Haskell.GHC.ExactPrint.Transform import Language.Haskell.GHC.ExactPrint.Types import Data.Maybe import System.Directory -- import Debug.Trace -- --------------------------------------------------------------------- -- | Convert an if expression to a case expression removeBracket :: RefactSettings -> GM.Options -> FilePath -> SimpPos -> SimpPos -> IO [FilePath] removeBracket settings opts fileName beginPos endPos = do absFileName <- canonicalizePath fileName let applied = (:[]) . fst <$> applyRefac (removeBracketTransform absFileName beginPos endPos) (RSFile absFileName) runRefacSession settings opts applied type HsExpr a = GHC.Located (GHC.HsExpr a) pattern HsPar l s = GHC.L l (GHC.HsPar s) removeBracketTransform :: FilePath -> SimpPos -> SimpPos -> RefactGhc () removeBracketTransform fileName beginPos endPos = do parseSourceFileGhc fileName parsed <- getRefactParsed let expr :: GHC.Located (GHC.HsExpr GHC.RdrName) expr = fromJust $ locToExp beginPos endPos parsed removePar :: HsExpr GHC.RdrName -> RefactGhc (HsExpr GHC.RdrName) removePar e@(HsPar _ s) | sameOccurrence e expr = do startAnns <- liftT $ getAnnsT let oldkey = mkAnnKey e newkey = mkAnnKey s newanns = fromMaybe startAnns $ replace oldkey newkey startAnns setRefactAnns newanns return s removePar e = return e p2 <- SYB.everywhereM (SYB.mkM removePar) parsed putRefactParsed p2 emptyAnns logm $ "logm: after refactor\n" ++ showGhc p2 -- EOF
RefactoringTools/HaRe
src/Language/Haskell/Refact/Refactoring/Simple.hs
bsd-3-clause
2,008
0
17
486
503
259
244
39
2
{-# LANGUAGE GADTs #-} module T15009 where -- T2 is an ordinary H98 data type, -- and f2 should typecheck with no problem data T2 a where MkT2 :: a -> T2 a f2 (MkT2 x) = not x -- T1 is a GADT, but the equality is really just a 'let' -- so f1 should also typecheck no problem data T1 a where MkT1 :: b ~ a => b -> T1 a f1 (MkT1 x) = not x
sdiehl/ghc
testsuite/tests/gadt/T15009.hs
bsd-3-clause
350
0
8
92
86
48
38
8
1
module File where import NemoPath import System.Directory import System.FilePath.Posix import Util data File = File { path :: NemoPath , contents :: String } deriving (Eq, Show, Ord) makeFile :: NemoPath -> String -> File makeFile path contents = File path contents load :: NemoPath -> IO File load path = fmap (makeFile path) (readFile $ toFilePath path) loadAll :: [NemoPath] -> IO [File] loadAll paths = sequence $ fmap load paths dump :: File -> IO () dump file = ifM (doesFileExist filePath) (return ()) $ writeFile filePath (contents file) where filePath = toFilePath $ path file dumpAll :: [File] -> IO () dumpAll files = mapM_ dump files identifier :: File -> String identifier file = filePart file extension :: File -> String extension file = takeExtension $ filePart file filePart :: File -> FilePath filePart file = filepath $ path file replaceFilePart :: FilePath -> File -> File replaceFilePart new file = makeFile newPath (contents file) where oldPath = path file proj = project oldPath sub = subdirectory oldPath newPath = makeNemoPath proj sub new replaceContents :: String -> File -> File replaceContents new file = makeFile (path file) new replaceSubdirectoryPart :: FilePath -> File -> File replaceSubdirectoryPart new file = makeFile newPath (contents file) where oldPath = path file proj = project oldPath filePart = filepath oldPath newPath = makeNemoPath proj new filePart
larioj/nemo
src/File.hs
mit
1,613
0
9
444
507
259
248
51
1
-- | -- Module: Math.NumberTheory.Primes.SieveTests -- Copyright: (c) 2016 Andrew Lelechenko -- Licence: MIT -- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com> -- Stability: Provisional -- -- Tests for Math.NumberTheory.Primes.Sieve -- {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} module Math.NumberTheory.Primes.SieveTests ( testSuite ) where import Prelude hiding (words) import Test.Tasty import Test.Tasty.HUnit import Math.NumberTheory.Primes.Sieve import qualified Math.NumberTheory.Primes.Heap as H import Math.NumberTheory.TestUtils -- | Check that both 'primes' produce the same. primesProperty1 :: Assertion primesProperty1 = do assertEqual "Sieve == Heap" (trim primes) (trim H.primes) where trim = take 100000 -- | Check that both 'sieveFrom' produce the same. sieveFromProperty1 :: AnySign Integer -> Bool sieveFromProperty1 (AnySign lowBound) = trim (sieveFrom lowBound) == trim (H.sieveFrom lowBound) where trim = take 1000 -- | Check that 'primeList' from 'primeSieve' matches truncated 'primes'. primeSieveProperty1 :: AnySign Integer -> Bool primeSieveProperty1 (AnySign highBound) = primeList (primeSieve highBound) == takeWhile (<= (highBound `max` 7)) primes -- | Check that 'primeList' from 'psieveList' matches 'primes'. psieveListProperty1 :: Assertion psieveListProperty1 = do assertEqual "primes == primeList . psieveList" (trim primes) (trim $ concatMap primeList psieveList) where trim = take 100000 -- | Check that 'primeList' from 'psieveFrom' matches 'sieveFrom'. psieveFromProperty1 :: AnySign Integer -> Bool psieveFromProperty1 (AnySign lowBound) = trim (sieveFrom lowBound) == trim (filter (>= lowBound) (concatMap primeList $ psieveFrom lowBound)) where trim = take 1000 testSuite :: TestTree testSuite = testGroup "Sieve" [ testCase "primes" primesProperty1 , testSmallAndQuick "sieveFrom" sieveFromProperty1 , testSmallAndQuick "primeSieve" primeSieveProperty1 , testCase "psieveList" psieveListProperty1 , testSmallAndQuick "psieveFrom" psieveFromProperty1 ]
cfredric/arithmoi
test-suite/Math/NumberTheory/Primes/SieveTests.hs
mit
2,174
0
11
351
414
227
187
37
1
-- Simple Conway's Game of Life implementation module GameOfHaskell where import Data.List type Cell = (Int, Int) type LivingCell = Cell -- We're tracking only alive cells. type Board = [LivingCell] nextState :: Board -> Board nextState board = -- Newborn: a cell not living before having exactly 3 living neighbours now. let newborn ((x,y), neighbours) = (x,y) `notElem` board && neighbours == 3 -- Survivor: present on board before, has 3 to 4 living neighbours now. survivor ((x,y), neighbours) = (x,y) `elem` board && (neighbours `elem` [2,3]) -- For every cell that has living neighbours, if the number of living -- neighbours suffices to be a living cell - become a living cell. in [ c | (c,n) <- livingNeighbours board, newborn (c,n) || survivor (c,n)] livingNeighbours :: Board -> [(Cell, Int)] livingNeighbours board = let deltas = [ (-1,-1),(0,-1),(1,-1), (-1, 0), (1, 0), (-1, 1),(0, 1),(1, 1) ] -- List of cells that have a living neighbour. Contains duplicates. allNeighbours = concatMap (\(x,y) -> map (\(a,b) -> (x+a,y+b)) deltas ) board -- Aggregated list of cells that have living neighbour(s) in format: -- (coordinates, neighbourCount). in (map (\xs@(x:_) -> (x, length xs)) . group . sort) allNeighbours -- I/O handling, below. main = play [(0,0),(0,1),(0,2),(1,2),(2,1)] play :: Board -> IO () play board = do display board putStrLn "Press return to continue..." getLine play $ nextState board display :: Board -> IO () display board = do mapM_ (\x -> do mapM_ (\y -> putChar $ if (x,y) `elem` board then 'x' else ' ') [-10 .. 10] putChar '\n' ) [-10 .. 2]
nbartlomiej/gameofhaskell
GameOfHaskell.hs
mit
1,686
0
18
374
628
365
263
30
2
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Text.XML.Mapping.NSMap -- Copyright : (c) Joseph Abrahamson 2013 -- License : MIT -- . -- Maintainer : me@jspha.com -- Stability : experimental -- Portability : non-portable -- . -- Prefix resolution mapping. module Text.XML.Mapping.NSMap ( -- * Core data type NSMap (..), -- * Name resolution resolve, -- * Construction and modification defaultNSMap, fromAttrs, undeclareNS ) where import qualified Data.ByteString as S import qualified Data.HashMap.Strict as Map import Data.List (foldl') import Data.Monoid import qualified Data.Text as T import Text.XML.Mapping.Schema.Namespace -- | An 'NSMap' contains all local namespace resolution information. data NSMap = NSMap { defaultNS :: !Namespace -- ^ The default namespace for un-tagged qualified names -- which get resolved to a default (i.e. not attributes -- which are maddeningly element-specific in their -- behavior). , nsMap :: !(Map.HashMap Prefix Namespace) } deriving ( Show, Eq ) -- | 'mappend' combines new 'NSMap' information with the \"rightmost\" -- 'NSMap' winning. This combination is not guaranteed to be a true -- 'Monoid' except under observation of 'resolve'. Namespace -- undeclaration is performed by forcing a particular 'Prefix' to map -- to 'Free'. These \"tombstone\" values may or may not be removed -- from the resulting map. instance Monoid NSMap where mempty = NSMap Free mempty mappend (NSMap _ map1) (NSMap def map2) = NSMap def $ Map.unionWith (\_ v2 -> v2) map1 map2 -- | Convert an attribute set to a fresh 'NSMap' representing the -- *new* information garnered from this particular attribute set. -- -- This is slightly looser than the actual XML spec demands---it -- merges multiple declarations of an @xmlns@ attribute \"to the -- right\". fromAttrs :: [(T.Text, S.ByteString)] -> NSMap fromAttrs = foldl' build mempty where build nsmap@(NSMap def hmap) (attr, val) = case prefix attr of Left name | name /= "xmlns" -> nsmap | otherwise -> NSMap (Namespace val) hmap Right (xmlns, pf) | xmlns /= "xmlns" -> nsmap -- what? | otherwise -> NSMap def $ Map.insert (Prefix $ getLocalName pf) (Namespace val) hmap -- | Whenever we encounter either an @xmlns=\"\"@ or (as of XML -- Namespaces 1.1) @xmlns:tag=\"\"@ we \"undeclare\" that namespace, -- i.e. allow it to be resolved upward. 'Free' undeclares the default -- namespace while 'Namespace' undeclares a particular one. -- -- @ -- prop> \pf nsmap tn -> -- realizeNS (undeclareNS pf map) (Right (pf, tn)) == Just (Free, tn) -- @ undeclareNS :: Maybe Prefix -> NSMap -> NSMap undeclareNS Nothing (NSMap _ hm) = NSMap Free hm undeclareNS (Just pf) (NSMap d hm) = NSMap d $ Map.delete pf hm -- | Takes the output of 'prefix' to a 'NamespaceName' or fails if it -- cannot. See 'resolve'. -- -- If there is no default namespace declaration in scope, the -- namespace name has no value. The namespace name for an unprefixed -- attribute name always has no value. In all cases, the local name is -- local part (which is of course the same as the unprefixed name -- itself). realizeNS :: NSMap -> Either LocalName (Prefix, LocalName) -> Either [Prefix] QName realizeNS nsmap (Left local) = Right $ QName (defaultNS nsmap) local realizeNS nsmap (Right (pf, tn)) = case Map.lookup pf (nsMap nsmap) of Nothing -> Left [pf] Just x -> Right $ QName x tn -- | Resolves a 'Text' fragment within a 'Namespace' context by -- treating it as a qualified name and then trying to resolving the -- namespace prefix in the 'NSMap'. Returns 'Nothing' if the qualified -- name has an unknown prefix. resolve :: NSMap -> T.Text -> Either [Prefix] QName resolve nsmap = realizeNS nsmap . prefix defaultNSMap :: NSMap defaultNSMap = NSMap Free $ Map.fromList [("xmlns", "http://www.w3.org/2000/xmlns/")]
tel/xml-mapping
src/Text/XML/Mapping/NSMap.hs
mit
4,137
0
15
987
695
390
305
49
2
import Data.List.Extra step :: [Int] -> [Int] step inp = flip mod 10 . abs . sum . step' inp <$> [0..l] where l = pred $ length inp step' is n = zipWith f is (ptn n) where f a b = a * b ptn n = drop 1 $ take (l+2) $ cycle $ concatMap r base where base = [0,1,0,-1] r = replicate (succ n) compute :: Int -> [Int] -> String compute n inp = take 8 $ concatMap show $ (!! n) $ iterate step inp parse :: String -> [Int] parse = map read . chunksOf 1 part_1 :: [Int] -> String part_1 = compute 100 main :: IO () main = do -- print $ compute 4 $ parse "12345678" -- print $ compute 100 $ parse "80871224585914546619083218645595" -- print $ compute 100 $ parse "19617804207202209144916044189917" -- print $ compute 100 $ parse "69317163492948606335995924319873" inp <- parse <$> getLine -- 68317988 putStrLn $ part_1 inp -- let t0 = compute 100 -- $ concat $ replicate 10000 $ parse "03036732577212944063491565474664" -- print t0
wizzup/advent_of_code
2019/haskell/exe/Day16.hs
mit
996
0
12
255
329
172
157
19
1
{-# LANGUAGE FlexibleContexts #-} module SecTypes where import Syntax import Control.Monad.Except hiding (join) import Control.Monad.Identity hiding (join) import Control.Monad.Writer hiding (join) type Flow = String type Step = String type SecType a = WriterT [Step] (ExceptT Flow Identity) a runSecTypeCheck :: Expr -> Either Flow (Label, [Step]) runSecTypeCheck = runIdentity . runExceptT . runWriterT . secCheck secCheck :: Expr -> SecType Label secCheck (Var n l) = do tell ["γ ⊦ " ++ n ++ " : " ++ show l] return l secCheck (Num n l) = do tell ["num " ++ show n ++ " " ++ show l] return l secCheck (Op op n1@(Num n _) n2@(Num n' _)) = do n1' <- secCheck n1 n2' <- secCheck n2 tell [show n ++ " " ++ show op ++ " " ++ show n' ++ " : " ++ show (join n1' n2')] return $ join n1' n2' secCheck (Op op n1@(Var n _) n2@(Var n' _)) = do n1' <- secCheck n1 n2' <- secCheck n2 tell [n ++ " " ++ show op ++ " " ++ n' ++ " : " ++ show (join n1' n2')] return $ join n1' n2' secCheck (BoolExpr _ l) = do tell ["bool " ++ show l] return l secCheck (Skip l) = do tell ["skip " ++ show l] return l secCheck (Seq e1 e2) = do tell ["seq"] _ <- secCheck e1 secCheck e2 secCheck (Assign var@(Var n _) val@(Var n' _)) = do var' <- secCheck var val' <- secCheck val if var' `confines` val' then do tell [n ++ " := " ++ n' ++ " : " ++ show (var' `join` val') ++ " cmd"] tell ["assign"] return var' else throwError "" secCheck (IfThenElse b c1 c2) = do b' <- secCheck b case (c1, c2) of (Assign{}, Assign{}) -> do c1' <- secCheck c1 c2' <- secCheck c2 let arms = c1' `meet` c2' in if b' `isSubTypeOf` arms then do tell ["if...then...else : " ++ show (b' `join` arms) ++ " Cmd"] return $ b' `join` arms else throwError $ flowError b' arms (_, _) -> throwError "arms of conditional can only be assignments in this simple language" secCheck err = throwError $ show err -- this should be unreachable flowError :: Label -> Label -> String flowError e1 e2 = "not typeable: implicit flow between " ++ show e1 ++ " and " ++ show e2 isSubTypeOf :: Label -> Label -> Bool l1 `isSubTypeOf` l2 = l1 `eq` l2 confines :: Label -> Label -> Bool confines l1 l2 = l2 `isSubTypeOf` l1
kellino/TypeSystems
volpano/SecTypes.hs
mit
2,456
0
23
739
1,020
508
512
67
4
{-| Module : PPatternSplitBenchmark Description : Short description Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017 License : MIT Maintainer : vialette@gmail.com Stability : experimental Here is a longer description of this module, containing some commentary with @some markup@. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} import Control.Exception import Formatting import Formatting.Clock import System.Clock import System.Console.CmdArgs import System.Random import qualified Data.Algorithm.PPattern.Perm as Perm import qualified Data.Algorithm.PPattern.Perm.Split as Perm.Split import qualified Data.Algorithm.PPattern.Search.ConflictSelection as ConflictSelection import qualified Data.Algorithm.PPattern as PPattern data Options = Options { psize :: Int , qsize :: Int , psplit :: Int , qsplit :: Int , seed :: Int } deriving (Data, Typeable) options :: Options options = Options { psize = def &= help "The pattern permutation size" , qsize = def &= help "The target permutation size" , psplit = def &= help "p is the union of at most psplit increasingss" , qsplit = def &= help "q is the union of at most qsplit increasings" , seed = def &= help "The seed of the random generator" } &= verbosity &= summary "ppattern-split-benchmark v0.1.0.0, (C) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-1017" &= program "ppattern-split-benchmark" doSearch :: Int -> Int -> Int -> Int -> Perm.Perm -> Perm.Perm -> ConflictSelection.Strategy -> IO () doSearch m n pk qk p q conflictSelectionStrategy = do start <- getTime Monotonic embedding <- evaluate (PPattern.searchWithConflictSelectionStrategy p q conflictSelectionStrategy) end <- getTime Monotonic putStr $ show m `mappend` "," `mappend` show n `mappend` "," `mappend` show pk `mappend` "," `mappend` show qk `mappend` ",\"" `mappend` show p `mappend` "\",\"" `mappend` show q `mappend` "\"," `mappend` "\"" `mappend` show embedding `mappend` "\"," `mappend` "\"" `mappend` show conflictSelectionStrategy `mappend` "\"," fprint (timeSpecs % "\n") start end search :: Int -> Int -> Int -> Int -> Perm.Perm -> Perm.Perm -> IO () search m n pk qk p q = do doSearch m n pk qk p q ConflictSelection.LeftmostConflictFirst doSearch m n pk qk p q ConflictSelection.LeftmostHorizontalConflictFirst doSearch m n pk qk p q ConflictSelection.LeftmostVerticalConflictFirst doSearch m n pk qk p q ConflictSelection.RightmostConflictFirst doSearch m n pk qk p q ConflictSelection.RightmostHorizontalConflictFirst doSearch m n pk qk p q ConflictSelection.RightmostVerticalConflictFirst go :: Options -> IO () go opts = search m n pk qk p q where m = psize opts n = qsize opts pk = psplit opts qk = qsplit opts g = mkStdGen (seed opts) (p, g') = Perm.Split.rand m pk g (q, _) = Perm.Split.rand n qk g' main :: IO () main = do opts <- cmdArgs options go opts
vialette/ppattern
src/PPatternSplitBenchmark.hs
mit
3,881
0
25
1,449
811
434
377
72
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE CPP #-} module Migrations.MigrateTest where #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) && MIN_VERSION_base(4,5,0) import GHC.Stack (HasCallStack) #endif import qualified Database.Orville.PostgreSQL as O import Data.Int (Int32, Int64) import qualified Data.List as List import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertBool, assertFailure, testCase) import qualified TestDB as TestDB import Migrations.Entity test_migrate :: TestTree test_migrate = testGroup "Migration tests" [ columnNameMigrationTests "snake_case" , columnNameMigrationTests "camelCase" -- Test postgreSQL reserved words can be used as column names , columnNameMigrationTests "order" ] -- given a column name, test the correct migrations are generated for it. columnNameMigrationTests :: String -> TestTree columnNameMigrationTests columnName = testGroup (columnName ++ " can be used as a column name") [ tableCreationTest columnName , nullableConstraintTest columnName , addAndDropTest columnName , alterColumnTypeTest columnName ] tableCreationTest :: String -> TestTree tableCreationTest columnName = TestDB.withOrvilleRun $ \run -> testCase "Creating Tables is idempotent" $ do run (TestDB.reset []) assertMigrationIdempotent run [O.Table tableDef] where tableDef :: O.TableDefinition (MigrationEntity Int32 MigrationEntityId) (MigrationEntity Int32 ()) MigrationEntityId tableDef = migrationEntityTable (O.int32Field columnName) nullableConstraintTest :: String -> TestTree nullableConstraintTest columnName = TestDB.withOrvilleRun $ \run -> testCase "Adding and Dropping non-null constraints is idempotent" $ do run (TestDB.reset [O.Table nonNullableTableDef]) assertMigrationIdempotent run [O.Table nullableTableDef] assertMigrationIdempotent run [O.Table nonNullableTableDef] where nonNullableTableDef :: O.TableDefinition (MigrationEntity Int32 MigrationEntityId) (MigrationEntity Int32 ()) MigrationEntityId nonNullableTableDef = migrationEntityTable (O.int32Field columnName) nullableTableDef :: O.TableDefinition (MigrationEntity (Maybe Int32) MigrationEntityId) (MigrationEntity (Maybe Int32) ()) MigrationEntityId nullableTableDef = migrationEntityTable (O.nullableField $ O.int32Field columnName) addAndDropTest :: String -> TestTree addAndDropTest columnName = TestDB.withOrvilleRun $ \run -> testCase "Adding and Dropping columns is idempotent" $ do run (TestDB.reset [O.Table tableDef]) assertMigrationIdempotent run [O.Table $ migrationEntityTableWithDroppedColumn columnName] assertMigrationIdempotent run [O.Table tableDef] where tableDef :: O.TableDefinition (MigrationEntity Int32 MigrationEntityId) (MigrationEntity Int32 ()) MigrationEntityId tableDef = migrationEntityTable (O.int32Field columnName) alterColumnTypeTest :: String -> TestTree alterColumnTypeTest columnName = TestDB.withOrvilleRun $ \run -> testCase "Modifying column type is idempotent" $ do run (TestDB.reset [O.Table int32TableDef]) assertMigrationIdempotent run [O.Table int64TableDef] where int32TableDef :: O.TableDefinition (MigrationEntity Int32 MigrationEntityId) (MigrationEntity Int32 ()) MigrationEntityId int32TableDef = migrationEntityTable (O.int32Field columnName) int64TableDef :: O.TableDefinition (MigrationEntity Int64 MigrationEntityId) (MigrationEntity Int64 ()) MigrationEntityId int64TableDef = migrationEntityTable (O.int64Field columnName) #if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0) && MIN_VERSION_base(4,5,0) assertMigrationIdempotent :: HasCallStack => TestDB.OrvilleRunner -> O.SchemaDefinition -> IO () #else assertMigrationIdempotent :: TestDB.OrvilleRunner -> O.SchemaDefinition -> IO () #endif assertMigrationIdempotent run migrationSchema = do trace <- run (TestDB.queryTrace isDDL (O.migrateSchema migrationSchema)) assertBool "Expected migration trace not to be empty, but it was!" (not (null trace)) plan <- run (O.generateMigrationPlan migrationSchema) case plan of Nothing -> pure () Just somethingToDo -> assertFailure $ "Expected migration plan to be Nothing when database is already migrated, but ddl was:\n" ++ showDDL somethingToDo isDDL :: O.QueryType -> Bool isDDL qt = qt == O.DDLQuery showDDL :: O.MigrationPlan -> String showDDL = List.intercalate "\n\n" . map O.migrationItemDDL . O.migrationPlanItems
flipstone/orville
orville-postgresql/test/Migrations/MigrateTest.hs
mit
4,884
0
15
1,065
1,020
517
503
96
2
module KeyGraph ( KeyGraph, nodes, neighbors, edge, edgesFrom, fromListUndirected, deleteUndirected, ) where import qualified Data.Map as M type KeyGraph nodetype weighttype = M.Map nodetype [(nodetype, weighttype)] nodes :: KeyGraph n e -> [n] nodes = M.keys neighbors :: Ord n => KeyGraph n e -> n -> Maybe [n] neighbors kg node = map fst <$> M.lookup node kg edge :: Ord n => KeyGraph n e -> n -> n -> Maybe e edge kg from to = M.lookup from kg >>= lookup to edgesFrom :: Ord n => KeyGraph n e -> n -> Maybe [(n, e)] edgesFrom = flip M.lookup fromListUndirected :: Ord n => [(n, n, e)] -> KeyGraph n e fromListUndirected = M.fromListWith (flip (++)) . concatMap makeEdges where makeEdges (n1, n2, e) = [(n1, [(n2, e)]), (n2, [(n1, e)])] deleteUndirected :: Ord n => KeyGraph n e -> n -> KeyGraph n e deleteUndirected kg node = M.map remove_refs $ M.delete node kg where remove_refs = filter ((/= node) . fst)
devonhollowood/adventofcode
2015/day9/KeyGraph.hs
mit
956
0
10
211
434
234
200
24
1
-- | Internal types. -- -- You may want to keep off these. module Text.Dot.Types.Internal ( module Text.Dot.Types.Internal -- * Re-exports , Identity(..) , Monoid(..) ) where import Data.Text (Text) import Control.Monad.Identity (Identity (..)) -- | Internal name of a graph, used to reference graphs and subgraphs type GraphName = Text -- | Type of a graph, directed or undirected. -- -- This also specifies what edge declarations look like. data GraphType = UndirectedGraph | DirectedGraph deriving (Show, Eq) -- | Attribute name: just text type AttributeName = Text -- | Attribute value: just text type AttributeValue = Text -- | Attribute: a tuple of name and value. type Attribute = (AttributeName, AttributeValue) -- | A node identifier. -- -- This is either a user supplied name or a generated numerical identifier. data NodeId = UserId Text | Nameless Int deriving (Show, Eq) -- | Declaration type -- -- Used to declare common attributes for nodes or edges. data DecType = DecGraph | DecNode | DecEdge deriving (Show, Eq) -- | A Haphviz Graph data DotGraph = Graph GraphType GraphName Dot deriving (Show, Eq) -- | Rankdir Type -- -- Used to specify the default node layout direction data RankdirType = LR | RL | TB | BT deriving (Show, Eq) -- | Haphviz internal graph content AST data Dot = Node NodeId [Attribute] | Edge NodeId NodeId [Attribute] | Declaration DecType [Attribute] | Ranksame Dot | Subgraph Text Dot | RawDot Text | Label Text | Rankdir RankdirType | DotSeq Dot Dot | DotEmpty deriving (Show, Eq) -- | Dot is a semigroup, duh, that's the point. instance Semigroup Dot where -- Left identity (<>) DotEmpty d = d -- Right identity (<>) d DotEmpty = d -- Associativity (<>) d (DotSeq d1 d2) = DotSeq ((<>) d d1) d2 (<>) d1 d2 = DotSeq d1 d2 -- | Dot is a monoid, duh, that's the point. instance Monoid Dot where mempty = DotEmpty
NorfairKing/haphviz
src/Text/Dot/Types/Internal.hs
mit
2,167
0
8
640
416
257
159
45
0
module Golf where import Data.List skips :: [a] -> [[a]] skips a = map (\n -> every n a) [1..(length a)] where every n xs = case drop (n - 1) xs of [] -> [] (y:ys) -> y : every n ys localMaxima :: [Integer] -> [Integer] localMaxima (a:b:c:xs) = (if b > a && b > c then [b] else []) ++ localMaxima (c:xs) localMaxima _ = [] histogram :: [Integer] -> String histogram nums = map (\n -> count n nums) [0..9] where count n (x:xs) = 'n' -- | n == x = 1 + count n xs -- | otherwise = count n xs
tamasgal/haskell_exercises
CIS-194/homework-03/Golf.hs
mit
568
0
11
188
278
150
128
13
2
{-# LANGUAGE LambdaCase #-} module Main where import qualified Asana as A import qualified Slack as S import Control.Applicative (empty) import Control.Concurrent (forkFinally) import Control.Monad (forever, when) import Control.Monad.Trans.Class (lift) import Data.Foldable (traverse_) import Data.List (intercalate, isInfixOf) import qualified Data.Set as Set import Data.Time.Clock (UTCTime (..), diffUTCTime, getCurrentTime) import Servant import Servant.Client import System.Environment (getEnv) import System.Exit (exitSuccess) handleInteraction :: A.AsanaClient -> String -> IO String handleInteraction client input = case input of "0" -> exitSuccess "1" -> mkAsanaRequest (A.workspaces client) showWorkspaces "2" -> mkAsanaRequest (A.projects client) showProjects "3" -> do line <- getInput "Which project?" let request = A.projectTasks client (read line :: Int) mkAsanaRequest request showTasks "4" -> do line <- getInput "Which workspace?" let request = A.webhooks client $ Just (read line :: Int) mkAsanaRequest request show "5" -> do resource <- getInput "Which resource?" target <- getInput "Which target?" let webhook = A.WebhookNew (read resource :: Int) target request = A.newWebhook client $ A.Request webhook mkAsanaRequest request show "6" -> do webhookId <- getInput "Which webhook?" let request = A.delWebhook client (read webhookId :: Int) mkAsanaRequest request show _ -> return "Unrecognized option" where mkAsanaRequest cm f = A.mkRequest cm f (\e -> "Error:\n" ++ show e) getInput q = putStrLn q >>= return getLine prettyPrintList f xs = intercalate "\n\n" $ map f xs showWorkspaces = prettyPrintList showWorkspace showWorkspace (A.Workspace id name) = "ID:\t" ++ show id ++ "\nName:\t" ++ name showProjects = prettyPrintList showProject showProject (A.Project id name) = "ID:\t" ++ show id ++ "\nName:\t" ++ name showTasks = prettyPrintList showTask showTask (A.Task id name _ _) = "ID:\t" ++ show id ++ "\nName:\t" ++ name webhookHandler :: A.AsanaClient -> A.WebhookHandler () webhookHandler client events = do let evtSet = Set.fromList events putStrLn $ prettyEvents evtSet mapM_ actOnEvent evtSet where prettyEvent (A.Event res usr ty act) = "Resource:\t" ++ show res ++ "\n" ++ "User:\t" ++ show usr ++ "\n" ++ "Type:\t" ++ show ty ++ "\n" ++ "Action:\t" ++ show act prettyEvents = intercalate ("\n" ++ replicate 30 '-' ++ "\n") . map prettyEvent . Set.toList actOnEvent (A.Event res usr A.TaskEvent A.AddedAction) = putStrLn $ "New Task added! [" ++ show res ++ "]" actOnEvent (A.Event taskId usr A.TaskEvent A.ChangedAction) = let request = A.getTask (A.mkTasksClient client taskId) in traverse_ withTask =<< A.mkRequest request Just (const Nothing) where withTask (A.Task _ name _ (Just completedAt)) = do currentTime <- getCurrentTime when (diffUTCTime currentTime completedAt < 60) <$> putStrLn $ "Task " ++ name ++ " completed!" withTask _ = return () actOnEvent _ = return () rtmListener :: S.RTMListener rtmListener self team users chans = \case (S.MessageEvt ch us tx ts Nothing) -> if S.selfId self `isInfixOf` tx then lift $ return (S.MessageReply 1 ch ("Hello <@" ++ us ++ ">")) else do lift $ putStrLn $ getChanName ch ++ ": " ++ getUserName us ++ " wrote " ++ tx empty (S.MessageEvt ch us tx ts (Just S.MeMessage)) -> do lift $ putStrLn $ getChanName ch ++ ": " ++ getUserName us ++ " is " ++ tx empty (S.MessageEvt ch us tx ts (Just S.ChannelJoin)) -> do lift $ putStrLn $ getChanName ch ++ ": " ++ getUserName us ++ " joined" empty (S.MessageEvt ch us tx ts (Just S.ChannelLeave)) -> do lift $ putStrLn $ getChanName ch ++ ": " ++ getUserName us ++ " left" empty (S.UserTypingEvt ch us) -> do lift $ putStrLn $ getChanName ch ++ ": " ++ getUserName us ++ " is typing" empty where lookupUsers = S.lookupIndex users lookupChans = S.lookupIndex chans getUserName = lookupUsers S.userName "An unknown user" getChanName = (:) '#' . lookupChans S.channelName "UNKNOWN" main :: IO () main = do startSlack =<< getEnv "SLACK_TOKEN" withClient <- A.mkClient `fmap` A.Token (Just A.Bearer) `fmap` getEnv "ASANA_TOKEN" startWebhookServer 8080 (webhookHandler withClient) forever (interaction withClient) where crashedHandler s = putStrLn . (++) (s ++ " crashed: ") .show startSlack token = do threadId <- forkFinally (S.startListening token rtmListener) $ either (crashedHandler "Slack bot") return putStrLn $ "Slack bot running in " ++ show threadId startWebhookServer port handler = do threadId <- forkFinally (A.runServer port handler) $ either (crashedHandler "Asana server") return putStrLn $ "Server runnning in " ++ show threadId interaction client = do putStrLn "\nAsana explorer:\n\ \1 - Print workspaces;\n\ \2 - Print projects;\n\ \3 - Print tasks;\n\ \4 - Print webhooks;\n\ \5 - New webhook;\n\ \6 - Delete webhook;\n\ \0 - Exit;\n" getLine >>= handleInteraction client >>= putStrLn
coompany/slackbots
src/Main.hs
mit
6,283
1
18
2,187
1,730
844
886
119
8
module System.TestLoop.Internal.Types where type PackageDbFile = String type TestSuiteName = String type MainModulePath = String type MainModuleName = String type HsSourcePaths = [String]
roman/testloop
src/System/TestLoop/Internal/Types.hs
mit
189
0
5
24
41
28
13
6
0
module Test.RawSql ( rawSqlTests, ) where import qualified Data.ByteString.Char8 as B8 import Data.Functor.Identity (runIdentity) import qualified Data.Text as T import qualified Hedgehog as HH import qualified Orville.PostgreSQL.Internal.PgTextFormatValue as PgTextFormatValue import qualified Orville.PostgreSQL.Internal.RawSql as RawSql import qualified Orville.PostgreSQL.Internal.SqlValue as SqlValue import qualified Test.Property as Property rawSqlTests :: Property.Group rawSqlTests = Property.group "RawSql" [ prop_concatenatesSQLStrings , prop_tracksPlaceholders , prop_escapesStringLiteralsForExamples ] prop_concatenatesSQLStrings :: Property.NamedProperty prop_concatenatesSQLStrings = Property.singletonNamedProperty "Builds concatenated sql from strings" $ do let rawSql = RawSql.fromString "SELECT * " <> RawSql.fromString "FROM foo " <> RawSql.fromString "WHERE id = 1" expectedBytes = B8.pack "SELECT * FROM foo WHERE id = 1" (actualBytes, actualParams) = runIdentity $ RawSql.toBytesAndParams RawSql.exampleEscaping rawSql actualBytes HH.=== expectedBytes actualParams HH.=== [] prop_tracksPlaceholders :: Property.NamedProperty prop_tracksPlaceholders = Property.singletonNamedProperty "Tracks value placeholders in concatenated order" $ do let rawSql = RawSql.fromString "SELECT * " <> RawSql.fromString "FROM foo " <> RawSql.fromString "WHERE id = " <> RawSql.parameter (SqlValue.fromInt32 1) <> RawSql.fromString " AND " <> RawSql.fromString "bar IN (" <> RawSql.intercalate RawSql.comma bars <> RawSql.fromString ")" bars = map RawSql.parameter [ SqlValue.fromText (T.pack "pants") , SqlValue.fromText (T.pack "cheese") ] expectedBytes = B8.pack "SELECT * FROM foo WHERE id = $1 AND bar IN ($2,$3)" expectedParams = [ Just . PgTextFormatValue.fromByteString . B8.pack $ "1" , Just . PgTextFormatValue.fromByteString . B8.pack $ "pants" , Just . PgTextFormatValue.fromByteString . B8.pack $ "cheese" ] (actualBytes, actualParams) = runIdentity $ RawSql.toBytesAndParams RawSql.exampleEscaping rawSql actualBytes HH.=== expectedBytes actualParams HH.=== expectedParams prop_escapesStringLiteralsForExamples :: Property.NamedProperty prop_escapesStringLiteralsForExamples = Property.singletonNamedProperty "Escapes and quotes string literals for examples" $ do let rawSql = RawSql.stringLiteral (B8.pack "Hel\\lo W'orld") expectedBytes = B8.pack "'Hel\\\\lo W\\'orld'" actualBytes = RawSql.toExampleBytes rawSql actualBytes HH.=== expectedBytes
flipstone/orville
orville-postgresql-libpq/test/Test/RawSql.hs
mit
2,932
0
19
736
561
298
263
69
1
module Model where import Token import ClassyPrelude.Yesod import Database.Persist.Quasi share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models") exists :: ( MonadIO m , PersistQuery (PersistEntityBackend v) , PersistEntity v ) => [Filter v] -> ReaderT (PersistEntityBackend v) m Bool exists = fmap (> 0) . count commandOutputs :: MonadIO m => CommandId -> Int -> ReaderT SqlBackend m [Output] commandOutputs commandId start = map entityVal <$> selectList [OutputCommand ==. commandId] [Asc OutputCreatedAt, OffsetBy start] deleteCommand :: MonadIO m => CommandId -> ReaderT SqlBackend m () deleteCommand commandId = do deleteWhere [OutputCommand ==. commandId] delete commandId
mrb/tee-io
src/Model.hs
mit
783
0
9
149
241
121
120
-1
-1
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Config.GameConfig ( GameConfig(..) , defaultConfig , defaultConfigWithRandomPositions , getRogue ) where import ClassyPrelude import qualified Config.Network as Network import Data.List (nub) import Network.Protocol import qualified System.Random as Random data GameConfig = GameConfig { players :: NonNull (Seq Player) , initialPlayerEnergies :: PlayerEnergies , initialPlayerPositions :: PlayerPositions , maxRounds :: Int , rogueShowsAt :: [Int] , network :: Network } deriving (Eq, Show, Read) getRogue :: GameConfig -> Player getRogue = head . players defaultConfigWithRandomPositions :: IO GameConfig defaultConfigWithRandomPositions = do playerPos <- randomPositions (length $ nodes Network.network) return GameConfig { players = impureNonNull $ fromList defaultPlayers , initialPlayerEnergies = defaultInitialPlayerEnergies , initialPlayerPositions = playerPos , maxRounds = 10 , rogueShowsAt = [1,4,7,10] , network = Network.network } randomPositions :: Int -> IO PlayerPositions randomPositions nodeNum = do gen <- Random.newStdGen let rands = nub $ Random.randomRs (1, nodeNum) gen return . mapFromList . zip defaultPlayers . map Node $ rands -- | The default GameConfig defaultConfig :: GameConfig defaultConfig = GameConfig { players = impureNonNull $ fromList defaultPlayers , initialPlayerEnergies = defaultInitialPlayerEnergies , initialPlayerPositions = defaultInitialPlayerPositions , maxRounds = 10 , rogueShowsAt = [1,4,7,10] , network = Network.network } defaultPlayers :: [Player] defaultPlayers = map Player ["Alice", "Bob", "Charlie"] defaultInitialPlayerPositions :: PlayerPositions defaultInitialPlayerPositions = mapFromList . zip defaultPlayers . map Node $ [1, 4, 12] defaultInitialPlayerEnergies :: PlayerEnergies defaultInitialPlayerEnergies = mapFromList . zip defaultPlayers . repeat $ initialEnergiesPerPlayer initialEnergiesPerPlayer :: EnergyMap initialEnergiesPerPlayer = mapFromList [ ( Orange, 7 ) , ( Blue, 4 ) , ( Red, 2 ) ]
Haskell-Praxis/core-catcher
src/Config/GameConfig.hs
mit
2,412
0
12
600
530
307
223
61
1
module Main where import FKats.Luhn import System.Environment main :: IO () main = do args <- getArgs if length args == 0 then error "'Gis an aul argument there, please." else case head args of "luhn" -> do let test = ["49927398716", "49927398717", "1234567812345678", "1234567812345670"] let results = map luhn test putStrLn $ "Results: " ++ show (zip test results) _ -> error "¯\\_(ツ)_/¯"
IanConnolly/functional_kats
src/FKats/main.hs
mit
496
0
16
165
136
68
68
14
3
{-# LANGUAGE TemplateHaskell #-} module Ruab.Backend.GDB -- exports {{{1 ( G.Context, G.Callback(..) , setup, shutdown, run , G.Location, G.file_line_location, G.file_function_location , G.Breakpoint(..), G.Stack(..), G.Frame(..), G.Stopped(..), G.StopReason(..), G.BkptNumber , set_breakpoint, remove_breakpoints, continue, step, next, finish, interrupt, backtrace, evaluate_expression , G.Notification(..), G.NotificationClass(..), G.Stream(..), G.StreamClass(..), G.AsyncClass(..) , G.asConst ) where -- imports {{{1 import Control.Monad (when, guard) import Prelude hiding (interact) import Ruab.Util (abort) import qualified Gdbmi.Commands as G import qualified Gdbmi.IO as G import qualified Gdbmi.Semantics as G import qualified Gdbmi.Representation as G setup :: Maybe FilePath -> FilePath -> G.Callback -> IO G.Context -- {{{1 setup logfile binary callback = do let config = G.Config (words "schroot -c quantal -p -- gdb") logfile ctx <- G.setup config callback resp <- G.send_command ctx (G.CLICommand Nothing "tty /dev/null") -- http://sourceware.org/bugzilla/show_bug.cgi?id=8759 when (G.respClass resp /= G.RCDone) ($abort ("unexpected response: " ++ show resp)) resp' <- G.send_command ctx (G.file_exec_and_symbols (Just binary)) when (G.respClass resp /= G.RCDone) ($abort ("unexpected response: " ++ show resp')) return ctx shutdown :: G.Context -> IO () -- {{{1 shutdown = G.shutdown interrupt :: G.Context -> IO () -- {{{1 interrupt ctx = do resp <- G.send_command ctx (G.exec_interrupt (Left True)) when (G.respClass resp /= G.RCDone) ($abort $ "unexpected response: " ++ show resp) set_breakpoint :: G.Context -> G.Location -> IO G.Breakpoint -- {{{1 set_breakpoint ctx loc = do resp <- G.send_command ctx (G.break_insert False False False False False Nothing Nothing Nothing loc) maybe ($abort ("unexpected response: " ++ show resp)) return (convert G.response_break_insert resp) remove_breakpoints :: G.Context -> [G.BkptNumber] -> IO () -- {{{1 remove_breakpoints _ [] = return () remove_breakpoints ctx bids = do resp <- G.send_command ctx (G.break_delete bids) when (G.respClass resp /= G.RCDone) ($abort $ "unexpected response: " ++ show resp) evaluate_expression :: G.Context -> String -> IO (Either String String) -- {{{1 evaluate_expression ctx expr = do resp <- G.send_command ctx (G.data_evaluate_expression expr) case G.respClass resp of G.RCDone -> maybe ($abort ("unexpected response: " ++ show resp)) (return . Right) (convert G.response_data_evaluate_expression resp) G.RCError -> maybe ($abort ("unexpected response: " ++ show resp)) (return . Left) ((G.response_error . G.respResults) resp) _ -> $abort $ "unexpected response: " ++ show resp run :: G.Context -> IO () -- {{{1 run ctx = do resp <- G.send_command ctx (G.exec_run (Left True)) when (G.respClass resp /= G.RCRunning) ($abort $ "unexpected response: " ++ show resp) continue :: G.Context -> IO () -- {{{1 continue ctx = do resp <- G.send_command ctx (G.exec_continue False (Left True)) when (G.respClass resp /= G.RCRunning) ($abort $ "unexpected response: " ++ show resp) step :: G.Context -> IO () -- {{{1 step ctx = do resp <- G.send_command ctx G.exec_step when (G.respClass resp /= G.RCRunning) ($abort $ "unexpected response: " ++ show resp) next :: G.Context -> IO () -- {{{1 next ctx = do resp <- G.send_command ctx G.exec_next when (G.respClass resp /= G.RCRunning) ($abort $ "unexpected response: " ++ show resp) finish :: G.Context -> IO () -- {{{1 finish ctx = do resp <- G.send_command ctx (G.exec_finish False) when (G.respClass resp /= G.RCRunning) ($abort $ "unexpected response: " ++ show resp) backtrace :: G.Context -> IO G.Stack -- {{{1 backtrace ctx = do resp <- G.send_command ctx (G.stack_list_frames Nothing) maybe ($abort ("unexpected response: " ++ show resp)) return (convert G.response_stack_list_frames resp) -- utils {{{1 convert :: ([G.Result] -> Maybe a) -> G.Response -> Maybe a -- {{{2 convert f resp = do guard (G.respClass resp /= G.RCError) f (G.respResults resp)
copton/ocram
ruab/src/Ruab/Backend/GDB.hs
gpl-2.0
4,234
0
15
802
1,567
796
771
97
3
-- Copyright (C) 2002-2004 David Roundy -- -- 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, 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; see the file COPYING. If not, write to -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. {-# LANGUAGE CPP, TypeOperators #-} module Darcs.UI.Commands.Push ( push ) where import Prelude hiding ( (^) ) import System.Exit ( exitWith, ExitCode( ExitSuccess, ExitFailure ), exitSuccess ) import Control.Monad ( when, unless ) import Data.Char ( toUpper ) import Data.Maybe ( isJust, isNothing ) import Darcs.UI.Commands ( DarcsCommand(..), withStdOpts , putVerbose , putInfo , abortRun , printDryRunMessageAndExit , setEnvDarcsPatches , formatPath , defaultRepo , amInHashedRepository ) import Darcs.UI.Flags ( DarcsFlag , isInteractive, verbosity, isUnified, hasSummary, diffAlgorithm , hasXmlOutput, selectDeps, applyAs , doReverse, dryRun, useCache, remoteRepos, setDefault, fixUrl ) import Darcs.UI.Options ( DarcsOption, (^), odesc, ocheck, onormalise , defaultFlags, parseFlags ) import qualified Darcs.UI.Options.All as O import Darcs.Repository.Flags ( DryRun (..) ) import Darcs.Patch.PatchInfoAnd ( PatchInfoAnd, hopefully ) import Darcs.Repository ( Repository, withRepository, RepoJob(..), identifyRepositoryFor, readRepo, checkUnrelatedRepos ) import Darcs.Patch ( RepoPatch, description ) import Darcs.Patch.Apply( ApplyState ) import Darcs.Patch.Witnesses.Ordered ( (:>)(..), RL, FL, nullRL, nullFL, reverseFL, mapFL_FL, mapRL ) import Darcs.Repository.Prefs ( addRepoSource, getPreflist ) import Darcs.UI.External ( maybeURLCmd, signString ) import Darcs.Util.URL ( isHttpUrl, isValidLocalPath ) import Darcs.Util.Path ( AbsolutePath ) import Darcs.UI.SelectChanges ( selectChanges , WhichChanges(..) , selectionContext , runSelection ) import qualified Darcs.UI.SelectChanges as S ( PatchSelectionOptions (..) ) import Darcs.Patch.Depends ( findCommonWithThem, countUsThem ) import Darcs.Patch.Bundle ( makeBundleN ) import Darcs.Patch.Patchy( ShowPatch ) import Darcs.Patch.Set ( PatchSet, Origin ) import Darcs.Util.Printer ( Doc, vcat, empty, text, ($$) ) import Darcs.UI.RemoteApply ( remoteApply ) import Darcs.UI.Email ( makeEmail ) import Darcs.Util.English (englishNum, Noun(..)) import Darcs.Util.Workaround ( getCurrentDirectory ) import Storage.Hashed.Tree( Tree ) #include "impossible.h" pushDescription :: String pushDescription = "Copy and apply patches from this repository to another one." pushHelp :: String pushHelp = unlines [ "Push is the opposite of pull. Push allows you to copy patches from the" , "current repository into another repository." , "" , "If you give the `--apply-as` flag, darcs will use sudo to apply the" , "patches as a different user. This can be useful if you want to set up a" , "system where several users can modify the same repository, but you don't" , "want to allow them full write access. This isn't secure against skilled" , "malicious attackers, but at least can protect your repository from clumsy," , "inept or lazy users." , "" , "Darcs push will by default compress the patch data before sending it to a" , "remote location via ssh. This works as long as the remote darcs is not" , "older than version 2.5. If you get errors that indicate a corrupt patch" , "bundle, you should try again with the `--no-compress` option to send the" , "data in un-compressed form (which is a lot slower for large patches, but" , "should always work)." ] pushBasicOpts :: DarcsOption a ([O.MatchFlag] -> O.SelectDeps -> Maybe Bool -> O.Sign -> O.DryRun -> O.XmlOutput -> Maybe O.Summary -> Maybe String -> Maybe Bool -> Bool -> a) pushBasicOpts = O.matchSeveral ^ O.selectDeps ^ O.interactive ^ O.sign ^ O.dryRunXml ^ O.summary ^ O.workingRepoDir ^ O.setDefault ^ O.allowUnrelatedRepos pushAdvancedOpts :: DarcsOption a (Maybe String -> O.RemoteRepos -> Bool -> O.Compression -> O.NetworkOptions -> a) pushAdvancedOpts = O.applyAs ^ O.remoteRepos ^ O.changesReverse ^ O.compress ^ O.network pushOpts :: DarcsOption a ([O.MatchFlag] -> O.SelectDeps -> Maybe Bool -> O.Sign -> DryRun -> O.XmlOutput -> Maybe O.Summary -> Maybe String -> Maybe Bool -> Bool -> Maybe O.StdCmdAction -> Bool -> Bool -> O.Verbosity -> Bool -> Maybe String -> O.RemoteRepos -> Bool -> O.Compression -> O.NetworkOptions -> O.UseCache -> Maybe String -> Bool -> Maybe String -> Bool -> a) pushOpts = pushBasicOpts `withStdOpts` pushAdvancedOpts push :: DarcsCommand [DarcsFlag] push = DarcsCommand { commandProgramName = "darcs" , commandName = "push" , commandHelp = pushHelp , commandDescription = pushDescription , commandExtraArgs = 1 , commandExtraArgHelp = ["[REPOSITORY]"] , commandCommand = pushCmd , commandPrereq = amInHashedRepository , commandGetArgPossibilities = getPreflist "repos" , commandArgdefaults = defaultRepo , commandAdvancedOptions = odesc pushAdvancedOpts , commandBasicOptions = odesc pushBasicOpts , commandDefaults = defaultFlags pushOpts , commandCheckOptions = ocheck pushOpts , commandParseOptions = onormalise pushOpts } pushCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO () pushCmd _ _ [""] = impossible pushCmd (_,o) opts [unfixedrepodir] = do repodir <- fixUrl o unfixedrepodir -- Test to make sure we aren't trying to push to the current repo here <- getCurrentDirectory checkOptionsSanity opts repodir when (repodir == here) $ fail "Cannot push from repository to itself." -- absolute '.' also taken into account by fix_filepath bundle <- withRepository (useCache opts) $ RepoJob $ prepareBundle opts repodir sbundle <- signString (parseFlags O.sign opts) bundle let body = if isValidLocalPath repodir then sbundle else makeEmail repodir [] Nothing Nothing sbundle Nothing rval <- remoteApply opts repodir body case rval of ExitFailure ec -> do putStrLn "Apply failed!" exitWith (ExitFailure ec) ExitSuccess -> putInfo opts $ text "Push successful." pushCmd _ _ _ = impossible prepareBundle :: forall p wR wU wT. (RepoPatch p, ApplyState p ~ Tree) => [DarcsFlag] -> String -> Repository p wR wU wT -> IO Doc prepareBundle opts repodir repository = do old_default <- getPreflist "defaultrepo" when (old_default == [repodir]) $ let pushing = if dryRun opts == YesDryRun then "Would push" else "Pushing" in putInfo opts $ text $ pushing++" to "++formatPath repodir++"..." them <- identifyRepositoryFor repository (useCache opts) repodir >>= readRepo addRepoSource repodir (dryRun opts) (remoteRepos opts) (setDefault False opts) us <- readRepo repository common :> us' <- return $ findCommonWithThem us them prePushChatter opts us (reverseFL us') them let direction = if doReverse opts then FirstReversed else First context = selectionContext direction "push" (pushPatchSelOpts opts) Nothing Nothing runSelection (selectChanges us') context >>= bundlePatches opts common prePushChatter :: forall p a wX wY wT . (RepoPatch p, ShowPatch a) => [DarcsFlag] -> PatchSet p Origin wX -> RL a wT wX -> PatchSet p Origin wY -> IO () prePushChatter opts us us' them = do checkUnrelatedRepos (parseFlags O.allowUnrelatedRepos opts) us them let num_to_pull = snd $ countUsThem us them pull_reminder = if num_to_pull > 0 then text $ "The remote repository has " ++ show num_to_pull ++ " " ++ englishNum num_to_pull (Noun "patch") " to pull." else empty putVerbose opts $ text "We have the following patches to push:" $$ vcat (mapRL description us') unless (nullRL us') $ putInfo opts pull_reminder when (nullRL us') $ do putInfo opts $ text "No recorded local patches to push!" exitSuccess bundlePatches :: forall t p wZ wW wA. (RepoPatch p, ApplyState p ~ Tree) => [DarcsFlag] -> PatchSet p wA wZ -> (FL (PatchInfoAnd p) :> t) wZ wW -> IO Doc bundlePatches opts common (to_be_pushed :> _) = do setEnvDarcsPatches to_be_pushed printDryRunMessageAndExit "push" (verbosity opts) (hasSummary O.NoSummary opts) (dryRun opts) (hasXmlOutput opts) (isInteractive True opts) to_be_pushed when (nullFL to_be_pushed) $ do putInfo opts $ text "You don't want to push any patches, and that's fine with me!" exitSuccess makeBundleN Nothing common (mapFL_FL hopefully to_be_pushed) checkOptionsSanity :: [DarcsFlag] -> String -> IO () checkOptionsSanity opts repodir = if isHttpUrl repodir then do when (isJust $ applyAs opts) $ abortRun opts $ text "Cannot --apply-as when pushing to URLs" maybeapply <- maybeURLCmd "APPLY" repodir when (isNothing maybeapply) $ let lprot = takeWhile (/= ':') repodir prot = map toUpper lprot msg = text ("Pushing to "++lprot++" URLs is not supported.\n"++ "You may be able to hack this to work"++ " using DARCS_APPLY_"++prot) in abortRun opts msg else when (parseFlags O.sign opts /= O.NoSign) $ abortRun opts $ text "Signing doesn't make sense for local repositories or when pushing over ssh." pushPatchSelOpts :: [DarcsFlag] -> S.PatchSelectionOptions pushPatchSelOpts flags = S.PatchSelectionOptions { S.verbosity = verbosity flags , S.matchFlags = parseFlags O.matchSeveral flags , S.diffAlgorithm = diffAlgorithm flags , S.interactive = isInteractive True flags , S.selectDeps = selectDeps flags , S.summary = hasSummary O.NoSummary flags , S.withContext = isUnified flags }
DavidAlphaFox/darcs
src/Darcs/UI/Commands/Push.hs
gpl-2.0
11,153
0
31
2,923
2,551
1,376
1,175
-1
-1
module Query where import Data.Maybe import Data.Foldable import qualified Data.Sequence as S import ChessData import Board import Vectors -- Check if a specific square is being attacked at depth 1 by the given colour isSqAttacked :: GameState -> Square -> Colour -> Bool isSqAttacked g sq c = sliders || pawns || nsliders where pieces = piecesByColour (board g) c sliders = or $ sliderPieceAttacking' g (excludeNonSliders pieces) sq pawns = pawnAttacking pieces c sq nsliders = or $ nonSliderPieceAttacking' sq $ excludeSliders (excludePiece Pawn pieces) -- Does the current game state have the king sq attacked? isInCheck :: GameState -> Bool isInCheck g@(GameState b stm _ _ _ _ _) = isSqAttacked g sq stm where (Just (sq,_)) = find ((== King).ptype.snd) (piecesByColour b (opposite stm)) -- Get the attack vectors for a pawn, and see if any pawn attacks the current sq pawnAttacking :: [(Square, Piece)] -> Colour -> Square -> Bool pawnAttacking pieces col sq = isJust p1 || isJust p2 where pawns = filterPieces Pawn pieces (sq1:sq2:_) = toList $ pawnAttackVectors (opposite col) sq p1 = lookup sq1 pawns p2 = lookup sq2 pawns negateY (x,y) = (x, -y) nonSliderPieceAttacking' :: Square -> [(Square, Piece)] -> [Bool] nonSliderPieceAttacking' sq pcs = map (\(_,Piece t c) -> nonSliderPieceAttacking t pcs sq) pcs nonSliderPieceAttacking :: PieceType -> [(Square, Piece)] -> Square -> Bool nonSliderPieceAttacking ptype' pieces sq = any isJust candidates where ps = filterPieces ptype' pieces vs = map (addPos sq) (toList $ moveVectors (Piece ptype' White)) candidates = map (`lookup` ps) vs sliderPieceAttacking' :: GameState -> [(Square,Piece)] -> Square -> [Bool] sliderPieceAttacking' g pcs sq = map (\(_,p) -> sliderPieceAttacking g p pcs sq) pcs sliderPieceAttacking :: GameState -> Piece -> [(Square, Piece)] -> Square -> Bool sliderPieceAttacking (GameState b _ _ _ _ _ _) p@(Piece ptype col) pieces sq = any isJust candidates where ps = filterPieces ptype pieces vs = concatMap (toList.slide b sq (opposite col)) $ moveVectors p candidates = map (`lookup` ps) vs filterPieces :: PieceType -> [(a, Piece)] -> [(a, Piece)] filterPieces ptype' = filter ((== ptype').ptype.snd) excludePiece :: PieceType -> [(a, Piece)] -> [(a, Piece)] excludePiece ptype' = filter ((/= ptype').ptype.snd) excludeNonSliders :: [(a, Piece)] -> [(a, Piece)] excludeNonSliders = filter (sliderPiece.ptype.snd) excludeSliders :: [(a, Piece)] -> [(a, Piece)] excludeSliders = filter (not.sliderPiece.ptype.snd)
CameronDiver/hschess
src/query.hs
gpl-3.0
2,637
0
12
525
950
518
432
48
1
-- Copyright 2017 Marcelo Garlet Millani -- This file is part of pictikz. -- pictikz 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. -- pictikz 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 pictikz. If not, see <http://www.gnu.org/licenses/>. module Pictikz.Organizer where import qualified Data.Set as S import qualified Data.Map as M import Pictikz.Graph import Pictikz.Elements import Data.List import Data.Maybe import qualified Debug.Trace as D (trace) boundingBox (Graph nodes edges) = let coords = map getPos nodes x0 = minimum $ map fst $ coords x1 = maximum $ map fst $ coords y0 = minimum $ map snd $ coords y1 = maximum $ map snd $ coords in (x0,y0,x1,y1) -- | Join equal vertices which stand on the same position in subsequent layers mergeLayers epsilon (Graph n0 e0) (Graph n1 e1) = Graph gnodes gedges -- TODO: only nodes of adjacent layers should be compared. Right now, n1 contains all nodes. where epsilon2 = epsilon * epsilon mergeNode n [] = ([], Nothing) mergeNode n (m:ms) = let (Node x0 y0 uid0 name0 style0 (t0, t1)) = n (Node x1 y1 uid1 name1 style1 (t2, t3)) = m d = (x1 - x0)^2 + (y1 - y0)^2 in if d < epsilon2 && t1 == (t2-1) && name0 == name1 && style0 == style1 then ((Node x1 y1 uid1 name1 style1 (t0,t3)) : ms, Just uid1) else let (r, rn) = mergeNode n ms in (m : r, rn) mergeNodes [] ms = (M.empty, ms) mergeNodes (n:ns) ms = let (ms', n') = mergeNode n ms (t, nodes') = mergeNodes ns ms' in case n' of Nothing -> (t, n : nodes') Just uid1 -> let (Node _ _ uid0 _ _ _) = n in (M.insert uid0 uid1 t, nodes') (table, gnodes) = mergeNodes n0 n1 edgeIda (Edge v u style (t0,t1)) = (v, u, style, t1) edgeIdb (Edge v u style (t0,t1)) = (v, u, style, t0-1) edgeInfo (Edge v u style time) = time gedges = map (\((v, u, style, _), time) -> Edge v u style time) $ M.toList $ M.unionWith (\(t0, _) (_,t1) -> (t0,t1)) (M.fromList $ map (\e -> (edgeIda e, edgeInfo e)) $ map updateEdge e0) (M.fromList $ map (\e -> (edgeIdb e, edgeInfo e)) $ map updateEdge e1) updateEdge (Edge v u style time) = (Edge (f v) (f u) style time) where f x = fromMaybe x $ table M.!? x fitToBox w h objects = let positions = map getPos objects xs = map fst positions ys = map snd positions shiftx = - minimum xs shifty = - minimum ys scalex = maximum xs scaley = maximum ys scale = max ((scalex + shiftx) / w) ((scaley + shifty) / h) in if scale == 0 then objects else map (fPos (\(x,y) -> ((x + shiftx) / scale, (y + shifty) / scale))) objects scaleToBox w h objects = let positions = map getPos objects xs = map fst positions ys = map snd positions shiftx = - minimum xs shifty = - minimum ys scalex' = shiftx + maximum xs scaley' = shifty + maximum ys scalex = if scalex' == 0 then 1 else scalex' scaley = if scaley' == 0 then 1 else scaley' in map (fPos (\(x,y) -> ((x + shiftx) * w/scalex, (y + shifty) * h/scaley))) objects -- | Reposition objects such that the minimum distance in x-axis equals x (and the analog for the y-axis). minDist xd yd objects = let positions = map getPos objects xs = sort $ map fst positions ys = sort $ map snd positions shiftx = - minimum xs shifty = - minimum ys minDistXs = filter (/= 0.0) $ zipWith (\x0 x1 -> abs $ x0 - x1) xs (tail xs) minDistYs = filter (/= 0.0) $ zipWith (\y0 y1 -> abs $ y0 - y1) ys (tail ys) mdX = if null minDistXs then xd else minimum minDistXs mdY = if null minDistYs then yd else minimum minDistYs in map (fPos (\(x,y) -> (xd * (x + shiftx) / mdX, yd * (y + shifty) / mdY))) objects average xs = realToFrac (sum xs) / genericLength xs -- | Organizes nodes in a way that the amount of x and y coordinates used is decreased. -- | The given parameter `d` the maximum difference in order to merge two coordinates. -- | The function `groupf` should convert coordinates into their grouped form uniformCoordinatesBy groupf d ns = let nsx = sortBy (\n m -> compare (fst $ getPos n) (fst $ getPos m)) ns xs = map (fst . getPos) nsx dx = max 1e-5 $ d * ((maximum xs) - (minimum xs)) ux = concat $ groupf dx xs -- update x coordinates ns1 = zipWith (\n x1 -> fPos (\(x,y) -> (x1,y)) n) nsx ux nsy = sortBy (\n m -> compare (snd $ getPos n) (snd $ getPos m)) ns1 ys = map (snd . getPos) nsy dy = max 1e-5 $ d * ((maximum ys) - (minimum ys)) uy = concat $ groupf dy ys in zipWith (\n y1 -> fPos (\(x,y) -> (x,y1)) n) nsy uy genGroup f d [] = [] genGroup f d as = let (bs, r1) = f d as in bs : genGroup f d r1 distanceGroup d0 [] = ([], []) distanceGroup d0 (a:as) = group' d0 d0 0 a (a:as) where group' d d0 l a0 as = let (g, rest) = span (\x -> x - a0 < d0) as a1 = average g l1 = genericLength g d1 = 0.55 * d in if g == [] then (take l $ repeat a0, rest) else (group' d d1 (l + l1) a1 rest) isometricGroup d0 as = let gs = genGroup distanceGroup d0 as in zipWith (\g i -> map (\x -> fromIntegral i) g) gs [0,1..]
mgmillani/pictikz
src/Pictikz/Organizer.hs
gpl-3.0
5,766
6
17
1,604
2,287
1,215
1,072
102
5
module HEP.Automation.MadGraph.Dataset.Set20110407set2 where import HEP.Storage.WebDAV import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Model.ZpHFull import HEP.Automation.MadGraph.Dataset.Common import qualified Data.ByteString as B processTopZpDecay :: [Char] processTopZpDecay = "\ngenerate P P > t zput QED=99, t > b w+, zput > b~ d @1 \nadd process P P > t~ zptu QED=99, zptu > b d~, t~ > b~ w- @2\n" psetup_zphfull_TopZpDecay :: ProcessSetup ZpHFull psetup_zphfull_TopZpDecay = PS { mversion = MadGraph4 , model = ZpHFull , process = processTopZpDecay , processBrief = "TopZpDecay" , workname = "407ZpH_TopZpDecay" } zpHFullParamSet :: [ModelParam ZpHFull] zpHFullParamSet = [ ZpHFullParam m g g | m <-[150.0] , g <- [0.7*sqrt 2] ] psetuplist :: [ProcessSetup ZpHFull] psetuplist = [ psetup_zphfull_TopZpDecay ] sets :: [Int] sets = [1] zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull] zptasklist ssetup csetup = [ WS ssetup (psetup_zphfull_TopZpDecay) (rsetupGen p NoMatch NoUserCutDef NoPGS 20000 num) csetup (WebDAVRemoteDir undefined) | p <- zpHFullParamSet , num <- sets ] totaltasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull] totaltasklist = zptasklist
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110407set2.hs
gpl-3.0
1,489
0
10
311
329
193
136
36
1
-- | -- Module : Commands.Depends -- Copyright : (C) 2014 Jens Petersen -- -- Maintainer : Jens Petersen <petersen@fedoraproject.org> -- Stability : alpha -- -- Explanation: determines dependencies -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. module Commands.Depends ( depends, Depends (..) ) where import Dependencies (dependencies, missingPackages, packageDependencies) import PackageUtils (PackageData (..), prepare, stripPkgDevel) import Setup (quiet) import SysCmd (repoquery, (+-+)) import Control.Applicative ((<$>)) import Control.Monad (filterM, unless, void) import Data.List (nub, sort, (\\)) import System.Directory (removeDirectoryRecursive) data Depends = Depends | Requires | Missing depends :: PackageData -> Depends -> IO () depends pkgdata action = do let pkgDesc = packageDesc pkgdata case action of Depends -> do (deps, tools, clibs, pkgcfgs, _) <- dependencies pkgDesc let clibs' = map (\ lib -> "lib" ++ lib ++ ".so") clibs let pkgcfgs' = map (++ ".pc") pkgcfgs mapM_ putStrLn $ deps ++ tools ++ clibs' ++ pkgcfgs' Requires -> do (deps, tools, clibs, pkgcfgs, _) <- packageDependencies pkgDesc mapM_ putStrLn $ sort $ deps ++ tools ++ clibs ++ pkgcfgs Missing -> do miss <- missingPackages pkgDesc >>= filterM notAvail let missing = map stripPkgDevel miss mapM_ putStrLn missing unless (null missing) $ putStrLn "" void $ recurseMissing miss missing recurseMissing :: [String] -> [String] -> IO [String] recurseMissing already [] = return already recurseMissing already (dep:deps) = do miss <- missingDepsPkg dep putMissing dep miss already let accum = nub $ miss ++ already deeper <- recurseMissing accum (miss \\ accum) let accum2 = nub $ accum ++ deeper more <- recurseMissing accum2 (deps \\ accum2) return $ nub $ accum2 ++ more notAvail :: String -> IO Bool notAvail pkg = null <$> repoquery [] pkg missingDepsPkg :: String -> IO [String] missingDepsPkg pkg = do pkgdata <- prepare (Just pkg) quiet maybe (return ()) removeDirectoryRecursive $ workingDir pkgdata missingPackages (packageDesc pkgdata) >>= filterM notAvail putMissing :: String -> [String] -> [String] -> IO () putMissing _ [] _ = return () putMissing pkg deps already = putStrLn $ pkg +-+ "needs:" +-+ unwords (markAlready deps) where markAlready :: [String] -> [String] markAlready [] = [] markAlready (d:ds) = let (op, cl) = if d `elem` already then ("(", ")") else ("", "") in (op ++ stripPkgDevel d ++ cl) : markAlready ds
mathstuf/cabal-rpm
src/Commands/Depends.hs
gpl-3.0
2,800
2
19
586
902
470
432
56
3
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-overlapping-patterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} module Handler.DB.Internal where import Handler.DB.Enums import Handler.DB.Esqueleto import qualified Handler.DB.PathPieces as PP import Prelude import Control.Monad (forM_, when) import Control.Monad.Catch (MonadThrow) import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT) import Database.Esqueleto import qualified Database.Esqueleto as E import qualified Database.Persist as P import Database.Persist.TH import Yesod.Auth (requireAuth, requireAuthId, YesodAuth, AuthId, YesodAuthPersist) import Yesod.Core hiding (fileName, fileContentType) import Yesod.Persist (runDB, YesodPersist, YesodPersistBackend) import Data.Aeson ((.:), (.:?), (.!=), FromJSON, parseJSON, decode) import Data.Aeson.TH import Data.Int import Data.Word import Data.Time import Data.Text.Encoding (encodeUtf8) import Data.Typeable (Typeable) import qualified Data.Attoparsec as AP import qualified Data.Aeson as A import qualified Data.Aeson.Types as AT import qualified Data.ByteString.Lazy as LBS import Data.Maybe import qualified Data.Text.Read import qualified Data.Text as T import Data.String (IsString(..)) import Data.Text (Text) import qualified Data.List as DL import Control.Monad (mzero) import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Network.HTTP.Conduit as C import qualified Network.Wai as W import Data.Conduit.Lazy (lazyConsume) import Network.HTTP.Types (status200, status400, status403, status404) import Blaze.ByteString.Builder.ByteString (fromByteString) import Control.Applicative ((<$>), (<*>)) import qualified Data.HashMap.Lazy as HML import qualified Data.HashMap.Strict as HMS import qualified Data.Text.Lazy.Builder as TLB data DB = DB share [mkPersist sqlSettings, mkMigrate "migrateDB" ] [persistLowerCase| File json contentType Text size Int32 previewOfFileId FileId Maybe default=NULL name Text activeId FileId Maybe default=NULL activeStartTime UTCTime Maybe activeEndTime UTCTime Maybe deletedVersionId VersionId Maybe default=NULL insertionTime UTCTime insertedByUserId UserId Maybe default=NULL UserGroupContent json userGroupId UserGroupId fileContentId FileId Maybe default=NULL userGroupContentId UserGroupId Maybe default=NULL userContentId UserId Maybe default=NULL receiptContentId ReceiptId Maybe default=NULL processPeriodContentId ProcessPeriodId Maybe default=NULL deletedVersionId VersionId Maybe default=NULL UserGroup json createPeriods Int32 "default=1" email Text "default=''" organization Text Maybe current Checkmark "default=True" nullable name Text activeId UserGroupId Maybe default=NULL activeStartTime UTCTime Maybe activeEndTime UTCTime Maybe deletedVersionId VersionId Maybe default=NULL UniqueUserGroup current name !force UserGroupItem json userGroupId UserGroupId userId UserId mode UserGroupMode deletedVersionId VersionId Maybe default=NULL User json firstName Text "default=''" lastName Text "default=''" organization Text "default=''" admin Bool "default=False" email Text "default=''" password Text "default=''" salt Text "default=''" passwordResetToken Text Maybe passwordResetValidUntil UTCTime Maybe contractStartDate Day Maybe contractEndDate Day Maybe defaultUserGroupId UserGroupId timeZone Text "default='Europe/Helsinki'" current Checkmark "default=True" nullable config Text "default='{}'" strictEmailCheck Bool "default=False" name Text activeId UserId Maybe default=NULL activeStartTime UTCTime Maybe activeEndTime UTCTime Maybe deletedVersionId VersionId Maybe default=NULL UniqueUser current name !force UniqueUserEmail current email !force deriving Typeable Version json time UTCTime userId UserId Receipt json fileId FileId processPeriodId ProcessPeriodId Maybe default=NULL amount Double processed Bool "default=False" name Text activeId ReceiptId Maybe default=NULL activeStartTime UTCTime Maybe activeEndTime UTCTime Maybe deletedVersionId VersionId Maybe default=NULL insertionTime UTCTime insertedByUserId UserId Maybe default=NULL ProcessPeriod json firstDay Day lastDay Day queued Bool "default=False" processed Bool "default=False" name Text |] newFile :: Text -> Int32 -> Text -> UTCTime -> File newFile contentType_ size_ name_ insertionTime_ = File { fileContentType = contentType_, fileSize = size_, filePreviewOfFileId = Nothing, fileName = name_, fileActiveId = Nothing, fileActiveStartTime = Nothing, fileActiveEndTime = Nothing, fileDeletedVersionId = Nothing, fileInsertionTime = insertionTime_, fileInsertedByUserId = Nothing } newUserGroupContent :: UserGroupId -> UserGroupContent newUserGroupContent userGroupId_ = UserGroupContent { userGroupContentUserGroupId = userGroupId_, userGroupContentFileContentId = Nothing, userGroupContentUserGroupContentId = Nothing, userGroupContentUserContentId = Nothing, userGroupContentReceiptContentId = Nothing, userGroupContentProcessPeriodContentId = Nothing, userGroupContentDeletedVersionId = Nothing } newUserGroup :: Text -> UserGroup newUserGroup name_ = UserGroup { userGroupCreatePeriods = 1, userGroupEmail = "", userGroupOrganization = Nothing, userGroupCurrent = Active, userGroupName = name_, userGroupActiveId = Nothing, userGroupActiveStartTime = Nothing, userGroupActiveEndTime = Nothing, userGroupDeletedVersionId = Nothing } newUserGroupItem :: UserGroupId -> UserId -> UserGroupMode -> UserGroupItem newUserGroupItem userGroupId_ userId_ mode_ = UserGroupItem { userGroupItemUserGroupId = userGroupId_, userGroupItemUserId = userId_, userGroupItemMode = mode_, userGroupItemDeletedVersionId = Nothing } newUser :: UserGroupId -> Text -> User newUser defaultUserGroupId_ name_ = User { userFirstName = "", userLastName = "", userOrganization = "", userAdmin = False, userEmail = "", userPassword = "", userSalt = "", userPasswordResetToken = Nothing, userPasswordResetValidUntil = Nothing, userContractStartDate = Nothing, userContractEndDate = Nothing, userDefaultUserGroupId = defaultUserGroupId_, userTimeZone = "Europe/Helsinki", userCurrent = Active, userConfig = "{}", userStrictEmailCheck = False, userName = name_, userActiveId = Nothing, userActiveStartTime = Nothing, userActiveEndTime = Nothing, userDeletedVersionId = Nothing } newVersion :: UTCTime -> UserId -> Version newVersion time_ userId_ = Version { versionTime = time_, versionUserId = userId_ } newReceipt :: FileId -> Double -> Text -> UTCTime -> Receipt newReceipt fileId_ amount_ name_ insertionTime_ = Receipt { receiptFileId = fileId_, receiptProcessPeriodId = Nothing, receiptAmount = amount_, receiptProcessed = False, receiptName = name_, receiptActiveId = Nothing, receiptActiveStartTime = Nothing, receiptActiveEndTime = Nothing, receiptDeletedVersionId = Nothing, receiptInsertionTime = insertionTime_, receiptInsertedByUserId = Nothing } newProcessPeriod :: Day -> Day -> Text -> ProcessPeriod newProcessPeriod firstDay_ lastDay_ name_ = ProcessPeriod { processPeriodFirstDay = firstDay_, processPeriodLastDay = lastDay_, processPeriodQueued = False, processPeriodProcessed = False, processPeriodName = name_ } class Named a where namedName :: a -> Text data NamedInstanceFieldName = NamedName instance Named File where namedName = fileName instance Named UserGroup where namedName = userGroupName instance Named User where namedName = userName instance Named Receipt where namedName = receiptName instance Named ProcessPeriod where namedName = processPeriodName data NamedInstance = NamedInstanceFile (Entity File) | NamedInstanceUserGroup (Entity UserGroup) | NamedInstanceUser (Entity User) | NamedInstanceReceipt (Entity Receipt) | NamedInstanceProcessPeriod (Entity ProcessPeriod) data NamedInstanceId = NamedInstanceFileId FileId | NamedInstanceUserGroupId UserGroupId | NamedInstanceUserId UserId | NamedInstanceReceiptId ReceiptId | NamedInstanceProcessPeriodId ProcessPeriodId deriving (Eq, Ord) reflectNamedInstanceId :: NamedInstanceId -> (Text, Int64) reflectNamedInstanceId x = case x of NamedInstanceFileId key -> ("File", fromSqlKey key) NamedInstanceUserGroupId key -> ("UserGroup", fromSqlKey key) NamedInstanceUserId key -> ("User", fromSqlKey key) NamedInstanceReceiptId key -> ("Receipt", fromSqlKey key) NamedInstanceProcessPeriodId key -> ("ProcessPeriod", fromSqlKey key) instance Named NamedInstance where namedName x = case x of NamedInstanceFile (Entity _ e) -> fileName e NamedInstanceUserGroup (Entity _ e) -> userGroupName e NamedInstanceUser (Entity _ e) -> userName e NamedInstanceReceipt (Entity _ e) -> receiptName e NamedInstanceProcessPeriod (Entity _ e) -> processPeriodName e data NamedInstanceFilterType = NamedInstanceNameFilter (SqlExpr (Database.Esqueleto.Value (Text)) -> SqlExpr (Database.Esqueleto.Value Bool)) lookupNamedInstance :: forall (m :: * -> *). (MonadIO m) => NamedInstanceId -> SqlPersistT m (Maybe NamedInstance) lookupNamedInstance k = case k of NamedInstanceFileId key -> runMaybeT $ do val <- MaybeT $ get key return $ NamedInstanceFile $ Entity key val NamedInstanceUserGroupId key -> runMaybeT $ do val <- MaybeT $ get key return $ NamedInstanceUserGroup $ Entity key val NamedInstanceUserId key -> runMaybeT $ do val <- MaybeT $ get key return $ NamedInstanceUser $ Entity key val NamedInstanceReceiptId key -> runMaybeT $ do val <- MaybeT $ get key return $ NamedInstanceReceipt $ Entity key val NamedInstanceProcessPeriodId key -> runMaybeT $ do val <- MaybeT $ get key return $ NamedInstanceProcessPeriod $ Entity key val selectNamed :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[NamedInstanceFilterType]] -> SqlPersistT m [NamedInstance] selectNamed filters = do result_File <- select $ from $ \e -> do let _ = e ^. FileId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. FileName ) exprs return e result_UserGroup <- select $ from $ \e -> do let _ = e ^. UserGroupId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. UserGroupName ) exprs return e result_User <- select $ from $ \e -> do let _ = e ^. UserId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. UserName ) exprs return e result_Receipt <- select $ from $ \e -> do let _ = e ^. ReceiptId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. ReceiptName ) exprs return e result_ProcessPeriod <- select $ from $ \e -> do let _ = e ^. ProcessPeriodId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. ProcessPeriodName ) exprs return e return $ concat [ map NamedInstanceFile result_File , map NamedInstanceUserGroup result_UserGroup , map NamedInstanceUser result_User , map NamedInstanceReceipt result_Receipt , map NamedInstanceProcessPeriod result_ProcessPeriod ] data NamedInstanceUpdateType = NamedInstanceUpdateName (SqlExpr (Database.Esqueleto.Value (Text))) updateNamed :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[NamedInstanceFilterType]] -> [NamedInstanceUpdateType] -> SqlPersistT m () updateNamed filters updates = do update $ \e -> do let _ = e ^. FileId set e $ map (\u -> case u of NamedInstanceUpdateName v -> FileName =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. FileName ) exprs update $ \e -> do let _ = e ^. UserGroupId set e $ map (\u -> case u of NamedInstanceUpdateName v -> UserGroupName =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. UserGroupName ) exprs update $ \e -> do let _ = e ^. UserId set e $ map (\u -> case u of NamedInstanceUpdateName v -> UserName =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. UserName ) exprs update $ \e -> do let _ = e ^. ReceiptId set e $ map (\u -> case u of NamedInstanceUpdateName v -> ReceiptName =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. ReceiptName ) exprs update $ \e -> do let _ = e ^. ProcessPeriodId set e $ map (\u -> case u of NamedInstanceUpdateName v -> ProcessPeriodName =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of NamedInstanceNameFilter op -> op $ e ^. ProcessPeriodName ) exprs return () class HasInsertInfo a where hasInsertInfoInsertionTime :: a -> UTCTime hasInsertInfoInsertedByUserId :: a -> Maybe UserId data HasInsertInfoInstanceFieldName = HasInsertInfoInsertionTime | HasInsertInfoInsertedByUserId instance HasInsertInfo File where hasInsertInfoInsertionTime = fileInsertionTime hasInsertInfoInsertedByUserId = fileInsertedByUserId instance HasInsertInfo Receipt where hasInsertInfoInsertionTime = receiptInsertionTime hasInsertInfoInsertedByUserId = receiptInsertedByUserId data HasInsertInfoInstance = HasInsertInfoInstanceFile (Entity File) | HasInsertInfoInstanceReceipt (Entity Receipt) data HasInsertInfoInstanceId = HasInsertInfoInstanceFileId FileId | HasInsertInfoInstanceReceiptId ReceiptId deriving (Eq, Ord) reflectHasInsertInfoInstanceId :: HasInsertInfoInstanceId -> (Text, Int64) reflectHasInsertInfoInstanceId x = case x of HasInsertInfoInstanceFileId key -> ("File", fromSqlKey key) HasInsertInfoInstanceReceiptId key -> ("Receipt", fromSqlKey key) instance HasInsertInfo HasInsertInfoInstance where hasInsertInfoInsertionTime x = case x of HasInsertInfoInstanceFile (Entity _ e) -> fileInsertionTime e HasInsertInfoInstanceReceipt (Entity _ e) -> receiptInsertionTime e hasInsertInfoInsertedByUserId x = case x of HasInsertInfoInstanceFile (Entity _ e) -> fileInsertedByUserId e HasInsertInfoInstanceReceipt (Entity _ e) -> receiptInsertedByUserId e data HasInsertInfoInstanceFilterType = HasInsertInfoInstanceInsertionTimeFilter (SqlExpr (Database.Esqueleto.Value (UTCTime)) -> SqlExpr (Database.Esqueleto.Value Bool)) | HasInsertInfoInstanceInsertedByUserIdFilter (SqlExpr (Database.Esqueleto.Value (Maybe UserId)) -> SqlExpr (Database.Esqueleto.Value Bool)) lookupHasInsertInfoInstance :: forall (m :: * -> *). (MonadIO m) => HasInsertInfoInstanceId -> SqlPersistT m (Maybe HasInsertInfoInstance) lookupHasInsertInfoInstance k = case k of HasInsertInfoInstanceFileId key -> runMaybeT $ do val <- MaybeT $ get key return $ HasInsertInfoInstanceFile $ Entity key val HasInsertInfoInstanceReceiptId key -> runMaybeT $ do val <- MaybeT $ get key return $ HasInsertInfoInstanceReceipt $ Entity key val selectHasInsertInfo :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[HasInsertInfoInstanceFilterType]] -> SqlPersistT m [HasInsertInfoInstance] selectHasInsertInfo filters = do result_File <- select $ from $ \e -> do let _ = e ^. FileId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of HasInsertInfoInstanceInsertionTimeFilter op -> op $ e ^. FileInsertionTime HasInsertInfoInstanceInsertedByUserIdFilter op -> op $ e ^. FileInsertedByUserId ) exprs return e result_Receipt <- select $ from $ \e -> do let _ = e ^. ReceiptId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of HasInsertInfoInstanceInsertionTimeFilter op -> op $ e ^. ReceiptInsertionTime HasInsertInfoInstanceInsertedByUserIdFilter op -> op $ e ^. ReceiptInsertedByUserId ) exprs return e return $ concat [ map HasInsertInfoInstanceFile result_File , map HasInsertInfoInstanceReceipt result_Receipt ] data HasInsertInfoInstanceUpdateType = HasInsertInfoInstanceUpdateInsertionTime (SqlExpr (Database.Esqueleto.Value (UTCTime))) | HasInsertInfoInstanceUpdateInsertedByUserId (SqlExpr (Database.Esqueleto.Value (Maybe UserId))) updateHasInsertInfo :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[HasInsertInfoInstanceFilterType]] -> [HasInsertInfoInstanceUpdateType] -> SqlPersistT m () updateHasInsertInfo filters updates = do update $ \e -> do let _ = e ^. FileId set e $ map (\u -> case u of HasInsertInfoInstanceUpdateInsertionTime v -> FileInsertionTime =. v HasInsertInfoInstanceUpdateInsertedByUserId v -> FileInsertedByUserId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of HasInsertInfoInstanceInsertionTimeFilter op -> op $ e ^. FileInsertionTime HasInsertInfoInstanceInsertedByUserIdFilter op -> op $ e ^. FileInsertedByUserId ) exprs update $ \e -> do let _ = e ^. ReceiptId set e $ map (\u -> case u of HasInsertInfoInstanceUpdateInsertionTime v -> ReceiptInsertionTime =. v HasInsertInfoInstanceUpdateInsertedByUserId v -> ReceiptInsertedByUserId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of HasInsertInfoInstanceInsertionTimeFilter op -> op $ e ^. ReceiptInsertionTime HasInsertInfoInstanceInsertedByUserIdFilter op -> op $ e ^. ReceiptInsertedByUserId ) exprs return () class Restricted a where instance Restricted File where instance Restricted UserGroup where instance Restricted User where instance Restricted Receipt where instance Restricted ProcessPeriod where data RestrictedInstance = RestrictedInstanceFile (Entity File) | RestrictedInstanceUserGroup (Entity UserGroup) | RestrictedInstanceUser (Entity User) | RestrictedInstanceReceipt (Entity Receipt) | RestrictedInstanceProcessPeriod (Entity ProcessPeriod) data RestrictedInstanceId = RestrictedInstanceFileId FileId | RestrictedInstanceUserGroupId UserGroupId | RestrictedInstanceUserId UserId | RestrictedInstanceReceiptId ReceiptId | RestrictedInstanceProcessPeriodId ProcessPeriodId deriving (Eq, Ord) reflectRestrictedInstanceId :: RestrictedInstanceId -> (Text, Int64) reflectRestrictedInstanceId x = case x of RestrictedInstanceFileId key -> ("File", fromSqlKey key) RestrictedInstanceUserGroupId key -> ("UserGroup", fromSqlKey key) RestrictedInstanceUserId key -> ("User", fromSqlKey key) RestrictedInstanceReceiptId key -> ("Receipt", fromSqlKey key) RestrictedInstanceProcessPeriodId key -> ("ProcessPeriod", fromSqlKey key) instance Restricted RestrictedInstance where lookupRestrictedInstance :: forall (m :: * -> *). (MonadIO m) => RestrictedInstanceId -> SqlPersistT m (Maybe RestrictedInstance) lookupRestrictedInstance k = case k of RestrictedInstanceFileId key -> runMaybeT $ do val <- MaybeT $ get key return $ RestrictedInstanceFile $ Entity key val RestrictedInstanceUserGroupId key -> runMaybeT $ do val <- MaybeT $ get key return $ RestrictedInstanceUserGroup $ Entity key val RestrictedInstanceUserId key -> runMaybeT $ do val <- MaybeT $ get key return $ RestrictedInstanceUser $ Entity key val RestrictedInstanceReceiptId key -> runMaybeT $ do val <- MaybeT $ get key return $ RestrictedInstanceReceipt $ Entity key val RestrictedInstanceProcessPeriodId key -> runMaybeT $ do val <- MaybeT $ get key return $ RestrictedInstanceProcessPeriod $ Entity key val selectRestricted :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => SqlPersistT m [RestrictedInstance] selectRestricted = do result_File <- select $ from $ \e -> do let _ = e ^. FileId return e result_UserGroup <- select $ from $ \e -> do let _ = e ^. UserGroupId return e result_User <- select $ from $ \e -> do let _ = e ^. UserId return e result_Receipt <- select $ from $ \e -> do let _ = e ^. ReceiptId return e result_ProcessPeriod <- select $ from $ \e -> do let _ = e ^. ProcessPeriodId return e return $ concat [ map RestrictedInstanceFile result_File , map RestrictedInstanceUserGroup result_UserGroup , map RestrictedInstanceUser result_User , map RestrictedInstanceReceipt result_Receipt , map RestrictedInstanceProcessPeriod result_ProcessPeriod ] class Versioned a where versionedActiveId :: a -> Maybe VersionedInstanceId versionedActiveStartTime :: a -> Maybe UTCTime versionedActiveEndTime :: a -> Maybe UTCTime data VersionedInstanceFieldName = VersionedActiveId | VersionedActiveStartTime | VersionedActiveEndTime instance Versioned File where versionedActiveId = (fmap VersionedInstanceFileId) . fileActiveId versionedActiveStartTime = fileActiveStartTime versionedActiveEndTime = fileActiveEndTime instance Versioned UserGroup where versionedActiveId = (fmap VersionedInstanceUserGroupId) . userGroupActiveId versionedActiveStartTime = userGroupActiveStartTime versionedActiveEndTime = userGroupActiveEndTime instance Versioned User where versionedActiveId = (fmap VersionedInstanceUserId) . userActiveId versionedActiveStartTime = userActiveStartTime versionedActiveEndTime = userActiveEndTime instance Versioned Receipt where versionedActiveId = (fmap VersionedInstanceReceiptId) . receiptActiveId versionedActiveStartTime = receiptActiveStartTime versionedActiveEndTime = receiptActiveEndTime data VersionedInstance = VersionedInstanceFile (Entity File) | VersionedInstanceUserGroup (Entity UserGroup) | VersionedInstanceUser (Entity User) | VersionedInstanceReceipt (Entity Receipt) data VersionedInstanceId = VersionedInstanceFileId FileId | VersionedInstanceUserGroupId UserGroupId | VersionedInstanceUserId UserId | VersionedInstanceReceiptId ReceiptId deriving (Eq, Ord) reflectVersionedInstanceId :: VersionedInstanceId -> (Text, Int64) reflectVersionedInstanceId x = case x of VersionedInstanceFileId key -> ("File", fromSqlKey key) VersionedInstanceUserGroupId key -> ("UserGroup", fromSqlKey key) VersionedInstanceUserId key -> ("User", fromSqlKey key) VersionedInstanceReceiptId key -> ("Receipt", fromSqlKey key) instance Versioned VersionedInstance where versionedActiveId x = case x of VersionedInstanceFile (Entity _ e) -> (fmap VersionedInstanceFileId) $ fileActiveId e VersionedInstanceUserGroup (Entity _ e) -> (fmap VersionedInstanceUserGroupId) $ userGroupActiveId e VersionedInstanceUser (Entity _ e) -> (fmap VersionedInstanceUserId) $ userActiveId e VersionedInstanceReceipt (Entity _ e) -> (fmap VersionedInstanceReceiptId) $ receiptActiveId e versionedActiveStartTime x = case x of VersionedInstanceFile (Entity _ e) -> fileActiveStartTime e VersionedInstanceUserGroup (Entity _ e) -> userGroupActiveStartTime e VersionedInstanceUser (Entity _ e) -> userActiveStartTime e VersionedInstanceReceipt (Entity _ e) -> receiptActiveStartTime e versionedActiveEndTime x = case x of VersionedInstanceFile (Entity _ e) -> fileActiveEndTime e VersionedInstanceUserGroup (Entity _ e) -> userGroupActiveEndTime e VersionedInstanceUser (Entity _ e) -> userActiveEndTime e VersionedInstanceReceipt (Entity _ e) -> receiptActiveEndTime e data VersionedInstanceFilterType = VersionedInstanceActiveStartTimeFilter (SqlExpr (Database.Esqueleto.Value (Maybe UTCTime)) -> SqlExpr (Database.Esqueleto.Value Bool)) | VersionedInstanceActiveEndTimeFilter (SqlExpr (Database.Esqueleto.Value (Maybe UTCTime)) -> SqlExpr (Database.Esqueleto.Value Bool)) lookupVersionedInstance :: forall (m :: * -> *). (MonadIO m) => VersionedInstanceId -> SqlPersistT m (Maybe VersionedInstance) lookupVersionedInstance k = case k of VersionedInstanceFileId key -> runMaybeT $ do val <- MaybeT $ get key return $ VersionedInstanceFile $ Entity key val VersionedInstanceUserGroupId key -> runMaybeT $ do val <- MaybeT $ get key return $ VersionedInstanceUserGroup $ Entity key val VersionedInstanceUserId key -> runMaybeT $ do val <- MaybeT $ get key return $ VersionedInstanceUser $ Entity key val VersionedInstanceReceiptId key -> runMaybeT $ do val <- MaybeT $ get key return $ VersionedInstanceReceipt $ Entity key val selectVersioned :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[VersionedInstanceFilterType]] -> SqlPersistT m [VersionedInstance] selectVersioned filters = do result_File <- select $ from $ \e -> do let _ = e ^. FileId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. FileActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. FileActiveEndTime ) exprs return e result_UserGroup <- select $ from $ \e -> do let _ = e ^. UserGroupId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. UserGroupActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. UserGroupActiveEndTime ) exprs return e result_User <- select $ from $ \e -> do let _ = e ^. UserId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. UserActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. UserActiveEndTime ) exprs return e result_Receipt <- select $ from $ \e -> do let _ = e ^. ReceiptId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. ReceiptActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. ReceiptActiveEndTime ) exprs return e return $ concat [ map VersionedInstanceFile result_File , map VersionedInstanceUserGroup result_UserGroup , map VersionedInstanceUser result_User , map VersionedInstanceReceipt result_Receipt ] data VersionedInstanceUpdateType = VersionedInstanceUpdateActiveStartTime (SqlExpr (Database.Esqueleto.Value (Maybe UTCTime))) | VersionedInstanceUpdateActiveEndTime (SqlExpr (Database.Esqueleto.Value (Maybe UTCTime))) updateVersioned :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[VersionedInstanceFilterType]] -> [VersionedInstanceUpdateType] -> SqlPersistT m () updateVersioned filters updates = do update $ \e -> do let _ = e ^. FileId set e $ map (\u -> case u of VersionedInstanceUpdateActiveStartTime v -> FileActiveStartTime =. v VersionedInstanceUpdateActiveEndTime v -> FileActiveEndTime =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. FileActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. FileActiveEndTime ) exprs update $ \e -> do let _ = e ^. UserGroupId set e $ map (\u -> case u of VersionedInstanceUpdateActiveStartTime v -> UserGroupActiveStartTime =. v VersionedInstanceUpdateActiveEndTime v -> UserGroupActiveEndTime =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. UserGroupActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. UserGroupActiveEndTime ) exprs update $ \e -> do let _ = e ^. UserId set e $ map (\u -> case u of VersionedInstanceUpdateActiveStartTime v -> UserActiveStartTime =. v VersionedInstanceUpdateActiveEndTime v -> UserActiveEndTime =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. UserActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. UserActiveEndTime ) exprs update $ \e -> do let _ = e ^. ReceiptId set e $ map (\u -> case u of VersionedInstanceUpdateActiveStartTime v -> ReceiptActiveStartTime =. v VersionedInstanceUpdateActiveEndTime v -> ReceiptActiveEndTime =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of VersionedInstanceActiveStartTimeFilter op -> op $ e ^. ReceiptActiveStartTime VersionedInstanceActiveEndTimeFilter op -> op $ e ^. ReceiptActiveEndTime ) exprs return () class Deletable a where deletableDeletedVersionId :: a -> Maybe VersionId data DeletableInstanceFieldName = DeletableDeletedVersionId instance Deletable File where deletableDeletedVersionId = fileDeletedVersionId instance Deletable UserGroupContent where deletableDeletedVersionId = userGroupContentDeletedVersionId instance Deletable UserGroup where deletableDeletedVersionId = userGroupDeletedVersionId instance Deletable UserGroupItem where deletableDeletedVersionId = userGroupItemDeletedVersionId instance Deletable User where deletableDeletedVersionId = userDeletedVersionId instance Deletable Receipt where deletableDeletedVersionId = receiptDeletedVersionId data DeletableInstance = DeletableInstanceFile (Entity File) | DeletableInstanceUserGroupContent (Entity UserGroupContent) | DeletableInstanceUserGroup (Entity UserGroup) | DeletableInstanceUserGroupItem (Entity UserGroupItem) | DeletableInstanceUser (Entity User) | DeletableInstanceReceipt (Entity Receipt) data DeletableInstanceId = DeletableInstanceFileId FileId | DeletableInstanceUserGroupContentId UserGroupContentId | DeletableInstanceUserGroupId UserGroupId | DeletableInstanceUserGroupItemId UserGroupItemId | DeletableInstanceUserId UserId | DeletableInstanceReceiptId ReceiptId deriving (Eq, Ord) reflectDeletableInstanceId :: DeletableInstanceId -> (Text, Int64) reflectDeletableInstanceId x = case x of DeletableInstanceFileId key -> ("File", fromSqlKey key) DeletableInstanceUserGroupContentId key -> ("UserGroupContent", fromSqlKey key) DeletableInstanceUserGroupId key -> ("UserGroup", fromSqlKey key) DeletableInstanceUserGroupItemId key -> ("UserGroupItem", fromSqlKey key) DeletableInstanceUserId key -> ("User", fromSqlKey key) DeletableInstanceReceiptId key -> ("Receipt", fromSqlKey key) instance Deletable DeletableInstance where deletableDeletedVersionId x = case x of DeletableInstanceFile (Entity _ e) -> fileDeletedVersionId e DeletableInstanceUserGroupContent (Entity _ e) -> userGroupContentDeletedVersionId e DeletableInstanceUserGroup (Entity _ e) -> userGroupDeletedVersionId e DeletableInstanceUserGroupItem (Entity _ e) -> userGroupItemDeletedVersionId e DeletableInstanceUser (Entity _ e) -> userDeletedVersionId e DeletableInstanceReceipt (Entity _ e) -> receiptDeletedVersionId e data DeletableInstanceFilterType = DeletableInstanceDeletedVersionIdFilter (SqlExpr (Database.Esqueleto.Value (Maybe VersionId)) -> SqlExpr (Database.Esqueleto.Value Bool)) lookupDeletableInstance :: forall (m :: * -> *). (MonadIO m) => DeletableInstanceId -> SqlPersistT m (Maybe DeletableInstance) lookupDeletableInstance k = case k of DeletableInstanceFileId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceFile $ Entity key val DeletableInstanceUserGroupContentId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceUserGroupContent $ Entity key val DeletableInstanceUserGroupId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceUserGroup $ Entity key val DeletableInstanceUserGroupItemId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceUserGroupItem $ Entity key val DeletableInstanceUserId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceUser $ Entity key val DeletableInstanceReceiptId key -> runMaybeT $ do val <- MaybeT $ get key return $ DeletableInstanceReceipt $ Entity key val selectDeletable :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[DeletableInstanceFilterType]] -> SqlPersistT m [DeletableInstance] selectDeletable filters = do result_File <- select $ from $ \e -> do let _ = e ^. FileId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. FileDeletedVersionId ) exprs return e result_UserGroupContent <- select $ from $ \e -> do let _ = e ^. UserGroupContentId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupContentDeletedVersionId ) exprs return e result_UserGroup <- select $ from $ \e -> do let _ = e ^. UserGroupId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupDeletedVersionId ) exprs return e result_UserGroupItem <- select $ from $ \e -> do let _ = e ^. UserGroupItemId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupItemDeletedVersionId ) exprs return e result_User <- select $ from $ \e -> do let _ = e ^. UserId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserDeletedVersionId ) exprs return e result_Receipt <- select $ from $ \e -> do let _ = e ^. ReceiptId forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. ReceiptDeletedVersionId ) exprs return e return $ concat [ map DeletableInstanceFile result_File , map DeletableInstanceUserGroupContent result_UserGroupContent , map DeletableInstanceUserGroup result_UserGroup , map DeletableInstanceUserGroupItem result_UserGroupItem , map DeletableInstanceUser result_User , map DeletableInstanceReceipt result_Receipt ] data DeletableInstanceUpdateType = DeletableInstanceUpdateDeletedVersionId (SqlExpr (Database.Esqueleto.Value (Maybe VersionId))) updateDeletable :: forall (m :: * -> *). (MonadLogger m, MonadIO m, MonadThrow m, MonadBaseControl IO m) => [[DeletableInstanceFilterType]] -> [DeletableInstanceUpdateType] -> SqlPersistT m () updateDeletable filters updates = do update $ \e -> do let _ = e ^. FileId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> FileDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. FileDeletedVersionId ) exprs update $ \e -> do let _ = e ^. UserGroupContentId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> UserGroupContentDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupContentDeletedVersionId ) exprs update $ \e -> do let _ = e ^. UserGroupId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> UserGroupDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupDeletedVersionId ) exprs update $ \e -> do let _ = e ^. UserGroupItemId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> UserGroupItemDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserGroupItemDeletedVersionId ) exprs update $ \e -> do let _ = e ^. UserId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> UserDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. UserDeletedVersionId ) exprs update $ \e -> do let _ = e ^. ReceiptId set e $ map (\u -> case u of DeletableInstanceUpdateDeletedVersionId v -> ReceiptDeletedVersionId =. v ) updates forM_ filters $ \exprs -> when (not . null $ exprs) $ where_ $ foldl1 (||.) $ map (\expr -> case expr of DeletableInstanceDeletedVersionIdFilter op -> op $ e ^. ReceiptDeletedVersionId ) exprs return () userGroupContentContentId :: UserGroupContent -> Maybe (RestrictedInstanceId) userGroupContentContentId e = listToMaybe $ catMaybes [ userGroupContentFileContentId e >>= (return . RestrictedInstanceFileId) , userGroupContentUserGroupContentId e >>= (return . RestrictedInstanceUserGroupId) , userGroupContentUserContentId e >>= (return . RestrictedInstanceUserId) , userGroupContentReceiptContentId e >>= (return . RestrictedInstanceReceiptId) , userGroupContentProcessPeriodContentId e >>= (return . RestrictedInstanceProcessPeriodId) ] class UserGroupContentContentIdField e where userGroupContentContentIdField :: SqlExpr (Database.Esqueleto.Value (Maybe (Key e))) -> EntityField UserGroupContent (Maybe (Key e)) instance UserGroupContentContentIdField ProcessPeriod where userGroupContentContentIdField _ = UserGroupContentProcessPeriodContentId instance UserGroupContentContentIdField Receipt where userGroupContentContentIdField _ = UserGroupContentReceiptContentId instance UserGroupContentContentIdField User where userGroupContentContentIdField _ = UserGroupContentUserContentId instance UserGroupContentContentIdField UserGroup where userGroupContentContentIdField _ = UserGroupContentUserGroupContentId instance UserGroupContentContentIdField File where userGroupContentContentIdField _ = UserGroupContentFileContentId userGroupContentContentIdExprFromString :: Text -> SqlExpr (Entity UserGroupContent) -> Text -> Maybe Text -> Maybe (SqlExpr (E.Value Bool)) userGroupContentContentIdExprFromString "ProcessPeriod" e op vt = case vt of Just vt' -> PP.fromPathPiece vt' >>= \v -> Just $ defaultFilterOp False op (e ^. UserGroupContentProcessPeriodContentId) (val v) Nothing -> Just $ defaultFilterOp False op (e ^. UserGroupContentProcessPeriodContentId) nothing userGroupContentContentIdExprFromString "Receipt" e op vt = case vt of Just vt' -> PP.fromPathPiece vt' >>= \v -> Just $ defaultFilterOp False op (e ^. UserGroupContentReceiptContentId) (val v) Nothing -> Just $ defaultFilterOp False op (e ^. UserGroupContentReceiptContentId) nothing userGroupContentContentIdExprFromString "User" e op vt = case vt of Just vt' -> PP.fromPathPiece vt' >>= \v -> Just $ defaultFilterOp False op (e ^. UserGroupContentUserContentId) (val v) Nothing -> Just $ defaultFilterOp False op (e ^. UserGroupContentUserContentId) nothing userGroupContentContentIdExprFromString "UserGroup" e op vt = case vt of Just vt' -> PP.fromPathPiece vt' >>= \v -> Just $ defaultFilterOp False op (e ^. UserGroupContentUserGroupContentId) (val v) Nothing -> Just $ defaultFilterOp False op (e ^. UserGroupContentUserGroupContentId) nothing userGroupContentContentIdExprFromString "File" e op vt = case vt of Just vt' -> PP.fromPathPiece vt' >>= \v -> Just $ defaultFilterOp False op (e ^. UserGroupContentFileContentId) (val v) Nothing -> Just $ defaultFilterOp False op (e ^. UserGroupContentFileContentId) nothing userGroupContentContentIdExprFromString _ _ _ _ = Nothing userGroupContentContentIdExpr2FromString :: Text -> SqlExpr (Entity UserGroupContent) -> Text -> SqlExpr (Entity UserGroupContent) -> Maybe (SqlExpr (E.Value Bool)) userGroupContentContentIdExpr2FromString "ProcessPeriod" e op e2 = Just $ defaultFilterOp False op (e ^. UserGroupContentProcessPeriodContentId) (e2 ^. UserGroupContentProcessPeriodContentId) userGroupContentContentIdExpr2FromString "Receipt" e op e2 = Just $ defaultFilterOp False op (e ^. UserGroupContentReceiptContentId) (e2 ^. UserGroupContentReceiptContentId) userGroupContentContentIdExpr2FromString "User" e op e2 = Just $ defaultFilterOp False op (e ^. UserGroupContentUserContentId) (e2 ^. UserGroupContentUserContentId) userGroupContentContentIdExpr2FromString "UserGroup" e op e2 = Just $ defaultFilterOp False op (e ^. UserGroupContentUserGroupContentId) (e2 ^. UserGroupContentUserGroupContentId) userGroupContentContentIdExpr2FromString "File" e op e2 = Just $ defaultFilterOp False op (e ^. UserGroupContentFileContentId) (e2 ^. UserGroupContentFileContentId) userGroupContentContentIdExpr2FromString _ _ _ _ = Nothing #ifdef ToJSON_Day instance ToJSON Day where toJSON = toJSON . show #endif #ifdef FromJSON_Day instance FromJSON Day where parseJSON x = do s <- parseJSON x case reads s of (d, _):_ -> return d [] -> mzero #endif instance ToJSON TimeOfDay where toJSON = toJSON . show instance FromJSON TimeOfDay where parseJSON x = do s <- parseJSON x case reads s of (d, _):_ -> return d [] -> mzero instance ToJSON Checkmark where toJSON Active = A.String "Active" toJSON Inactive = A.String "Inactive" instance FromJSON Checkmark where parseJSON (A.String "Active") = return Active parseJSON (A.String "Inactive") = return Inactive parseJSON _ = mzero
tlaitinen/receipts
backend/Handler/DB/Internal.hs
gpl-3.0
48,523
0
22
12,402
12,256
6,219
6,037
-1
-1
-- Copyright (C) 2013 Michael Zuser mikezuser@gmail.com -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (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, see <http://www.gnu.org/licenses/>. -- | Tree search. module KitchenSink.Search where import KitchenSink.Combinators import Control.Parallel -- | A simple depth first search depthFirstSearch :: (a -> [a]) -- ^ successor function -> (a -> Bool) -- ^ goal test -> [a] -- ^ inital states -> Maybe a -- ^ first found goal state if any depthFirstSearch succs test = go where go [] = Nothing go (curr:rest) | test curr = Just curr | otherwise = recCurr <|> recRest where recCurr = go $ succs curr recRest = go rest -- | A simple depth first search with added parallelism parDepthFirstSearch :: Int -- ^ maximum parallel depth -> (a -> [a]) -- ^ successor function -> (a -> Bool) -- ^ goal test -> [a] -- ^ inital states -> Maybe a -- ^ first found goal state if any parDepthFirstSearch depth succs test = go depth where go 0 fringe = depthFirstSearch succs test fringe go _ [] = Nothing go depth (curr:rest) | test curr = Just curr | otherwise = recCurr `par` recRest `pseq` (recCurr <|> recRest) where recCurr = go (depth - 1) $ succs curr recRest = go depth rest
bacchanalia/KitchenSink
KitchenSink/Search.hs
gpl-3.0
2,013
0
12
599
347
190
157
27
3
module IcfpcEndo.Endo where import qualified Data.ByteString.Char8 as BS import qualified Data.Sequence as S import qualified Data.IORef as IO type Dna = BS.ByteString data DnaIndex = DnaFrom Int | DnaFromTo Int Int data PatternItem = Base Char | Skip Int | Search Dna | Open | Close deriving (Show, Read, Eq) type Pattern = S.Seq PatternItem data Endo = Endo { endoDna :: IO.IORef Dna , endoDnaIndex :: DnaIndex , endoPattern :: Pattern , endoLevel :: Int , endoDecodingAction :: DecodingAction } data DecodingAction = NoDecoding | ParsePattern | ParseTemplate | MatchReplace emptyPattern = S.empty mkEndo dna n = Endo dna (DnaFrom n) emptyPattern 0 NoDecoding toDna :: String -> Dna toDna = BS.pack emptyDna :: Dna emptyDna = BS.empty from :: Int -> DnaIndex from = DnaFrom to :: DnaIndex -> Int -> DnaIndex to (DnaFrom i) = DnaFromTo i only :: Int -> DnaIndex only i = DnaFromTo i (i + 1) (|-) :: Dna -> DnaIndex -> Dna dna |- (DnaFrom i) = BS.drop i dna dna |- (DnaFromTo i k) = BS.take (k - i) . BS.drop i $ dna checkPrefix = BS.isPrefixOf appendPatternItem = (S.<|) toPattern :: [PatternItem] -> Pattern toPattern = S.fromList
graninas/ICFPC2007
Endo/IcfpcEndo/Endo.hs
gpl-3.0
1,387
0
10
451
419
236
183
42
1
module DL3024 (tests) where import Data.Text as Text import Helpers import Test.Hspec tests :: SpecWith () tests = do let ?rulesConfig = mempty describe "DL3024 - Duplicate aliases" $ do it "warn on duplicate aliases" $ let dockerFile = [ "FROM node as foo", "RUN something", "FROM scratch as foo", "RUN something" ] in ruleCatches "DL3024" $ Text.unlines dockerFile it "don't warn on unique aliases" $ let dockerFile = [ "FROM scratch as build", "RUN foo", "FROM node as run", "RUN baz" ] in ruleCatchesNot "DL3024" $ Text.unlines dockerFile
lukasmartinelli/hadolint
test/DL3024.hs
gpl-3.0
716
0
15
262
148
76
72
-1
-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.Compute.NodeGroups.GetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the access control policy for a resource. May be empty if no such -- policy or resource exists. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.nodeGroups.getIamPolicy@. module Network.Google.Resource.Compute.NodeGroups.GetIAMPolicy ( -- * REST Resource NodeGroupsGetIAMPolicyResource -- * Creating a Request , nodeGroupsGetIAMPolicy , NodeGroupsGetIAMPolicy -- * Request Lenses , nggipProject , nggipZone , nggipResource , nggipOptionsRequestedPolicyVersion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.nodeGroups.getIamPolicy@ method which the -- 'NodeGroupsGetIAMPolicy' request conforms to. type NodeGroupsGetIAMPolicyResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "nodeGroups" :> Capture "resource" Text :> "getIamPolicy" :> QueryParam "optionsRequestedPolicyVersion" (Textual Int32) :> QueryParam "alt" AltJSON :> Get '[JSON] Policy -- | Gets the access control policy for a resource. May be empty if no such -- policy or resource exists. -- -- /See:/ 'nodeGroupsGetIAMPolicy' smart constructor. data NodeGroupsGetIAMPolicy = NodeGroupsGetIAMPolicy' { _nggipProject :: !Text , _nggipZone :: !Text , _nggipResource :: !Text , _nggipOptionsRequestedPolicyVersion :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NodeGroupsGetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nggipProject' -- -- * 'nggipZone' -- -- * 'nggipResource' -- -- * 'nggipOptionsRequestedPolicyVersion' nodeGroupsGetIAMPolicy :: Text -- ^ 'nggipProject' -> Text -- ^ 'nggipZone' -> Text -- ^ 'nggipResource' -> NodeGroupsGetIAMPolicy nodeGroupsGetIAMPolicy pNggipProject_ pNggipZone_ pNggipResource_ = NodeGroupsGetIAMPolicy' { _nggipProject = pNggipProject_ , _nggipZone = pNggipZone_ , _nggipResource = pNggipResource_ , _nggipOptionsRequestedPolicyVersion = Nothing } -- | Project ID for this request. nggipProject :: Lens' NodeGroupsGetIAMPolicy Text nggipProject = lens _nggipProject (\ s a -> s{_nggipProject = a}) -- | The name of the zone for this request. nggipZone :: Lens' NodeGroupsGetIAMPolicy Text nggipZone = lens _nggipZone (\ s a -> s{_nggipZone = a}) -- | Name or id of the resource for this request. nggipResource :: Lens' NodeGroupsGetIAMPolicy Text nggipResource = lens _nggipResource (\ s a -> s{_nggipResource = a}) -- | Requested IAM Policy version. nggipOptionsRequestedPolicyVersion :: Lens' NodeGroupsGetIAMPolicy (Maybe Int32) nggipOptionsRequestedPolicyVersion = lens _nggipOptionsRequestedPolicyVersion (\ s a -> s{_nggipOptionsRequestedPolicyVersion = a}) . mapping _Coerce instance GoogleRequest NodeGroupsGetIAMPolicy where type Rs NodeGroupsGetIAMPolicy = Policy type Scopes NodeGroupsGetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient NodeGroupsGetIAMPolicy'{..} = go _nggipProject _nggipZone _nggipResource _nggipOptionsRequestedPolicyVersion (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy NodeGroupsGetIAMPolicyResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/NodeGroups/GetIAMPolicy.hs
mpl-2.0
4,647
0
18
1,073
571
336
235
92
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.AdSenseHost.CustomChannels.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get a specific custom channel from the host AdSense account. -- -- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.customchannels.get@. module Network.Google.Resource.AdSenseHost.CustomChannels.Get ( -- * REST Resource CustomChannelsGetResource -- * Creating a Request , customChannelsGet , CustomChannelsGet -- * Request Lenses , ccgCustomChannelId , ccgAdClientId ) where import Network.Google.AdSenseHost.Types import Network.Google.Prelude -- | A resource alias for @adsensehost.customchannels.get@ method which the -- 'CustomChannelsGet' request conforms to. type CustomChannelsGetResource = "adsensehost" :> "v4.1" :> "adclients" :> Capture "adClientId" Text :> "customchannels" :> Capture "customChannelId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] CustomChannel -- | Get a specific custom channel from the host AdSense account. -- -- /See:/ 'customChannelsGet' smart constructor. data CustomChannelsGet = CustomChannelsGet' { _ccgCustomChannelId :: !Text , _ccgAdClientId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CustomChannelsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccgCustomChannelId' -- -- * 'ccgAdClientId' customChannelsGet :: Text -- ^ 'ccgCustomChannelId' -> Text -- ^ 'ccgAdClientId' -> CustomChannelsGet customChannelsGet pCcgCustomChannelId_ pCcgAdClientId_ = CustomChannelsGet' { _ccgCustomChannelId = pCcgCustomChannelId_ , _ccgAdClientId = pCcgAdClientId_ } -- | Custom channel to get. ccgCustomChannelId :: Lens' CustomChannelsGet Text ccgCustomChannelId = lens _ccgCustomChannelId (\ s a -> s{_ccgCustomChannelId = a}) -- | Ad client from which to get the custom channel. ccgAdClientId :: Lens' CustomChannelsGet Text ccgAdClientId = lens _ccgAdClientId (\ s a -> s{_ccgAdClientId = a}) instance GoogleRequest CustomChannelsGet where type Rs CustomChannelsGet = CustomChannel type Scopes CustomChannelsGet = '["https://www.googleapis.com/auth/adsensehost"] requestClient CustomChannelsGet'{..} = go _ccgAdClientId _ccgCustomChannelId (Just AltJSON) adSenseHostService where go = buildClient (Proxy :: Proxy CustomChannelsGetResource) mempty
brendanhay/gogol
gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/CustomChannels/Get.hs
mpl-2.0
3,372
0
14
752
381
229
152
66
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.CloudUserAccounts.Groups.AddMember -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds users to the specified group. -- -- /See:/ <https://cloud.google.com/compute/docs/access/user-accounts/api/latest/ Cloud User Accounts API Reference> for @clouduseraccounts.groups.addMember@. module Network.Google.Resource.CloudUserAccounts.Groups.AddMember ( -- * REST Resource GroupsAddMemberResource -- * Creating a Request , groupsAddMember , GroupsAddMember -- * Request Lenses , gamProject , gamPayload , gamGroupName ) where import Network.Google.Prelude import Network.Google.UserAccounts.Types -- | A resource alias for @clouduseraccounts.groups.addMember@ method which the -- 'GroupsAddMember' request conforms to. type GroupsAddMemberResource = "clouduseraccounts" :> "beta" :> "projects" :> Capture "project" Text :> "global" :> "groups" :> Capture "groupName" Text :> "addMember" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GroupsAddMemberRequest :> Post '[JSON] Operation -- | Adds users to the specified group. -- -- /See:/ 'groupsAddMember' smart constructor. data GroupsAddMember = GroupsAddMember' { _gamProject :: !Text , _gamPayload :: !GroupsAddMemberRequest , _gamGroupName :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'GroupsAddMember' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gamProject' -- -- * 'gamPayload' -- -- * 'gamGroupName' groupsAddMember :: Text -- ^ 'gamProject' -> GroupsAddMemberRequest -- ^ 'gamPayload' -> Text -- ^ 'gamGroupName' -> GroupsAddMember groupsAddMember pGamProject_ pGamPayload_ pGamGroupName_ = GroupsAddMember' { _gamProject = pGamProject_ , _gamPayload = pGamPayload_ , _gamGroupName = pGamGroupName_ } -- | Project ID for this request. gamProject :: Lens' GroupsAddMember Text gamProject = lens _gamProject (\ s a -> s{_gamProject = a}) -- | Multipart request metadata. gamPayload :: Lens' GroupsAddMember GroupsAddMemberRequest gamPayload = lens _gamPayload (\ s a -> s{_gamPayload = a}) -- | Name of the group for this request. gamGroupName :: Lens' GroupsAddMember Text gamGroupName = lens _gamGroupName (\ s a -> s{_gamGroupName = a}) instance GoogleRequest GroupsAddMember where type Rs GroupsAddMember = Operation type Scopes GroupsAddMember = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud.useraccounts"] requestClient GroupsAddMember'{..} = go _gamProject _gamGroupName (Just AltJSON) _gamPayload userAccountsService where go = buildClient (Proxy :: Proxy GroupsAddMemberResource) mempty
rueshyna/gogol
gogol-useraccounts/gen/Network/Google/Resource/CloudUserAccounts/Groups/AddMember.hs
mpl-2.0
3,776
0
17
921
472
281
191
77
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.Plus -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Builds on top of the Google+ platform. -- -- /See:/ <https://developers.google.com/+/api/ Google+ API Reference> module Network.Google.Plus ( -- * Service Configuration plusService -- * OAuth Scopes , userInfoProFileScope , plusLoginScope , userInfoEmailScope , plusMeScope -- * API Declaration , PlusAPI -- * Resources -- ** plus.activities.get , module Network.Google.Resource.Plus.Activities.Get -- ** plus.activities.list , module Network.Google.Resource.Plus.Activities.List -- ** plus.activities.search , module Network.Google.Resource.Plus.Activities.Search -- ** plus.comments.get , module Network.Google.Resource.Plus.Comments.Get -- ** plus.comments.list , module Network.Google.Resource.Plus.Comments.List -- ** plus.people.get , module Network.Google.Resource.Plus.People.Get -- ** plus.people.list , module Network.Google.Resource.Plus.People.List -- ** plus.people.listByActivity , module Network.Google.Resource.Plus.People.ListByActivity -- ** plus.people.search , module Network.Google.Resource.Plus.People.Search -- * Types -- ** ActivityProvider , ActivityProvider , activityProvider , apTitle -- ** ActivityObjectAttachmentsItemEmbed , ActivityObjectAttachmentsItemEmbed , activityObjectAttachmentsItemEmbed , aoaieURL , aoaieType -- ** CommentPlusoners , CommentPlusoners , commentPlusoners , cpTotalItems -- ** CommentActorClientSpecificActorInfo , CommentActorClientSpecificActorInfo , commentActorClientSpecificActorInfo , cacsaiYouTubeActorInfo -- ** ActivityObjectActorClientSpecificActorInfoYouTubeActorInfo , ActivityObjectActorClientSpecificActorInfoYouTubeActorInfo , activityObjectActorClientSpecificActorInfoYouTubeActorInfo , aoacsaiytaiChannelId -- ** ActivityObjectPlusoners , ActivityObjectPlusoners , activityObjectPlusoners , aopTotalItems , aopSelfLink -- ** PersonEmailsItem , PersonEmailsItem , personEmailsItem , peiValue , peiType -- ** CommentActorImage , CommentActorImage , commentActorImage , caiURL -- ** ActivityObjectAttachmentsItemThumbnailsItemImage , ActivityObjectAttachmentsItemThumbnailsItemImage , activityObjectAttachmentsItemThumbnailsItemImage , aoaitiiHeight , aoaitiiURL , aoaitiiWidth , aoaitiiType -- ** PlacePosition , PlacePosition , placePosition , ppLatitude , ppLongitude -- ** PersonPlacesLivedItem , PersonPlacesLivedItem , personPlacesLivedItem , ppliValue , ppliPrimary -- ** ActivityActorClientSpecificActorInfo , ActivityActorClientSpecificActorInfo , activityActorClientSpecificActorInfo , aacsaiYouTubeActorInfo -- ** Person , Person , person , pCurrentLocation , pAgeRange , pEtag , pImage , pBraggingRights , pPlacesLived , pPlusOneCount , pObjectType , pCover , pKind , pRelationshipStatus , pURLs , pDomain , pURL , pVerified , pBirthday , pIsPlusUser , pTagline , pGender , pName , pEmails , pOccupation , pSkills , pLanguage , pAboutMe , pDisplayName , pId , pNickname , pOrganizations , pCircledByCount -- ** ActivityObjectAttachmentsItemImage , ActivityObjectAttachmentsItemImage , activityObjectAttachmentsItemImage , aoaiiHeight , aoaiiURL , aoaiiWidth , aoaiiType -- ** CommentActor , CommentActor , commentActor , caClientSpecificActorInfo , caImage , caURL , caDisplayName , caId , caVerification -- ** ActivityObject , ActivityObject , activityObject , aoPlusoners , aoAttachments , aoObjectType , aoOriginalContent , aoURL , aoActor , aoContent , aoReplies , aoId , aoResharers -- ** ActivityObjectActor , ActivityObjectActor , activityObjectActor , aoaClientSpecificActorInfo , aoaImage , aoaURL , aoaDisplayName , aoaId , aoaVerification -- ** ActivityObjectAttachmentsItemFullImage , ActivityObjectAttachmentsItemFullImage , activityObjectAttachmentsItemFullImage , aoaifiHeight , aoaifiURL , aoaifiWidth , aoaifiType -- ** PeopleListByActivityCollection , PeopleListByActivityCollection (..) -- ** ActivityActorImage , ActivityActorImage , activityActorImage , aaiURL -- ** PeopleFeed , PeopleFeed , peopleFeed , pfTotalItems , pfEtag , pfNextPageToken , pfKind , pfItems , pfSelfLink , pfTitle -- ** PersonCoverCoverPhoto , PersonCoverCoverPhoto , personCoverCoverPhoto , pccpHeight , pccpURL , pccpWidth -- ** PersonAgeRange , PersonAgeRange , personAgeRange , parMax , parMin -- ** ActivityObjectActorImage , ActivityObjectActorImage , activityObjectActorImage , aoaiURL -- ** CommentActorClientSpecificActorInfoYouTubeActorInfo , CommentActorClientSpecificActorInfoYouTubeActorInfo , commentActorClientSpecificActorInfoYouTubeActorInfo , cacsaiytaiChannelId -- ** PeopleListOrderBy , PeopleListOrderBy (..) -- ** ActivityObjectReplies , ActivityObjectReplies , activityObjectReplies , aorTotalItems , aorSelfLink -- ** ActivitiesListCollection , ActivitiesListCollection (..) -- ** ActivityActorVerification , ActivityActorVerification , activityActorVerification , aavAdHocVerified -- ** ActivityObjectActorClientSpecificActorInfo , ActivityObjectActorClientSpecificActorInfo , activityObjectActorClientSpecificActorInfo , aoacsaiYouTubeActorInfo -- ** PeopleListCollection , PeopleListCollection (..) -- ** ActivityObjectAttachmentsItem , ActivityObjectAttachmentsItem , activityObjectAttachmentsItem , aFullImage , aImage , aObjectType , aURL , aEmbed , aContent , aThumbnails , aDisplayName , aId -- ** ActivityFeed , ActivityFeed , activityFeed , afEtag , afNextPageToken , afNextLink , afKind , afItems , afSelfLink , afId , afUpdated , afTitle -- ** ActivityObjectActorVerification , ActivityObjectActorVerification , activityObjectActorVerification , aoavAdHocVerified -- ** PersonName , PersonName , personName , pnGivenName , pnMiddleName , pnFormatted , pnHonorificPrefix , pnFamilyName , pnHonorificSuffix -- ** PersonImage , PersonImage , personImage , piURL , piIsDefault -- ** ActivityActorClientSpecificActorInfoYouTubeActorInfo , ActivityActorClientSpecificActorInfoYouTubeActorInfo , activityActorClientSpecificActorInfoYouTubeActorInfo , aacsaiytaiChannelId -- ** PlusACLentryResource , PlusACLentryResource , plusACLentryResource , parDisplayName , parId , parType -- ** Activity , Activity , activity , actAccess , actPlaceName , actEtag , actAnnotation , actLocation , actGeocode , actKind , actRadius , actPublished , actURL , actActor , actAddress , actObject , actId , actUpdated , actTitle , actVerb , actCrosspostSource , actPlaceId , actProvider -- ** PlaceAddress , PlaceAddress , placeAddress , paFormatted -- ** ActivityObjectAttachmentsItemThumbnailsItem , ActivityObjectAttachmentsItemThumbnailsItem , activityObjectAttachmentsItemThumbnailsItem , aoaitiImage , aoaitiURL , aoaitiDescription -- ** PersonCover , PersonCover , personCover , pcLayout , pcCoverInfo , pcCoverPhoto -- ** CommentInReplyToItem , CommentInReplyToItem , commentInReplyToItem , cirtiURL , cirtiId -- ** PersonOrganizationsItem , PersonOrganizationsItem , personOrganizationsItem , poiDePartment , poiLocation , poiEndDate , poiPrimary , poiStartDate , poiName , poiTitle , poiType , poiDescription -- ** PersonURLsItem , PersonURLsItem , personURLsItem , puiValue , puiType , puiLabel -- ** ActivitiesSearchOrderBy , ActivitiesSearchOrderBy (..) -- ** PersonCoverCoverInfo , PersonCoverCoverInfo , personCoverCoverInfo , pcciTopImageOffSet , pcciLeftImageOffSet -- ** ActivityObjectResharers , ActivityObjectResharers , activityObjectResharers , aTotalItems , aSelfLink -- ** Comment , Comment , comment , cEtag , cPlusoners , cKind , cPublished , cActor , cSelfLink , cObject , cId , cUpdated , cVerb , cInReplyTo -- ** Place , Place , place , plaKind , plaAddress , plaDisplayName , plaId , plaPosition -- ** ACL , ACL , acl , aKind , aItems , aDescription -- ** ActivityActor , ActivityActor , activityActor , aaClientSpecificActorInfo , aaImage , aaURL , aaName , aaDisplayName , aaId , aaVerification -- ** CommentsListSortOrder , CommentsListSortOrder (..) -- ** CommentObject , CommentObject , commentObject , coObjectType , coOriginalContent , coContent -- ** CommentFeed , CommentFeed , commentFeed , cfEtag , cfNextPageToken , cfNextLink , cfKind , cfItems , cfId , cfUpdated , cfTitle -- ** CommentActorVerification , CommentActorVerification , commentActorVerification , cavAdHocVerified -- ** ActivityActorName , ActivityActorName , activityActorName , aanGivenName , aanFamilyName ) where import Network.Google.Plus.Types import Network.Google.Prelude import Network.Google.Resource.Plus.Activities.Get import Network.Google.Resource.Plus.Activities.List import Network.Google.Resource.Plus.Activities.Search import Network.Google.Resource.Plus.Comments.Get import Network.Google.Resource.Plus.Comments.List import Network.Google.Resource.Plus.People.Get import Network.Google.Resource.Plus.People.List import Network.Google.Resource.Plus.People.ListByActivity import Network.Google.Resource.Plus.People.Search {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Google+ API service. type PlusAPI = ActivitiesListResource :<|> ActivitiesGetResource :<|> ActivitiesSearchResource :<|> PeopleListResource :<|> PeopleGetResource :<|> PeopleListByActivityResource :<|> PeopleSearchResource :<|> CommentsListResource :<|> CommentsGetResource
rueshyna/gogol
gogol-plus/gen/Network/Google/Plus.hs
mpl-2.0
11,465
0
12
2,960
1,331
935
396
365
0
{-# LANGUAGE OverloadedStrings, OverloadedLabels #-} module Main (main) where import Data.Colour.RGBSpace as Colour import Data.IORef import Data.Text ( Text , pack ) import Data.Text.IO as TextIO ( readFile ) import Data.Version ( showVersion ) import Control.Exception import Control.Monad import Options.Applicative import qualified GI.Gtk as Gtk import Data.GI.Base ( get , new , on , set , AttrOp((:=)) ) import Data.GI.Gtk.Threading ( postGUIASync ) import GI.Cairo.Render.Connector ( renderWithContext ) import qualified GI.Cairo.Render as Cairo import GI.Gdk.Flags ( EventMask ( EventMaskButtonPressMask , EventMaskPointerMotionMask ) ) import GI.Gdk.Structs ( RGBA , newZeroRGBA ) import GI.GdkPixbuf.Objects.Pixbuf ( Pixbuf , pixbufNewFromFile ) import Paths_missile ( version ) import Async import Field import Game import Rendering import Cli data MainWindow = MainWindow { mwWindow :: Gtk.Window , mwNewImageMenuItem :: Gtk.ImageMenuItem , mwOpenImageMenuItem :: Gtk.ImageMenuItem , mwSaveImageMenuItem :: Gtk.ImageMenuItem , mwExportAsSvgMenuItem :: Gtk.MenuItem , mwExitImageMenuItem :: Gtk.ImageMenuItem , mwUndoImageMenuItem :: Gtk.ImageMenuItem , mwPreferencesImageMenuItem :: Gtk.ImageMenuItem , mwAboutImageMenuItem :: Gtk.ImageMenuItem , mwDrawingArea :: Gtk.DrawingArea , mwCoordLabel :: Gtk.Label } data PreferencesDialog = PreferencesDialog { pdDialog :: Gtk.Dialog , pdRedColorButton :: Gtk.ColorButton , pdBlackColorButton :: Gtk.ColorButton , pdBackgroundColorButton :: Gtk.ColorButton , pdGridColorButton :: Gtk.ColorButton , pdFillingAlphaSpinButton :: Gtk.SpinButton , pdFullFillCheckButton :: Gtk.CheckButton , pdGridThicknessSpinButton :: Gtk.SpinButton , pdPointRadiusSpinButton :: Gtk.SpinButton , pdHReflectionCheckButton :: Gtk.CheckButton , pdVReflectionCheckButton :: Gtk.CheckButton } rgbToGtkRgba :: RGB Double -> IO RGBA rgbToGtkRgba (RGB r g b) = do rgba <- newZeroRGBA rgba `set` [ #red := r , #green := g , #blue := b , #alpha := 1 ] return rgba gtkRgbaToRgb :: RGBA -> IO (RGB Double) gtkRgbaToRgb rgba = do r <- rgba `get` #red g <- rgba `get` #green b <- rgba `get` #blue return $ RGB r g b getSettings :: DrawSettings -> PreferencesDialog -> IO DrawSettings getSettings startSettings preferencesDialog = do curRedColor <- pdRedColorButton preferencesDialog `get` #rgba >>= maybe (return $ dsRedColor startSettings) gtkRgbaToRgb curBlackColor <- pdBlackColorButton preferencesDialog `get` #rgba >>= maybe (return $ dsBlackColor startSettings) gtkRgbaToRgb curBackgroundColor <- pdBackgroundColorButton preferencesDialog `get` #rgba >>= maybe (return $ dsBackgroundColor startSettings) gtkRgbaToRgb curGridColor <- pdGridColorButton preferencesDialog `get` #rgba >>= maybe (return $ dsGridColor startSettings) gtkRgbaToRgb curFillingAlpha <- pdFillingAlphaSpinButton preferencesDialog `get` #value curFullFill <- pdFullFillCheckButton preferencesDialog `get` #active curGridThickness <- round <$> pdGridThicknessSpinButton preferencesDialog `get` #value curPointRadius <- pdPointRadiusSpinButton preferencesDialog `get` #value curHorizontalReflection <- pdHReflectionCheckButton preferencesDialog `get` #active curVerticalReflection <- pdVReflectionCheckButton preferencesDialog `get` #active return DrawSettings { dsHReflection = curHorizontalReflection , dsVReflection = curVerticalReflection , dsGridThickness = curGridThickness , dsGridColor = curGridColor , dsBackgroundColor = curBackgroundColor , dsRedColor = curRedColor , dsBlackColor = curBlackColor , dsPointRadius = curPointRadius , dsFillingAlpha = curFillingAlpha , dsFullFill = curFullFill } preferencesDialogNew :: MainWindow -> DrawSettings -> IO PreferencesDialog preferencesDialogNew mainWindow startSettings = do applyButton <- new Gtk.Button [ #label := "_Apply" , #useUnderline := True ] okButton <- new Gtk.Button [ #label := "_Ok" , #useUnderline := True ] cancelButton <- new Gtk.Button [ #label := "_Cancel" , #useUnderline := True ] redColorLabel <- new Gtk.Label [ #label := "Red's color" ] redColor <- rgbToGtkRgba $ dsRedColor startSettings redColorButton <- new Gtk.ColorButton [ #rgba := redColor ] blackColorLabel <- new Gtk.Label [ #label := "Black's color" ] blackColor <- rgbToGtkRgba $ dsBlackColor startSettings blackColorButton <- new Gtk.ColorButton [ #rgba := blackColor ] backgroundColorLabel <- new Gtk.Label [ #label := "Background color" ] backgroundColor <- rgbToGtkRgba $ dsBackgroundColor startSettings backgroundColorButton <- new Gtk.ColorButton [ #rgba := backgroundColor ] gridColorLabel <- new Gtk.Label [ #label := "Grid color" ] gridColor <- rgbToGtkRgba $ dsGridColor startSettings gridColorButton <- new Gtk.ColorButton [ #rgba := gridColor ] fillingAlphaLabel <- new Gtk.Label [ #label := "Filling alpha" ] fillingAlphaAdjustment <- new Gtk.Adjustment [ #lower := 0 , #stepIncrement := 0.01 , #upper := 1 , #value := dsFillingAlpha startSettings ] fillingAlphaSpinButton <- new Gtk.SpinButton [ #adjustment := fillingAlphaAdjustment , #digits := 2 ] fullFillCheckButton <- new Gtk.CheckButton [ #active := dsFullFill startSettings , #label := "Full fill" ] gridThicknessLabel <- new Gtk.Label [ #label := "Grid thickness" ] gridThicknessAdjustment <- new Gtk.Adjustment [ #lower := 1 , #stepIncrement := 1 , #upper := 5 , #value := fromIntegral $ dsGridThickness startSettings ] gridThicknessSpinButton <- new Gtk.SpinButton [ #adjustment := gridThicknessAdjustment ] pointRadiusLabel <- new Gtk.Label [ #label := "Point radius" ] pointRadiusAdjustment <- new Gtk.Adjustment [ #lower := 0.5 , #stepIncrement := 0.1 , #upper := 2 , #value := dsPointRadius startSettings ] pointRadiusSpinButton <- new Gtk.SpinButton [ #adjustment := pointRadiusAdjustment , #digits := 1 ] hReflectionCheckButton <- new Gtk.CheckButton [ #active := dsHReflection startSettings , #label := "Horizontal reflection" ] vReflectionCheckButton <- new Gtk.CheckButton [ #active := dsVReflection startSettings , #label := "Vertical reflection" ] grid <- new Gtk.Grid [] #attach grid redColorLabel 0 0 1 1 #attach grid redColorButton 1 0 1 1 #attach grid blackColorLabel 2 0 1 1 #attach grid blackColorButton 3 0 1 1 #attach grid backgroundColorLabel 0 1 1 1 #attach grid backgroundColorButton 1 1 1 1 #attach grid gridColorLabel 2 1 1 1 #attach grid gridColorButton 3 1 1 1 #attach grid fillingAlphaLabel 0 2 1 1 #attach grid fillingAlphaSpinButton 1 2 1 1 #attach grid fullFillCheckButton 2 2 2 1 #attach grid gridThicknessLabel 0 3 1 1 #attach grid gridThicknessSpinButton 1 3 1 1 #attach grid pointRadiusLabel 2 3 1 1 #attach grid pointRadiusSpinButton 3 3 1 1 #attach grid hReflectionCheckButton 0 4 2 1 #attach grid vReflectionCheckButton 2 4 2 1 frame <- new Gtk.Frame [ #label := "Draw settings" ] #add frame grid preferencesDialog <- new Gtk.Dialog [ #modal := True , #title := "Draw settings" , #transientFor := mwWindow mainWindow ] #addActionWidget preferencesDialog applyButton $ (fromIntegral . fromEnum) Gtk.ResponseTypeApply #addActionWidget preferencesDialog okButton $ (fromIntegral . fromEnum) Gtk.ResponseTypeOk #addActionWidget preferencesDialog cancelButton $ (fromIntegral . fromEnum) Gtk.ResponseTypeCancel preferencesDialogContent <- #getContentArea preferencesDialog #add preferencesDialogContent frame return PreferencesDialog { pdDialog = preferencesDialog , pdRedColorButton = redColorButton , pdBlackColorButton = blackColorButton , pdBackgroundColorButton = backgroundColorButton , pdGridColorButton = gridColorButton , pdFillingAlphaSpinButton = fillingAlphaSpinButton , pdFullFillCheckButton = fullFillCheckButton , pdGridThicknessSpinButton = gridThicknessSpinButton , pdPointRadiusSpinButton = pointRadiusSpinButton , pdHReflectionCheckButton = hReflectionCheckButton , pdVReflectionCheckButton = vReflectionCheckButton } runPreferencesDialog :: DrawSettings -> PreferencesDialog -> (DrawSettings -> IO ()) -> IO () runPreferencesDialog startSettings preferencesDialog f = do #showAll $ pdDialog preferencesDialog response <- fmap (toEnum . fromIntegral) $ #run $ pdDialog preferencesDialog let apply = getSettings startSettings preferencesDialog >>= f destroy = #destroy $ pdDialog preferencesDialog continue = runPreferencesDialog startSettings preferencesDialog f case response of Gtk.ResponseTypeCancel -> destroy Gtk.ResponseTypeDeleteEvent -> destroy Gtk.ResponseTypeApply -> apply >> continue Gtk.ResponseTypeOk -> apply >> destroy _ -> error $ "runPreferencesDialog: unexpected response: " ++ show response mainWindowNew :: Pixbuf -> IO MainWindow mainWindowNew logo = do newImage <- new Gtk.Image [ #iconName := "document-new" ] newImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_New" , #useUnderline := True , #image := newImage ] openImage <- new Gtk.Image [ #iconName := "document-open" ] openImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_Open" , #useUnderline := True , #image := openImage ] saveImage <- new Gtk.Image [ #iconName := "document-save" ] saveImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_Save" , #useUnderline := True , #image := saveImage ] exportAsSvgMenuItem <- new Gtk.MenuItem [ #label := "_Export as SVG" , #useUnderline := True ] fileSeparatorMenuItem <- new Gtk.SeparatorMenuItem [] exitImage <- new Gtk.Image [ #iconName := "application-exit" ] exitImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_Exit" , #useUnderline := True , #image := exitImage ] fileMenu <- new Gtk.Menu [] #add fileMenu newImageMenuItem #add fileMenu openImageMenuItem #add fileMenu saveImageMenuItem #add fileMenu exportAsSvgMenuItem #add fileMenu fileSeparatorMenuItem #add fileMenu exitImageMenuItem fileMenuItem <- new Gtk.MenuItem [ #label := "_File" , #submenu := fileMenu , #useUnderline := True ] undoImage <- new Gtk.Image [ #iconName := "edit-undo" ] undoImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_Undo" , #useUnderline := True , #image := undoImage ] editSeparatorMenuItem <- new Gtk.SeparatorMenuItem [] preferencesImage <- new Gtk.Image [ #iconName := "document-properties" ] preferencesImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_Preferences" , #useUnderline := True , #image := preferencesImage ] editMenu <- new Gtk.Menu [] #add editMenu undoImageMenuItem #add editMenu editSeparatorMenuItem #add editMenu preferencesImageMenuItem editMenuItem <- new Gtk.MenuItem [ #label := "_Edit" , #submenu := editMenu , #useUnderline := True ] aboutImage <- new Gtk.Image [ #iconName := "help-about" ] aboutImageMenuItem <- new Gtk.ImageMenuItem [ #label := "_About" , #useUnderline := True , #image := aboutImage ] helpMenu <- new Gtk.Menu [] #add helpMenu aboutImageMenuItem helpMenuItem <- new Gtk.MenuItem [ #label := "_Help" , #submenu := helpMenu , #useUnderline := True ] menuBar <- new Gtk.MenuBar [] #add menuBar fileMenuItem #add menuBar editMenuItem #add menuBar helpMenuItem drawingArea <- new Gtk.DrawingArea [] #setHexpand drawingArea True #setVexpand drawingArea True #addEvents drawingArea [ EventMaskButtonPressMask , EventMaskPointerMotionMask ] coordLabel <- new Gtk.Label [] grid <- new Gtk.Grid [] #attach grid drawingArea 0 0 1 1 #attach grid coordLabel 0 1 1 1 box <- new Gtk.Box [ #orientation := Gtk.OrientationVertical ] #add box menuBar #add box grid #setChildPacking box grid True True 0 Gtk.PackTypeStart mainWindow <- new Gtk.Window [ #child := box , #defaultWidth := 800 , #defaultHeight := 600 , #icon := logo , #title := "Missile" ] return MainWindow { mwWindow = mainWindow , mwNewImageMenuItem = newImageMenuItem , mwOpenImageMenuItem = openImageMenuItem , mwSaveImageMenuItem = saveImageMenuItem , mwExportAsSvgMenuItem = exportAsSvgMenuItem , mwExitImageMenuItem = exitImageMenuItem , mwUndoImageMenuItem = undoImageMenuItem , mwPreferencesImageMenuItem = preferencesImageMenuItem , mwAboutImageMenuItem = aboutImageMenuItem , mwDrawingArea = drawingArea , mwCoordLabel = coordLabel } withPos :: Gtk.DrawingArea -> Field -> DrawSettings -> Double -> Double -> (Pos -> IO ()) -> IO () withPos drawingArea field drawSettings x y f = do width <- fromIntegral <$> #getAllocatedWidth drawingArea height <- fromIntegral <$> #getAllocatedHeight drawingArea let fieldWidth' = fieldWidth field fieldHeight' = fieldHeight field hReflection' = dsHReflection drawSettings vReflection' = dsVReflection drawSettings (_, _, toGamePosX, toGamePosY) = fromToFieldPos hReflection' vReflection' fieldWidth' fieldHeight' width height posX = toGamePosX x posY = toGamePosY y when (posX >= 0 && posY >= 0 && posX < fieldWidth' && posY < fieldHeight') $ f (posX, posY) updateCoordLabel :: Gtk.Label -> Gtk.DrawingArea -> Field -> DrawSettings -> Double -> Double -> IO () updateCoordLabel coordLabel drawingArea field drawSettings x y = withPos drawingArea field drawSettings x y $ \(posX, posY) -> do let text = pack $ show (posX + 1) ++ ":" ++ show (posY + 1) labelText <- coordLabel `get` #label when (labelText /= text) $ coordLabel `set` [ #label := text ] drawToSvg :: String -> DrawSettings -> [Field] -> IO () drawToSvg filename drawSettings fields = let field = head fields fieldWidth' = fieldWidth field fieldHeight' = fieldHeight field width = 800 height = width / fromIntegral fieldWidth' * fromIntegral fieldHeight' in Cairo.withSVGSurface filename width height $ flip Cairo.renderWith $ draw drawSettings width height fields listenMainWindow :: MainWindow -> Pixbuf -> Text -> IORef DrawSettings -> IORef Game -> (SomeException -> IO ()) -> IO () listenMainWindow mainWindow logo license drawSettingsIORef gameIORef callbackError = do _ <- mwWindow mainWindow `on` #deleteEvent $ \_ -> do game <- readIORef gameIORef evalAsync (const $ return ()) $ gameStopBots game 1000000 >> now Gtk.mainQuit return False _ <- mwExitImageMenuItem mainWindow `on` #activate $ do game <- readIORef gameIORef #destroy $ mwWindow mainWindow evalAsync (const $ return ()) $ gameStopBots game 1000000 >> now Gtk.mainQuit _ <- mwAboutImageMenuItem mainWindow `on` #activate $ do aboutDialog <- new Gtk.AboutDialog [ #authors := ["Evgeny Kurnevsky"] , #license := license , #logo := logo , #programName := "Missile" , #transientFor := mwWindow mainWindow , #version := pack $ showVersion version , #website := "https://gitlab.com/points/missile" ] _ <- #run aboutDialog #destroy aboutDialog _ <- mwPreferencesImageMenuItem mainWindow `on` #activate $ do drawSettings <- readIORef drawSettingsIORef preferencesDialog <- preferencesDialogNew mainWindow drawSettings runPreferencesDialog drawSettings preferencesDialog $ \newSettings -> do writeIORef drawSettingsIORef newSettings #queueDraw $ mwDrawingArea mainWindow _ <- mwExportAsSvgMenuItem mainWindow `on` #activate $ do fileFilter <- new Gtk.FileFilter [] #addPattern fileFilter "*.svg" fileChooserDialog <- new Gtk.FileChooserDialog [ #action := Gtk.FileChooserActionSave , #doOverwriteConfirmation := True , #filter := fileFilter , #transientFor := mwWindow mainWindow ] _ <- #addButton fileChooserDialog "_Cancel" $ (fromIntegral . fromEnum) Gtk.ResponseTypeCancel _ <- #addButton fileChooserDialog "_Save" $ (fromIntegral . fromEnum) Gtk.ResponseTypeAccept response <- fmap (toEnum . fromIntegral) $ #run fileChooserDialog case response of Gtk.ResponseTypeCancel -> #destroy fileChooserDialog Gtk.ResponseTypeDeleteEvent -> #destroy fileChooserDialog Gtk.ResponseTypeAccept -> do maybeFilename <- #getFilename fileChooserDialog case maybeFilename of Just filename -> do drawSettings <- readIORef drawSettingsIORef game <- readIORef gameIORef fields <- gameFields game drawToSvg filename drawSettings fields Nothing -> return () #destroy fileChooserDialog _ -> error $ "runFileChooserDialog: unexpected response: " ++ show response _ <- mwDrawingArea mainWindow `on` #draw $ \context -> do drawSettings <- readIORef drawSettingsIORef game <- readIORef gameIORef fields <- gameFields game width' <- #getAllocatedWidth $ mwDrawingArea mainWindow height' <- #getAllocatedHeight $ mwDrawingArea mainWindow flip renderWithContext context $ draw drawSettings (fromIntegral width') (fromIntegral height') fields return False _ <- mwDrawingArea mainWindow `on` #motionNotifyEvent $ \event -> do x <- event `get` #x y <- event `get` #y drawSettings <- readIORef drawSettingsIORef game <- readIORef gameIORef field <- head <$> gameFields game updateCoordLabel (mwCoordLabel mainWindow) (mwDrawingArea mainWindow) field drawSettings x y return False _ <- mwDrawingArea mainWindow `on` #buttonPressEvent $ \event -> do button <- event `get` #button when (button == 1) $ do x <- event `get` #x y <- event `get` #y drawSettings <- readIORef drawSettingsIORef game <- readIORef gameIORef field <- head <$> gameFields game withPos (mwDrawingArea mainWindow) field drawSettings x y $ evalAsync callbackError . gamePutPoint game return False return () main :: IO () main = do cliArguments <- execParser $ info cliArgumentsParser (fullDesc <> progDesc "Points game.") _ <- Gtk.init Nothing logo <- pixbufNewFromFile "Logo.svg" license <- TextIO.readFile "LICENSE.txt" mainWindow <- mainWindowNew logo let callbackError exception = postGUIASync $ do -- todo kill bots? messageDialog <- new Gtk.MessageDialog [ #buttons := Gtk.ButtonsTypeOk , #messageType := Gtk.MessageTypeError , #text := pack $ show exception , #transientFor := mwWindow mainWindow ] _ <- #run messageDialog #destroy messageDialog callback = postGUIASync $ #queueDraw $ mwDrawingArea mainWindow game <- gameNew (cliGameSettings cliArguments) callback evalAsync callbackError $ gameInitBots game gameIORef <- newIORef game let drawSettings = cliDrawSettings cliArguments drawSettingsIORef <- newIORef drawSettings listenMainWindow mainWindow logo license drawSettingsIORef gameIORef callbackError #showAll (mwWindow mainWindow) postGUIASync $ do (x, y) <- #getPointer $ mwDrawingArea mainWindow field <- head <$> gameFields game updateCoordLabel (mwCoordLabel mainWindow) (mwDrawingArea mainWindow) field drawSettings (fromIntegral x) (fromIntegral y) Gtk.main
kurnevsky/missile
src/Main.hs
agpl-3.0
25,884
0
22
10,344
5,359
2,640
2,719
406
5
{-# LANGUAGE TypeOperators,DataKinds,TypeFamilies#-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE Rank2Types #-} module Main where import System.Exit import OpenCog.AtomSpace import OpenCog.Test import Test.Tasty import Test.Tasty.SmallCheck import Test.SmallCheck.Series import Data.Typeable import GHC.Exts import Control.Exception main :: IO () main = defaultMain suite setDepth (SmallCheckDepth d) = SmallCheckDepth 4 suite :: TestTree suite = adjustOption setDepth $ testGroup "Haskell Test-Suite" [ testProperty "simple Insert Test" testInsertGet] --Simple Test that inserts Atoms and retrives them --if the inserted and retirived Atoms are the same the test passes testInsertGet :: Gen AtomT -> Property IO testInsertGet a = monadic $ do let prog = genInsert a >> genGet a res <- runOnNewAtomSpace prog case res of Just na -> return (na == a) Nothing -> return False
cosmoharrigan/atomspace
tests/haskell/Main.hs
agpl-3.0
1,134
0
13
216
217
115
102
31
2
{-# OPTIONS -XFlexibleInstances #-} {-# OPTIONS -XTypeSynonymInstances #-} {-# OPTIONS -XMultiParamTypeClasses #-} -------------------------------------------------------------------------------- -- $Id: GraphMatch.hs,v 1.19 2004/02/09 22:22:44 graham Exp $ -- -- Copyright (c) 2003, G. KLYNE. All rights reserved. -- See end of this file for licence information. -------------------------------------------------------------------------------- -- | -- Module : GraphMatch -- Copyright : (c) 2003, Graham Klyne -- License : GPL V2 -- -- Maintainer : Graham Klyne -- Stability : provisional -- Portability : H98 -- -- This module contains graph-matching logic. -- -- The algorithm used is derived from a paper on RDF graph matching -- by Jeremy Carroll [1]. -- -- [1] http://www.hpl.hp.com/techreports/2001/HPL-2001-293.html -- -------------------------------------------------------------------------------- module Swish.HaskellRDF.GraphMatch ( graphMatch, -- The rest exported for testing only LabelMap, GenLabelMap(..), LabelEntry, GenLabelEntry(..), ScopedLabel(..), makeScopedLabel, makeScopedArc, LabelIndex, EquivalenceClass, nullLabelVal, emptyMap, labelIsVar, labelHash, mapLabelIndex, setLabelHash, newLabelMap, graphLabels, assignLabelMap, newGenerationMap, graphMatch1, graphMatch2, equivalenceClasses, reclassify ) where import Swish.HaskellUtils.LookupMap import Swish.HaskellUtils.ListHelpers import Swish.HaskellUtils.MiscHelpers import Swish.HaskellUtils.TraceHelpers( trace, traceShow ) import Swish.HaskellRDF.GraphClass import Data.Maybe( isJust ) import Data.List( nub, sortBy, partition ) import qualified Data.List -------------------------- -- Label index value type -------------------------- -- -- LabelIndex is a unique value assigned to each label, such that -- labels with different values are definitely different values -- in the graph; e.g. do not map to each other in the graph -- bijection. The first member is a generation counter that -- ensures new values are distinct from earlier passes. type LabelIndex = (Int,Int) nullLabelVal :: LabelIndex nullLabelVal = (0,0) ----------------------- -- Label mapping types ----------------------- data (Label lb) => GenLabelEntry lb lv = LabelEntry lb lv type LabelEntry lb = GenLabelEntry lb LabelIndex instance (Label lb, Eq lb, Show lb, Eq lv, Show lv) => LookupEntryClass (GenLabelEntry lb lv) lb lv where keyVal (LabelEntry k v) = (k,v) newEntry (k,v) = LabelEntry k v instance (Label lb, Eq lb, Show lb, Eq lv, Show lv) => Show (GenLabelEntry lb lv) where show = entryShow instance (Label lb, Eq lb, Show lb, Eq lv, Show lv) => Eq (GenLabelEntry lb lv) where (==) = entryEq -- Type for label->index lookup table data (Label lb, Eq lv, Show lv) => GenLabelMap lb lv = LabelMap Int (LookupMap (GenLabelEntry lb lv)) type LabelMap lb = GenLabelMap lb LabelIndex instance (Label lb) => Show (LabelMap lb) where show = showLabelMap instance (Label lb) => Eq (LabelMap lb) where LabelMap gen1 lmap1 == LabelMap gen2 lmap2 = (gen1 == gen2) && (es1 `equiv` es2) where es1 = listLookupMap lmap1 es2 = listLookupMap lmap2 emptyMap :: (Label lb) => LabelMap lb emptyMap = LabelMap 1 $ makeLookupMap [] -------------------------- -- Equivalence class type -------------------------- -- -- Type for equivalence class description -- (An equivalence class is a collection of labels with -- the same LabelIndex value.) type EquivalenceClass lb = (LabelIndex,[lb]) ecIndex :: EquivalenceClass lb -> LabelIndex ecIndex = fst ecLabels :: EquivalenceClass lb -> [lb] ecLabels = snd ecSize :: EquivalenceClass lb -> Int ecSize (_,ls) = length ls ecRemoveLabel :: (Label lb) => EquivalenceClass lb -> lb -> EquivalenceClass lb ecRemoveLabel (lv,ls) l = (lv,Data.List.delete l ls) ------------------------------------------------------------ -- Augmented graph label value - for graph matching ------------------------------------------------------------ -- -- This instance of class label adds a graph identifier to -- each variable label, so that variable labels from -- different graphs are always seen as distinct values. -- -- The essential logic added by this class instance is embodied -- in the eq and hash functions. Note that variable label hashes -- depend only on the graph in which they appear, and non-variable -- label hashes depend only on the variable. Label hash values are -- used when initializing a label equivalence-class map (and, for -- non-variable labels, also for resolving hash collisions). data (Label lb) => ScopedLabel lb = ScopedLabel Int lb makeScopedLabel :: (Label lb) => Int -> lb -> ScopedLabel lb makeScopedLabel scope lab = ScopedLabel scope lab makeScopedArc :: (Label lb) => Int -> Arc lb -> Arc (ScopedLabel lb) makeScopedArc scope a1 = arc (s arcSubj a1) (s arcPred a1) (s arcObj a1) where s f a = (ScopedLabel scope (f a)) instance (Label lb) => Label (ScopedLabel lb) where getLocal lab = error $ "getLocal for ScopedLabel: "++show lab makeLabel locnam = error $ "makeLabel for ScopedLabel: "++locnam labelIsVar (ScopedLabel _ lab) = labelIsVar lab labelHash seed (ScopedLabel scope lab) | labelIsVar lab = hash seed $ (show scope)++"???" | otherwise = labelHash seed lab instance (Label lb) => Eq (ScopedLabel lb) where (ScopedLabel s1 l1) == (ScopedLabel s2 l2) = ( l1 == l2 ) && (s1 == s2) instance (Label lb) => Show (ScopedLabel lb) where show (ScopedLabel s1 l1) = (show s1) ++ ":" ++ (show l1) instance (Label lb) => Ord (ScopedLabel lb) where compare (ScopedLabel s1 l1) (ScopedLabel s2 l2) = case (compare s1 s2) of LT -> LT EQ -> compare l1 l2 GT -> GT -------------- -- graphMatch -------------- -- -- Graph matching function accepting two lists of arcs and -- returning a node map if successful -- -- matchable -- is a function that tests for additional constraints -- that may prevent the matching of a supplied pair -- of nodes. Returns True if the supplied nodes may be -- matched. (Used in RDF graph matching for checking -- that formula assignments are compatible.) -- gs1 is the first of two graphs to be compared, -- supplied as a list of arcs. -- gs2 is the second of two graphs to be compared, -- supplied as a list of arcs. -- -- returns a label map that maps each label to an equivalence -- class identifier, or Nothing if the graphs cannot be -- matched. graphMatch :: (Label lb) => (lb -> lb -> Bool) -> [Arc lb] -> [Arc lb] -> (Bool,LabelMap (ScopedLabel lb)) graphMatch matchable gs1 gs2 = let sgs1 = {- trace "sgs1 " $ -} map (makeScopedArc 1) gs1 sgs2 = {- trace "sgs2 " $ -} map (makeScopedArc 2) gs2 ls1 = {- traceShow "ls1 " $ -} graphLabels sgs1 ls2 = {- traceShow "ls2 " $ -} graphLabels sgs2 lmap = {- traceShow "lmap " $ -} newGenerationMap $ assignLabelMap ls1 $ assignLabelMap ls2 emptyMap ec1 = {- traceShow "ec1 " $ -} equivalenceClasses lmap ls1 ec2 = {- traceShow "ec2 " $ -} equivalenceClasses lmap ls2 ecpairs = zip (pairSort ec1) (pairSort ec2) matchableScoped (ScopedLabel _ l1) (ScopedLabel _ l2) = matchable l1 l2 match = graphMatch1 False matchableScoped sgs1 sgs2 lmap ecpairs in if (length ec1) /= (length ec2) then (False,emptyMap) else match -- Recursive graph matching function -- This function assumes that no variable label appears in both graphs. -- (Function graphMatch, which calls this, ensures that all variable -- labels are distinct.) -- -- matchable -- is a function that tests for additional constraints -- that may prevent the matching of a supplied pair -- of nodes. Returns True if the supplied nodes may be -- matched. -- guessed is True if a guess has been used before trying this comparison, -- False if nodes are being matched without any guesswork. -- gs1 is the first of two lists of arcs (triples) to be compared -- gs2 is the second of two lists of arcs (triples) to be compared -- lmap is the map so far used to map label values to equivalence -- class values -- ecpairs list of pairs of corresponding equivalence classes of nodes -- from gs1 and gs2 that have not been confirmed in 1:1 -- correspondence with each other. -- Each pair of equivalence classes contains nodes that must -- be placed in 1:1 correspondence with each other. -- -- returns a pair (match,map), where 'match' is Tue if the supplied -- sets of arcs can be matched, in which case 'map' is a -- corresponding map from labels to equivalence class identifiers. -- When 'match' is False, 'map' is the most detailed equivalence -- class map obtained before a mismatch was detected or a guess -- was required -- this is intended to help identify where the -- graph mismatch may be. -- -- [[[TODO: replace Equivalence class pair by (index,[lb],[lb]) ?]]] -- [[[TODO: possible optimization: the graphMapEq test should be -- needed only if graphMatch2 has been used to guess a -- mapping; either (a) supply flag saying guess has been -- used, or (b) move test to graphMatch2 and use different -- test to prevent rechecking for each guess used.]]] graphMatch1 :: (Label lb) => Bool -> (lb -> lb -> Bool) -> [Arc lb] -> [Arc lb] -> LabelMap lb -> [(EquivalenceClass lb,EquivalenceClass lb)] -> (Bool,(LabelMap lb)) graphMatch1 guessed matchable gs1 gs2 lmap ecpairs = let (secs,mecs) = partition uniqueEc ecpairs uniqueEc ( (_,[_]) , (_,[_]) ) = True uniqueEc ( _ , _ ) = False doMatch ( (_,[l1]) , (_,[l2]) ) = labelMatch matchable lmap l1 l2 ecEqSize ( (_,ls1) , (_,ls2) ) = (length ls1) == (length ls2) ecSize ( (_,ls1) , _ ) = length ls1 ecCompareSize ec1 ec2 = compare (ecSize ec1) (ecSize ec2) (lmap',mecs',newEc,matchEc) = reclassify gs1 gs2 lmap mecs match2 = graphMatch2 matchable gs1 gs2 lmap $ sortBy ecCompareSize mecs in -- trace ("graphMatch1\nsingle ECs:\n"++show secs++ -- "\nmultiple ECs:\n"++show mecs++ -- "\n\n") $ -- if mismatch in singleton equivalence classes, fail if not $ all doMatch secs then (False,lmap) else -- if no multi-member equivalence classes, -- check and return label map supplied -- trace ("graphMatch1\ngraphMapEq: "++show (graphMapEq lmap gs1 gs2)) $ if null mecs then (graphMapEq lmap gs1 gs2,lmap) else -- if size mismatch in equivalence classes, fail -- trace ("graphMatch1\nall ecEqSize mecs: "++show (all ecEqSize mecs)) $ if not $ all ecEqSize mecs then (False,lmap) else -- invoke reclassification, and deal with result if not matchEc then (False,lmap) else if newEc then graphMatch1 guessed matchable gs1 gs2 lmap' mecs' else -- if guess does not result in a match, return supplied label map if fst match2 then match2 else (False,lmap) -- Auxiliary graph matching function -- This function is called when deterministic decomposition of node -- mapping equivalence classes has run its course. -- -- It picks a pair of equivalence classes in ecpairs, and arbitrarily matches -- pairs of nodes in those equivalence classes, recursively calling the -- graph matching function until a suitable node mapping is discovered -- (success), or until all such pairs have been tried (failure). -- -- This function represents a point to which arbitrary choices are backtracked. -- The list comprehension 'glp' represents the alternative choices at the -- point of backtracking -- -- The selected pair of nodes are placed in a new equivalence class based on their -- original equivalence class value, but with a new NodeVal generation number. graphMatch2 :: (Label lb) => (lb -> lb -> Bool) -> [Arc lb] -> [Arc lb] -> LabelMap lb -> [(EquivalenceClass lb,EquivalenceClass lb)] -> (Bool,(LabelMap lb)) graphMatch2 matchable gs1 gs2 lmap ((ec1@(ev1,ls1),ec2@(ev2,ls2)):ecpairs) = let (_,v1) = ev1 (_,v2) = ev2 -- Return any equivalence-mapping obtained by matching a pair -- of labels in the supplied list, or Nothing. try [] = (False,lmap) try ((l1,l2):lps) = if equiv try1 l1 l2 then try1 else try lps where try1 = graphMatch1 True matchable gs1 gs2 lmap' ecpairs' lmap' = newLabelMap lmap [(l1,v1),(l2,v1)] ecpairs' = ((ev',[l1]),(ev',[l2])):ec':ecpairs ev' = mapLabelIndex lmap' l1 ec' = (ecRemoveLabel ec1 l1,ecRemoveLabel ec2 l2) -- [[[TODO: replace this: if isJust try ?]]] equiv (False,_) _ _ = False equiv (True,lmap) l1 l2 = (mapLabelIndex m1 l1) == (mapLabelIndex m2 l2) where m1 = remapLabels gs1 lmap [l1] m2 = remapLabels gs2 lmap [l2] -- glp is a list of label-pair candidates for matching, -- selected from the first label-equivalence class. -- NOTE: final test is call of external matchable function glp = [ (l1,l2) | l1 <- ls1 , l2 <- ls2 , matchable l1 l2 ] in assert (ev1==ev2) "GraphMatch2: Equivalence class value mismatch" $ try glp ---------------------- -- LabelMap functions ---------------------- ---------------- -- showLabelMap ---------------- -- -- Returns a string representation of a LabelMap value showLabelMap :: (Label lb) => LabelMap lb -> String showLabelMap (LabelMap gn lmap) = "LabelMap gen="++(Prelude.show gn)++", map="++ foldl (++) "" ((map ("\n "++)) (map Prelude.show es )) where es = listLookupMap lmap ----------------- -- mapLabelIndex ----------------- -- -- Map a label to its corresponding label index value in the supplied LabelMap mapLabelIndex :: (Label lb) => LabelMap lb -> lb -> LabelIndex mapLabelIndex (LabelMap _ lxms) lb = mapFind nullLabelVal lb lxms -------------- -- labelMatch -------------- -- -- Confirm that a given pair of labels are matchable, and are -- mapped to the same value by the supplied label map labelMatch :: (Label lb) => (lb -> lb -> Bool) -> LabelMap lb -> lb -> lb -> Bool labelMatch matchable lmap l1 l2 = (matchable l1 l2) && ((mapLabelIndex lmap l1) == (mapLabelIndex lmap l1)) --------------- -- newLabelMap --------------- -- -- Replace selected values in a label map with new values from the supplied -- list of labels and new label index values. The generation number is -- supplied from the current label map. The generation number in the -- resulting label map is incremented. newLabelMap :: (Label lb) => LabelMap lb -> [(lb,Int)] -> LabelMap lb newLabelMap (LabelMap g f) [] = (LabelMap (g+1) f) -- new generation newLabelMap lmap (lv:lvs) = setLabelHash (newLabelMap lmap lvs) lv ---------------- -- setLabelHash ---------------- -- -- setLabelHash replaces a label and its associated value in a label map -- with a new value using the supplied hash value and the current -- LabelMap generation number. If the key is not found, then no change -- is made to the label map. setLabelHash :: (Label lb) => LabelMap lb -> (lb,Int) -> LabelMap lb setLabelHash (LabelMap g lmap) (lb,lh) = LabelMap g ( mapReplaceAll lmap $ newEntry (lb,(g,lh)) ) -------------------- -- newGenerationMap -------------------- -- -- Increment generation of label map. -- Returns a new label map identical to the supplied value -- but with an incremented generation number. newGenerationMap :: (Label lb) => LabelMap lb -> LabelMap lb newGenerationMap (LabelMap g lvs) = (LabelMap (g+1) lvs) ------------------ -- assignLabelMap ------------------ -- -- Scan label list, assigning initial label map values, -- adding new values to the label map supplied. -- -- Label map values are assigned on the basis of the -- label alone, without regard for it's connectivity in -- the graph. (cf. reClassify) -- -- All variable node labels are assigned the same initial -- value, as they may be matched with each other. assignLabelMap :: (Label lb) => [lb] -> LabelMap lb -> LabelMap lb assignLabelMap [] lmap = lmap assignLabelMap (n:ns) lmap = assignLabelMap ns (assignLabelMap1 n lmap) assignLabelMap1 :: (Label lb) => lb -> LabelMap lb -> LabelMap lb assignLabelMap1 lab (LabelMap g lvs) = LabelMap g lvs' where lvs' = (mapAddIfNew lvs $ newEntry (lab,(g,initVal lab))) -- Calculate initial value for a node initVal :: (Label lb) => lb -> Int initVal n = hashVal 0 n hashVal :: (Label lb) => Int -> lb -> Int hashVal seed lab = if (labelIsVar lab) then (hash seed "???") else (labelHash seed lab) ---------------------- -- equivalenceClasses ---------------------- -- -- lmap label map -- ls list of nodes to be reclassified -- -- return list of equivalence classes of the supplied labels under -- the supplied label map. equivalenceClasses :: (Label lb) => LabelMap lb -> [lb] -> [EquivalenceClass lb] equivalenceClasses lmap ls = pairGroup $ map labelPair ls where labelPair l = (mapLabelIndex lmap l,l) -------------- -- reclassify -------------- -- -- Reclassify labels -- -- Examines the supplied label equivalence classes (based on the supplied -- label map), and evaluates new equivalence subclasses based on node -- values and adjacency (for variable nodes) and rehashing -- (for non-variable nodes). -- -- Note, assumes that all all equivalence classes supplied are -- non-singletons; i.e. contain more than one label. -- -- gs1 is the first of two lists of arcs (triples) to perform a -- basis for reclassifying the labels in the first equivalence -- class in each pair of 'ecpairs'. -- gs2 is the second of two lists of arcs (triples) to perform a -- basis for reclassifying the labels in the second equivalence -- class in each pair of 'ecpairs'. -- lmap is a label map used for classification of the labels in -- the supplied equivalence classes. -- ecpairs a list of pairs of corresponding equivalence classes of -- nodes from gs1 and gs2 that have not been confirmed -- in 1:1 correspondence with each other. -- -- return a quadruple of: -- (a) a revised label map reflecting the reclassification, -- (b) a new list of equivalence class pairs based on the -- new node map, and -- (c) if the reclassification partitions any of the -- supplied equivalence classes then True, else False. -- any of the supplied equivalence classes -- (d) if reclassification results in each equivalence class -- being split same-sized equivalence classes in the two graphs, -- then True, otherwise False. reclassify :: (Label lb) => [Arc lb] -> [Arc lb] -> LabelMap lb -> [(EquivalenceClass lb,EquivalenceClass lb)] -> (LabelMap lb,[(EquivalenceClass lb,EquivalenceClass lb)],Bool,Bool) reclassify gs1 gs2 lmap@(LabelMap _ lm) ecpairs = assert (gen1==gen2) "Label map generation mismatch" $ (LabelMap gen1 lm',ecpairs',newPart,matchPart) where LabelMap gen1 lm1 = remapLabels gs1 lmap $ foldl1 (++) $ map (ecLabels . fst) ecpairs LabelMap gen2 lm2 = remapLabels gs2 lmap $ foldl1 (++) $ map (ecLabels . snd) ecpairs lm' = mapReplaceMap lm $ mapMerge lm1 lm2 -- ecGroups :: [([EquivalenceClass lb],[EquivalenceClass lb])] ecGroups = [ (remapEc ec1,remapEc ec2) | (ec1,ec2) <- ecpairs ] ecpairs' = concat $ map (uncurry zip) ecGroups newPart = or $ map pairG1 lenGroups matchPart = and $ map pairEq lenGroups lenGroups = map subLength ecGroups pairEq (p1,p2) = p1 == p2 pairG1 (p1,p2) = (p1 > 1) || (p2 > 1) subLength (ls1,ls2) = (length ls1,length ls2) remapEc ec = pairGroup $ map (newIndex lm') $ pairUngroup ec newIndex lm (_,lab) = (mapFind nullLabelVal lab lm,lab) --------------- -- remapLabels --------------- -- -- Calculate a new index value for a supplied list of labels based on the -- supplied label map and adjacency calculations in the supplied graph -- -- gs is a list of Arcs used for adjacency calculations when remapping -- lmap is a label map used for obtaining current label index values -- ls is a list of graph labels for which new mappings are to be -- created and returned. -- return a new label map containing recalculated label index values -- for the labels in ls. The label map generation number is -- incremented by 1 from the supplied 'lmap' value. remapLabels :: (Label lb) => [Arc lb] -> LabelMap lb -> [lb] -> LabelMap lb remapLabels gs lmap@(LabelMap gen _) ls = LabelMap gen' (LookupMap newEntries) where gen' = gen+1 newEntries = [ newEntry (l, (gen',newIndex l)) | l <- ls ] newIndex l | labelIsVar l = mapAdjacent l -- adjacency classifies variable labels | otherwise = hashVal gen l -- otherwise rehash (to disentangle collisions) mapAdjacent l = ( sum (sigsOver l) ) `rem` hashModulus sigsOver l = select (hasLabel l) gs (arcSignatures lmap gs) ----------------------------- -- Graph auxiliary functions ----------------------------- --------------- -- graphLabels --------------- -- -- Return list of distinct labels used in a graph graphLabels :: (Label lb) => [Arc lb] -> [lb] graphLabels gs = nub $ concat $ map arcLabels gs {- OLD CODE: graphLabels gs = graphLabels1 gs [] graphLabels1 (t:gs) ls = graphLabels1 gs $ foldl (flip addSetElem) ls (arcLabels t) graphLabels1 [] ls = ls -} -- addSetElem :: lb -> [lb] -> [lb] ----------------- -- arcSignatures ----------------- -- -- Calculate a signature value for each arc that can be used in constructing an -- adjacency based value for a node. The adjacancy value for a label is obtained -- by summing the signatures of all statements containing that label. -- -- lmap is a label map used for obtaining current label index values -- gs is the list of arcs for which signaturews are calculated -- return a list of signature values in correspondence with gs arcSignatures :: (Label lb) => LabelMap lb -> [Arc lb] -> [Int] arcSignatures lmap gs = map (sigCalc . arcToTriple) gs where sigCalc (s,p,o) = ( (labelVal2 s) + (labelVal2 p)*3 + (labelVal2 o)*5 ) `rem` hashModulus labelVal l = mapLabelIndex lmap l labelVal2 = (\v -> (fst v) * (snd v) ) . labelVal ------------ -- graphMap ------------ -- -- Return new graph that is supplied graph with every node/arc -- mapped to a new value according to the supplied function. -- -- Used for testing for graph equivalence under a supplied -- label mapping; e.g. -- -- if ( graphMap nodeMap gs1 ) `equiv` ( graphMap nodeMap gs2 ) then (same) graphMap :: (Label lb) => LabelMap lb -> [Arc lb] -> [Arc LabelIndex] graphMap lmap = map $ fmap (mapLabelIndex lmap) -- graphMapStmt -------------- -- graphMapEq -------------- -- -- Compare a pair of graphs for equivalence under a given mapping -- function. -- -- This is used to perform the ultimate test that two graphs are -- indeed equivalent: guesswork in graphMatch2 means that it is -- occasionally possible to construct a node mapping that generates -- the required singleton equivalence classes, but does not fully -- reflect the topology of the graphs. graphMapEq :: (Label lb) => LabelMap lb -> [Arc lb] -> [Arc lb] -> Bool graphMapEq lmap gs1 gs2 = (graphMap lmap gs1) `equiv` (graphMap lmap gs2) -------------------------------------------------------------------------------- -- -- Copyright (c) 2003, G. KLYNE. 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 -- -------------------------------------------------------------------------------- -- $Source: /file/cvsdev/HaskellRDF/GraphMatch.hs,v $ -- $Author: graham $ -- $Revision: 1.19 $ -- $Log: GraphMatch.hs,v $ -- Revision 1.19 2004/02/09 22:22:44 graham -- Graph matching updates: change return value to give some indication -- of the extent match achieved in the case of no match. -- Added new module GraphPartition and test cases. -- Add VehicleCapcity demonstration script. -- -- Revision 1.18 2004/01/07 19:49:12 graham -- Reorganized RDFLabel details to eliminate separate language field, -- and to use ScopedName rather than QName. -- Removed some duplicated functions from module Namespace. -- -- Revision 1.17 2003/12/04 02:53:27 graham -- More changes to LookupMap functions. -- SwishScript logic part complete, type-checks OK. -- -- Revision 1.16 2003/10/24 21:03:25 graham -- Changed kind-structure of LookupMap type classes. -- -- Revision 1.15 2003/09/24 18:50:52 graham -- Revised module format to be Haddock compatible. -- -- Revision 1.14 2003/06/03 19:24:13 graham -- Updated all source modules to cite GNU Public Licence -- -- Revision 1.13 2003/05/29 01:50:56 graham -- More performance tuning, courtesy of GHC profiler. -- All modules showing reasonable performance now. -- -- Revision 1.12 2003/05/28 19:57:50 graham -- Adjusting code to compile with GHC -- -- Revision 1.11 2003/05/23 16:29:20 graham -- Partial code cleanup: -- - Arc is an alebraic type -- - Arc is an instance of Functor -- - add gmap function to Graph interface -- - remove some duplicate functions from GraphMatch -- This in preparation for adding graph merge facility with -- blank node renaming. -- -- Revision 1.10 2003/05/14 11:13:15 graham -- Fixed bug in graph matching. -- (A graph-equivalence check is needed to weed out false matches -- caused by the "guessing" stage.) -- -- Revision 1.9 2003/05/14 02:01:59 graham -- GraphMatch recoded and almost working, but -- there are a couple of -- obscure bugs that are proving rather stubborn to squash. -- -- Revision 1.8 2003/05/09 00:29:14 graham -- Started to restructure graph matching code -- -- Revision 1.7 2003/05/08 18:55:36 graham -- Updated graph matching module to deal consistently -- with graphs containing formulae. All graph tests now -- run OK, but the GraphMatch module is a mess and -- desperately needs restructuring. Also, graph matching -- performance needs to be improved. -- -- Revision 1.6 2003/05/01 23:15:44 graham -- GraphTest passes all tests using refactored LookupMap -- Extensive changes to GraphMatch were required. -- -- Revision 1.5 2003/04/24 23:41:39 graham -- Added Ord class membership to graph nodes -- Added empty lookup table definition -- Started on N3 formatter module -- -- Revision 1.4 2003/04/11 18:12:10 graham -- Renamed GraphHelpers to ListHelpers -- LookupMapTest, GraphTest, RDFGraphTest all run OK -- -- Revision 1.3 2003/04/11 18:04:49 graham -- Rename GraphLookupMap to LookupMap: -- GraphTest runs OK. -- -- Revision 1.2 2003/04/10 16:47:04 graham -- Minor code cleanup -- -- Revision 1.1 2003/04/10 13:35:34 graham -- Separated GraphMatch logic from GraphMem --
amccausl/Swish
Swish/HaskellRDF/GraphMatch.hs
lgpl-2.1
29,430
0
15
7,484
4,794
2,741
2,053
-1
-1
module Database.QUDB (S.new, S.load, S.dump, query, S.DB, Value(IntValue, StringValue)) where import qualified Database.QUDB.Structure as S import Database.QUDB.EntityTypes (Value(IntValue, StringValue)) import Database.QUDB.Parser (parse) query :: S.DB -> String -> Either String (S.DB, [[Value]]) query db str = case parse str of Left msg -> Left msg Right q -> case S.query db q of Left error -> Left $ show error Right results -> Right results
jstepien/qudb
Database/QUDB.hs
lgpl-3.0
554
0
12
171
188
105
83
13
3
import Data.List pair [] _ = [] pair (a:as) b = let x = map (\y -> (a, y) ) b in x ++ (pair as b) cmp (a,b) (c,d) = compare (a+b) (c+d) search _ [] = [] search dif ((a,b):r) = if dif == (a - b) * 2 then (a,b):(search dif r) else (search dif r) ans' a b = let ma = last a mb = last b df = (sum a) - (sum b) s0 = search df $ pair (nub a) (nub b) s1 = head $ sortBy cmp s0 in if s0 == [] then "-1" else unwords $ map show [ fst s1, snd s1 ] ans ([0,0]:_) = [] ans ([n,m]:x) = let a = sort $ concat $ take n x b = sort $ concat $ take m $ drop n x r = drop (n+m) x s = ans' a b in s:(ans r) main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = ans i mapM_ putStrLn o
a143753/AOJ
1153.hs
apache-2.0
857
6
14
343
555
276
279
32
2
module Main where import System.IO import Control.Concurrent import Data.Char import Network.Socket import System.Environment(getArgs) telnetIAC :: Int telnetIAC = 255 telnetWONT :: Int telnetWONT = 252 newtype Credentials = Credential (String, String) password :: Handle -> String -> IO () password h pwd = do char <- hGetChar h case char of ':' -> do hPutStrLn h pwd hFlush h otherwise -> password h pwd login :: Handle -> Credentials -> IO () login h c@(Credential (user, pwd)) = do hPutStrLn h user hFlush h password h pwd putStrLn "Logged in" declineHandshakeOption :: Handle -> Credentials -> IO () declineHandshakeOption h c = do ignoreChar <- hGetChar h optionChar <- hGetChar h hPutChar h $ chr telnetIAC hPutChar h $ chr telnetWONT hPutChar h $ optionChar hFlush h handshakeAndLogin h c handleHandshakeInput :: Handle -> Char -> Credentials -> IO() handleHandshakeInput h char credentials | ord char == telnetIAC = declineHandshakeOption h credentials | char == ':' = login h credentials | otherwise = handshakeAndLogin h credentials handshakeAndLogin :: Handle -> Credentials -> IO () handshakeAndLogin h credentials = do char <- hGetChar h handleHandshakeInput h char credentials main :: IO () main = withSocketsDo $ do args <- getArgs addrinfos <- getAddrInfo Nothing (Just (args !! 0)) (Just "23") let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol connect sock (addrAddress serveraddr) putStrLn "Connected" h <- socketToHandle sock ReadWriteMode hSetBuffering h (BlockBuffering Nothing) handshakeAndLogin h $ Credential (args !! 1, args !! 2) hPutStrLn h (args !! 3) hFlush h putStrLn "Command sent" threadDelay 1000000
jazir1979/haskell-play
telnet-client/TelnetClient.hs
apache-2.0
1,825
12
13
405
654
305
349
57
2
{-# LANGUAGE DeriveDataTypeable #-} module Propellor.Types.Chroot where import Propellor.Types import Propellor.Types.Empty import Propellor.Types.Info import Data.Monoid import qualified Data.Map as M data ChrootInfo = ChrootInfo { _chroots :: M.Map FilePath Host , _chrootCfg :: ChrootCfg } deriving (Show, Typeable) instance IsInfo ChrootInfo where propagateInfo _ = PropagateInfo False instance Monoid ChrootInfo where mempty = ChrootInfo mempty mempty mappend old new = ChrootInfo { _chroots = M.union (_chroots old) (_chroots new) , _chrootCfg = _chrootCfg old <> _chrootCfg new } instance Empty ChrootInfo where isEmpty i = and [ isEmpty (_chroots i) , isEmpty (_chrootCfg i) ] data ChrootCfg = NoChrootCfg | SystemdNspawnCfg [(String, Bool)] deriving (Show, Eq) instance Monoid ChrootCfg where mempty = NoChrootCfg mappend v NoChrootCfg = v mappend NoChrootCfg v = v mappend (SystemdNspawnCfg l1) (SystemdNspawnCfg l2) = SystemdNspawnCfg (l1 <> l2) instance Empty ChrootCfg where isEmpty c= c == NoChrootCfg
ArchiveTeam/glowing-computing-machine
src/Propellor/Types/Chroot.hs
bsd-2-clause
1,056
20
10
182
347
186
161
34
0
{-# LANGUAGE NoImplicitPrelude #-} -- -- Geometry: tests of Geometry module -- module UnitTest.Aya.Geometry where import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck import Test.HUnit import Test.QuickCheck import Data.Maybe import NumericPrelude import Aya.Algebra import Aya.Geometry main :: IO () main = defaultMain testSuite testSuite = hUnitTestToTests $ tests tests = "Aya Geometry" ~: [ "Plain" ~: testPlain , "Sphere" ~: testSphere , "Polygon" ~: testPolygon , "Ray" ~: testRay ] -- -- Plain -- testPlain = test [ show p1 ~=? "Just [[0.0,1.0,0.0],1.0]" , show p2 ~=? "Just [[" ++ (show rt13) ++ "," ++ (show rt13) ++ "," ++ (show rt13) ++ "],-10.0]" , distance (fromJust p1) (fromJust rp1) ~=? [] , distance (fromJust p1) (fromJust rp2) ~=? [(sqrt 2, fromJust p1, Inside)] , distance (fromJust p1) (fromJust rp3) ~=? [(-(sqrt 2), fromJust p1, Outside)] , getNormal (fromJust p1) (Vector3 0 (-1) 0) Inside ~=? ey3 , getNormal (fromJust p1) (Vector3 0 (-1) 0) Outside ~=? negate ey3 ] where p1 = initPlain (Vector3 0 1 0) 1 p2 = initPlain (Vector3 1 1 1) (-10) rt13 :: Double rt13 = 1 / sqrt 3 rp1 = initRay (Vector3 0 0 0) (Vector3 0 0 1) rp2 = initRay (Vector3 0 0 0) (Vector3 0 (-1) 1) rp3 = initRay (Vector3 0 0 0) (Vector3 0 1 1) -- -- Sphere -- testSphere = test [ show s1 ~=? "Just [[0.0,0.0,0.0],1.0]" , show s2 ~=? "Just [[1.0,1.0,1.0],10.0]" , show s3 ~=? "Nothing" , side (fromJust s1) (Vector3 2 0 0) ~=? 1.0 , side (fromJust s1) (Vector3 0.5 0 0) ~=? -0.5 , distance (fromJust s1) (fromJust r1) ~=? [(2, fromJust s1, Inside), (4, fromJust s1, Outside)] ] where s1 = initSphere (Vector3 0 0 0) 1 s2 = initSphere (Vector3 1 1 1) 10 s3 = initSphere (Vector3 1 1 1) (-5) r1 = initRay (Vector3 0 0 (-3)) ez3 -- -- Polygon -- testPolygon = test [ p1 ~=? Nothing , p2 ~=? Nothing , p3 ~=? Nothing , p4 ~=? Nothing , poly_v p5 ~=? Vector3 1 1 1 , poly_e1 p5 ~=? Vector3 2 0 4 , poly_e2 p5 ~=? Vector3 3 0 1 , poly_n p5 ~=? Vector3 0 10 0 , side p5 (Vector3 0 2 0) ~=? 10 , side p5 (Vector3 0 0 0) ~=? -10 , side p5 (Vector3 1000 2 1000) ~=? 10 , side p5 (Vector3 1000 0 1000) ~=? -10 , side p5 (Vector3 1000 (-1) 1000) ~=? -20 , side p5 (Vector3 1000 1 1000) ~=? 0 , d1 ~=? [(-1, p5, Outside)] , d2 ~=? [(-1, p5, Inside)] , d3 ~=? [(1, p5, Inside)] , d4 ~=? [] , d5 ~=? [(sqrt 14, p5, Inside)] , n1 ~=? Vector3 0 1 0 , n2 ~=? Vector3 0 1 0 , poly_v p6 ~=? Vector3 0 0 0 , poly_e1 p6 ~=? Vector3 0 0 0.5 , poly_e2 p6 ~=? Vector3 (-0.5) 0 0.5 , poly_n p6 ~=? Vector3 0 (-0.25) 0 , getNormal p5 (Vector3 2 1 2) Outside ~=? Vector3 0 (-1) 0 , getNormal p5 (Vector3 2 1 2) Inside ~=? Vector3 0 1 0 , getNormal p7 (Vector3 0 0 (-0.3)) Outside ~=? Vector3 0 1 0 ] where p1 = initPolygon (Vector3 0 0 0) (Vector3 1 2 3) (Vector3 3 6 9) p2 = initPolygon zero (Vector3 1 2 3) (Vector3 3 6 9) p3 = initPolygon (Vector3 1 2 3) zero (Vector3 3 6 9) p4 = initPolygon (Vector3 1 2 3) (Vector3 3 6 9) zero p5 = fromJust $ initPolygon (Vector3 1 1 1) (Vector3 3 1 5) (Vector3 4 1 2) d1 = distance p5 (fromJust (initRay (Vector3 2 2 2) ey3)) d2 = distance p5 (fromJust (initRay (Vector3 2 0 2) (negate ey3))) d3 = distance p5 (fromJust (initRay (Vector3 1 2 1) (negate ey3))) d4 = distance p5 (fromJust (initRay (Vector3 2 2 1) (negate ey3))) d5 = distance p5 (fromJust (initRay (Vector3 4 2 5) (Vector3 (-2) (-1) (-3)))) n1 = getNormal p5 (Vector3 1 1 1) Inside n2 = getNormal p5 (Vector3 2 2 2) Inside p6 = fromJust $ initPolygon (Vector3 0 0 0) (Vector3 0 0 0.5) (Vector3 (-0.5) 0 0.5) p7 = fromJust $ initPolygon (Vector3 0 0 (-0.5)) (Vector3 0.5 0 0) (Vector3 (-0.5) 0 0) -- -- Ray -- testRay = test [ show r1 ~=? "Just (Ray {rpos = [0.0,0.0,0.0], rdir = [1.0,0.0,0.0]})" ] where r1 = initRay zero ex3
eiji-a/aya
src/UnitTest/Aya/Geometry.hs
bsd-3-clause
4,089
0
15
1,057
1,929
1,005
924
91
1