code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# Language OverloadedStrings #-}
module Model.Note (indexNote) where
import Text.HyperEstraier
import Import
import Data.Text (pack, unpack, append)
import Network.URI
import Data.Conduit.Pool
indexNote :: NoteId -> UTCTime -> (Route App -> Text) -> Handler ()
indexNote noteId time urlRenderer = do
i <- indexPool <$> getYesod
runDB $ withResource i (indexNote' noteId time urlRenderer)
indexNote' :: NoteId -> UTCTime -> (Route App -> Text) -> Database -> YesodDB sub App ()
indexNote' noteId time urlRenderer db = do
note <- get404 noteId
liftIO $ deleteOld
liftIO $ indexNew note
where
deleteOld = do
cond <- newCondition
addAttrCond cond $ append "@key STREQ " (pack $ show noteId)
docids <- searchDatabase db cond
mapM_ (\docid -> removeDocument db docid [CleaningRemove]) docids
indexNew note = do
doc <- newDocument
setAttribute doc "@title" (Just $ noteTitle note)
setAttribute doc "@topic" (Just $ noteTopic note)
setAttribute doc "@edited" (Just $ pack $ show time)
setAttribute doc "@key" (Just $ pack $ show noteId)
setURI doc $ parseURI $ unpack $ urlRenderer (ViewR noteId)
addText doc (unTextarea $ noteText note)
putDocument db doc []
| MasseR/introitu | Model/Note.hs | bsd-2-clause | 1,249 | 0 | 13 | 273 | 442 | 213 | 229 | 30 | 1 |
module Database.Narc.Pretty where
import Database.Narc.Common
-- Pretty-printing ------------------------------------------------=====
class Pretty t where
pretty :: t -> String
| ezrakilty/narc | Database/Narc/Pretty.hs | bsd-2-clause | 183 | 0 | 7 | 22 | 32 | 19 | 13 | 4 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE ViewPatterns #-}
import Control.Monad
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Writer
import Data.Functor.Identity
import qualified Data.IntSet as IntSet
import System.IO.Unsafe
import System.Log.Logger (Priority(DEBUG),rootLoggerName,setLevel,updateGlobalLogger)
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit hiding (Path,Test)
import Test.QuickCheck.Arbitrary hiding ((><))
import Test.QuickCheck.Gen hiding (shuffle)
import Test.QuickCheck.Instances ()
import LogicGrowsOnTrees
import LogicGrowsOnTrees.Testing
main :: IO ()
main = do
updateGlobalLogger rootLoggerName (setLevel DEBUG)
defaultMain [tests]
tests :: Test
tests = testGroup "LogicGrowsOnTrees"
[testGroup "Eq instance"
[testProperty "self" $ \(v :: Tree [()]) → v == v
]
,testProperty "allFrom" $ \(x :: [Int]) → x == allFrom x
,testProperty "between" $ do
x ← choose ( 0,100) :: Gen Int
y ← choose (50,100)
return $ between x y == [x..y]
,testGroup "exploreTree"
[testCase "return" $ exploreTree (return [()]) @?= [()]
,testCase "mzero" $ exploreTree (mzero :: Tree [()]) @?= []
,testCase "mplus" $ exploreTree (return [1::Int] `mplus` return [2]) @?= [1,2]
,testCase "cache" $ exploreTree (cache [42]) @?= [42::Int]
,testGroup "cacheMaybe"
[testCase "Nothing" $ exploreTree (cacheMaybe (Nothing :: Maybe [()])) @?= []
,testCase "Just" $ exploreTree (cacheMaybe (Just [42])) @?= [42::Int]
]
,testGroup "cacheGuard"
[testCase "True" $ exploreTree (cacheGuard False >> return [()]) @?= []
,testCase "False" $ exploreTree (cacheGuard True >> return [()]) @?= [()]
]
]
,testGroup "exploreTreeT"
[testCase "Writer" $
(runWriter . exploreTreeT $ do
cache [1 :: Int] >>= lift . tell
(lift (tell [2]) `mplus` lift (tell [3]))
return [42::Int]
) @?= ([42,42],[1,2,3])
]
,testGroup "exploreTreeTAndIgnoreResults"
[testCase "Writer" $
(runWriter . exploreTreeTAndIgnoreResults $ do
cache [1 :: Int] >>= lift . tell
(lift (tell [2]) `mplus` lift (tell [3]))
return [42::Int]
) @?= ((),[1,2,3])
]
,testGroup "exploreTreeUntilFirst"
[testCase "return" $ exploreTreeUntilFirst (return 42) @=? (Just 42 :: Maybe Int)
,testCase "null" $ exploreTreeUntilFirst mzero @=? (Nothing :: Maybe Int)
,testProperty "compared to exploreTree" $ \(tree :: Tree String) →
exploreTreeUntilFirst tree
==
case exploreTree (fmap (:[]) tree) of
[] → Nothing
(x:_) → Just x
]
,testGroup "exploreTreeTUntilFirst"
[testCase "return" $ runIdentity (exploreTreeTUntilFirst (return 42)) @=? (Just 42 :: Maybe Int)
,testCase "null" $ runIdentity(exploreTreeTUntilFirst mzero) @=? (Nothing :: Maybe Int)
,testProperty "compared to exploreTreeT" $ \(tree :: TreeT Identity String) →
runIdentity (exploreTreeTUntilFirst tree)
==
case runIdentity (exploreTreeT (fmap (:[]) tree)) of
[] → Nothing
(x:_) → Just x
]
,testGroup "exploreTreeUntilFound"
[testProperty "compared to exploreTree" $ do
UniqueTree tree ← arbitrary
let solutions = exploreTree tree
threshold ← (+1) <$> choose (0,2*IntSet.size solutions)
pure . unsafePerformIO . checkFoundAgainstThreshold threshold solutions $
exploreTreeUntilFound ((>= threshold) . IntSet.size) tree
]
,testGroup "exploreTreeTUntilFound"
[testProperty "compared to exploreTreeT" $ do
UniqueTree tree ← arbitrary
let solutions = runIdentity (exploreTreeT tree)
threshold ← (+1) <$> choose (0,2*IntSet.size solutions)
return . unsafePerformIO . checkFoundAgainstThreshold threshold solutions . runIdentity $
exploreTreeTUntilFound ((>= threshold) . IntSet.size) tree
]
]
| gcross/LogicGrowsOnTrees | LogicGrowsOnTrees/tests/test-LogicGrowsOnTrees.hs | bsd-2-clause | 4,743 | 0 | 20 | 1,266 | 1,471 | 780 | 691 | 99 | 3 |
{-# LANGUAGE GADTs #-}
module RISK.Compile
( compile
, indent
, block
) where
import Data.List (intercalate)
import Language.GIGL
import Text.Printf
import RISK.Kernel
import RISK.Spec
-- | Compiles a configured RISK kernel to C.
compile :: Spec -> String
compile spec = unlines $
[ printf "void %s (void);" name | (name, _) <- procs ] ++
[""] ++
map compileProc procs
where
procs = kernelProgram spec
compileProc :: (Name, Stmt Intrinsic) -> String
compileProc (name, stmt) = unlines
[ printf "void %s(void)" name
, block $ compileStmt stmt
]
compileStmt :: Stmt Intrinsic -> String
compileStmt a = case a of
Comment a -> "// " ++ a ++ "\n"
Null -> ""
Seq a b -> compileStmt a ++ compileStmt b
If a b c -> unlines
[ printf "if (%s)" $ compileExpr a
, block $ compileStmt b
, "else"
, block $ compileStmt c
]
Assign (Var a) b -> printf "%s = %s;\n" a $ compileExpr b
Assign _ _ -> error "Invalid LHS in assignment."
Call a -> printf "%s();\n" a
Intrinsic a -> case a of
SetMemoryPtrs -> "risk_set_memory_ptrs();\n"
ExitSimulation -> "exit(0);\n"
Return -> "return;\n"
SaveContext name -> printf "asm(\"movq %%%%rsp, %%0\" : \"=r\" (%s_stack_ptr) : );\n" name
RestoreContext name -> printf "asm(\"movq %%0, %%%%rsp\" : : \"r\" (%s_stack_ptr));\n" name
StartPartition name -> printf "%s_main();\n" name
TransferMessages from sendSize to recvSize -> printf "risk_transfer_messages(%s);\n" $ intercalate ", " args
where
args :: [String]
args =
[ printf "0x%xULL" $ (2 ^ sendSize :: Int)
, printf "(word *) %s_to_%s_send_buffer" from to
, printf "0x%xULL" $ (2 ^ recvSize - 1 :: Int)
, printf "(word *) %s_from_%s_recv_buffer" to from
, printf "* (word *) %s_from_%s_head_index" to from
, printf "(word *) %s_from_%s_tail_index" to from
]
compileExpr :: E a -> String
compileExpr a = case a of
Var a -> a
Index _ _ -> error "Array Index not supported."
Let _ _ _ -> error "Let expressions not supported."
Untyped a -> f a
Pair _ _ -> error "Pair expressions not supported."
Fst _ -> error "Fst expressions not supported."
Snd _ -> error "Snd expressions not supported."
Const a -> cValue $ value a
Add a b -> f2 "+" a b
Sub a b -> f2 "-" a b
Not a -> f1 "!" a
And a b -> f2 "&&" a b
Or a b -> f2 "||" a b
Imply a b -> printf "(! %s || %s)" (f a) (f b)
Equiv a b -> f2 "==" a b
Eq a b -> f2 "==" a b
Mux a b c -> printf "(%s ? %s : %s)" (f a) (f b) (f c)
where
f :: E a -> String
f = compileExpr
f1 :: String -> E a -> String
f1 op a = "(" ++ op ++ " " ++ f a ++ ")"
f2 :: String -> E a -> E a -> String
f2 op a b = "(" ++ f a ++ " " ++ op ++ " " ++ f b ++ ")"
cValue :: Value -> String
cValue a = case a of
VBool True -> "1"
VBool False -> "0"
VWord64 a -> printf "0x%016xULL" a
VPair _ _ -> error "Pair values not supported."
indent :: String -> String
indent = intercalate "\n" . map ("\t" ++) . lines
block :: String -> String
block a = "{\n" ++ (indent a) ++ "\n}\n"
| tomahawkins/risk | RISK/Compile.hs | bsd-2-clause | 3,245 | 0 | 17 | 956 | 1,127 | 546 | 581 | 84 | 20 |
---------------------------------------------------------------------------
-- |
-- Module : Control.Agent.Free.Interfaces
-- Copyright : (c) Nickolay Kudasov 2013
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : nickolay.kudasov@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- Common interfaces.
---------------------------------------------------------------------------
module Control.Agent.Free.Interfaces (
module Control.Agent.Free.Interfaces.SendRecv
) where
import Control.Agent.Free.Interfaces.SendRecv
| fizruk/free-agent | src/Control/Agent/Free/Interfaces.hs | bsd-3-clause | 572 | 0 | 5 | 76 | 39 | 32 | 7 | 3 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Coord where
import qualified Control.Monad.Random as Random
import GHC.Generics
import Prelude hiding (Either(..), id, (.))
import Control.Category
import Data.Default
import Control.Lens
import Data.Map.Strict as Map
import qualified System.Random.Shuffle as Random
import Control.Monad
data Coord = Coord
{ __x :: Integer
, __y :: Integer
} deriving (Eq,Show,Read,Ord,Generic)
makeLenses ''Coord
data Bounds = Bounds
{ lower :: Coord
, upper :: Coord
} deriving (Eq,Show,Read,Ord,Generic)
instance Default Bounds where
def = Bounds def def
instance Default Coord where
def = Coord 0 0
type WorldCoord = Coord
type ScreenCoord = Coord
type DeltaCoord = Coord
type CoordMap a = Map.Map Coord a
instance Num Coord where
(+) (Coord x y) (Coord x' y') = Coord (x + x') (y + y')
(*) (Coord x y) (Coord x' y') = Coord (x * x') (y * y')
negate (Coord x y) = Coord (-x) (-y)
abs (Coord x y) = Coord (abs x) (abs y)
signum (Coord x y) = Coord (signum x) (signum y)
fromInteger i = Coord i' i'
where
i' = fromInteger i
quot :: Coord -> Coord -> Coord
quot (Coord ax ay) (Coord bx by) =
Coord (ax `Prelude.quot` bx) (ay `Prelude.quot` by)
toPair :: Integral i => Coord -> (i, i)
toPair (Coord x y) = (fromInteger x, fromInteger y)
fromPair :: Integral i => (i, i) -> Coord
fromPair (x,y) = Coord (fromIntegral x) (fromIntegral y)
boundsToPair :: Integral i => Bounds -> ((i, i), (i, i))
boundsToPair bounds = ( toPair <<< lower $ bounds, toPair <<< upper $ bounds)
coordsWithin :: Bounds -> [Coord]
coordsWithin (Bounds (Coord lx ly) (Coord ux uy)) =
[ Coord x y
| x <- [lx .. ux]
, y <- [ly .. uy] ]
borderCoords :: Bounds -> [Coord]
borderCoords (Bounds (Coord lx ly) (Coord ux uy)) =
[ Coord x y
| x <- [lx .. ux]
, y <- [ly .. uy]
, x == lx || x == ux || y == ly || y == uy ]
between
:: (Ord a)
=> a -> a -> a -> Bool
between test l u = test >= l && test < u
within :: Coord -> Bounds -> Bool
within (Coord cx cy) (Bounds (Coord lx ly) (Coord ux uy)) = withinX && withinY
where
withinX = between cx lx ux
withinY = between cy ly uy
coordSgn :: Coord -> Coord
coordSgn (Coord x y) = Coord sx sy
where
sx = signum x
sy = signum y
randomWithin
:: Random.MonadRandom m
=> Bounds -> m Coord
randomWithin b = Random.uniform (coordsWithin b)
-- Direction
data Direction
= Up
| Down
| Left
| Right
deriving (Show,Read,Eq,Generic)
fromDirection :: Direction -> Coord
fromDirection d =
case d of
Left -> Coord 0 (-1)
Right -> Coord 0 1
Up -> Coord (-1) 0
Down -> Coord 1 0
origin :: Coord
origin = Coord 0 0
flipOrder :: Coord -> Coord
flipOrder (Coord x y) = Coord y x
insetBounds :: Integer -> Bounds -> Bounds
insetBounds i (Bounds l u) = (Bounds l' u')
where
offset = (Coord i i)
l' = l + offset
u' = u - offset
splitCoordDelta :: Coord -> [Coord]
splitCoordDelta (Coord x y) =
[ (Coord xs ys)
| xs <- [x, 0]
, ys <- [y, 0] ]
getRandomDirection
:: (Random.MonadRandom m)
=> m Direction
getRandomDirection =
Random.uniform [Coord.Left, Coord.Right, Coord.Down, Coord.Up]
randomDeltas
:: (Random.MonadRandom m)
=> m [Coord]
randomDeltas =
Random.shuffleM
[ (Coord xs ys)
| xs <- [-1, 0, 1]
, ys <- [-1, 0, 1] ]
pairDistance :: (Int, Int) -> (Int, Int) -> Double
pairDistance (x0, y0) (x1, y1) = sqrt $ fromIntegral ((x1 - x0)^(2 :: Integer) + (y1 - y0)^(2 :: Integer))
distance :: Coord -> Coord -> Double
distance (Coord x0 y0) (Coord x1 y1) = sqrt $ fromIntegral ((x1 - x0)^(2 :: Integer) + (y1 - y0)^(2 :: Integer))
line :: Coord -> Coord -> [Coord]
line c0 c1 = fromPair <$> line' (toPair c0) (toPair c1)
segment :: Coord -> Coord -> [Coord] -- Does not include final point
segment p1 p2 = takeWhile (/= p2 )$ line p1 p2
circleCoords :: Integer -> Coord -> [Coord]
circleCoords r center = fmap (+ center) $ do
x <- [-r..r]
y <- [-r..r]
guard (distance origin (Coord x y) < fromIntegral r)
return (Coord x y)
line' :: (Int, Int) -> (Int, Int) -> [(Int, Int)]
line' (x0, y0) (x1, y1) =
let (dx, dy) = (x1 - x0, y1 - y0)
xyStep b (x, y) = (x + signum dx, y + signum dy * b)
yxStep b (x, y) = (x + signum dx * b, y + signum dy)
(p, q, step) | abs dx > abs dy = (abs dy, abs dx, xyStep)
| otherwise = (abs dx, abs dy, yxStep)
walk w xy = xy : walk (tail w) (step (head w) xy)
in walk (balancedWord p q 0) (x0, y0)
where
balancedWord :: Int -> Int -> Int -> [Int]
balancedWord p q eps | eps + p < q = 0 : balancedWord p q (eps + p)
balancedWord p q eps = 1 : balancedWord p q (eps + p - q)
| fros1y/umbral | src/Coord.hs | bsd-3-clause | 4,858 | 0 | 14 | 1,295 | 2,315 | 1,237 | 1,078 | 139 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Miso.Html.Property
-- Copyright : (C) 2016-2018 David M. Johnson
-- License : BSD3-style (see the file LICENSE)
-- Maintainer : David M. Johnson <djohnson.m@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Construct custom properties on DOM elements
--
-- > div_ [ prop "id" "foo" ] [ ]
--
----------------------------------------------------------------------------
module Miso.Html.Property
( -- * Construction
textProp
, stringProp
, boolProp
, intProp
, integerProp
, doubleProp
-- * Common attributes
, class_
, classList_
, id_
, title_
, hidden_
-- * Inputs
, type_
, value_
, defaultValue_
, checked_
, placeholder_
, selected_
-- * Input Helpers
, accept_
, acceptCharset_
, action_
, autocomplete_
, autofocus_
, autosave_
, disabled_
, enctype_
, formation_
, list_
, maxlength_
, minlength_
, method_
, multiple_
, name_
, novalidate_
, pattern_
, readonly_
, required_
, size_
, for_
, ref_
, form_
-- * Input Ranges
, max_
, min_
, step_
-- * Input Text areas
, cols_
, rows_
, wrap_
-- * Links and areas
, href_
, target_
, download_
, downloadAs_
, hreflang_
, media_
, ping_
, rel_
-- * Maps
, ismap_
, usemap_
, shape_
, coords_
-- * Embedded Content
, src_
, height_
, width_
, alt_
, loading_
-- * Audio and Video
, autoplay_
, controls_
, loop_
, preload_
, poster_
, default_
, kind_
, srclang_
-- * iframes
, sandbox_
, seamless_
, srcdoc_
-- * Ordered lists
, reversed_
, start_
-- * Tables
, align_
, colspan_
, rowspan_
, headers_
, scope_
-- * Headers
, async_
, charset_
, content_
, defer_
, httpEquiv_
, language_
, scoped_
-- * Data
, data_
, styleInline_
) where
import Miso.Html.Types
import Miso.String (MisoString, intercalate)
#if __GLASGOW_HASKELL__ < 841
import Data.Monoid ((<>))
#endif
-- | Set field to `Bool` value
boolProp :: MisoString -> Bool -> Attribute action
boolProp = prop
-- | Set field to `String` value
stringProp :: MisoString -> String -> Attribute action
stringProp = prop
-- | Set field to `Text` value
textProp :: MisoString -> MisoString -> Attribute action
textProp = prop
-- | Set field to `Int` value
intProp :: MisoString -> Int -> Attribute action
intProp = prop
-- | Set field to `Integer` value
integerProp :: MisoString -> Int -> Attribute action
integerProp = prop
-- | Set field to `Double` value
doubleProp :: MisoString -> Double -> Attribute action
doubleProp = prop
-- | Define multiple classes conditionally
--
-- > div_ [ classList_ [ ("empty", null items) ] [ ]
--
classList_ :: [(MisoString, Bool)] -> Attribute action
classList_ xs =
textProp "class" $ intercalate (" " :: MisoString) [ t | (t, True) <- xs ]
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/title>
title_ :: MisoString -> Attribute action
title_ = textProp "title"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/selected>
selected_ :: Bool -> Attribute action
selected_ = boolProp "selected"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/hidden>
hidden_ :: Bool -> Attribute action
hidden_ = boolProp "hidden"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/value>
value_ :: MisoString -> Attribute action
value_ = textProp "value"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/defaultValue>
defaultValue_ :: MisoString -> Attribute action
defaultValue_ = textProp "defaultValue"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/accept>
accept_ :: MisoString -> Attribute action
accept_ = textProp "accept"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/acceptCharset>
acceptCharset_ :: MisoString -> Attribute action
acceptCharset_ = textProp "acceptCharset"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/action>
action_ :: MisoString -> Attribute action
action_ = textProp "action"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/autocomplete>
autocomplete_ :: Bool -> Attribute action
autocomplete_ b = textProp "autocomplete" (if b then "on" else "off")
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/autosave>
autosave_ :: MisoString -> Attribute action
autosave_ = textProp "autosave"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/disabled>
disabled_ :: Bool -> Attribute action
disabled_ = boolProp "disabled"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/enctype>
enctype_ :: MisoString -> Attribute action
enctype_ = textProp "enctype"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/formation>
formation_ :: MisoString -> Attribute action
formation_ = textProp "formation"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/list>
list_ :: MisoString -> Attribute action
list_ = textProp "list"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/maxlength>
maxlength_ :: MisoString -> Attribute action
maxlength_ = textProp "maxlength"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/minlength>
minlength_ :: MisoString -> Attribute action
minlength_ = textProp "minlength"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/method>
method_ :: MisoString -> Attribute action
method_ = textProp "method"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/multiple>
multiple_ :: Bool -> Attribute action
multiple_ = boolProp "multiple"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/novalidate>
novalidate_ :: Bool -> Attribute action
novalidate_ = boolProp "noValidate"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/pattern>
pattern_ :: MisoString -> Attribute action
pattern_ = textProp "pattern"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/readonly>
readonly_ :: Bool -> Attribute action
readonly_ = boolProp "readOnly"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/required>
required_ :: Bool -> Attribute action
required_ = boolProp "required"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/size>
size_ :: MisoString -> Attribute action
size_ = textProp "size"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/for>
for_ :: MisoString -> Attribute action
for_ = textProp "for"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/ref>
ref_ :: MisoString -> Attribute action
ref_ = textProp "ref"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/form>
form_ :: MisoString -> Attribute action
form_ = textProp "form"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/max>
max_ :: MisoString -> Attribute action
max_ = textProp "max"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/min>
min_ :: MisoString -> Attribute action
min_ = textProp "min"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/step>
step_ :: MisoString -> Attribute action
step_ = textProp "step"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/cols>
cols_ :: MisoString -> Attribute action
cols_ = textProp "cols"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/rows>
rows_ :: MisoString -> Attribute action
rows_ = textProp "rows"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/wrap>
wrap_ :: MisoString -> Attribute action
wrap_ = textProp "wrap"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/target>
target_ :: MisoString -> Attribute action
target_ = textProp "target"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/download>
download_ :: MisoString -> Attribute action
download_ = textProp "download"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/downloadAs>
downloadAs_ :: MisoString -> Attribute action
downloadAs_ = textProp "downloadAs"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/hreflang>
hreflang_ :: MisoString -> Attribute action
hreflang_ = textProp "hreflang"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/media>
media_ :: MisoString -> Attribute action
media_ = textProp "media"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/ping>
ping_ :: MisoString -> Attribute action
ping_ = textProp "ping"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/rel>
rel_ :: MisoString -> Attribute action
rel_ = textProp "rel"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/ismap>
ismap_ :: MisoString -> Attribute action
ismap_ = textProp "ismap"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/usemap>
usemap_ :: MisoString -> Attribute action
usemap_ = textProp "usemap"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/shape>
shape_ :: MisoString -> Attribute action
shape_ = textProp "shape"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/coords>
coords_ :: MisoString -> Attribute action
coords_ = textProp "coords"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/src>
src_ :: MisoString -> Attribute action
src_ = textProp "src"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/height>
height_ :: MisoString -> Attribute action
height_ = textProp "height"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/width>
width_ :: MisoString -> Attribute action
width_ = textProp "width"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/alt>
alt_ :: MisoString -> Attribute action
alt_ = textProp "alt"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/loading>
loading_ :: MisoString -> Attribute action
loading_ = textProp "loading"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/autoplay>
autoplay_ :: Bool -> Attribute action
autoplay_ = boolProp "autoplay"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/controls>
controls_ :: Bool -> Attribute action
controls_ = boolProp "controls"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/loop>
loop_ :: Bool -> Attribute action
loop_ = boolProp "loop"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/preload>
preload_ :: MisoString -> Attribute action
preload_ = textProp "preload"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/poster>
poster_ :: MisoString -> Attribute action
poster_ = textProp "poster"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/default>
default_ :: Bool -> Attribute action
default_ = boolProp "default"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/kind>
kind_ :: MisoString -> Attribute action
kind_ = textProp "kind"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/srclang>
srclang_ :: MisoString -> Attribute action
srclang_ = textProp "srclang"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/sandbox>
sandbox_ :: MisoString -> Attribute action
sandbox_ = textProp "sandbox"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/seamless>
seamless_ :: MisoString -> Attribute action
seamless_ = textProp "seamless"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/srcdoc>
srcdoc_ :: MisoString -> Attribute action
srcdoc_ = textProp "srcdoc"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/reversed>
reversed_ :: MisoString -> Attribute action
reversed_ = textProp "reversed"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/start>
start_ :: MisoString -> Attribute action
start_ = textProp "start"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/align>
align_ :: MisoString -> Attribute action
align_ = textProp "align"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/colspan>
colspan_ :: MisoString -> Attribute action
colspan_ = textProp "colspan"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/rowspan>
rowspan_ :: MisoString -> Attribute action
rowspan_ = textProp "rowspan"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/headers>
headers_ :: MisoString -> Attribute action
headers_ = textProp "headers"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/scope>
scope_ :: MisoString -> Attribute action
scope_ = textProp "scope"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/async>
async_ :: MisoString -> Attribute action
async_ = textProp "async"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/charset>
charset_ :: MisoString -> Attribute action
charset_ = textProp "charset"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/content>
content_ :: MisoString -> Attribute action
content_ = textProp "content"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/defer>
defer_ :: MisoString -> Attribute action
defer_ = textProp "defer"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/httpEquiv>
httpEquiv_ :: MisoString -> Attribute action
httpEquiv_ = textProp "httpEquiv"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/language>
language_ :: MisoString -> Attribute action
language_ = textProp "language"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/scoped>
scoped_ :: MisoString -> Attribute action
scoped_ = textProp "scoped"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/type>
type_ :: MisoString -> Attribute action
type_ = textProp "type"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/name>
name_ :: MisoString -> Attribute action
name_ = textProp "name"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/href>
href_ :: MisoString -> Attribute action
href_ = textProp "href"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/id>
id_ :: MisoString -> Attribute action
id_ = textProp "id"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/placeholder>
placeholder_ :: MisoString -> Attribute action
placeholder_ = textProp "placeholder"
-- | <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/checked>
checked_ :: Bool -> Attribute action
checked_ = boolProp "checked"
-- | Set "autofocus" property
-- <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/autofocus>
autofocus_ :: Bool -> Attribute action
autofocus_ = boolProp "autofocus"
-- | Set "className" property
-- <https://developer.mozilla.org/en-US/docs/Web/API/Element/className>
class_ :: MisoString -> Attribute action
class_ = textProp "class"
-- | Set "data-*" property
-- https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*
data_ :: MisoString -> MisoString -> Attribute action
data_ k v = textProp ("data-" <> k) v
-- | Set "style" property
--
-- > view m = div_ [ styleInline_ "background-color:red;color:blue;" ] [ "foo" ]
--
-- https://developer.mozilla.org/en-US/docs/Web/CSS
styleInline_ :: MisoString -> Attribute action
styleInline_ = textProp "style"
| dmjio/miso | src/Miso/Html/Property.hs | bsd-3-clause | 16,824 | 0 | 10 | 2,818 | 2,327 | 1,288 | 1,039 | 278 | 2 |
main = interact deleteSpace
deleteSpace "" = ""
deleteSpace ('(':' ':cs) = '(' : deleteSpace cs
deleteSpace (' ':')':cs) = ')' : deleteSpace cs
deleteSpace ('[':' ':cs) = '[' : deleteSpace cs
deleteSpace ('\n' : ' ' : ']' : cs) = '\n' : ' ' : ']' : deleteSpace cs
deleteSpace (' ':']':cs) = ']' : deleteSpace cs
deleteSpace (c : cs) = c : deleteSpace cs
| YoshikuniJujo/toyhaskell_haskell | tools/deleteSpaceInParens.hs | bsd-3-clause | 364 | 14 | 9 | 78 | 195 | 97 | 98 | 8 | 1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Freeze
-- Copyright : (c) David Himmelstrup 2005
-- Duncan Coutts 2011
-- License : BSD-like
--
-- Maintainer : cabal-devel@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- The cabal freeze command
-----------------------------------------------------------------------------
module Distribution.Client.Freeze (
freeze,
) where
import Distribution.Client.Config ( SavedConfig(..) )
import Distribution.Client.Types
import Distribution.Client.Targets
import Distribution.Client.Dependency
import Distribution.Client.Dependency.Types
( ConstraintSource(..), LabeledPackageConstraint(..) )
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackages, getInstalledPackages )
import Distribution.Client.InstallPlan
( InstallPlan, PlanPackage )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.PkgConfigDb
( PkgConfigDb, readPkgConfigDb )
import Distribution.Client.Setup
( GlobalFlags(..), FreezeFlags(..), ConfigExFlags(..)
, RepoContext(..) )
import Distribution.Client.Sandbox.PackageEnvironment
( loadUserConfig, pkgEnvSavedConfig, showPackageEnvironment,
userPackageEnvironmentFile )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Package
( Package, packageId, packageName, packageVersion )
import Distribution.Simple.Compiler
( Compiler, compilerInfo, PackageDBStack )
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import Distribution.Simple.Program
( ProgramConfiguration )
import Distribution.Simple.Setup
( fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Simple.Utils
( die, notice, debug, writeFileAtomic )
import Distribution.System
( Platform )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import Control.Monad
( when )
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( mempty )
#endif
import Data.Version
( showVersion )
import Distribution.Version
( thisVersion )
-- ------------------------------------------------------------
-- * The freeze command
-- ------------------------------------------------------------
-- | Freeze all of the dependencies by writing a constraints section
-- constraining each dependency to an exact version.
--
freeze :: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> Platform
-> ProgramConfiguration
-> Maybe SandboxPackageInfo
-> GlobalFlags
-> FreezeFlags
-> IO ()
freeze verbosity packageDBs repoCtxt comp platform conf mSandboxPkgInfo
globalFlags freezeFlags = do
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
sourcePkgDb <- getSourcePackages verbosity repoCtxt
pkgConfigDb <- readPkgConfigDb verbosity conf
pkgSpecifiers <- resolveUserTargets verbosity repoCtxt
(fromFlag $ globalWorldFile globalFlags)
(packageIndex sourcePkgDb)
[UserTargetLocalDir "."]
sanityCheck pkgSpecifiers
pkgs <- planPackages
verbosity comp platform mSandboxPkgInfo freezeFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers
if null pkgs
then notice verbosity $ "No packages to be frozen. "
++ "As this package has no dependencies."
else if dryRun
then notice verbosity $ unlines $
"The following packages would be frozen:"
: formatPkgs pkgs
else freezePackages globalFlags verbosity pkgs
where
dryRun = fromFlag (freezeDryRun freezeFlags)
sanityCheck pkgSpecifiers = do
when (not . null $ [n | n@(NamedPackage _ _) <- pkgSpecifiers]) $
die $ "internal error: 'resolveUserTargets' returned "
++ "unexpected named package specifiers!"
when (length pkgSpecifiers /= 1) $
die $ "internal error: 'resolveUserTargets' returned "
++ "unexpected source package specifiers!"
planPackages :: Verbosity
-> Compiler
-> Platform
-> Maybe SandboxPackageInfo
-> FreezeFlags
-> InstalledPackageIndex
-> SourcePackageDb
-> PkgConfigDb
-> [PackageSpecifier SourcePackage]
-> IO [PlanPackage]
planPackages verbosity comp platform mSandboxPkgInfo freezeFlags
installedPkgIndex sourcePkgDb pkgConfigDb pkgSpecifiers = do
solver <- chooseSolver verbosity
(fromFlag (freezeSolver freezeFlags)) (compilerInfo comp)
notice verbosity "Resolving dependencies..."
installPlan <- foldProgress logMsg die return $
resolveDependencies
platform (compilerInfo comp) pkgConfigDb
solver
resolverParams
return $ pruneInstallPlan installPlan pkgSpecifiers
where
resolverParams =
setMaxBackjumps (if maxBackjumps < 0 then Nothing
else Just maxBackjumps)
. setIndependentGoals independentGoals
. setReorderGoals reorderGoals
. setShadowPkgs shadowPkgs
. setStrongFlags strongFlags
. addConstraints
[ let pkg = pkgSpecifierTarget pkgSpecifier
pc = PackageConstraintStanzas pkg stanzas
in LabeledPackageConstraint pc ConstraintSourceFreeze
| pkgSpecifier <- pkgSpecifiers ]
. maybe id applySandboxInstallPolicy mSandboxPkgInfo
$ standardInstallPolicy installedPkgIndex sourcePkgDb pkgSpecifiers
logMsg message rest = debug verbosity message >> rest
stanzas = [ TestStanzas | testsEnabled ]
++ [ BenchStanzas | benchmarksEnabled ]
testsEnabled = fromFlagOrDefault False $ freezeTests freezeFlags
benchmarksEnabled = fromFlagOrDefault False $ freezeBenchmarks freezeFlags
reorderGoals = fromFlag (freezeReorderGoals freezeFlags)
independentGoals = fromFlag (freezeIndependentGoals freezeFlags)
shadowPkgs = fromFlag (freezeShadowPkgs freezeFlags)
strongFlags = fromFlag (freezeStrongFlags freezeFlags)
maxBackjumps = fromFlag (freezeMaxBackjumps freezeFlags)
-- | Remove all unneeded packages from an install plan.
--
-- A package is unneeded if it is either
--
-- 1) the package that we are freezing, or
--
-- 2) not a dependency (directly or transitively) of the package we are
-- freezing. This is useful for removing previously installed packages
-- which are no longer required from the install plan.
pruneInstallPlan :: InstallPlan
-> [PackageSpecifier SourcePackage]
-> [PlanPackage]
pruneInstallPlan installPlan pkgSpecifiers =
removeSelf pkgIds $
InstallPlan.dependencyClosure installPlan (map fakeUnitId pkgIds)
where
pkgIds = [ packageId pkg
| SpecificSourcePackage pkg <- pkgSpecifiers ]
removeSelf [thisPkg] = filter (\pp -> packageId pp /= packageId thisPkg)
removeSelf _ = error $ "internal error: 'pruneInstallPlan' given "
++ "unexpected package specifiers!"
freezePackages :: Package pkg => GlobalFlags -> Verbosity -> [pkg] -> IO ()
freezePackages globalFlags verbosity pkgs = do
pkgEnv <- fmap (createPkgEnv . addFrozenConstraints) $
loadUserConfig verbosity "" (flagToMaybe . globalConstraintsFile $ globalFlags)
writeFileAtomic userPackageEnvironmentFile $ showPkgEnv pkgEnv
where
addFrozenConstraints config =
config {
savedConfigureExFlags = (savedConfigureExFlags config) {
configExConstraints = map constraint pkgs
}
}
constraint pkg =
(pkgIdToConstraint $ packageId pkg, ConstraintSourceUserConfig userPackageEnvironmentFile)
where
pkgIdToConstraint pkgId =
UserConstraintVersion (packageName pkgId)
(thisVersion $ packageVersion pkgId)
createPkgEnv config = mempty { pkgEnvSavedConfig = config }
showPkgEnv = BS.Char8.pack . showPackageEnvironment
formatPkgs :: Package pkg => [pkg] -> [String]
formatPkgs = map $ showPkg . packageId
where
showPkg pid = name pid ++ " == " ++ version pid
name = display . packageName
version = showVersion . packageVersion
| garetxe/cabal | cabal-install/Distribution/Client/Freeze.hs | bsd-3-clause | 8,787 | 0 | 20 | 2,239 | 1,602 | 862 | 740 | 166 | 3 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import qualified Data.Aeson as A
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Traversable as T
import Data.Yaml
import Database.Persist
import Database.Persist.Types
import DirectedKeys.GenerateCfg
import GHC.Generics
import Persist.Mongo.Settings
import Prelude
main :: IO ()
main = do
dbConf <- readDBConf "config.yml"
genConf <- readKeyGen "config.yml"
let hosts = (hostList genConf)
eBoundList <- T.sequence $ (\conf -> createAndMatchKeys conf getAlarmId hosts) <$> dbConf
case eBoundList of
Left _ -> putStrLn "Error reading config file"
Right boundList -> BSL.putStrLn . A.encode $ listToOutput boundList
getAlarmId :: Entity Alarm -> Key Alarm
getAlarmId = entityKey
getOnpingTagPid :: Entity OnpingTagHistory -> Maybe Int
getOnpingTagPid = onpingTagHistoryPid . entityVal
readKeyGen :: FilePath -> IO KeyGenConfig
readKeyGen fp = do
contents <- BS.readFile fp
case (decodeEither contents) of
Left _ -> fail "Unable to parse KeyGenConfig"
Right kgcfg -> return kgcfg
listToOutput :: [(a,b)] -> [KeyGenOutput b a]
listToOutput sList = map (\(host, bound) -> KeyGenOutput bound host ) sList
data KeyGenConfig = KeyGenConfig {
hostList :: [String]
} deriving (Eq, Show, Generic)
instance FromJSON KeyGenConfig where
data KeyGenOutput a b = KeyGenOutput {
keyGenHost :: a
, keyGenBound :: b
} deriving (Eq, Show)
instance (ToJSON a, ToJSON b) => ToJSON (KeyGenOutput a b) where
toJSON (KeyGenOutput {..}) = object ["host" .= keyGenHost
,"upperBound" .= keyGenBound]
| plow-technologies/dkrouter-generator | src/Main.hs | bsd-3-clause | 1,940 | 0 | 12 | 470 | 526 | 283 | 243 | 49 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Instances () where
import Prelude.Compat
import Control.Applicative (empty)
import Control.Monad
import Data.Aeson.Types
import qualified Data.Aeson.KeyMap as KM
import Data.Function (on)
import Data.Time (ZonedTime(..), TimeZone(..))
import Data.Time.Clock (UTCTime(..))
import Functions
import Test.QuickCheck (Arbitrary(..), elements, oneof, sized, Gen, chooseInt, shuffle)
import Types
import qualified Data.Aeson.Key as Key
import qualified Data.DList as DList
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as HM
import Data.Orphans ()
import Test.QuickCheck.Instances ()
-- "System" types.
instance Arbitrary DotNetTime where
arbitrary = DotNetTime `fmap` arbitrary
shrink = map DotNetTime . shrink . fromDotNetTime
-- | Compare timezone part only on 'timeZoneMinutes'
instance Eq ZonedTime where
ZonedTime a (TimeZone a' _ _) == ZonedTime b (TimeZone b' _ _) =
a == b && a' == b'
-- Compare equality to within a millisecond, allowing for rounding
-- error (ECMA 262 requires milliseconds to rounded to zero, not
-- rounded to nearest).
instance ApproxEq UTCTime where
a =~ b = ((==) `on` utctDay) a b &&
(approxEqWith 1 1 `on` ((* 1e3) . utctDayTime)) a b
instance ApproxEq DotNetTime where
(=~) = (=~) `on` fromDotNetTime
instance ApproxEq Float where
a =~ b
| isNaN a && isNaN b = True
| otherwise = approxEq a b
instance ApproxEq Double where
a =~ b
| isNaN a && isNaN b = True
| otherwise = approxEq a b
instance (ApproxEq k, Eq v) => ApproxEq (HM.HashMap k v) where
a =~ b = and $ zipWith eq (HM.toList a) (HM.toList b)
where
eq (x,y) (u,v) = x =~ u && y == v
-- Test-related types.
instance Arbitrary Foo where
arbitrary = liftM4 Foo arbitrary arbitrary arbitrary arbitrary
instance Eq Foo where
a == b = fooInt a == fooInt b &&
fooDouble a `approxEq` fooDouble b &&
fooTuple a == fooTuple b
instance ToJSON Foo where
toJSON Foo{..} = object [ "fooInt" .= fooInt
, "fooDouble" .= fooDouble
, "fooTuple" .= fooTuple
, "fooMap" .= fooMap
]
instance FromJSON Foo where
parseJSON (Object v) = Foo <$>
v .: "fooInt" <*>
v .: "fooDouble" <*>
v .: "fooTuple" <*>
v .: "fooMap"
parseJSON _ = empty
instance Arbitrary UFoo where
arbitrary = UFoo <$> arbitrary <*> arbitrary
where _ = uFooInt
instance Arbitrary OneConstructor where
arbitrary = return OneConstructor
instance FromJSON OneConstructor
instance ToJSON OneConstructor
instance (Arbitrary a, Arbitrary b) => Arbitrary (Product2 a b) where
arbitrary = liftM2 Product2 arbitrary arbitrary
instance (FromJSON a, FromJSON b) => FromJSON (Product2 a b)
instance (ToJSON a, ToJSON b) => ToJSON (Product2 a b)
instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e,
Arbitrary f) => Arbitrary (Product6 a b c d e f) where
arbitrary = Product6 <$> arbitrary <*> arbitrary <*> arbitrary <*>
arbitrary <*> arbitrary <*> arbitrary
instance (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e,
FromJSON f) => FromJSON (Product6 a b c d e f)
instance (ToJSON a, ToJSON b, ToJSON c, ToJSON d, ToJSON e,
ToJSON f) => ToJSON (Product6 a b c d e f)
instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d)
=> Arbitrary (Sum4 a b c d) where
arbitrary = oneof [Alt1 <$> arbitrary, Alt2 <$> arbitrary,
Alt3 <$> arbitrary, Alt4 <$> arbitrary]
instance (FromJSON a, FromJSON b, FromJSON c, FromJSON d)
=> FromJSON (Sum4 a b c d)
instance (ToJSON a, ToJSON b, ToJSON c, ToJSON d) => ToJSON (Sum4 a b c d)
instance (Arbitrary a) => Arbitrary (Approx a) where
arbitrary = Approx <$> arbitrary
instance (FromJSON a) => FromJSON (Approx a) where
parseJSON a = Approx <$> parseJSON a
instance (ToJSON a) => ToJSON (Approx a) where
toJSON = toJSON . fromApprox
instance Arbitrary Nullary where
arbitrary = elements [C1, C2, C3]
instance Arbitrary a => Arbitrary (SomeType a) where
arbitrary = oneof [ pure Nullary
, Unary <$> arbitrary
, Product <$> arbitrary <*> arbitrary <*> arbitrary
, Record <$> arbitrary <*> arbitrary <*> arbitrary
, List <$> arbitrary
]
instance Arbitrary EitherTextInt where
arbitrary = oneof
[ LeftBool <$> arbitrary
, RightInt <$> arbitrary
, BothTextInt <$> arbitrary <*> arbitrary
, pure NoneNullary
]
instance Arbitrary (GADT String) where
arbitrary = GADT <$> arbitrary
#if !MIN_VERSION_base(4,16,0)
instance Arbitrary OptionField where
arbitrary = OptionField <$> arbitrary
#endif
instance ApproxEq Char where
(=~) = (==)
instance (ApproxEq a) => ApproxEq [a] where
a =~ b = length a == length b && all (uncurry (=~)) (zip a b)
instance Arbitrary a => Arbitrary (DList.DList a) where
arbitrary = DList.fromList <$> arbitrary
instance Arbitrary Key where
arbitrary = Key.fromText <$> arbitrary
instance Arbitrary Value where
arbitrary = sized arb where
arb :: Int -> Gen Value
arb n
| n <= 1 = oneof
[ return Null
, fmap Bool arbitrary
, fmap String arbitrary
, fmap Number arbitrary
]
| otherwise = oneof [arr n, obj n]
arr n = do
pars <- arbPartition (n - 1)
fmap (Array . V.fromList) (traverse arb pars)
obj n = do
pars <- arbPartition (n - 1)
fmap (Object . KM.fromList) (traverse pair pars)
pair n = do
k <- arbitrary
v <- arb n
return (k, v)
arbPartition :: Int -> Gen [Int]
arbPartition k = case compare k 1 of
LT -> pure []
EQ -> pure [1]
GT -> do
first <- chooseInt (1, k)
rest <- arbPartition $ k - first
shuffle (first : rest)
| dmjio/aeson | tests/Instances.hs | bsd-3-clause | 6,571 | 0 | 15 | 1,985 | 2,112 | 1,102 | 1,010 | 151 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Physics.Falling3d.Box
(
Box(..)
, boxVolume
, boxInertiaTensor
)
where
import Data.Vect.Double.Base
import Physics.Falling.Shape.ImplicitShape
import Physics.Falling3d.InertiaTensor3d
-- | A 3D box described by its half-extents along each axis.
-- /FIXME: will be replaced by an n-dimensional box on the future./
data Box = Box Double Double Double
deriving(Show)
instance ImplicitShape Box Vec3 where
supportPoint (Box rx ry rz) (Vec3 dx dy dz) = Vec3 (signum dx * rx)
(signum dy * ry)
(signum dz * rz)
-- | The volume of a 3D box.
boxVolume :: Box -> Double
boxVolume (Box rx ry rz) = 8.0 * rx * ry * rz
-- | The local-space inertia tensor of a 3D box.
boxInertiaTensor :: Box -> Double -> InertiaTensor3d
boxInertiaTensor (Box rx ry rz) m = InertiaTensor3d
$ scaling
$ Vec3 (m_12 * (ry2 + rz2))
(m_12 * (rx2 + rz2))
(m_12 * (rx2 + ry2))
where
m_12 = m / 12.0
rx2 = rx * rx
ry2 = ry * ry
rz2 = rz * rz
| sebcrozet/falling3d | Physics/Falling3d/Box.hs | bsd-3-clause | 1,417 | 0 | 10 | 637 | 311 | 172 | 139 | 27 | 1 |
module Problem65 where
import Data.Ratio
main :: IO ()
main = print $ digitSum (numerator $ e 100)
fk :: Int -> Integer
fk x = case x `mod` 3 of
2 -> 2 * fromIntegral (x `div` 3 + 1)
_ -> 1
fractions :: [Integer]
fractions = map fk [1..]
inverse :: Rational -> Rational
inverse x = denominator x % numerator x
e :: Int -> Rational
e acc = 2 + go (take (acc - 1) fractions)
where
go :: [Integer] -> Rational
go [] = 0
go [i] = 1 % i
go (i:is) = inverse (fromIntegral i + go is)
digitSum :: Integer -> Integer
digitSum x = sum $ map (read . (:[])) (show x)
| noraesae/euler | src/Problem65.hs | bsd-3-clause | 590 | 0 | 12 | 157 | 302 | 159 | 143 | 20 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
-- | Sample program that sends a signal to the given PID after N calls.
module Main where
import Control.Concurrent (threadDelay)
import Control.Monad (when)
import Control.Monad.Reader
import Control.Monad.State
import Data.Acid
import Data.SafeCopy
import System.Console.CmdArgs.Implicit
import System.Posix.Signals (sigINT, signalProcess)
----------------------------------------------------------------------
-- State
----------------------------------------------------------------------
data KillState = KillState
{ sN :: Int -- ^ Number of calls.
, sSIG :: Int -- ^ The signal to send.
, sPID :: Int -- ^ The process ID the signal should be sent to.
}
deriving Typeable
data MKS = MKS (Maybe KillState)
deriving Typeable
deriveSafeCopy 0 'base ''KillState
deriveSafeCopy 0 'base ''MKS
writeState :: MKS -> Update MKS ()
writeState = put
queryState :: Query MKS MKS
queryState = ask
makeAcidic ''MKS
[ 'writeState
, 'queryState
]
openState :: IO (AcidState MKS)
openState = openLocalState (MKS Nothing)
closeState :: AcidState MKS -> IO ()
closeState = closeAcidState
-- | Return any previously saved state.
getState :: IO (Maybe KillState)
getState = do
a <- openState
MKS s <- query a QueryState
closeState a
return s
-- | If the PID and SIG are the same as previously saved, this increment the
-- call counter. Otherwise, the counter is put back to 1.
updateState :: Int -> Int -> IO KillState
updateState sig pid = do
a <- openState
MKS s <- query a QueryState
let n = case s of
Just (KillState{..}) | (sig, pid) == (sSIG, sPID) -> sN + 1
_ -> 1
_ <- update a $ WriteState (MKS . Just $ KillState n sig pid)
closeState a
return $ KillState n sig pid
-- | Remove any previously saved state.
resetState :: IO ()
resetState = do
a <- openState
_ <- update a $ WriteState (MKS Nothing)
closeState a
----------------------------------------------------------------------
-- Command-line
----------------------------------------------------------------------
main :: IO ()
main = (runCmd =<<) $ cmdArgs $
modes
[ cmdKill
, cmdReport
]
&= summary versionString
&= program "sentry-kill"
-- | String with the program name, version and copyright.
versionString :: String
versionString =
"Sentry Kill - Process monitoring. Copyright (c) 2012 Vo Minh Thu."
-- TODO add the version.
-- | Data type representing the different command-line subcommands.
data Cmd =
Kill { cmdSIG :: Int, cmdPID :: Int, cmdN :: Int, cmdSeconds :: Int }
-- ^ Send a signal to a process after N calls.
| Report
-- ^ Report the last used arguments for the `kill` sub-command.
deriving (Data, Typeable)
-- | Create a 'Kill' command.
cmdKill :: Cmd
cmdKill = Kill
{ cmdSIG = def
&= explicit
&= name "sig"
, cmdPID = def
&= explicit
&= name "pid"
, cmdN = def
&= explicit
&= name "n"
, cmdSeconds = def
&= explicit
&= name "seconds"
} &= help "Send a signal to a process after N calls."
&= explicit
&= name "kill"
-- | Create a 'Report' command.
cmdReport :: Cmd
cmdReport = Report
&= help "Report the last used arguments for the `kill` sub-command."
&= explicit
&= name "report"
-- | Run a sub-command.
runCmd :: Cmd -> IO ()
runCmd Kill{..} = do
KillState{..} <- updateState cmdSIG cmdPID
threadDelay $ cmdSeconds * 1000 * 1000
when (cmdN == sN) $ do
resetState
putStrLn $ "Killing " ++ show cmdPID ++ "."
signalProcess sigINT $ fromIntegral cmdPID -- TODO cmdSIG
runCmd Report{..} = do
ms <- getState
case ms of
Just (KillState{..}) ->
putStrLn $ "PID SIG N: " ++ unwords (map show [sPID, sSIG, sN])
Nothing -> putStrLn "No previously saved state."
| noteed/sentry | bin/sentry-kill.hs | bsd-3-clause | 3,914 | 0 | 17 | 825 | 971 | 508 | 463 | 105 | 2 |
module Language.TNT.Namer (name) where
import Control.Applicative
import Control.Comonad
import Control.Monad.Identity hiding (mapM)
import Data.Traversable
import Language.TNT.Error
import Language.TNT.Location
import Language.TNT.Name
import Language.TNT.Scope
import Language.TNT.Stmt
import Prelude hiding (lookup, mapM)
type Namer = ScopeT (ErrorT (Located String) Identity)
name :: Dec Located String ->
ErrorT (Located String) Identity (Dec Located Name)
name = runScopeT . nameDec
nameDec :: Dec Located String -> Namer (Dec Located Name)
nameDec (FunD a b c) = do
x <- define (a <$ c)
y <- mapM define (map (<$ c) b)
z <- mapM nameStmt c
return $ FunD x y z
nameStmt :: Stmt Located String -> Namer (Stmt Located Name)
nameStmt s = case s of
ImportS a b -> do
x <- define b
return $ ImportS a (x <$ b)
DefS a b -> do
y <- nameExp b
x <- define a
return $ DefS (x <$ a) y
FunDefS a b c -> do
x <- define a
nest $ do
y <- mapM (mapM define') b
z <- mapM nameStmt c
return $ FunDefS (x <$ a) y z
IfThenS a b ->
IfThenS
<$> nameExp a
<*> mapM nameStmt b
IfThenElseS a b c ->
IfThenElseS
<$> nameExp a
<*> mapM nameStmt b
<*> mapM nameStmt c
ForS a b c d ->
nest $
ForS
<$> mapM nameStmt a
<*> nameExp b
<*> nameExp c
<*> mapM nameStmt d
ForEachS a b c ->
nest $ do
x <- define a
y <- nameExp b
z <- mapM nameStmt c
return (ForEachS (x <$ a) y z)
WhileS a b ->
WhileS
<$> nameExp a
<*> mapM nameStmt b
ReturnS a ->
ReturnS
<$> nameExp a
ThrowS a ->
ThrowS
<$> nameExp a
ExpS a -> do
x <- nameExp a
return $ ExpS x
BlockS xs ->
nest $
BlockS
<$> mapM (mapM nameStmt) xs
nameExp :: Located (Exp Located String) -> Namer (Located (Exp Located Name))
nameExp e = liftM (<$ e) m
where
m = case (extract e) of
VarE a -> do
x <- lookup (a <$ e)
return $ VarE x
FunE a b -> do
x <- lookup (a <$ e)
y <- mapM lookup (map (<$ e) b)
return $ FunE x y
NumE a ->
return $ NumE a
StrE a ->
return $ StrE a
CharE a ->
return $ CharE a
NullE ->
return NullE
BoolE a ->
return $ BoolE a
ObjE a ->
ObjE
<$> mapM (mapM nameProperty) a
ListE a ->
ListE
<$> mapM nameExp a
AccessE a b -> do
x <- nameExp a
return $ AccessE x b
MutateE a b c -> do
x <- nameExp a
z <- nameExp c
return $ MutateE x b z
AssignE a b -> do
x <- lookup a
y <- nameExp b
return (AssignE (x <$ a) y)
AppE a b ->
AppE
<$> nameExp a
<*> mapM (mapM nameExp) b
FunAppE a b ->
FunAppE
<$> define' a
<*> mapM (mapM nameExp) b
OrE a b ->
OrE
<$> nameExp a
<*> nameExp b
AndE a b ->
AndE
<$> nameExp a
<*> nameExp b
define' :: Located String -> Namer (Located Name)
define' w = liftM (<$ w) (define w)
nameProperty :: Property Located String -> Namer (Property Located Name)
nameProperty (a, b) = do
y <- nameExp b
return $ (a, y) | sonyandy/tnt | Language/TNT/Namer.hs | bsd-3-clause | 3,316 | 0 | 16 | 1,198 | 1,410 | 663 | 747 | 134 | 16 |
import System.Environment (getArgs)
import Data.Char (isLower, isUpper)
import Text.Printf (printf)
ratios :: String -> String
ratios s | t > 0 = printf "lowercase: %.2f uppercase: %.2f" (100 * l / t) (100 * u / t)
| otherwise = "lowercase: 0.00 uppercase: 0.00"
where l = fromIntegral (length [x | x <- s, isLower x]) :: Double
u = fromIntegral (length [x | x <- s, isUpper x]) :: Double
t = l + u
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map ratios $ lines input
| nikai3d/ce-challenges | easy/lettercase.hs | bsd-3-clause | 581 | 0 | 12 | 166 | 236 | 120 | 116 | 14 | 1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module TcEvidence (
-- HsWrapper
HsWrapper(..),
(<.>), mkWpTyApps, mkWpEvApps, mkWpEvVarApps, mkWpTyLams, mkWpLams, mkWpLet, mkWpCast,
mkWpFun, idHsWrapper, isIdHsWrapper, pprHsWrapper,
-- Evidence bindings
TcEvBinds(..), EvBindsVar(..),
EvBindMap(..), emptyEvBindMap, extendEvBinds,
lookupEvBind, evBindMapBinds, foldEvBindMap,
EvBind(..), emptyTcEvBinds, isEmptyTcEvBinds, mkGivenEvBind, mkWantedEvBind,
EvTerm(..), mkEvCast, evVarsOfTerm, mkEvTupleSelectors, mkEvScSelectors,
EvLit(..), evTermCoercion,
EvCallStack(..),
EvTypeable(..),
-- TcCoercion
TcCoercion(..), LeftOrRight(..), pickLR,
mkTcReflCo, mkTcNomReflCo, mkTcRepReflCo,
mkTcTyConAppCo, mkTcAppCo, mkTcAppCos, mkTcFunCo,
mkTcAxInstCo, mkTcUnbranchedAxInstCo, mkTcForAllCo, mkTcForAllCos,
mkTcSymCo, mkTcTransCo, mkTcNthCo, mkTcLRCo, mkTcSubCo, maybeTcSubCo,
tcDowngradeRole, mkTcTransAppCo,
mkTcAxiomRuleCo, mkTcPhantomCo,
tcCoercionKind, coVarsOfTcCo, isEqVar, mkTcCoVarCo,
isTcReflCo, getTcCoVar_maybe,
tcCoercionRole, eqVarRole,
unwrapIP, wrapIP
) where
#include "HsVersions.h"
import Var
import Coercion
import PprCore () -- Instance OutputableBndr TyVar
import TypeRep -- Knows type representation
import TcType
import Type
import TyCon
import Class( Class )
import CoAxiom
import PrelNames
import VarEnv
import VarSet
import Name
import Util
import Bag
import Pair
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
import Data.Traversable (traverse, sequenceA)
#endif
import qualified Data.Data as Data
import Outputable
import FastString
import SrcLoc
import Data.IORef( IORef )
{-
Note [TcCoercions]
~~~~~~~~~~~~~~~~~~
| TcCoercions are a hack used by the typechecker. Normally,
Coercions have free variables of type (a ~# b): we call these
CoVars. However, the type checker passes around equality evidence
(boxed up) at type (a ~ b).
An TcCoercion is simply a Coercion whose free variables have the
boxed type (a ~ b). After we are done with typechecking the
desugarer finds the free variables, unboxes them, and creates a
resulting real Coercion with kosher free variables.
We can use most of the Coercion "smart constructors" to build TcCoercions.
However, mkCoVarCo will not work! The equivalent is mkTcCoVarCo.
The data type is similar to Coercion.Coercion, with the following
differences
* Most important, TcLetCo adds let-bindings for coercions.
This is what lets us unify two for-all types and generate
equality constraints underneath
* The kind of a TcCoercion is t1 ~ t2 (resp. Coercible t1 t2)
of a Coercion is t1 ~# t2 (resp. t1 ~#R t2)
* UnsafeCo aren't required, but we do have TcPhantomCo
* Representation invariants are weaker:
- we are allowed to have type synonyms in TcTyConAppCo
- the first arg of a TcAppCo can be a TcTyConAppCo
- TcSubCo is not applied as deep as done with mkSubCo
Reason: they'll get established when we desugar to Coercion
* TcAxiomInstCo has a [TcCoercion] parameter, and not a [Type] parameter.
This differs from the formalism, but corresponds to AxiomInstCo (see
[Coercion axioms applied to coercions]).
Note [mkTcTransAppCo]
~~~~~~~~~~~~~~~~~~~~~
Suppose we have
co1 :: a ~R Maybe
co2 :: b ~R Int
and we want
co3 :: a b ~R Maybe Int
This seems sensible enough. But, we can't let (co3 = co1 co2), because
that's ill-roled! Note that mkTcAppCo requires a *nominal* second coercion.
The way around this is to use transitivity:
co3 = (co1 <b>_N) ; (Maybe co2) :: a b ~R Maybe Int
Or, it's possible everything is the other way around:
co1' :: Maybe ~R a
co2' :: Int ~R b
and we want
co3' :: Maybe Int ~R a b
then
co3' = (Maybe co2') ; (co1' <b>_N)
This is exactly what `mkTcTransAppCo` builds for us. Information for all
the arguments tends to be to hand at call sites, so it's quicker than
using, say, tcCoercionKind.
-}
data TcCoercion
= TcRefl Role TcType
| TcTyConAppCo Role TyCon [TcCoercion]
| TcAppCo TcCoercion TcCoercion
| TcForAllCo TyVar TcCoercion
| TcCoVarCo EqVar
| TcAxiomInstCo (CoAxiom Branched) Int [TcCoercion] -- Int specifies branch number
-- See [CoAxiom Index] in Coercion.hs
-- This is number of types and coercions are expected to match to CoAxiomRule
-- (i.e., the CoAxiomRules are always fully saturated)
| TcAxiomRuleCo CoAxiomRule [TcType] [TcCoercion]
| TcPhantomCo TcType TcType
| TcSymCo TcCoercion
| TcTransCo TcCoercion TcCoercion
| TcNthCo Int TcCoercion
| TcLRCo LeftOrRight TcCoercion
| TcSubCo TcCoercion
| TcCastCo TcCoercion TcCoercion -- co1 |> co2
| TcLetCo TcEvBinds TcCoercion
| TcCoercion Coercion -- embed a Core Coercion
deriving (Data.Data, Data.Typeable)
isEqVar :: Var -> Bool
-- Is lifted coercion variable (only!)
isEqVar v = case tyConAppTyCon_maybe (varType v) of
Just tc -> tc `hasKey` eqTyConKey
Nothing -> False
isTcReflCo_maybe :: TcCoercion -> Maybe TcType
isTcReflCo_maybe (TcRefl _ ty) = Just ty
isTcReflCo_maybe (TcCoercion co) = isReflCo_maybe co
isTcReflCo_maybe _ = Nothing
isTcReflCo :: TcCoercion -> Bool
isTcReflCo (TcRefl {}) = True
isTcReflCo (TcCoercion co) = isReflCo co
isTcReflCo _ = False
getTcCoVar_maybe :: TcCoercion -> Maybe CoVar
getTcCoVar_maybe (TcCoVarCo v) = Just v
getTcCoVar_maybe _ = Nothing
mkTcReflCo :: Role -> TcType -> TcCoercion
mkTcReflCo = TcRefl
mkTcNomReflCo :: TcType -> TcCoercion
mkTcNomReflCo = TcRefl Nominal
mkTcRepReflCo :: TcType -> TcCoercion
mkTcRepReflCo = TcRefl Representational
mkTcFunCo :: Role -> TcCoercion -> TcCoercion -> TcCoercion
mkTcFunCo role co1 co2 = mkTcTyConAppCo role funTyCon [co1, co2]
mkTcTyConAppCo :: Role -> TyCon -> [TcCoercion] -> TcCoercion
mkTcTyConAppCo role tc cos -- No need to expand type synonyms
-- See Note [TcCoercions]
| Just tys <- traverse isTcReflCo_maybe cos
= TcRefl role (mkTyConApp tc tys) -- See Note [Refl invariant]
| otherwise = TcTyConAppCo role tc cos
-- input coercion is Nominal
-- mkSubCo will do some normalisation. We do not do it for TcCoercions, but
-- defer that to desugaring; just to reduce the code duplication a little bit
mkTcSubCo :: TcCoercion -> TcCoercion
mkTcSubCo co = ASSERT2( tcCoercionRole co == Nominal, ppr co)
TcSubCo co
-- See Note [Role twiddling functions] in Coercion
-- | Change the role of a 'TcCoercion'. Returns 'Nothing' if this isn't
-- a downgrade.
tcDowngradeRole_maybe :: Role -- desired role
-> Role -- current role
-> TcCoercion -> Maybe TcCoercion
tcDowngradeRole_maybe Representational Nominal = Just . mkTcSubCo
tcDowngradeRole_maybe Nominal Representational = const Nothing
tcDowngradeRole_maybe Phantom _
= panic "tcDowngradeRole_maybe Phantom"
-- not supported (not needed at the moment)
tcDowngradeRole_maybe _ Phantom = const Nothing
tcDowngradeRole_maybe _ _ = Just
-- See Note [Role twiddling functions] in Coercion
-- | Change the role of a 'TcCoercion'. Panics if this isn't a downgrade.
tcDowngradeRole :: Role -- ^ desired role
-> Role -- ^ current role
-> TcCoercion -> TcCoercion
tcDowngradeRole r1 r2 co
= case tcDowngradeRole_maybe r1 r2 co of
Just co' -> co'
Nothing -> pprPanic "tcDowngradeRole" (ppr r1 <+> ppr r2 <+> ppr co)
-- | If the EqRel is ReprEq, makes a TcSubCo; otherwise, does nothing.
-- Note that the input coercion should always be nominal.
maybeTcSubCo :: EqRel -> TcCoercion -> TcCoercion
maybeTcSubCo NomEq = id
maybeTcSubCo ReprEq = mkTcSubCo
mkTcAxInstCo :: Role -> CoAxiom br -> Int -> [TcType] -> TcCoercion
mkTcAxInstCo role ax index tys
| ASSERT2( not (role == Nominal && ax_role == Representational) , ppr (ax, tys) )
arity == n_tys = tcDowngradeRole role ax_role $
TcAxiomInstCo ax_br index rtys
| otherwise = ASSERT( arity < n_tys )
tcDowngradeRole role ax_role $
foldl TcAppCo (TcAxiomInstCo ax_br index (take arity rtys))
(drop arity rtys)
where
n_tys = length tys
ax_br = toBranchedAxiom ax
branch = coAxiomNthBranch ax_br index
arity = length $ coAxBranchTyVars branch
ax_role = coAxiomRole ax
arg_roles = coAxBranchRoles branch
rtys = zipWith mkTcReflCo (arg_roles ++ repeat Nominal) tys
mkTcAxiomRuleCo :: CoAxiomRule -> [TcType] -> [TcCoercion] -> TcCoercion
mkTcAxiomRuleCo = TcAxiomRuleCo
mkTcUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [TcType] -> TcCoercion
mkTcUnbranchedAxInstCo role ax tys
= mkTcAxInstCo role ax 0 tys
mkTcAppCo :: TcCoercion -> TcCoercion -> TcCoercion
-- No need to deal with TyConApp on the left; see Note [TcCoercions]
-- Second coercion *must* be nominal
mkTcAppCo (TcRefl r ty1) (TcRefl _ ty2) = TcRefl r (mkAppTy ty1 ty2)
mkTcAppCo co1 co2 = TcAppCo co1 co2
-- | Like `mkTcAppCo`, but allows the second coercion to be other than
-- nominal. See Note [mkTcTransAppCo]. Role r3 cannot be more stringent
-- than either r1 or r2.
mkTcTransAppCo :: Role -- ^ r1
-> TcCoercion -- ^ co1 :: ty1a ~r1 ty1b
-> TcType -- ^ ty1a
-> TcType -- ^ ty1b
-> Role -- ^ r2
-> TcCoercion -- ^ co2 :: ty2a ~r2 ty2b
-> TcType -- ^ ty2a
-> TcType -- ^ ty2b
-> Role -- ^ r3
-> TcCoercion -- ^ :: ty1a ty2a ~r3 ty1b ty2b
mkTcTransAppCo r1 co1 ty1a ty1b r2 co2 ty2a ty2b r3
-- How incredibly fiddly! Is there a better way??
= case (r1, r2, r3) of
(_, _, Phantom)
-> mkTcPhantomCo (mkAppTy ty1a ty2a) (mkAppTy ty1b ty2b)
(_, _, Nominal)
-> ASSERT( r1 == Nominal && r2 == Nominal )
mkTcAppCo co1 co2
(Nominal, Nominal, Representational)
-> mkTcSubCo (mkTcAppCo co1 co2)
(_, Nominal, Representational)
-> ASSERT( r1 == Representational )
mkTcAppCo co1 co2
(Nominal, Representational, Representational)
-> go (mkTcSubCo co1)
(_ , _, Representational)
-> ASSERT( r1 == Representational && r2 == Representational )
go co1
where
go co1_repr
| Just (tc1b, tys1b) <- tcSplitTyConApp_maybe ty1b
, nextRole ty1b == r2
= (co1_repr `mkTcAppCo` mkTcNomReflCo ty2a) `mkTcTransCo`
(mkTcTyConAppCo Representational tc1b
(zipWith mkTcReflCo (tyConRolesX Representational tc1b) tys1b
++ [co2]))
| Just (tc1a, tys1a) <- tcSplitTyConApp_maybe ty1a
, nextRole ty1a == r2
= (mkTcTyConAppCo Representational tc1a
(zipWith mkTcReflCo (tyConRolesX Representational tc1a) tys1a
++ [co2]))
`mkTcTransCo`
(co1_repr `mkTcAppCo` mkTcNomReflCo ty2b)
| otherwise
= pprPanic "mkTcTransAppCo" (vcat [ ppr r1, ppr co1, ppr ty1a, ppr ty1b
, ppr r2, ppr co2, ppr ty2a, ppr ty2b
, ppr r3 ])
mkTcSymCo :: TcCoercion -> TcCoercion
mkTcSymCo co@(TcRefl {}) = co
mkTcSymCo (TcSymCo co) = co
mkTcSymCo co = TcSymCo co
mkTcTransCo :: TcCoercion -> TcCoercion -> TcCoercion
mkTcTransCo (TcRefl {}) co = co
mkTcTransCo co (TcRefl {}) = co
mkTcTransCo co1 co2 = TcTransCo co1 co2
mkTcNthCo :: Int -> TcCoercion -> TcCoercion
mkTcNthCo n (TcRefl r ty) = TcRefl r (tyConAppArgN n ty)
mkTcNthCo n co = TcNthCo n co
mkTcLRCo :: LeftOrRight -> TcCoercion -> TcCoercion
mkTcLRCo lr (TcRefl r ty) = TcRefl r (pickLR lr (tcSplitAppTy ty))
mkTcLRCo lr co = TcLRCo lr co
mkTcPhantomCo :: TcType -> TcType -> TcCoercion
mkTcPhantomCo = TcPhantomCo
mkTcAppCos :: TcCoercion -> [TcCoercion] -> TcCoercion
mkTcAppCos co1 tys = foldl mkTcAppCo co1 tys
mkTcForAllCo :: Var -> TcCoercion -> TcCoercion
-- note that a TyVar should be used here, not a CoVar (nor a TcTyVar)
mkTcForAllCo tv (TcRefl r ty) = ASSERT( isTyVar tv ) TcRefl r (mkForAllTy tv ty)
mkTcForAllCo tv co = ASSERT( isTyVar tv ) TcForAllCo tv co
mkTcForAllCos :: [Var] -> TcCoercion -> TcCoercion
mkTcForAllCos tvs (TcRefl r ty) = ASSERT( all isTyVar tvs ) TcRefl r (mkForAllTys tvs ty)
mkTcForAllCos tvs co = ASSERT( all isTyVar tvs ) foldr TcForAllCo co tvs
mkTcCoVarCo :: EqVar -> TcCoercion
-- ipv :: s ~ t (the boxed equality type) or Coercible s t (the boxed representational equality type)
mkTcCoVarCo ipv = TcCoVarCo ipv
-- Previously I checked for (ty ~ ty) and generated Refl,
-- but in fact ipv may not even (visibly) have a (t1 ~ t2) type, because
-- the constraint solver does not substitute in the types of
-- evidence variables as it goes. In any case, the optimisation
-- will be done in the later zonking phase
tcCoercionKind :: TcCoercion -> Pair Type
tcCoercionKind co = go co
where
go (TcRefl _ ty) = Pair ty ty
go (TcLetCo _ co) = go co
go (TcCastCo _ co) = case getEqPredTys (pSnd (go co)) of
(ty1,ty2) -> Pair ty1 ty2
go (TcTyConAppCo _ tc cos)= mkTyConApp tc <$> (sequenceA $ map go cos)
go (TcAppCo co1 co2) = mkAppTy <$> go co1 <*> go co2
go (TcForAllCo tv co) = mkForAllTy tv <$> go co
go (TcCoVarCo cv) = eqVarKind cv
go (TcAxiomInstCo ax ind cos)
= let branch = coAxiomNthBranch ax ind
tvs = coAxBranchTyVars branch
Pair tys1 tys2 = sequenceA (map go cos)
in ASSERT( cos `equalLength` tvs )
Pair (substTyWith tvs tys1 (coAxNthLHS ax ind))
(substTyWith tvs tys2 (coAxBranchRHS branch))
go (TcPhantomCo ty1 ty2) = Pair ty1 ty2
go (TcSymCo co) = swap (go co)
go (TcTransCo co1 co2) = Pair (pFst (go co1)) (pSnd (go co2))
go (TcNthCo d co) = tyConAppArgN d <$> go co
go (TcLRCo lr co) = (pickLR lr . tcSplitAppTy) <$> go co
go (TcSubCo co) = go co
go (TcAxiomRuleCo ax ts cs) =
case coaxrProves ax ts (map tcCoercionKind cs) of
Just res -> res
Nothing -> panic "tcCoercionKind: malformed TcAxiomRuleCo"
go (TcCoercion co) = coercionKind co
eqVarRole :: EqVar -> Role
eqVarRole cv = getEqPredRole (varType cv)
eqVarKind :: EqVar -> Pair Type
eqVarKind cv
| Just (tc, [_kind,ty1,ty2]) <- tcSplitTyConApp_maybe (varType cv)
= ASSERT(tc `hasKey` eqTyConKey)
Pair ty1 ty2
| otherwise = pprPanic "eqVarKind, non coercion variable" (ppr cv <+> dcolon <+> ppr (varType cv))
tcCoercionRole :: TcCoercion -> Role
tcCoercionRole = go
where
go (TcRefl r _) = r
go (TcTyConAppCo r _ _) = r
go (TcAppCo co _) = go co
go (TcForAllCo _ co) = go co
go (TcCoVarCo cv) = eqVarRole cv
go (TcAxiomInstCo ax _ _) = coAxiomRole ax
go (TcPhantomCo _ _) = Phantom
go (TcSymCo co) = go co
go (TcTransCo co1 _) = go co1 -- same as go co2
go (TcNthCo n co) = let Pair ty1 _ = tcCoercionKind co
(tc, _) = tcSplitTyConApp ty1
in nthRole (go co) tc n
go (TcLRCo _ _) = Nominal
go (TcSubCo _) = Representational
go (TcAxiomRuleCo c _ _) = coaxrRole c
go (TcCastCo c _) = go c
go (TcLetCo _ c) = go c
go (TcCoercion co) = coercionRole co
coVarsOfTcCo :: TcCoercion -> VarSet
-- Only works on *zonked* coercions, because of TcLetCo
coVarsOfTcCo tc_co
= go tc_co
where
go (TcRefl _ _) = emptyVarSet
go (TcTyConAppCo _ _ cos) = mapUnionVarSet go cos
go (TcAppCo co1 co2) = go co1 `unionVarSet` go co2
go (TcCastCo co1 co2) = go co1 `unionVarSet` go co2
go (TcForAllCo _ co) = go co
go (TcCoVarCo v) = unitVarSet v
go (TcAxiomInstCo _ _ cos) = mapUnionVarSet go cos
go (TcPhantomCo _ _) = emptyVarSet
go (TcSymCo co) = go co
go (TcTransCo co1 co2) = go co1 `unionVarSet` go co2
go (TcNthCo _ co) = go co
go (TcLRCo _ co) = go co
go (TcSubCo co) = go co
go (TcLetCo (EvBinds bs) co) = foldrBag (unionVarSet . go_bind) (go co) bs
`minusVarSet` get_bndrs bs
go (TcLetCo {}) = emptyVarSet -- Harumph. This does legitimately happen in the call
-- to evVarsOfTerm in the DEBUG check of setEvBind
go (TcAxiomRuleCo _ _ cos) = mapUnionVarSet go cos
go (TcCoercion co) = -- the use of coVarsOfTcCo in dsTcCoercion will
-- fail if there are any proper, unlifted covars
ASSERT( isEmptyVarSet (coVarsOfCo co) )
emptyVarSet
-- We expect only coercion bindings, so use evTermCoercion
go_bind :: EvBind -> VarSet
go_bind (EvBind { eb_rhs =tm }) = go (evTermCoercion tm)
get_bndrs :: Bag EvBind -> VarSet
get_bndrs = foldrBag (\ (EvBind { eb_lhs = b }) bs -> extendVarSet bs b) emptyVarSet
-- Pretty printing
instance Outputable TcCoercion where
ppr = pprTcCo
pprTcCo, pprParendTcCo :: TcCoercion -> SDoc
pprTcCo co = ppr_co TopPrec co
pprParendTcCo co = ppr_co TyConPrec co
ppr_co :: TyPrec -> TcCoercion -> SDoc
ppr_co _ (TcRefl r ty) = angleBrackets (ppr ty) <> ppr_role r
ppr_co p co@(TcTyConAppCo _ tc [_,_])
| tc `hasKey` funTyConKey = ppr_fun_co p co
ppr_co p (TcTyConAppCo r tc cos) = pprTcApp p ppr_co tc cos <> ppr_role r
ppr_co p (TcLetCo bs co) = maybeParen p TopPrec $
sep [ptext (sLit "let") <+> braces (ppr bs), ppr co]
ppr_co p (TcAppCo co1 co2) = maybeParen p TyConPrec $
pprTcCo co1 <+> ppr_co TyConPrec co2
ppr_co p (TcCastCo co1 co2) = maybeParen p FunPrec $
ppr_co FunPrec co1 <+> ptext (sLit "|>") <+> ppr_co FunPrec co2
ppr_co p co@(TcForAllCo {}) = ppr_forall_co p co
ppr_co _ (TcCoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv)
ppr_co p (TcAxiomInstCo con ind cos)
= pprPrefixApp p (ppr (getName con) <> brackets (ppr ind)) (map pprParendTcCo cos)
ppr_co p (TcTransCo co1 co2) = maybeParen p FunPrec $
ppr_co FunPrec co1
<+> ptext (sLit ";")
<+> ppr_co FunPrec co2
ppr_co p (TcPhantomCo t1 t2) = pprPrefixApp p (ptext (sLit "PhantomCo")) [pprParendType t1, pprParendType t2]
ppr_co p (TcSymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendTcCo co]
ppr_co p (TcNthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <+> int n) [pprParendTcCo co]
ppr_co p (TcLRCo lr co) = pprPrefixApp p (ppr lr) [pprParendTcCo co]
ppr_co p (TcSubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendTcCo co]
ppr_co p (TcAxiomRuleCo co ts ps) = maybeParen p TopPrec
$ ppr_tc_axiom_rule_co co ts ps
ppr_co p (TcCoercion co) = pprPrefixApp p (text "Core co:") [ppr co]
ppr_tc_axiom_rule_co :: CoAxiomRule -> [TcType] -> [TcCoercion] -> SDoc
ppr_tc_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps)
where
ppTs [] = Outputable.empty
ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t
ppTs ts = ptext (sLit "@") <>
parens (hsep $ punctuate comma $ map pprType ts)
ppPs [] = Outputable.empty
ppPs [p] = pprParendTcCo p
ppPs (p : ps) = ptext (sLit "(") <+> pprTcCo p $$
vcat [ ptext (sLit ",") <+> pprTcCo q | q <- ps ] $$
ptext (sLit ")")
ppr_role :: Role -> SDoc
ppr_role r = underscore <> pp_role
where pp_role = case r of
Nominal -> char 'N'
Representational -> char 'R'
Phantom -> char 'P'
ppr_fun_co :: TyPrec -> TcCoercion -> SDoc
ppr_fun_co p co = pprArrowChain p (split co)
where
split :: TcCoercion -> [SDoc]
split (TcTyConAppCo _ f [arg,res])
| f `hasKey` funTyConKey
= ppr_co FunPrec arg : split res
split co = [ppr_co TopPrec co]
ppr_forall_co :: TyPrec -> TcCoercion -> SDoc
ppr_forall_co p ty
= maybeParen p FunPrec $
sep [pprForAll tvs, ppr_co TopPrec rho]
where
(tvs, rho) = split1 [] ty
split1 tvs (TcForAllCo tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
{-
************************************************************************
* *
HsWrapper
* *
************************************************************************
-}
data HsWrapper
= WpHole -- The identity coercion
| WpCompose HsWrapper HsWrapper
-- (wrap1 `WpCompose` wrap2)[e] = wrap1[ wrap2[ e ]]
--
-- Hence (\a. []) `WpCompose` (\b. []) = (\a b. [])
-- But ([] a) `WpCompose` ([] b) = ([] b a)
| WpFun HsWrapper HsWrapper TcType TcType
-- (WpFun wrap1 wrap2 t1 t2)[e] = \(x:t1). wrap2[ e wrap1[x] ] :: t2
-- So note that if wrap1 :: exp_arg <= act_arg
-- wrap2 :: act_res <= exp_res
-- then WpFun wrap1 wrap2 : (act_arg -> arg_res) <= (exp_arg -> exp_res)
-- This isn't the same as for mkTcFunCo, but it has to be this way
-- because we can't use 'sym' to flip around these HsWrappers
| WpCast TcCoercion -- A cast: [] `cast` co
-- Guaranteed not the identity coercion
-- At role Representational
-- Evidence abstraction and application
-- (both dictionaries and coercions)
| WpEvLam EvVar -- \d. [] the 'd' is an evidence variable
| WpEvApp EvTerm -- [] d the 'd' is evidence for a constraint
-- Kind and Type abstraction and application
| WpTyLam TyVar -- \a. [] the 'a' is a type/kind variable (not coercion var)
| WpTyApp KindOrType -- [] t the 't' is a type (not coercion)
| WpLet TcEvBinds -- Non-empty (or possibly non-empty) evidence bindings,
-- so that the identity coercion is always exactly WpHole
deriving (Data.Data, Data.Typeable)
(<.>) :: HsWrapper -> HsWrapper -> HsWrapper
WpHole <.> c = c
c <.> WpHole = c
c1 <.> c2 = c1 `WpCompose` c2
mkWpFun :: HsWrapper -> HsWrapper -> TcType -> TcType -> HsWrapper
mkWpFun WpHole WpHole _ _ = WpHole
mkWpFun WpHole (WpCast co2) t1 _ = WpCast (mkTcFunCo Representational (mkTcRepReflCo t1) co2)
mkWpFun (WpCast co1) WpHole _ t2 = WpCast (mkTcFunCo Representational (mkTcSymCo co1) (mkTcRepReflCo t2))
mkWpFun (WpCast co1) (WpCast co2) _ _ = WpCast (mkTcFunCo Representational (mkTcSymCo co1) co2)
mkWpFun co1 co2 t1 t2 = WpFun co1 co2 t1 t2
mkWpCast :: TcCoercion -> HsWrapper
mkWpCast co
| isTcReflCo co = WpHole
| otherwise = ASSERT2(tcCoercionRole co == Representational, ppr co)
WpCast co
mkWpTyApps :: [Type] -> HsWrapper
mkWpTyApps tys = mk_co_app_fn WpTyApp tys
mkWpEvApps :: [EvTerm] -> HsWrapper
mkWpEvApps args = mk_co_app_fn WpEvApp args
mkWpEvVarApps :: [EvVar] -> HsWrapper
mkWpEvVarApps vs = mkWpEvApps (map EvId vs)
mkWpTyLams :: [TyVar] -> HsWrapper
mkWpTyLams ids = mk_co_lam_fn WpTyLam ids
mkWpLams :: [Var] -> HsWrapper
mkWpLams ids = mk_co_lam_fn WpEvLam ids
mkWpLet :: TcEvBinds -> HsWrapper
-- This no-op is a quite a common case
mkWpLet (EvBinds b) | isEmptyBag b = WpHole
mkWpLet ev_binds = WpLet ev_binds
mk_co_lam_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
mk_co_lam_fn f as = foldr (\x wrap -> f x <.> wrap) WpHole as
mk_co_app_fn :: (a -> HsWrapper) -> [a] -> HsWrapper
-- For applications, the *first* argument must
-- come *last* in the composition sequence
mk_co_app_fn f as = foldr (\x wrap -> wrap <.> f x) WpHole as
idHsWrapper :: HsWrapper
idHsWrapper = WpHole
isIdHsWrapper :: HsWrapper -> Bool
isIdHsWrapper WpHole = True
isIdHsWrapper _ = False
{-
************************************************************************
* *
Evidence bindings
* *
************************************************************************
-}
data TcEvBinds
= TcEvBinds -- Mutable evidence bindings
EvBindsVar -- Mutable because they are updated "later"
-- when an implication constraint is solved
| EvBinds -- Immutable after zonking
(Bag EvBind)
deriving( Data.Typeable )
data EvBindsVar = EvBindsVar (IORef EvBindMap) Unique
-- The Unique is only for debug printing
instance Data.Data TcEvBinds where
-- Placeholder; we can't travers into TcEvBinds
toConstr _ = abstractConstr "TcEvBinds"
gunfold _ _ = error "gunfold"
dataTypeOf _ = Data.mkNoRepType "TcEvBinds"
-----------------
newtype EvBindMap
= EvBindMap {
ev_bind_varenv :: VarEnv EvBind
} -- Map from evidence variables to evidence terms
emptyEvBindMap :: EvBindMap
emptyEvBindMap = EvBindMap { ev_bind_varenv = emptyVarEnv }
extendEvBinds :: EvBindMap -> EvBind -> EvBindMap
extendEvBinds bs ev_bind
= EvBindMap { ev_bind_varenv = extendVarEnv (ev_bind_varenv bs)
(eb_lhs ev_bind)
ev_bind }
lookupEvBind :: EvBindMap -> EvVar -> Maybe EvBind
lookupEvBind bs = lookupVarEnv (ev_bind_varenv bs)
evBindMapBinds :: EvBindMap -> Bag EvBind
evBindMapBinds = foldEvBindMap consBag emptyBag
foldEvBindMap :: (EvBind -> a -> a) -> a -> EvBindMap -> a
foldEvBindMap k z bs = foldVarEnv k z (ev_bind_varenv bs)
-----------------
-- All evidence is bound by EvBinds; no side effects
data EvBind
= EvBind { eb_lhs :: EvVar
, eb_rhs :: EvTerm
, eb_is_given :: Bool -- True <=> given
-- See Note [Tracking redundant constraints] in TcSimplify
}
mkWantedEvBind :: EvVar -> EvTerm -> EvBind
mkWantedEvBind ev tm = EvBind { eb_is_given = False, eb_lhs = ev, eb_rhs = tm }
mkGivenEvBind :: EvVar -> EvTerm -> EvBind
mkGivenEvBind ev tm = EvBind { eb_is_given = True, eb_lhs = ev, eb_rhs = tm }
data EvTerm
= EvId EvId -- Any sort of evidence Id, including coercions
| EvCoercion TcCoercion -- (Boxed) coercion bindings
-- See Note [Coercion evidence terms]
| EvCast EvTerm TcCoercion -- d |> co, the coercion being at role representational
| EvDFunApp DFunId -- Dictionary instance application
[Type] [EvId]
| EvTupleSel EvTerm Int -- n'th component of the tuple, 0-indexed
| EvTupleMk [EvId] -- tuple built from this stuff
| EvDelayedError Type FastString -- Used with Opt_DeferTypeErrors
-- See Note [Deferring coercion errors to runtime]
-- in TcSimplify
| EvSuperClass EvTerm Int -- n'th superclass. Used for both equalities and
-- dictionaries, even though the former have no
-- selector Id. We count up from _0_
| EvLit EvLit -- Dictionary for KnownNat and KnownSymbol classes.
-- Note [KnownNat & KnownSymbol and EvLit]
| EvCallStack EvCallStack -- Dictionary for CallStack implicit parameters
| EvTypeable EvTypeable -- Dictionary for `Typeable`
deriving( Data.Data, Data.Typeable )
-- | Instructions on how to make a 'Typeable' dictionary.
data EvTypeable
= EvTypeableTyCon TyCon [Kind]
-- ^ Dicitionary for concrete type constructors.
| EvTypeableTyApp (EvTerm,Type) (EvTerm,Type)
-- ^ Dictionary for type applications; this is used when we have
-- a type expression starting with a type variable (e.g., @Typeable (f a)@)
| EvTypeableTyLit Type
-- ^ Dictionary for a type literal.
deriving ( Data.Data, Data.Typeable )
data EvLit
= EvNum Integer
| EvStr FastString
deriving( Data.Data, Data.Typeable )
-- | Evidence for @CallStack@ implicit parameters.
data EvCallStack
-- See Note [Overview of implicit CallStacks]
= EvCsEmpty
| EvCsPushCall Name RealSrcSpan EvTerm
-- ^ @EvCsPushCall name loc stk@ represents a call to @name@, occurring at
-- @loc@, in a calling context @stk@.
| EvCsTop FastString RealSrcSpan EvTerm
-- ^ @EvCsTop name loc stk@ represents a use of an implicit parameter
-- @?name@, occurring at @loc@, in a calling context @stk@.
deriving( Data.Data, Data.Typeable )
{-
Note [Coercion evidence terms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "coercion evidence term" takes one of these forms
co_tm ::= EvId v where v :: t1 ~ t2
| EvCoercion co
| EvCast co_tm co
We do quite often need to get a TcCoercion from an EvTerm; see
'evTermCoercion'.
INVARIANT: The evidence for any constraint with type (t1~t2) is
a coercion evidence term. Consider for example
[G] d :: F Int a
If we have
ax7 a :: F Int a ~ (a ~ Bool)
then we do NOT generate the constraint
[G] (d |> ax7 a) :: a ~ Bool
because that does not satisfy the invariant (d is not a coercion variable).
Instead we make a binding
g1 :: a~Bool = g |> ax7 a
and the constraint
[G] g1 :: a~Bool
See Trac [7238] and Note [Bind new Givens immediately] in TcRnTypes
Note [EvBinds/EvTerm]
~~~~~~~~~~~~~~~~~~~~~
How evidence is created and updated. Bindings for dictionaries,
and coercions and implicit parameters are carried around in TcEvBinds
which during constraint generation and simplification is always of the
form (TcEvBinds ref). After constraint simplification is finished it
will be transformed to t an (EvBinds ev_bag).
Evidence for coercions *SHOULD* be filled in using the TcEvBinds
However, all EvVars that correspond to *wanted* coercion terms in
an EvBind must be mutable variables so that they can be readily
inlined (by zonking) after constraint simplification is finished.
Conclusion: a new wanted coercion variable should be made mutable.
[Notice though that evidence variables that bind coercion terms
from super classes will be "given" and hence rigid]
Note [KnownNat & KnownSymbol and EvLit]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A part of the type-level literals implementation are the classes
"KnownNat" and "KnownSymbol", which provide a "smart" constructor for
defining singleton values. Here is the key stuff from GHC.TypeLits
class KnownNat (n :: Nat) where
natSing :: SNat n
newtype SNat (n :: Nat) = SNat Integer
Conceptually, this class has infinitely many instances:
instance KnownNat 0 where natSing = SNat 0
instance KnownNat 1 where natSing = SNat 1
instance KnownNat 2 where natSing = SNat 2
...
In practice, we solve `KnownNat` predicates in the type-checker
(see typecheck/TcInteract.hs) because we can't have infinately many instances.
The evidence (aka "dictionary") for `KnownNat` is of the form `EvLit (EvNum n)`.
We make the following assumptions about dictionaries in GHC:
1. The "dictionary" for classes with a single method---like `KnownNat`---is
a newtype for the type of the method, so using a evidence amounts
to a coercion, and
2. Newtypes use the same representation as their definition types.
So, the evidence for `KnownNat` is just a value of the representation type,
wrapped in two newtype constructors: one to make it into a `SNat` value,
and another to make it into a `KnownNat` dictionary.
Also note that `natSing` and `SNat` are never actually exposed from the
library---they are just an implementation detail. Instead, users see
a more convenient function, defined in terms of `natSing`:
natVal :: KnownNat n => proxy n -> Integer
The reason we don't use this directly in the class is that it is simpler
and more efficient to pass around an integer rather than an entier function,
especialy when the `KnowNat` evidence is packaged up in an existential.
The story for kind `Symbol` is analogous:
* class KnownSymbol
* newtype SSymbol
* Evidence: EvLit (EvStr n)
Note [Overview of implicit CallStacks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(See https://ghc.haskell.org/trac/ghc/wiki/ExplicitCallStack/ImplicitLocations)
The goal of CallStack evidence terms is to reify locations
in the program source as runtime values, without any support
from the RTS. We accomplish this by assigning a special meaning
to implicit parameters of type GHC.Stack.CallStack. A use of
a CallStack IP, e.g.
head [] = error (show (?loc :: CallStack))
head (x:_) = x
will be solved with the source location that gave rise to the IP
constraint (here, the use of ?loc). If there is already
a CallStack IP in scope, e.g. passed-in as an argument
head :: (?loc :: CallStack) => [a] -> a
head [] = error (show (?loc :: CallStack))
head (x:_) = x
we will push the new location onto the CallStack that was passed
in. These two cases are reflected by the EvCallStack evidence
type. In the first case, we will create an evidence term
EvCsTop "?loc" <?loc's location> EvCsEmpty
and in the second we'll have a given constraint
[G] d :: IP "loc" CallStack
in scope, and will create an evidence term
EvCsTop "?loc" <?loc's location> d
When we call a function that uses a CallStack IP, e.g.
f = head xs
we create an evidence term
EvCsPushCall "head" <head's location> EvCsEmpty
again pushing onto a given evidence term if one exists.
This provides a lightweight mechanism for building up call-stacks
explicitly, but is notably limited by the fact that the stack will
stop at the first function whose type does not include a CallStack IP.
For example, using the above definition of head:
f :: [a] -> a
f = head
g = f []
the resulting CallStack will include use of ?loc inside head and
the call to head inside f, but NOT the call to f inside g, because f
did not explicitly request a CallStack.
Important Details:
- GHC should NEVER report an insoluble CallStack constraint.
- A CallStack (defined in GHC.Stack) is a [(String, SrcLoc)], where the String
is the name of the binder that is used at the SrcLoc. SrcLoc is defined in
GHC.SrcLoc and contains the package/module/file name, as well as the full
source-span. Both CallStack and SrcLoc are kept abstract so only GHC can
construct new values.
- Consider the use of ?stk in:
head :: (?stk :: CallStack) => [a] -> a
head [] = error (show ?stk)
When solving the use of ?stk we'll have a given
[G] d :: IP "stk" CallStack
in scope. In the interaction phase, GHC would normally solve the use of ?stk
directly from the given, i.e. re-using the dicionary. But this is NOT what we
want! We want to generate a *new* CallStack with ?loc's SrcLoc pushed onto
the given CallStack. So we must take care in TcInteract.interactDict to
prioritize solving wanted CallStacks.
- We will automatically solve any wanted CallStack regardless of the name of the
IP, i.e.
f = show (?stk :: CallStack)
g = show (?loc :: CallStack)
are both valid. However, we will only push new SrcLocs onto existing
CallStacks when the IP names match, e.g. in
head :: (?loc :: CallStack) => [a] -> a
head [] = error (show (?stk :: CallStack))
the printed CallStack will NOT include head's call-site. This reflects the
standard scoping rules of implicit-parameters. (See TcInteract.interactDict)
- An EvCallStack term desugars to a CoreExpr of type `IP "some str" CallStack`.
The desugarer will need to unwrap the IP newtype before pushing a new
call-site onto a given stack (See DsBinds.dsEvCallStack)
- We only want to intercept constraints that arose due to the use of an IP or a
function call. In particular, we do NOT want to intercept the
(?stk :: CallStack) => [a] -> a
~
(?stk :: CallStack) => [a] -> a
constraint that arises from the ambiguity check on `head`s type signature.
(See TcEvidence.isCallStackIP)
-}
mkEvCast :: EvTerm -> TcCoercion -> EvTerm
mkEvCast ev lco
| ASSERT2(tcCoercionRole lco == Representational, (vcat [ptext (sLit "Coercion of wrong role passed to mkEvCast:"), ppr ev, ppr lco]))
isTcReflCo lco = ev
| otherwise = EvCast ev lco
mkEvTupleSelectors :: EvTerm -> [TcPredType] -> [(TcPredType, EvTerm)]
mkEvTupleSelectors ev preds = zipWith mk_pr preds [0..]
where
mk_pr pred i = (pred, EvTupleSel ev i)
mkEvScSelectors :: EvTerm -> Class -> [TcType] -> [(TcPredType, EvTerm)]
mkEvScSelectors ev cls tys
= zipWith mk_pr (immSuperClasses cls tys) [0..]
where
mk_pr pred i = (pred, EvSuperClass ev i)
emptyTcEvBinds :: TcEvBinds
emptyTcEvBinds = EvBinds emptyBag
isEmptyTcEvBinds :: TcEvBinds -> Bool
isEmptyTcEvBinds (EvBinds b) = isEmptyBag b
isEmptyTcEvBinds (TcEvBinds {}) = panic "isEmptyTcEvBinds"
evTermCoercion :: EvTerm -> TcCoercion
-- Applied only to EvTerms of type (s~t)
-- See Note [Coercion evidence terms]
evTermCoercion (EvId v) = mkTcCoVarCo v
evTermCoercion (EvCoercion co) = co
evTermCoercion (EvCast tm co) = TcCastCo (evTermCoercion tm) co
evTermCoercion tm = pprPanic "evTermCoercion" (ppr tm)
evVarsOfTerm :: EvTerm -> VarSet
evVarsOfTerm (EvId v) = unitVarSet v
evVarsOfTerm (EvCoercion co) = coVarsOfTcCo co
evVarsOfTerm (EvDFunApp _ _ evs) = mkVarSet evs
evVarsOfTerm (EvTupleSel ev _) = evVarsOfTerm ev
evVarsOfTerm (EvSuperClass v _) = evVarsOfTerm v
evVarsOfTerm (EvCast tm co) = evVarsOfTerm tm `unionVarSet` coVarsOfTcCo co
evVarsOfTerm (EvTupleMk evs) = mkVarSet evs
evVarsOfTerm (EvDelayedError _ _) = emptyVarSet
evVarsOfTerm (EvLit _) = emptyVarSet
evVarsOfTerm (EvCallStack cs) = evVarsOfCallStack cs
evVarsOfTerm (EvTypeable ev) = evVarsOfTypeable ev
evVarsOfTerms :: [EvTerm] -> VarSet
evVarsOfTerms = mapUnionVarSet evVarsOfTerm
evVarsOfCallStack :: EvCallStack -> VarSet
evVarsOfCallStack cs = case cs of
EvCsEmpty -> emptyVarSet
EvCsTop _ _ tm -> evVarsOfTerm tm
EvCsPushCall _ _ tm -> evVarsOfTerm tm
evVarsOfTypeable :: EvTypeable -> VarSet
evVarsOfTypeable ev =
case ev of
EvTypeableTyCon _ _ -> emptyVarSet
EvTypeableTyApp e1 e2 -> evVarsOfTerms (map fst [e1,e2])
EvTypeableTyLit _ -> emptyVarSet
{-
************************************************************************
* *
Pretty printing
* *
************************************************************************
-}
instance Outputable HsWrapper where
ppr co_fn = pprHsWrapper (ptext (sLit "<>")) co_fn
pprHsWrapper :: SDoc -> HsWrapper -> SDoc
-- In debug mode, print the wrapper
-- otherwise just print what's inside
pprHsWrapper doc wrap
= getPprStyle (\ s -> if debugStyle s then (help (add_parens doc) wrap False) else doc)
where
help :: (Bool -> SDoc) -> HsWrapper -> Bool -> SDoc
-- True <=> appears in function application position
-- False <=> appears as body of let or lambda
help it WpHole = it
help it (WpCompose f1 f2) = help (help it f2) f1
help it (WpFun f1 f2 t1 _) = add_parens $ ptext (sLit "\\(x") <> dcolon <> ppr t1 <> ptext (sLit ").") <+>
help (\_ -> it True <+> help (\_ -> ptext (sLit "x")) f1 True) f2 False
help it (WpCast co) = add_parens $ sep [it False, nest 2 (ptext (sLit "|>")
<+> pprParendTcCo co)]
help it (WpEvApp id) = no_parens $ sep [it True, nest 2 (ppr id)]
help it (WpTyApp ty) = no_parens $ sep [it True, ptext (sLit "@") <+> pprParendType ty]
help it (WpEvLam id) = add_parens $ sep [ ptext (sLit "\\") <> pp_bndr id, it False]
help it (WpTyLam tv) = add_parens $ sep [ptext (sLit "/\\") <> pp_bndr tv, it False]
help it (WpLet binds) = add_parens $ sep [ptext (sLit "let") <+> braces (ppr binds), it False]
pp_bndr v = pprBndr LambdaBind v <> dot
add_parens, no_parens :: SDoc -> Bool -> SDoc
add_parens d True = parens d
add_parens d False = d
no_parens d _ = d
instance Outputable TcEvBinds where
ppr (TcEvBinds v) = ppr v
ppr (EvBinds bs) = ptext (sLit "EvBinds") <> braces (vcat (map ppr (bagToList bs)))
instance Outputable EvBindsVar where
ppr (EvBindsVar _ u) = ptext (sLit "EvBindsVar") <> angleBrackets (ppr u)
instance Outputable EvBind where
ppr (EvBind { eb_lhs = v, eb_rhs = e, eb_is_given = is_given })
= sep [ pp_gw <+> ppr v
, nest 2 $ equals <+> ppr e ]
where
pp_gw = brackets (if is_given then char 'G' else char 'W')
-- We cheat a bit and pretend EqVars are CoVars for the purposes of pretty printing
instance Outputable EvTerm where
ppr (EvId v) = ppr v
ppr (EvCast v co) = ppr v <+> (ptext (sLit "`cast`")) <+> pprParendTcCo co
ppr (EvCoercion co) = ptext (sLit "CO") <+> ppr co
ppr (EvTupleSel v n) = ptext (sLit "tupsel") <> parens (ppr (v,n))
ppr (EvTupleMk vs) = ptext (sLit "tupmk") <+> ppr vs
ppr (EvSuperClass d n) = ptext (sLit "sc") <> parens (ppr (d,n))
ppr (EvDFunApp df tys ts) = ppr df <+> sep [ char '@' <> ppr tys, ppr ts ]
ppr (EvLit l) = ppr l
ppr (EvCallStack cs) = ppr cs
ppr (EvDelayedError ty msg) = ptext (sLit "error")
<+> sep [ char '@' <> ppr ty, ppr msg ]
ppr (EvTypeable ev) = ppr ev
instance Outputable EvLit where
ppr (EvNum n) = integer n
ppr (EvStr s) = text (show s)
instance Outputable EvCallStack where
ppr EvCsEmpty
= ptext (sLit "[]")
ppr (EvCsTop name loc tm)
= angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm
ppr (EvCsPushCall name loc tm)
= angleBrackets (ppr (name,loc)) <+> ptext (sLit ":") <+> ppr tm
instance Outputable EvTypeable where
ppr ev =
case ev of
EvTypeableTyCon tc ks -> parens (ppr tc <+> sep (map ppr ks))
EvTypeableTyApp t1 t2 -> parens (ppr (fst t1) <+> ppr (fst t2))
EvTypeableTyLit x -> ppr x
----------------------------------------------------------------------
-- Helper functions for dealing with IP newtype-dictionaries
----------------------------------------------------------------------
-- | Create a 'Coercion' that unwraps an implicit-parameter dictionary
-- to expose the underlying value. We expect the 'Type' to have the form
-- `IP sym ty`, return a 'Coercion' `co :: IP sym ty ~ ty`.
unwrapIP :: Type -> Coercion
unwrapIP ty =
case unwrapNewTyCon_maybe tc of
Just (_,_,ax) -> mkUnbranchedAxInstCo Representational ax tys
Nothing -> pprPanic "unwrapIP" $
text "The dictionary for" <+> quotes (ppr tc)
<+> text "is not a newtype!"
where
(tc, tys) = splitTyConApp ty
-- | Create a 'Coercion' that wraps a value in an implicit-parameter
-- dictionary. See 'unwrapIP'.
wrapIP :: Type -> Coercion
wrapIP ty = mkSymCo (unwrapIP ty)
| christiaanb/ghc | compiler/typecheck/TcEvidence.hs | bsd-3-clause | 43,991 | 0 | 17 | 11,774 | 9,231 | 4,760 | 4,471 | 585 | 17 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
-- Needed to derive ToSym Tok Tok
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, TypeFamilies #-}
-- A lexer for Example 3. This is a really naive lexer and should not be used
-- in production. It is merely for showing how the parser works.
module Ex3FunLex
( Tok(..), lexToks
, var, con, op, num
) where
import Data.Char
import Data.Data
import Language.Haskell.TH.Lift
import Data.Parser.Grempa.Static
import Data.Parser.Grempa.Grammar (ToSym(..), Symbol(STerm))
-- | Token datatype
data Tok
= Var {fromTok :: String}
| Con {fromTok :: String}
| Op {fromTok :: String}
| Data
| Case | Of
| Let | In
| Num {fromNum :: Integer}
| Equals
| RightArrow
| LParen | RParen
| LCurl | RCurl
| SemiColon
| Bar
deriving (Eq, Ord, Data, Typeable, Show, Read)
$(deriveLift ''Tok)
instance ToPat Tok where toPat = toConstrPat
instance ToSym Tok Tok where
type ToSymT Tok Tok = Tok
toSym = STerm
-- * Shorthands for constructors applied to something
-- (could be anything since the ToPat instance creates wildcard patterns for
-- everything save for the constructor)
var, con, op, num :: Tok
var = Var ""
con = Con ""
op = Op ""
num = Num 0
-- | Do the lexing!
lexToks :: String -> [Tok]
lexToks [] = []
lexToks ('d':'a':'t':'a':as) | testHead (not . isId) as = Data : lexToks as
lexToks ('c':'a':'s':'e':as) | testHead (not . isId) as = Case : lexToks as
lexToks ('o':'f' :as) | testHead (not . isId) as = Of : lexToks as
lexToks ('l':'e':'t' :as) | testHead (not . isId) as = Let : lexToks as
lexToks ('i':'n' :as) | testHead (not . isId) as = In : lexToks as
lexToks ('=' :as) | testHead (not . isSym) as = Equals : lexToks as
lexToks ('-':'>' :as) | testHead (not . isSym) as = RightArrow : lexToks as
lexToks ('|' :as) | testHead (not . isSym) as = RParen : lexToks as
lexToks ('(' :as) = LParen : lexToks as
lexToks (')' :as) = RParen : lexToks as
lexToks ('{' :as) = LCurl : lexToks as
lexToks ('}' :as) = RCurl : lexToks as
lexToks (';' :as) = SemiColon : lexToks as
lexToks as@(a:rest)
| isLower a = go Var isId as
| isUpper a = go Con isId as
| isDigit a = go (Num . read) isDigit as
| isSym a = go Op isSym as
| otherwise = lexToks rest
testHead :: (Char -> Bool) -> String -> Bool
testHead _ "" = True
testHead f (a:_) = f a
isId :: Char -> Bool
isId c = isAlphaNum c || c == '_' || c == '\''
isSym :: Char -> Bool
isSym '(' = False
isSym ')' = False
isSym c = isPunctuation c || isSymbol c
go :: (String -> Tok) -> (Char -> Bool) -> String -> [Tok]
go c p xs = let (v, rest) = span p xs in c v : lexToks rest
| ollef/Grempa | examples/Ex3FunLex.hs | bsd-3-clause | 2,811 | 0 | 10 | 738 | 1,109 | 578 | 531 | 67 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module SimulationDSL.Compiler.CodeGen ( compile
, printQ ) where
import qualified Data.Vector as V hiding ( (!) )
import Data.Vector ( (!) )
import Data.Char ( toUpper )
import Language.Haskell.TH hiding ( Exp )
import SimulationDSL.Data.Vector3
import SimulationDSL.Data.Value
import SimulationDSL.Data.ExpType
import SimulationDSL.Compiler.Register
import {-# SOURCE #-} SimulationDSL.Compiler.Machine
import SimulationDSL.Language.Exp
compile :: [String] -> Machine -> ExpQ
compile outs m = letE (compileLetDecs m deps)
(compileLetExp deps outs)
where deps = machineRegisterDependency m
-- let updateAll = updateX . updateV . updateA
-- updateX (x,v,a) = ...
-- updateV (x,v,a) = ...
-- updateA (x,v,a) = ...
-- initialCondition = ...
-- in ...
compileLetDecs :: Machine -> [String] -> [DecQ]
compileLetDecs m xs = [ updateAllDec xs ] ++
map (updateOneDec m xs) xs ++
[ initialConditionDec m xs ]
-- updateAll = updateX . updateV . updateA
updateAllDec :: [String] -> DecQ
updateAllDec xs = valD (updateAllDecPat)
(updateAllDecBody xs)
[]
-- updateAll = ...
updateAllDecPat :: PatQ
updateAllDecPat = varP $ mkName "updateAll"
-- ... = updateX . updateV . updateA
updateAllDecBody :: [String] -> BodyQ
updateAllDecBody xs = normalB $ foldl1 aux
$ map (varE . mkName . updateOneName) xs
where aux x y = infixApp x (varE $ mkName ".") y
updateOneName :: String -> String
updateOneName = (++) "update" . capitalize
-- updateX (x,v,a) = let x' = ...
-- in (x',v,a)
updateOneDec :: Machine -> [String] -> String -> DecQ
updateOneDec m xs x = funD (mkName $ updateOneName x)
[updateOneDecClause m xs x]
-- ... (x,v,a) = let x' = ...
-- in (x',v,a)
updateOneDecClause :: Machine -> [String] -> String -> ClauseQ
updateOneDecClause m xs x = clause [updateOneDecClausePat xs]
(updateOneDecClauseBody m xs x)
[]
-- ... (x,v,a) = ...
updateOneDecClausePat :: [String] -> PatQ
updateOneDecClausePat xs = tupP $ map (varP . mkName) xs
-- ... = let x' = ...
-- in (x',v,a)
updateOneDecClauseBody :: Machine -> [String] -> String -> BodyQ
updateOneDecClauseBody m xs x = normalB exp
where exp = letE [updateOneDecClauseBodyDec m xs x]
(updateOneDecClauseBodyExp xs x)
-- ... x' = V.imap (\i x -> ...) x
updateOneDecClauseBodyDec :: Machine -> [String] -> String -> DecQ
updateOneDecClauseBodyDec m xs x = valD (varP $ mkName (x ++ "'"))
(normalB exp)
[]
where exp = let var = varE $ mkName x
lam = updateOneDecClauseBodyDecLam m x
in [| V.imap $(lam) ($var) |]
-- ... \i x -> ...
updateOneDecClauseBodyDecLam :: Machine -> String -> ExpQ
updateOneDecClauseBodyDecLam m x = lamE [ varP $ mkName "i"
, varP $ mkName $ x ++ "i" ]
[| $(compileExp m x exp) |]
where exp = registerExp $ machineRegister m x
-- ... in (x',v,a)
updateOneDecClauseBodyExp :: [String] -> String -> ExpQ
updateOneDecClauseBodyExp xs x = tupE $ map (varE . mkName . aux) xs
where aux x' | x == x' = x' ++ "'"
| otherwise = x'
-- initialCondition = let x0 = ...
-- v0 = ...
-- a0 = ...
-- in (x0,v0,a0)
initialConditionDec :: Machine -> [String] -> DecQ
initialConditionDec m xs = valD initialConditionDecPat
(initialConditionDecBody m xs)
[]
-- initialCondition = ...
initialConditionDecPat :: PatQ
initialConditionDecPat = varP $ mkName "initialCondition"
-- ... = let x0 = V.fromList ...
-- v0 = V.fromList ...
-- a0 = V.fromList ...
-- in (x0,v0,a0)
initialConditionDecBody :: Machine -> [String] -> BodyQ
initialConditionDecBody m xs = normalB exp
where exp = letE (map (initialConditionDecBodyDec m) xs)
(initialConditionDecBodyExp xs)
-- ... x0 = V.fromList ...
initialConditionDecBodyDec :: Machine -> String -> DecQ
initialConditionDecBodyDec m x
= valD (varP $ mkName $ x ++ "0")
(normalB $ initialConditionDecBodyDecExp m x)
[]
-- ... = V.fromList ...
initialConditionDecBodyDecExp m x
= let values = registerValue $ machineRegister m x
xs = listE $ map aux (V.toList values)
in [| V.fromList $(xs) |]
where aux (ValueScalar x) = litE $ RationalL $ toRational x
aux (ValueVector (x,y,z)) = tupE
$ map (litE . RationalL
. toRational) [x,y,z]
-- ... (x0,v0,a0)
initialConditionDecBodyExp :: [String] -> ExpQ
initialConditionDecBodyExp xs = tupE $ map (varE . mkName . flip (++) "0") xs
-- let ...
-- in map (\(x,v,a,f) -> (x)) $ iterate updateAll initialCondition
compileLetExp :: [String] -> [String] -> ExpQ
compileLetExp deps outs
= let updateAll = varE $ mkName "updateAll"
initialCondition = varE $ mkName "initialCondition"
in [| map $(compileLetExpLam deps outs)
$ iterate $(updateAll) $(initialCondition) |]
-- ... (\(x,v,a,f) -> (x)) ...
compileLetExpLam :: [String] -> [String] -> ExpQ
compileLetExpLam deps outs = lam1E (compileLetExpLamPat deps)
(compileLetExpLamExp outs)
-- ... \(x,v,a,f) -> ...
compileLetExpLamPat :: [String] -> PatQ
compileLetExpLamPat deps = tupP $ map (varP . mkName) deps
-- ... (x) ...
compileLetExpLamExp :: [String] -> ExpQ
compileLetExpLamExp outs = tupE $ map (varE . mkName) outs
compileExp :: Machine -> String -> Exp -> ExpQ
compileExp m s (Integral exp)
= let xi = varE $ mkName $ s ++ "i"
i = varE $ mkName "i"
in case registerType $ machineRegister m s of
ExpTypeScalar -> [| $xi + $(compileExp m s exp) |]
ExpTypeVector -> [| addVector $xi $(compileExp m s exp) |]
compileExp _ _ (Constant val) = compileValue val
compileExp _ _ (Var symbol) = let x = varE $ mkName symbol
i = varE $ mkName "i"
in [| $x ! $i |]
compileExp _ _ (Var' symbol) = let x = varE $ mkName symbol
j = varE $ mkName "j"
in [| $x ! $j |]
compileExp m s (Add x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> [| $x' + $y' |]
(ExpTypeVector, ExpTypeVector) -> [| addVector $x' $y' |]
otherwise -> error "compileExp: invalid operand(s)"
where x' = compileExp m s x
y' = compileExp m s y
compileExp m s (Sub x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> [| $x' - $y' |]
(ExpTypeVector, ExpTypeVector) -> [| subVector $x' $y' |]
otherwise -> error "compileExp: invalid operand(s)"
where x' = compileExp m s x
y' = compileExp m s y
compileExp m s (Mul x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> [| $x' * $y' |]
(ExpTypeScalar, ExpTypeVector) -> [| scaleVector $x' $y' |]
(ExpTypeVector, ExpTypeScalar) -> [| scaleVector $y' $x' |]
otherwise -> error "compileExp: invalid operand(s)"
where x' = compileExp m s x
y' = compileExp m s y
compileExp m s (Div x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> [| $x' / $y' |]
(ExpTypeVector, ExpTypeScalar) -> [| scaleVector (recip $y') $x' |]
otherwise -> error "compileExp: invalid operand(s)"
where x' = compileExp m s x
y' = compileExp m s y
compileExp m s (Norm x)
= case expType m x of
ExpTypeVector -> [| normVector $x' |]
where x' = compileExp m s x
compileExp m s (Sigma exp)
= let x = varE $ mkName s
i = varE $ mkName "i"
in [| let n = V.length $x
aux = $(lam1E (varP $ mkName "j")
(compileExp m s exp))
in foldl1 $(addOp) $ map aux (filter (/= $i) [0..n-1]) |]
where addOp = case expType m exp of
ExpTypeScalar -> [| (+) |]
ExpTypeVector -> [| addVector |]
compileValue :: Value -> ExpQ
compileValue (ValueScalar v) = litE $ RationalL $ toRational v
compileValue (ValueVector v) = let (x,y,z) = v
in tupE $ map ( litE
. RationalL
. toRational) [x,y,z]
expType :: Machine -> Exp -> ExpType
expType m (Integral exp) = expType m exp
expType _ (Constant x)
= case x of
ValueScalar _ -> ExpTypeScalar
ValueVector _ -> ExpTypeVector
expType m (Var symbol) = registerType $ machineRegister m symbol
expType m (Var' symbol) = registerType $ machineRegister m symbol
expType m (Add x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeVector) -> ExpTypeVector
otherwise -> error "expType: invalid operand(s)"
expType m (Sub x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeVector) -> ExpTypeVector
otherwise -> error "expType: invalid operand(s)"
expType m (Mul x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeScalar, ExpTypeVector) -> ExpTypeVector
(ExpTypeVector, ExpTypeScalar) -> ExpTypeVector
otherwise -> error "expType: invalid operand(s)"
expType m (Div x y)
= case (expType m x, expType m y) of
(ExpTypeScalar, ExpTypeScalar) -> ExpTypeScalar
(ExpTypeVector, ExpTypeScalar) -> ExpTypeVector
otherwise -> error "expType: invalid operand(s)"
expType m (Norm x)
= case expType m x of
ExpTypeVector -> ExpTypeScalar
otherwise -> error "expType: invalid operand(s)"
expType m (Sigma exp)
= expType m exp
capitalize :: String -> String
capitalize [] = []
capitalize (c:cs) = toUpper c : cs
printQ :: Ppr a => Q a -> IO ()
printQ x = fmap pprint (runQ x) >>= putStrLn
| takagi/SimulationDSL | SimulationDSL/SimulationDSL/Compiler/CodeGen.hs | bsd-3-clause | 10,530 | 0 | 13 | 3,279 | 2,884 | 1,533 | 1,351 | 203 | 12 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.DebugLabel
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.DebugLabel (
-- * Extension Support
glGetEXTDebugLabel,
gl_EXT_debug_label,
-- * Enums
pattern GL_BUFFER_OBJECT_EXT,
pattern GL_PROGRAM_OBJECT_EXT,
pattern GL_PROGRAM_PIPELINE_OBJECT_EXT,
pattern GL_QUERY_OBJECT_EXT,
pattern GL_SAMPLER,
pattern GL_SHADER_OBJECT_EXT,
pattern GL_TRANSFORM_FEEDBACK,
pattern GL_VERTEX_ARRAY_OBJECT_EXT,
-- * Functions
glGetObjectLabelEXT,
glLabelObjectEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/EXT/DebugLabel.hs | bsd-3-clause | 959 | 0 | 5 | 132 | 95 | 66 | 29 | 17 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
module Main where
import Graphics.VR.Pal
import Graphics.GL.Pal
import Control.Monad.State.Strict
import Control.Lens.Extra
import Halive.Utils
import Data.Time
import Animation.Pal
import Types
import Render
import Random
data Moment = Moment
{ momPitch :: !Float
, momHue :: !Float
, momScale :: !Float
}
data Pattern = Pattern
{ ptnPitch :: [Float]
, ptnHue :: [Float]
, ptnScale :: [Float]
}
spawnCube :: (MonadState World m, MonadIO m) => m ()
spawnCube = do
startTime <- utctDayTime <$> liftIO getCurrentTime
let hue = sin . realToFrac $ startTime
x = (* 10) . sin . (* 2) . realToFrac $ startTime
y = (* 10) . cos . (* 2) . realToFrac $ startTime
color <- randomColorWithHue hue
let fromShapeState = newShapeState
& rndrColor .~ color
& rndrPose . posOrientation .~ (axisAngle (V3 0 1 0) 0)
& rndrPose . posPosition . _x .~ x
& rndrPose . posPosition . _y .~ y
toShapeState <- ShapeState
<$> (randomPose <&> posPosition +~ V3 x y 0)
<*> randomColorWithHue hue
<*> pure 0
let shapeAnim = Animation
{ animStart = startTime
, animDuration = 1
, animFunc = animator (undefined :: ShapeState)
, animFrom = fromShapeState
, animTo = toShapeState
}
wldAnimations <>= [shapeAnim]
main :: IO ()
main = do
vrPal@VRPal{..} <- reacquire 0 $ initVRPal "VRPal" []
-- Set up our cube resources
cubeProg <- createShaderProgram "test/cube.vert" "test/cube.frag"
cubeGeo <- cubeGeometry (1 :: V3 GLfloat) (V3 1 1 1)
shape <- makeShape cubeGeo cubeProg
glEnable GL_DEPTH_TEST
glClearColor 0 0 0.1 1
useProgram (sProgram shape)
let world = World (newPose {_posPosition = V3 0 0 10}) []
onSpawnTimer <- makeTimer 0.001
void . flip runStateT world . whileWindow gpWindow $ do
-- applyMouseLook gpWindow wldPlayer
applyWASD gpWindow wldPlayer
player <- use wldPlayer
(headM44, events) <- tickVR vrPal (transformationFromPose player)
forM_ events $ \case
GLFWEvent e -> do
closeOnEscape gpWindow e
applyGamepadJoystickMovement e wldPlayer
onKeyDown e Key'E $ replicateM_ 100 spawnCube
_ -> return ()
onSpawnTimer spawnCube
now <- utctDayTime <$> liftIO getCurrentTime
(shapeStates, newAnims, _finishedAnims) <- evalAnimations now <$> use wldAnimations
wldAnimations .= newAnims
renderWith vrPal headM44 $ \projM44 viewM44 -> do
glClear (GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT)
render shape shapeStates projM44 viewM44
| lukexi/animation-pal | test/MainExplosion.hs | bsd-3-clause | 2,981 | 0 | 22 | 895 | 840 | 425 | 415 | -1 | -1 |
module RomanNumbersKata.Day7Spec (spec) where
import Test.Hspec
import RomanNumbersKata.Day7 (toRomanNumber)
spec :: Spec
spec = do
it "returns an empty string when given 0"
(toRomanNumber 0 == "")
it "returns \"I\" when given 1"
(toRomanNumber 1 == "I")
it "returns \"V\" when given 5"
(toRomanNumber 5 == "V")
it "returns \"X\" when given 10"
(toRomanNumber 10 == "X")
it "returns \"IV\" when given 4"
(toRomanNumber 4 == "IV")
it "returns \"XIV\" when given 14"
(toRomanNumber 14 == "XIV")
it "returns \"IX\" when given 9"
(toRomanNumber 9 == "IX")
it "returns \"L\" when given 50"
(toRomanNumber 50 == "L")
it "returns \"XLIX\" when given 49"
(toRomanNumber 49 == "XLIX")
it "returns \"MMMCMXCIX\" when given 3999"
(toRomanNumber 3999 == "MMMCMXCIX")
| Alex-Diez/haskell-tdd-kata | old-katas/test/RomanNumbersKata/Day7Spec.hs | bsd-3-clause | 982 | 0 | 10 | 344 | 216 | 102 | 114 | 25 | 1 |
{-# LINE 1 "Foreign.Marshal.Utils.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Marshal.Utils
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Utilities for primitive marshaling
--
-----------------------------------------------------------------------------
module Foreign.Marshal.Utils (
-- * General marshalling utilities
-- ** Combined allocation and marshalling
--
with,
new,
-- ** Marshalling of Boolean values (non-zero corresponds to 'True')
--
fromBool,
toBool,
-- ** Marshalling of Maybe values
--
maybeNew,
maybeWith,
maybePeek,
-- ** Marshalling lists of storable objects
--
withMany,
-- ** Haskellish interface to memcpy and memmove
-- | (argument order: destination, source)
--
copyBytes,
moveBytes,
-- ** Filling up memory area with required values
--
fillBytes,
) where
import Data.Maybe
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.Storable ( Storable(poke) )
import Foreign.C.Types ( CSize(..), CInt(..) )
import Foreign.Marshal.Alloc ( malloc, alloca )
import Data.Word ( Word8 )
import GHC.Real ( fromIntegral )
import GHC.Num
import GHC.Base
-- combined allocation and marshalling
-- -----------------------------------
-- |Allocate a block of memory and marshal a value into it
-- (the combination of 'malloc' and 'poke').
-- The size of the area allocated is determined by the 'Foreign.Storable.sizeOf'
-- method from the instance of 'Storable' for the appropriate type.
--
-- The memory may be deallocated using 'Foreign.Marshal.Alloc.free' or
-- 'Foreign.Marshal.Alloc.finalizerFree' when no longer required.
--
new :: Storable a => a -> IO (Ptr a)
new val =
do
ptr <- malloc
poke ptr val
return ptr
-- |@'with' val f@ executes the computation @f@, passing as argument
-- a pointer to a temporarily allocated block of memory into which
-- @val@ has been marshalled (the combination of 'alloca' and 'poke').
--
-- The memory is freed when @f@ terminates (either normally or via an
-- exception), so the pointer passed to @f@ must /not/ be used after this.
--
with :: Storable a => a -> (Ptr a -> IO b) -> IO b
with val f =
alloca $ \ptr -> do
poke ptr val
res <- f ptr
return res
-- marshalling of Boolean values (non-zero corresponds to 'True')
-- -----------------------------
-- |Convert a Haskell 'Bool' to its numeric representation
--
fromBool :: Num a => Bool -> a
fromBool False = 0
fromBool True = 1
-- |Convert a Boolean in numeric representation to a Haskell value
--
toBool :: (Eq a, Num a) => a -> Bool
toBool = (/= 0)
-- marshalling of Maybe values
-- ---------------------------
-- |Allocate storage and marshal a storable value wrapped into a 'Maybe'
--
-- * the 'nullPtr' is used to represent 'Nothing'
--
maybeNew :: ( a -> IO (Ptr b))
-> (Maybe a -> IO (Ptr b))
maybeNew = maybe (return nullPtr)
-- |Converts a @withXXX@ combinator into one marshalling a value wrapped
-- into a 'Maybe', using 'nullPtr' to represent 'Nothing'.
--
maybeWith :: ( a -> (Ptr b -> IO c) -> IO c)
-> (Maybe a -> (Ptr b -> IO c) -> IO c)
maybeWith = maybe ($ nullPtr)
-- |Convert a peek combinator into a one returning 'Nothing' if applied to a
-- 'nullPtr'
--
maybePeek :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)
maybePeek peek ptr | ptr == nullPtr = return Nothing
| otherwise = do a <- peek ptr; return (Just a)
-- marshalling lists of storable objects
-- -------------------------------------
-- |Replicates a @withXXX@ combinator over a list of objects, yielding a list of
-- marshalled objects
--
withMany :: (a -> (b -> res) -> res) -- withXXX combinator for one object
-> [a] -- storable objects
-> ([b] -> res) -- action on list of marshalled obj.s
-> res
withMany _ [] f = f []
withMany withFoo (x:xs) f = withFoo x $ \x' ->
withMany withFoo xs (\xs' -> f (x':xs'))
-- Haskellish interface to memcpy and memmove
-- ------------------------------------------
-- |Copies the given number of bytes from the second area (source) into the
-- first (destination); the copied areas may /not/ overlap
--
copyBytes :: Ptr a -> Ptr a -> Int -> IO ()
copyBytes dest src size = do _ <- memcpy dest src (fromIntegral size)
return ()
-- |Copies the given number of bytes from the second area (source) into the
-- first (destination); the copied areas /may/ overlap
--
moveBytes :: Ptr a -> Ptr a -> Int -> IO ()
moveBytes dest src size = do _ <- memmove dest src (fromIntegral size)
return ()
-- Filling up memory area with required values
-- -------------------------------------------
-- |Fill a given number of bytes in memory area with a byte value.
--
-- @since 4.8.0.0
fillBytes :: Ptr a -> Word8 -> Int -> IO ()
fillBytes dest char size = do
_ <- memset dest (fromIntegral char) (fromIntegral size)
return ()
-- auxilliary routines
-- -------------------
-- |Basic C routines needed for memory copying
--
foreign import ccall unsafe "string.h" memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)
foreign import ccall unsafe "string.h" memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)
foreign import ccall unsafe "string.h" memset :: Ptr a -> CInt -> CSize -> IO (Ptr a)
| phischu/fragnix | builtins/base/Foreign.Marshal.Utils.hs | bsd-3-clause | 5,794 | 0 | 12 | 1,410 | 1,108 | 605 | 503 | 69 | 1 |
module Codec.Archive.Smooth.Function where
import Prelude
import Data.Conduit
import Control.Monad.Error.Class
import qualified Data.ByteString.Lazy as LB
import Data.ByteString (ByteString)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Trans.Resource (MonadResource)
import Control.Monad.Trans.Except (runExceptT)
#if MIN_VERSION_conduit(1, 3, 0)
import Control.Monad.Primitive (PrimMonad)
#endif
import Codec.Archive.Smooth.Types
autoDecompress :: ( MonadThrow m, MonadResource m
#if MIN_VERSION_conduit(1, 3, 0)
, PrimMonad m
#endif
, CompressFormat a, FormatDetect a)
=> a
#if MIN_VERSION_conduit(1, 3, 0)
-> ConduitT ByteString ByteString m ()
#else
-> Conduit ByteString m ByteString
#endif
autoDecompress x = do
(matched, bs) <- magicMatch x
leftover $ LB.toStrict bs
if matched
then decompress x
else awaitForever yield
autoDecompressByCompressors :: ( MonadThrow m, MonadResource m
#if MIN_VERSION_conduit(1, 3, 0)
, PrimMonad m
#endif
)
=> [SomeDetectiveCompressor]
#if MIN_VERSION_conduit(1, 3, 0)
-> ConduitT ByteString ByteString m ()
#else
-> Conduit ByteString m ByteString
#endif
autoDecompressByCompressors = go
where
go [] = awaitForever yield
go (SomeDetectiveCompressor x:xs) = do
(matched, bs) <- magicMatch x
leftover $ LB.toStrict bs
if matched
then decompress x
else go xs
autoExtractFiles :: (MonadError String m, Functor m)
=> [SomeDetectiveArchive]
#if MIN_VERSION_conduit(1, 3, 0)
-> ConduitT ByteString FileEntry m ()
#else
-> Conduit ByteString m FileEntry
#endif
autoExtractFiles [] = mempty
autoExtractFiles (ax@(SomeDetectiveArchive x _):xs) = do
(matched, bs) <- magicMatch x
leftover $ LB.toStrict bs
if matched
then extractFilesByDetectiveArchive ax
else autoExtractFiles xs
extractFilesByDetectiveArchive :: (MonadError String m, Functor m)
=> SomeDetectiveArchive
#if MIN_VERSION_conduit(1, 3, 0)
-> ConduitT ByteString FileEntry m ()
#else
-> Conduit ByteString m FileEntry
#endif
extractFilesByDetectiveArchive (SomeDetectiveArchive x convert_err) =
transPipe (\me -> runExceptT me >>= either (throwError . err_to_str) return) $
transPipe convert_err $ extractEntries x
where
err_to_str e = "Failed to extract files by format "
++ show (formatName x)
++ ": " ++ e
-- | detect archive format from bytestring
-- NOTE: This functions will put back any bytes it possible consumed.
-- So the upstream conduit can be reused from the begining.
autoDetectArchive :: (Monad m)
=> [SomeDetectiveArchive]
#if MIN_VERSION_conduit(1, 3, 0)
-> ConduitT ByteString Void m (Maybe SomeDetectiveArchive)
#else
-> Sink ByteString m (Maybe SomeDetectiveArchive)
#endif
autoDetectArchive [] = return Nothing
autoDetectArchive (ax@(SomeDetectiveArchive x _):xs) = do
(matched, bs) <- magicMatch x
leftover $ LB.toStrict bs
if matched
then return $ Just ax
else autoDetectArchive xs
| txkaduo/hs-simple-archive-conduit | Codec/Archive/Smooth/Function.hs | mit | 3,744 | 0 | 13 | 1,297 | 725 | 389 | 336 | -1 | -1 |
{-# Language RebindableSyntax #-}
{-# Language TypeOperators #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module PingMulti00 where
import Prelude hiding (lookup, (>>=), (>>), fail, return)
import Symmetry.Language
import Symmetry.Verify
m1 :: DSL repr => repr Int -> repr (Int :+: ())
m1 = inl
m2 :: DSL repr => repr (Int :+: ())
m2 = inr tt
mainProc :: forall repr.
(DSL repr) => repr (Int -> ())
mainProc = lam $ \n -> exec $ do r <- newRMulti
me <- self
workers <- spawnMany r n (app worker me)
let p = workers `lookup` int 0
send p (m1 (int 0))
doMany workers (lam $ \p -> send p m2 >> recv :: repr (Process repr ()))
return tt
where
workerLoop = lam $ \f -> lam $ \_ -> do m <- recv
match (m :: repr (Int :+: ()))
(lam $ \_ -> app f tt)
(lam $ \_ -> return tt)
worker = lam $ \master ->
do m <- recv
match (m :: repr (Int :+: ()))
(lam $ \_ -> return tt)
(lam $ \_ -> send master tt >> return tt)
main :: IO ()
main = checkerMain (int 3 |> mainProc)
| abakst/symmetry | checker/tests/neg/TestLookup00.hs | mit | 1,595 | 0 | 18 | 691 | 496 | 260 | 236 | 35 | 1 |
--
--
--
------------------
-- Exercise 10.18.
------------------
--
--
--
module E'10'18 where
filterFirst :: (a -> Bool) -> [a] -> [a]
filterFirst _ [] = []
filterFirst predicate ( item : remainingItems )
| not ( predicate item ) = remainingItems
| otherwise = item : filterFirst predicate remainingItems
{- GHCi>
:{
let isZero :: Integer -> Bool ;
isZero integer = integer == 0
:}
filterFirst isZero [ 0 , 1 , 2 , 0 ]
-}
-- [ 0 , 2 , 0 ]
-- From chapter 5 ...
type Person = String
type Book = String
type Loan = ( Person , Book )
type Database = [ Loan ]
-- ...
returnLoan :: Database -> Loan -> Database
returnLoan database referenceLoan
= filterFirst isLoan database
where
isLoan :: Loan -> Bool
isLoan loan = loan == referenceLoan
{- GHCi>
:{
let database :: Database ;
database = [
( "P1" , "B1" ) ,
( "P2" , "B1" ) ,
( "P3" , "B2" )
]
:}
returnLoan database ( "P2" , "B1" )
-}
-- [
-- ( "P2" , "B1" ) ,
-- ( "P3" , "B2" )
-- ]
| pascal-knodel/haskell-craft | _/links/E'10'18.hs | mit | 1,097 | 0 | 10 | 360 | 196 | 114 | 82 | 15 | 1 |
{-# LANGUAGE UnboxedTuples, ForeignFunctionInterface, NoImplicitPrelude #-}
module Jhc.Prim(module Jhc.Prim.Bits, module Jhc.Prim, module Jhc.Prim.Prim, module Jhc.Prim.IO, module Jhc.Prim.Type.Basic, module Jhc.Prim.Type.Word) where
import Jhc.Prim.Bits
import Jhc.Prim.IO
-- | this is wrapped around arbitrary expressions and just evaluates them to whnf
foreign import primitive "seq" runRaw :: a -> World__ -> World__
foreign import primitive "unsafeCoerce" unsafeCoerce__ :: a -> b
-- like 'const' but creates an artificial dependency on its second argument to guide optimization.
foreign import primitive dependingOn :: a -> b -> a
| dec9ue/jhc_copygc | lib/jhc/Jhc/Prim.hs | gpl-2.0 | 640 | 3 | 6 | 86 | 101 | 69 | 32 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./Syntax/AS_Structured.der.hs
Description : abstract syntax of DOL OMS and CASL structured specifications
Copyright : (c) Klaus Luettich, Uni Bremen 2002-2016
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : provisional
Portability : non-portable(Grothendieck)
Abstract syntax of HetCASL (heterogeneous) structured specifications
Follows Sect. II:2.2.3 of the CASL Reference Manual.
Abstract syntax of DOL OMS and networks
Follows the DOL OMG standard, clauses 9.4, 9.5, M.2 and M.3
-}
module Syntax.AS_Structured where
-- DrIFT command:
{-! global: GetRange !-}
import Common.Id
import Common.IRI
import Common.AS_Annotation
import Data.Typeable
import qualified Data.Set as Set
import Logic.Logic
import Logic.Grothendieck
( G_basic_spec
, G_symb_items_list
, G_symb_map_items_list
, LogicGraph
, setCurLogic
, setSyntax )
-- for spec-defn and view-defn see AS_Library
data SPEC = Basic_spec G_basic_spec Range
| EmptySpec Range
| Extraction (Annoted SPEC) EXTRACTION
| Translation (Annoted SPEC) RENAMING
| Reduction (Annoted SPEC) RESTRICTION
| Approximation (Annoted SPEC) APPROXIMATION
| Minimization (Annoted SPEC) MINIMIZATION
| Filtering (Annoted SPEC) FILTERING
| Bridge (Annoted SPEC) [RENAMING] (Annoted SPEC) Range
| Union [Annoted SPEC] Range
-- pos: "and"s
| Intersection [Annoted SPEC] Range
-- pos: "intersect"s
| Extension [Annoted SPEC] Range
-- pos: "then"s
| Free_spec (Annoted SPEC) Range
-- pos: "free"
| Cofree_spec (Annoted SPEC) Range
-- pos: "cofree"
| Minimize_spec (Annoted SPEC) Range
-- pos: "minimize", "closed-world"
| Local_spec (Annoted SPEC) (Annoted SPEC) Range
-- pos: "local", "within"
| Closed_spec (Annoted SPEC) Range
-- pos: "closed"
| Group (Annoted SPEC) Range
-- pos: "{","}"
| Spec_inst SPEC_NAME [Annoted FIT_ARG] (Maybe IRI) Range
{- pos: many of "[","]"; one balanced pair per FIT_ARG
an optional ImpName for DOL -}
| Qualified_spec LogicDescr (Annoted SPEC) Range
-- pos: "logic", Logic_name,":"
| Data AnyLogic AnyLogic (Annoted SPEC) (Annoted SPEC) Range
-- pos: "data"
| Combination Network Range
-- pos: "combine"
| Apply IRI G_basic_spec Range
-- pos: "apply", use a basic spec parser to parse a sentence
deriving (Show, Typeable)
data Network = Network [LABELED_ONTO_OR_INTPR_REF] [IRI] Range
deriving (Show, Eq, Typeable)
data FILTERING = FilterBasicSpec Bool G_basic_spec Range
| FilterSymbolList Bool G_symb_items_list Range
deriving (Show, Eq, Typeable)
data EXTRACTION = ExtractOrRemove Bool [IRI] Range
deriving (Show, Eq, Typeable)
data APPROXIMATION = ForgetOrKeep Bool [G_hiding] (Maybe IRI) Range
deriving (Show, Eq, Typeable)
data MINIMIZATION = Mini Token [IRI] [IRI] Range
deriving (Show, Eq, Typeable)
data RENAMING = Renaming [G_mapping] Range
-- pos: "with", list of comma pos
deriving (Show, Eq, Typeable)
data RESTRICTION = Hidden [G_hiding] Range
-- pos: "hide", list of comma pos
| Revealed G_symb_map_items_list Range
-- pos: "reveal", list of comma pos
deriving (Show, Eq, Typeable)
{- Renaming and Hiding can be performend with intermediate Logic
mappings / Logic projections.
-}
data G_mapping = G_symb_map G_symb_map_items_list
| G_logic_translation Logic_code
deriving (Show, Eq, Typeable)
data G_hiding = G_symb_list G_symb_items_list
| G_logic_projection Logic_code
deriving (Show, Eq, Typeable)
data FIT_ARG = Fit_spec (Annoted SPEC) [G_mapping] Range
-- pos: opt "fit"
| Fit_view IRI [Annoted FIT_ARG] Range
-- annotations before the view keyword are stored in Spec_inst
deriving (Show, Typeable)
type SPEC_NAME = IRI
-- | a logic with serialization or a DOL qualification
data LogicDescr = LogicDescr Logic_name (Maybe IRI) Range
-- pos: "serialization"
| SyntaxQual IRI
| LanguageQual IRI
deriving (Show, Typeable)
data Logic_code = Logic_code (Maybe String)
(Maybe Logic_name)
(Maybe Logic_name) Range
{- pos: "logic",<encoding>,":",<src-logic>,"->",<targ-logic>
one of <encoding>, <src-logic> or <targ-logic>
must be given (by Just)
"logic bla" => <encoding> only
"logic bla ->" => <src-logic> only
"logic -> bla" => <targ-logic> only
"logic bla1 -> bla2" => <src-logic> and <targ-logic>
-- "logic bla1:bla2" => <encoding> and <src-logic>
this notation is not very useful and is not maintained
"logic bla1:bla2 ->" => <encoding> and <src-logic> (!)
"logic bla1: ->bla2" => <encoding> and <targ-logic> -}
deriving (Show, Eq, Typeable)
data Logic_name = Logic_name
String -- looked-up logic name
(Maybe Token) -- sublogic part
(Maybe SPEC_NAME) -- for a sublogic based on the given theory
deriving (Show, Eq, Typeable)
data LABELED_ONTO_OR_INTPR_REF = Labeled (Maybe Token) IRI
deriving (Show, Eq, Typeable)
nameToLogicDescr :: Logic_name -> LogicDescr
nameToLogicDescr n = LogicDescr n Nothing nullRange
setLogicName :: LogicDescr -> LogicGraph -> LogicGraph
setLogicName ld = case ld of
LogicDescr (Logic_name lid _ _) s _ -> setSyntax s . setCurLogic lid
_ -> id
makeSpec :: G_basic_spec -> Annoted SPEC
makeSpec gbs = emptyAnno $ Basic_spec gbs nullRange
makeSpecInst :: SPEC_NAME -> Annoted SPEC
makeSpecInst n = emptyAnno $ Spec_inst n [] Nothing nullRange
addImports :: [SPEC_NAME] -> Annoted SPEC -> Annoted SPEC
addImports is bs = case map makeSpecInst is of
[] -> bs
js@(i : rs) -> emptyAnno $ Extension
[ if null rs then i else
emptyAnno $ Union js nullRange, bs] nullRange
data CORRESPONDENCE = Correspondence_block
(Maybe RELATION_REF)
(Maybe CONFIDENCE)
[CORRESPONDENCE]
| Single_correspondence
(Maybe Annotation)
G_symb_items_list -- was ENTITY_REF
G_symb_items_list -- was TERM_OR_ENTITY_REF
(Maybe RELATION_REF)
(Maybe CONFIDENCE)
| Default_correspondence
deriving (Show, Eq, Typeable)
data RELATION_REF = Subsumes | IsSubsumed | Equivalent | Incompatible
| HasInstance | InstanceOf | DefaultRelation
| Iri IRI
deriving (Show, Eq, Typeable)
refToRel :: RELATION_REF -> REL_REF
refToRel Subsumes = Subs
refToRel IsSubsumed = IsSubs
refToRel Equivalent = Equiv
refToRel Incompatible = Incomp
refToRel HasInstance = HasInst
refToRel InstanceOf = InstOf
refToRel DefaultRelation = DefRel
refToRel (Iri i) = RelName i
type CONFIDENCE = Double -- NOTE: will be revised
instance GetRange Double where
getRange = const nullRange
getSpecNames :: SPEC -> Set.Set SPEC_NAME
getSpecNames sp = let f = getSpecNames . item in case sp of
Translation as _ -> f as
Reduction as _ -> f as
Approximation as _ -> f as
Minimization as _ -> f as
Filtering as _ -> f as
Union as _ -> Set.unions $ map f as
Intersection as _ -> Set.unions $ map f as
Extraction as _ -> f as
Extension as _ -> Set.unions $ map f as
Free_spec as _ -> f as
Cofree_spec as _ -> f as
Minimize_spec as _ -> f as
Local_spec s1 s2 _ -> Set.union (f s1) $ f s2
Closed_spec as _ -> f as
Group as _ -> f as
Spec_inst sn fas _ _ -> Set.insert sn
. Set.unions . map f $ concatMap (getSpecs . item) fas
Qualified_spec _ as _ -> f as
Data _ _ s1 s2 _ -> Set.union (f s1) $ f s2
_ -> Set.empty
getSpecs :: FIT_ARG -> [Annoted SPEC]
getSpecs fa = case fa of
Fit_spec as _ _ -> [as]
Fit_view _ fas _ -> concatMap (getSpecs . item) fas
| spechub/Hets | Syntax/AS_Structured.der.hs | gpl-2.0 | 8,506 | 0 | 14 | 2,501 | 1,893 | 995 | 898 | 150 | 19 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.AutoScaling.UpdateAutoScalingGroup
-- Copyright : (c) 2013-2015 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)
--
-- Updates the configuration for the specified Auto Scaling group.
--
-- To update an Auto Scaling group with a launch configuration with
-- 'InstanceMonitoring' set to 'False', you must first disable the
-- collection of group metrics. Otherwise, you will get an error. If you
-- have previously enabled the collection of group metrics, you can disable
-- it using DisableMetricsCollection.
--
-- The new settings are registered upon the completion of this call. Any
-- launch configuration settings take effect on any triggers after this
-- call returns. Scaling activities that are currently in progress aren\'t
-- affected.
--
-- Note the following:
--
-- - If you specify a new value for 'MinSize' without specifying a value
-- for 'DesiredCapacity', and the new 'MinSize' is larger than the
-- current size of the group, we implicitly call SetDesiredCapacity to
-- set the size of the group to the new value of 'MinSize'.
--
-- - If you specify a new value for 'MaxSize' without specifying a value
-- for 'DesiredCapacity', and the new 'MaxSize' is smaller than the
-- current size of the group, we implicitly call SetDesiredCapacity to
-- set the size of the group to the new value of 'MaxSize'.
--
-- - All other optional parameters are left unchanged if not specified.
--
--
-- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_UpdateAutoScalingGroup.html AWS API Reference> for UpdateAutoScalingGroup.
module Network.AWS.AutoScaling.UpdateAutoScalingGroup
(
-- * Creating a Request
updateAutoScalingGroup
, UpdateAutoScalingGroup
-- * Request Lenses
, uasgTerminationPolicies
, uasgHealthCheckGracePeriod
, uasgVPCZoneIdentifier
, uasgDefaultCooldown
, uasgMaxSize
, uasgAvailabilityZones
, uasgDesiredCapacity
, uasgMinSize
, uasgLaunchConfigurationName
, uasgHealthCheckType
, uasgPlacementGroup
, uasgAutoScalingGroupName
-- * Destructuring the Response
, updateAutoScalingGroupResponse
, UpdateAutoScalingGroupResponse
) where
import Network.AWS.AutoScaling.Types
import Network.AWS.AutoScaling.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'updateAutoScalingGroup' smart constructor.
data UpdateAutoScalingGroup = UpdateAutoScalingGroup'
{ _uasgTerminationPolicies :: !(Maybe [Text])
, _uasgHealthCheckGracePeriod :: !(Maybe Int)
, _uasgVPCZoneIdentifier :: !(Maybe Text)
, _uasgDefaultCooldown :: !(Maybe Int)
, _uasgMaxSize :: !(Maybe Int)
, _uasgAvailabilityZones :: !(Maybe (List1 Text))
, _uasgDesiredCapacity :: !(Maybe Int)
, _uasgMinSize :: !(Maybe Int)
, _uasgLaunchConfigurationName :: !(Maybe Text)
, _uasgHealthCheckType :: !(Maybe Text)
, _uasgPlacementGroup :: !(Maybe Text)
, _uasgAutoScalingGroupName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateAutoScalingGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uasgTerminationPolicies'
--
-- * 'uasgHealthCheckGracePeriod'
--
-- * 'uasgVPCZoneIdentifier'
--
-- * 'uasgDefaultCooldown'
--
-- * 'uasgMaxSize'
--
-- * 'uasgAvailabilityZones'
--
-- * 'uasgDesiredCapacity'
--
-- * 'uasgMinSize'
--
-- * 'uasgLaunchConfigurationName'
--
-- * 'uasgHealthCheckType'
--
-- * 'uasgPlacementGroup'
--
-- * 'uasgAutoScalingGroupName'
updateAutoScalingGroup
:: Text -- ^ 'uasgAutoScalingGroupName'
-> UpdateAutoScalingGroup
updateAutoScalingGroup pAutoScalingGroupName_ =
UpdateAutoScalingGroup'
{ _uasgTerminationPolicies = Nothing
, _uasgHealthCheckGracePeriod = Nothing
, _uasgVPCZoneIdentifier = Nothing
, _uasgDefaultCooldown = Nothing
, _uasgMaxSize = Nothing
, _uasgAvailabilityZones = Nothing
, _uasgDesiredCapacity = Nothing
, _uasgMinSize = Nothing
, _uasgLaunchConfigurationName = Nothing
, _uasgHealthCheckType = Nothing
, _uasgPlacementGroup = Nothing
, _uasgAutoScalingGroupName = pAutoScalingGroupName_
}
-- | A standalone termination policy or a list of termination policies used
-- to select the instance to terminate. The policies are executed in the
-- order that they are listed.
--
-- For more information, see
-- <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-termination-policy.html Choosing a Termination Policy for Your Auto Scaling Group>
-- in the /Auto Scaling Developer Guide/.
uasgTerminationPolicies :: Lens' UpdateAutoScalingGroup [Text]
uasgTerminationPolicies = lens _uasgTerminationPolicies (\ s a -> s{_uasgTerminationPolicies = a}) . _Default . _Coerce;
-- | The amount of time, in seconds, that Auto Scaling waits before checking
-- the health status of an instance. The grace period begins when the
-- instance passes the system status and instance status checks from Amazon
-- EC2. For more information, see < >.
uasgHealthCheckGracePeriod :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgHealthCheckGracePeriod = lens _uasgHealthCheckGracePeriod (\ s a -> s{_uasgHealthCheckGracePeriod = a});
-- | The ID of the subnet, if you are launching into a VPC. You can specify
-- several subnets in a comma-separated list.
--
-- When you specify 'VPCZoneIdentifier' with 'AvailabilityZones', ensure
-- that the subnets\' Availability Zones match the values you specify for
-- 'AvailabilityZones'.
--
-- For more information, see
-- <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html Auto Scaling and Amazon Virtual Private Cloud>
-- in the /Auto Scaling Developer Guide/.
uasgVPCZoneIdentifier :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgVPCZoneIdentifier = lens _uasgVPCZoneIdentifier (\ s a -> s{_uasgVPCZoneIdentifier = a});
-- | The amount of time, in seconds, after a scaling activity completes
-- before another scaling activity can start. For more information, see
-- <http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/Cooldown.html Understanding Auto Scaling Cooldowns>.
uasgDefaultCooldown :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgDefaultCooldown = lens _uasgDefaultCooldown (\ s a -> s{_uasgDefaultCooldown = a});
-- | The maximum size of the Auto Scaling group.
uasgMaxSize :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgMaxSize = lens _uasgMaxSize (\ s a -> s{_uasgMaxSize = a});
-- | One or more Availability Zones for the group.
uasgAvailabilityZones :: Lens' UpdateAutoScalingGroup (Maybe (NonEmpty Text))
uasgAvailabilityZones = lens _uasgAvailabilityZones (\ s a -> s{_uasgAvailabilityZones = a}) . mapping _List1;
-- | The number of EC2 instances that should be running in the Auto Scaling
-- group. This number must be greater than or equal to the minimum size of
-- the group and less than or equal to the maximum size of the group.
uasgDesiredCapacity :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgDesiredCapacity = lens _uasgDesiredCapacity (\ s a -> s{_uasgDesiredCapacity = a});
-- | The minimum size of the Auto Scaling group.
uasgMinSize :: Lens' UpdateAutoScalingGroup (Maybe Int)
uasgMinSize = lens _uasgMinSize (\ s a -> s{_uasgMinSize = a});
-- | The name of the launch configuration.
uasgLaunchConfigurationName :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgLaunchConfigurationName = lens _uasgLaunchConfigurationName (\ s a -> s{_uasgLaunchConfigurationName = a});
-- | The type of health check for the instances in the Auto Scaling group.
-- The health check type can either be 'EC2' for Amazon EC2 or 'ELB' for
-- Elastic Load Balancing.
uasgHealthCheckType :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgHealthCheckType = lens _uasgHealthCheckType (\ s a -> s{_uasgHealthCheckType = a});
-- | The name of the placement group into which you\'ll launch your
-- instances, if any. For more information, see
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html Placement Groups>.
uasgPlacementGroup :: Lens' UpdateAutoScalingGroup (Maybe Text)
uasgPlacementGroup = lens _uasgPlacementGroup (\ s a -> s{_uasgPlacementGroup = a});
-- | The name of the Auto Scaling group.
uasgAutoScalingGroupName :: Lens' UpdateAutoScalingGroup Text
uasgAutoScalingGroupName = lens _uasgAutoScalingGroupName (\ s a -> s{_uasgAutoScalingGroupName = a});
instance AWSRequest UpdateAutoScalingGroup where
type Rs UpdateAutoScalingGroup =
UpdateAutoScalingGroupResponse
request = postQuery autoScaling
response
= receiveNull UpdateAutoScalingGroupResponse'
instance ToHeaders UpdateAutoScalingGroup where
toHeaders = const mempty
instance ToPath UpdateAutoScalingGroup where
toPath = const "/"
instance ToQuery UpdateAutoScalingGroup where
toQuery UpdateAutoScalingGroup'{..}
= mconcat
["Action" =:
("UpdateAutoScalingGroup" :: ByteString),
"Version" =: ("2011-01-01" :: ByteString),
"TerminationPolicies" =:
toQuery
(toQueryList "member" <$> _uasgTerminationPolicies),
"HealthCheckGracePeriod" =:
_uasgHealthCheckGracePeriod,
"VPCZoneIdentifier" =: _uasgVPCZoneIdentifier,
"DefaultCooldown" =: _uasgDefaultCooldown,
"MaxSize" =: _uasgMaxSize,
"AvailabilityZones" =:
toQuery
(toQueryList "member" <$> _uasgAvailabilityZones),
"DesiredCapacity" =: _uasgDesiredCapacity,
"MinSize" =: _uasgMinSize,
"LaunchConfigurationName" =:
_uasgLaunchConfigurationName,
"HealthCheckType" =: _uasgHealthCheckType,
"PlacementGroup" =: _uasgPlacementGroup,
"AutoScalingGroupName" =: _uasgAutoScalingGroupName]
-- | /See:/ 'updateAutoScalingGroupResponse' smart constructor.
data UpdateAutoScalingGroupResponse =
UpdateAutoScalingGroupResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateAutoScalingGroupResponse' with the minimum fields required to make a request.
--
updateAutoScalingGroupResponse
:: UpdateAutoScalingGroupResponse
updateAutoScalingGroupResponse = UpdateAutoScalingGroupResponse'
| fmapfmapfmap/amazonka | amazonka-autoscaling/gen/Network/AWS/AutoScaling/UpdateAutoScalingGroup.hs | mpl-2.0 | 11,144 | 0 | 13 | 2,121 | 1,318 | 795 | 523 | 150 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ELB.Types.Product
-- Copyright : (c) 2013-2015 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.AWS.ELB.Types.Product where
import Network.AWS.ELB.Types.Sum
import Network.AWS.Prelude
-- | Information about the 'AccessLog' attribute.
--
-- /See:/ 'accessLog' smart constructor.
data AccessLog = AccessLog'
{ _alEmitInterval :: !(Maybe Int)
, _alS3BucketPrefix :: !(Maybe Text)
, _alS3BucketName :: !(Maybe Text)
, _alEnabled :: !Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AccessLog' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'alEmitInterval'
--
-- * 'alS3BucketPrefix'
--
-- * 'alS3BucketName'
--
-- * 'alEnabled'
accessLog
:: Bool -- ^ 'alEnabled'
-> AccessLog
accessLog pEnabled_ =
AccessLog'
{ _alEmitInterval = Nothing
, _alS3BucketPrefix = Nothing
, _alS3BucketName = Nothing
, _alEnabled = pEnabled_
}
-- | The interval for publishing the access logs. You can specify an interval
-- of either 5 minutes or 60 minutes.
--
-- Default: 60 minutes
alEmitInterval :: Lens' AccessLog (Maybe Int)
alEmitInterval = lens _alEmitInterval (\ s a -> s{_alEmitInterval = a});
-- | The logical hierarchy you created for your Amazon S3 bucket, for example
-- 'my-bucket-prefix\/prod'. If the prefix is not provided, the log is
-- placed at the root level of the bucket.
alS3BucketPrefix :: Lens' AccessLog (Maybe Text)
alS3BucketPrefix = lens _alS3BucketPrefix (\ s a -> s{_alS3BucketPrefix = a});
-- | The name of the Amazon S3 bucket where the access logs are stored.
alS3BucketName :: Lens' AccessLog (Maybe Text)
alS3BucketName = lens _alS3BucketName (\ s a -> s{_alS3BucketName = a});
-- | Specifies whether access log is enabled for the load balancer.
alEnabled :: Lens' AccessLog Bool
alEnabled = lens _alEnabled (\ s a -> s{_alEnabled = a});
instance FromXML AccessLog where
parseXML x
= AccessLog' <$>
(x .@? "EmitInterval") <*> (x .@? "S3BucketPrefix")
<*> (x .@? "S3BucketName")
<*> (x .@ "Enabled")
instance ToQuery AccessLog where
toQuery AccessLog'{..}
= mconcat
["EmitInterval" =: _alEmitInterval,
"S3BucketPrefix" =: _alS3BucketPrefix,
"S3BucketName" =: _alS3BucketName,
"Enabled" =: _alEnabled]
-- | This data type is reserved.
--
-- /See:/ 'additionalAttribute' smart constructor.
data AdditionalAttribute = AdditionalAttribute'
{ _aaValue :: !(Maybe Text)
, _aaKey :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AdditionalAttribute' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aaValue'
--
-- * 'aaKey'
additionalAttribute
:: AdditionalAttribute
additionalAttribute =
AdditionalAttribute'
{ _aaValue = Nothing
, _aaKey = Nothing
}
-- | This parameter is reserved.
aaValue :: Lens' AdditionalAttribute (Maybe Text)
aaValue = lens _aaValue (\ s a -> s{_aaValue = a});
-- | This parameter is reserved.
aaKey :: Lens' AdditionalAttribute (Maybe Text)
aaKey = lens _aaKey (\ s a -> s{_aaKey = a});
instance FromXML AdditionalAttribute where
parseXML x
= AdditionalAttribute' <$>
(x .@? "Value") <*> (x .@? "Key")
instance ToQuery AdditionalAttribute where
toQuery AdditionalAttribute'{..}
= mconcat ["Value" =: _aaValue, "Key" =: _aaKey]
-- | Information about a policy for application-controlled session
-- stickiness.
--
-- /See:/ 'appCookieStickinessPolicy' smart constructor.
data AppCookieStickinessPolicy = AppCookieStickinessPolicy'
{ _acspPolicyName :: !(Maybe Text)
, _acspCookieName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'AppCookieStickinessPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acspPolicyName'
--
-- * 'acspCookieName'
appCookieStickinessPolicy
:: AppCookieStickinessPolicy
appCookieStickinessPolicy =
AppCookieStickinessPolicy'
{ _acspPolicyName = Nothing
, _acspCookieName = Nothing
}
-- | The mnemonic name for the policy being created. The name must be unique
-- within a set of policies for this load balancer.
acspPolicyName :: Lens' AppCookieStickinessPolicy (Maybe Text)
acspPolicyName = lens _acspPolicyName (\ s a -> s{_acspPolicyName = a});
-- | The name of the application cookie used for stickiness.
acspCookieName :: Lens' AppCookieStickinessPolicy (Maybe Text)
acspCookieName = lens _acspCookieName (\ s a -> s{_acspCookieName = a});
instance FromXML AppCookieStickinessPolicy where
parseXML x
= AppCookieStickinessPolicy' <$>
(x .@? "PolicyName") <*> (x .@? "CookieName")
-- | Information about the configuration of a back-end server.
--
-- /See:/ 'backendServerDescription' smart constructor.
data BackendServerDescription = BackendServerDescription'
{ _bsdPolicyNames :: !(Maybe [Text])
, _bsdInstancePort :: !(Maybe Nat)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'BackendServerDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bsdPolicyNames'
--
-- * 'bsdInstancePort'
backendServerDescription
:: BackendServerDescription
backendServerDescription =
BackendServerDescription'
{ _bsdPolicyNames = Nothing
, _bsdInstancePort = Nothing
}
-- | The names of the policies enabled for the back-end server.
bsdPolicyNames :: Lens' BackendServerDescription [Text]
bsdPolicyNames = lens _bsdPolicyNames (\ s a -> s{_bsdPolicyNames = a}) . _Default . _Coerce;
-- | The port on which the back-end server is listening.
bsdInstancePort :: Lens' BackendServerDescription (Maybe Natural)
bsdInstancePort = lens _bsdInstancePort (\ s a -> s{_bsdInstancePort = a}) . mapping _Nat;
instance FromXML BackendServerDescription where
parseXML x
= BackendServerDescription' <$>
(x .@? "PolicyNames" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "InstancePort")
-- | Information about the 'ConnectionDraining' attribute.
--
-- /See:/ 'connectionDraining' smart constructor.
data ConnectionDraining = ConnectionDraining'
{ _cdTimeout :: !(Maybe Int)
, _cdEnabled :: !Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ConnectionDraining' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdTimeout'
--
-- * 'cdEnabled'
connectionDraining
:: Bool -- ^ 'cdEnabled'
-> ConnectionDraining
connectionDraining pEnabled_ =
ConnectionDraining'
{ _cdTimeout = Nothing
, _cdEnabled = pEnabled_
}
-- | The maximum time, in seconds, to keep the existing connections open
-- before deregistering the instances.
cdTimeout :: Lens' ConnectionDraining (Maybe Int)
cdTimeout = lens _cdTimeout (\ s a -> s{_cdTimeout = a});
-- | Specifies whether connection draining is enabled for the load balancer.
cdEnabled :: Lens' ConnectionDraining Bool
cdEnabled = lens _cdEnabled (\ s a -> s{_cdEnabled = a});
instance FromXML ConnectionDraining where
parseXML x
= ConnectionDraining' <$>
(x .@? "Timeout") <*> (x .@ "Enabled")
instance ToQuery ConnectionDraining where
toQuery ConnectionDraining'{..}
= mconcat
["Timeout" =: _cdTimeout, "Enabled" =: _cdEnabled]
-- | Information about the 'ConnectionSettings' attribute.
--
-- /See:/ 'connectionSettings' smart constructor.
newtype ConnectionSettings = ConnectionSettings'
{ _csIdleTimeout :: Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ConnectionSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csIdleTimeout'
connectionSettings
:: Natural -- ^ 'csIdleTimeout'
-> ConnectionSettings
connectionSettings pIdleTimeout_ =
ConnectionSettings'
{ _csIdleTimeout = _Nat # pIdleTimeout_
}
-- | The time, in seconds, that the connection is allowed to be idle (no data
-- has been sent over the connection) before it is closed by the load
-- balancer.
csIdleTimeout :: Lens' ConnectionSettings Natural
csIdleTimeout = lens _csIdleTimeout (\ s a -> s{_csIdleTimeout = a}) . _Nat;
instance FromXML ConnectionSettings where
parseXML x
= ConnectionSettings' <$> (x .@ "IdleTimeout")
instance ToQuery ConnectionSettings where
toQuery ConnectionSettings'{..}
= mconcat ["IdleTimeout" =: _csIdleTimeout]
-- | Information about the 'CrossZoneLoadBalancing' attribute.
--
-- /See:/ 'crossZoneLoadBalancing' smart constructor.
newtype CrossZoneLoadBalancing = CrossZoneLoadBalancing'
{ _czlbEnabled :: Bool
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CrossZoneLoadBalancing' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'czlbEnabled'
crossZoneLoadBalancing
:: Bool -- ^ 'czlbEnabled'
-> CrossZoneLoadBalancing
crossZoneLoadBalancing pEnabled_ =
CrossZoneLoadBalancing'
{ _czlbEnabled = pEnabled_
}
-- | Specifies whether cross-zone load balancing is enabled for the load
-- balancer.
czlbEnabled :: Lens' CrossZoneLoadBalancing Bool
czlbEnabled = lens _czlbEnabled (\ s a -> s{_czlbEnabled = a});
instance FromXML CrossZoneLoadBalancing where
parseXML x
= CrossZoneLoadBalancing' <$> (x .@ "Enabled")
instance ToQuery CrossZoneLoadBalancing where
toQuery CrossZoneLoadBalancing'{..}
= mconcat ["Enabled" =: _czlbEnabled]
-- | Information about a health check.
--
-- /See:/ 'healthCheck' smart constructor.
data HealthCheck = HealthCheck'
{ _hcTarget :: !Text
, _hcInterval :: !Nat
, _hcTimeout :: !Nat
, _hcUnhealthyThreshold :: !Nat
, _hcHealthyThreshold :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'HealthCheck' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hcTarget'
--
-- * 'hcInterval'
--
-- * 'hcTimeout'
--
-- * 'hcUnhealthyThreshold'
--
-- * 'hcHealthyThreshold'
healthCheck
:: Text -- ^ 'hcTarget'
-> Natural -- ^ 'hcInterval'
-> Natural -- ^ 'hcTimeout'
-> Natural -- ^ 'hcUnhealthyThreshold'
-> Natural -- ^ 'hcHealthyThreshold'
-> HealthCheck
healthCheck pTarget_ pInterval_ pTimeout_ pUnhealthyThreshold_ pHealthyThreshold_ =
HealthCheck'
{ _hcTarget = pTarget_
, _hcInterval = _Nat # pInterval_
, _hcTimeout = _Nat # pTimeout_
, _hcUnhealthyThreshold = _Nat # pUnhealthyThreshold_
, _hcHealthyThreshold = _Nat # pHealthyThreshold_
}
-- | The instance being checked. The protocol is either TCP, HTTP, HTTPS, or
-- SSL. The range of valid ports is one (1) through 65535.
--
-- TCP is the default, specified as a TCP: port pair, for example
-- \"TCP:5000\". In this case, a health check simply attempts to open a TCP
-- connection to the instance on the specified port. Failure to connect
-- within the configured timeout is considered unhealthy.
--
-- SSL is also specified as SSL: port pair, for example, SSL:5000.
--
-- For HTTP\/HTTPS, you must include a ping path in the string. HTTP is
-- specified as a HTTP:port;\/;PathToPing; grouping, for example
-- \"HTTP:80\/weather\/us\/wa\/seattle\". In this case, a HTTP GET request
-- is issued to the instance on the given port and path. Any answer other
-- than \"200 OK\" within the timeout period is considered unhealthy.
--
-- The total length of the HTTP ping target must be 1024 16-bit Unicode
-- characters or less.
hcTarget :: Lens' HealthCheck Text
hcTarget = lens _hcTarget (\ s a -> s{_hcTarget = a});
-- | The approximate interval, in seconds, between health checks of an
-- individual instance.
hcInterval :: Lens' HealthCheck Natural
hcInterval = lens _hcInterval (\ s a -> s{_hcInterval = a}) . _Nat;
-- | The amount of time, in seconds, during which no response means a failed
-- health check.
--
-- This value must be less than the 'Interval' value.
hcTimeout :: Lens' HealthCheck Natural
hcTimeout = lens _hcTimeout (\ s a -> s{_hcTimeout = a}) . _Nat;
-- | The number of consecutive health check failures required before moving
-- the instance to the 'Unhealthy' state.
hcUnhealthyThreshold :: Lens' HealthCheck Natural
hcUnhealthyThreshold = lens _hcUnhealthyThreshold (\ s a -> s{_hcUnhealthyThreshold = a}) . _Nat;
-- | The number of consecutive health checks successes required before moving
-- the instance to the 'Healthy' state.
hcHealthyThreshold :: Lens' HealthCheck Natural
hcHealthyThreshold = lens _hcHealthyThreshold (\ s a -> s{_hcHealthyThreshold = a}) . _Nat;
instance FromXML HealthCheck where
parseXML x
= HealthCheck' <$>
(x .@ "Target") <*> (x .@ "Interval") <*>
(x .@ "Timeout")
<*> (x .@ "UnhealthyThreshold")
<*> (x .@ "HealthyThreshold")
instance ToQuery HealthCheck where
toQuery HealthCheck'{..}
= mconcat
["Target" =: _hcTarget, "Interval" =: _hcInterval,
"Timeout" =: _hcTimeout,
"UnhealthyThreshold" =: _hcUnhealthyThreshold,
"HealthyThreshold" =: _hcHealthyThreshold]
-- | The ID of a back-end instance.
--
-- /See:/ 'instance'' smart constructor.
newtype Instance = Instance'
{ _iInstanceId :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Instance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iInstanceId'
instance'
:: Instance
instance' =
Instance'
{ _iInstanceId = Nothing
}
-- | The ID of the instance.
iInstanceId :: Lens' Instance (Maybe Text)
iInstanceId = lens _iInstanceId (\ s a -> s{_iInstanceId = a});
instance FromXML Instance where
parseXML x = Instance' <$> (x .@? "InstanceId")
instance ToQuery Instance where
toQuery Instance'{..}
= mconcat ["InstanceId" =: _iInstanceId]
-- | Information about the state of a back-end instance.
--
-- /See:/ 'instanceState' smart constructor.
data InstanceState = InstanceState'
{ _isInstanceId :: !(Maybe Text)
, _isState :: !(Maybe Text)
, _isReasonCode :: !(Maybe Text)
, _isDescription :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'InstanceState' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'isInstanceId'
--
-- * 'isState'
--
-- * 'isReasonCode'
--
-- * 'isDescription'
instanceState
:: InstanceState
instanceState =
InstanceState'
{ _isInstanceId = Nothing
, _isState = Nothing
, _isReasonCode = Nothing
, _isDescription = Nothing
}
-- | The ID of the instance.
isInstanceId :: Lens' InstanceState (Maybe Text)
isInstanceId = lens _isInstanceId (\ s a -> s{_isInstanceId = a});
-- | The current state of the instance.
--
-- Valid values: 'InService' | 'OutOfService' | 'Unknown'
isState :: Lens' InstanceState (Maybe Text)
isState = lens _isState (\ s a -> s{_isState = a});
-- | Information about the cause of 'OutOfService' instances. Specifically,
-- whether the cause is Elastic Load Balancing or the instance.
--
-- Valid values: 'ELB' | 'Instance' | 'N\/A'
isReasonCode :: Lens' InstanceState (Maybe Text)
isReasonCode = lens _isReasonCode (\ s a -> s{_isReasonCode = a});
-- | A description of the instance state. This string can contain one or more
-- of the following messages.
--
-- - 'N\/A'
--
-- - 'A transient error occurred. Please try again later.'
--
-- - 'Instance has failed at least the UnhealthyThreshold number of health checks consecutively.'
--
-- - 'Instance has not passed the configured HealthyThreshold number of health checks consecutively.'
--
-- - 'Instance registration is still in progress.'
--
-- - 'Instance is in the EC2 Availability Zone for which LoadBalancer is not configured to route traffic to.'
--
-- - 'Instance is not currently registered with the LoadBalancer.'
--
-- - 'Instance deregistration currently in progress.'
--
-- - 'Disable Availability Zone is currently in progress.'
--
-- - 'Instance is in pending state.'
--
-- - 'Instance is in stopped state.'
--
-- - 'Instance is in terminated state.'
--
isDescription :: Lens' InstanceState (Maybe Text)
isDescription = lens _isDescription (\ s a -> s{_isDescription = a});
instance FromXML InstanceState where
parseXML x
= InstanceState' <$>
(x .@? "InstanceId") <*> (x .@? "State") <*>
(x .@? "ReasonCode")
<*> (x .@? "Description")
-- | Information about a policy for duration-based session stickiness.
--
-- /See:/ 'lBCookieStickinessPolicy' smart constructor.
data LBCookieStickinessPolicy = LBCookieStickinessPolicy'
{ _lbcspPolicyName :: !(Maybe Text)
, _lbcspCookieExpirationPeriod :: !(Maybe Integer)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LBCookieStickinessPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbcspPolicyName'
--
-- * 'lbcspCookieExpirationPeriod'
lBCookieStickinessPolicy
:: LBCookieStickinessPolicy
lBCookieStickinessPolicy =
LBCookieStickinessPolicy'
{ _lbcspPolicyName = Nothing
, _lbcspCookieExpirationPeriod = Nothing
}
-- | The name for the policy being created. The name must be unique within
-- the set of policies for this load balancer.
lbcspPolicyName :: Lens' LBCookieStickinessPolicy (Maybe Text)
lbcspPolicyName = lens _lbcspPolicyName (\ s a -> s{_lbcspPolicyName = a});
-- | The time period, in seconds, after which the cookie should be considered
-- stale. If this parameter is not specified, the stickiness session lasts
-- for the duration of the browser session.
lbcspCookieExpirationPeriod :: Lens' LBCookieStickinessPolicy (Maybe Integer)
lbcspCookieExpirationPeriod = lens _lbcspCookieExpirationPeriod (\ s a -> s{_lbcspCookieExpirationPeriod = a});
instance FromXML LBCookieStickinessPolicy where
parseXML x
= LBCookieStickinessPolicy' <$>
(x .@? "PolicyName") <*>
(x .@? "CookieExpirationPeriod")
-- | Information about a listener.
--
-- For information about the protocols and the ports supported by Elastic
-- Load Balancing, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-listener-config.html Listener Configurations for Elastic Load Balancing>
-- in the /Elastic Load Balancing Developer Guide/.
--
-- /See:/ 'listener' smart constructor.
data Listener = Listener'
{ _lInstanceProtocol :: !(Maybe Text)
, _lSSLCertificateId :: !(Maybe Text)
, _lProtocol :: !Text
, _lLoadBalancerPort :: !Int
, _lInstancePort :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Listener' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lInstanceProtocol'
--
-- * 'lSSLCertificateId'
--
-- * 'lProtocol'
--
-- * 'lLoadBalancerPort'
--
-- * 'lInstancePort'
listener
:: Text -- ^ 'lProtocol'
-> Int -- ^ 'lLoadBalancerPort'
-> Natural -- ^ 'lInstancePort'
-> Listener
listener pProtocol_ pLoadBalancerPort_ pInstancePort_ =
Listener'
{ _lInstanceProtocol = Nothing
, _lSSLCertificateId = Nothing
, _lProtocol = pProtocol_
, _lLoadBalancerPort = pLoadBalancerPort_
, _lInstancePort = _Nat # pInstancePort_
}
-- | The protocol to use for routing traffic to back-end instances: HTTP,
-- HTTPS, TCP, or SSL.
--
-- If the front-end protocol is HTTP, HTTPS, TCP, or SSL,
-- 'InstanceProtocol' must be at the same protocol.
--
-- If there is another listener with the same 'InstancePort' whose
-- 'InstanceProtocol' is secure, (HTTPS or SSL), the listener\'s
-- 'InstanceProtocol' must also be secure.
--
-- If there is another listener with the same 'InstancePort' whose
-- 'InstanceProtocol' is HTTP or TCP, the listener\'s 'InstanceProtocol'
-- must be HTTP or TCP.
lInstanceProtocol :: Lens' Listener (Maybe Text)
lInstanceProtocol = lens _lInstanceProtocol (\ s a -> s{_lInstanceProtocol = a});
-- | The Amazon Resource Name (ARN) of the server certificate.
lSSLCertificateId :: Lens' Listener (Maybe Text)
lSSLCertificateId = lens _lSSLCertificateId (\ s a -> s{_lSSLCertificateId = a});
-- | The load balancer transport protocol to use for routing: HTTP, HTTPS,
-- TCP, or SSL.
lProtocol :: Lens' Listener Text
lProtocol = lens _lProtocol (\ s a -> s{_lProtocol = a});
-- | The port on which the load balancer is listening. The supported ports
-- are: 25, 80, 443, 465, 587, and 1024-65535.
lLoadBalancerPort :: Lens' Listener Int
lLoadBalancerPort = lens _lLoadBalancerPort (\ s a -> s{_lLoadBalancerPort = a});
-- | The port on which the instance is listening.
lInstancePort :: Lens' Listener Natural
lInstancePort = lens _lInstancePort (\ s a -> s{_lInstancePort = a}) . _Nat;
instance FromXML Listener where
parseXML x
= Listener' <$>
(x .@? "InstanceProtocol") <*>
(x .@? "SSLCertificateId")
<*> (x .@ "Protocol")
<*> (x .@ "LoadBalancerPort")
<*> (x .@ "InstancePort")
instance ToQuery Listener where
toQuery Listener'{..}
= mconcat
["InstanceProtocol" =: _lInstanceProtocol,
"SSLCertificateId" =: _lSSLCertificateId,
"Protocol" =: _lProtocol,
"LoadBalancerPort" =: _lLoadBalancerPort,
"InstancePort" =: _lInstancePort]
-- | The policies enabled for a listener.
--
-- /See:/ 'listenerDescription' smart constructor.
data ListenerDescription = ListenerDescription'
{ _ldPolicyNames :: !(Maybe [Text])
, _ldListener :: !(Maybe Listener)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListenerDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldPolicyNames'
--
-- * 'ldListener'
listenerDescription
:: ListenerDescription
listenerDescription =
ListenerDescription'
{ _ldPolicyNames = Nothing
, _ldListener = Nothing
}
-- | The policies. If there are no policies enabled, the list is empty.
ldPolicyNames :: Lens' ListenerDescription [Text]
ldPolicyNames = lens _ldPolicyNames (\ s a -> s{_ldPolicyNames = a}) . _Default . _Coerce;
-- | Undocumented member.
ldListener :: Lens' ListenerDescription (Maybe Listener)
ldListener = lens _ldListener (\ s a -> s{_ldListener = a});
instance FromXML ListenerDescription where
parseXML x
= ListenerDescription' <$>
(x .@? "PolicyNames" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "Listener")
-- | The attributes for a load balancer.
--
-- /See:/ 'loadBalancerAttributes' smart constructor.
data LoadBalancerAttributes = LoadBalancerAttributes'
{ _lbaCrossZoneLoadBalancing :: !(Maybe CrossZoneLoadBalancing)
, _lbaAccessLog :: !(Maybe AccessLog)
, _lbaAdditionalAttributes :: !(Maybe [AdditionalAttribute])
, _lbaConnectionSettings :: !(Maybe ConnectionSettings)
, _lbaConnectionDraining :: !(Maybe ConnectionDraining)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LoadBalancerAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbaCrossZoneLoadBalancing'
--
-- * 'lbaAccessLog'
--
-- * 'lbaAdditionalAttributes'
--
-- * 'lbaConnectionSettings'
--
-- * 'lbaConnectionDraining'
loadBalancerAttributes
:: LoadBalancerAttributes
loadBalancerAttributes =
LoadBalancerAttributes'
{ _lbaCrossZoneLoadBalancing = Nothing
, _lbaAccessLog = Nothing
, _lbaAdditionalAttributes = Nothing
, _lbaConnectionSettings = Nothing
, _lbaConnectionDraining = Nothing
}
-- | If enabled, the load balancer routes the request traffic evenly across
-- all back-end instances regardless of the Availability Zones.
--
-- For more information, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-disable-crosszone-lb.html Enable Cross-Zone Load Balancing>
-- in the /Elastic Load Balancing Developer Guide/.
lbaCrossZoneLoadBalancing :: Lens' LoadBalancerAttributes (Maybe CrossZoneLoadBalancing)
lbaCrossZoneLoadBalancing = lens _lbaCrossZoneLoadBalancing (\ s a -> s{_lbaCrossZoneLoadBalancing = a});
-- | If enabled, the load balancer captures detailed information of all
-- requests and delivers the information to the Amazon S3 bucket that you
-- specify.
--
-- For more information, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-access-logs.html Enable Access Logs>
-- in the /Elastic Load Balancing Developer Guide/.
lbaAccessLog :: Lens' LoadBalancerAttributes (Maybe AccessLog)
lbaAccessLog = lens _lbaAccessLog (\ s a -> s{_lbaAccessLog = a});
-- | This parameter is reserved.
lbaAdditionalAttributes :: Lens' LoadBalancerAttributes [AdditionalAttribute]
lbaAdditionalAttributes = lens _lbaAdditionalAttributes (\ s a -> s{_lbaAdditionalAttributes = a}) . _Default . _Coerce;
-- | If enabled, the load balancer allows the connections to remain idle (no
-- data is sent over the connection) for the specified duration.
--
-- By default, Elastic Load Balancing maintains a 60-second idle connection
-- timeout for both front-end and back-end connections of your load
-- balancer. For more information, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/config-idle-timeout.html Configure Idle Connection Timeout>
-- in the /Elastic Load Balancing Developer Guide/.
lbaConnectionSettings :: Lens' LoadBalancerAttributes (Maybe ConnectionSettings)
lbaConnectionSettings = lens _lbaConnectionSettings (\ s a -> s{_lbaConnectionSettings = a});
-- | If enabled, the load balancer allows existing requests to complete
-- before the load balancer shifts traffic away from a deregistered or
-- unhealthy back-end instance.
--
-- For more information, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/config-conn-drain.html Enable Connection Draining>
-- in the /Elastic Load Balancing Developer Guide/.
lbaConnectionDraining :: Lens' LoadBalancerAttributes (Maybe ConnectionDraining)
lbaConnectionDraining = lens _lbaConnectionDraining (\ s a -> s{_lbaConnectionDraining = a});
instance FromXML LoadBalancerAttributes where
parseXML x
= LoadBalancerAttributes' <$>
(x .@? "CrossZoneLoadBalancing") <*>
(x .@? "AccessLog")
<*>
(x .@? "AdditionalAttributes" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "ConnectionSettings")
<*> (x .@? "ConnectionDraining")
instance ToQuery LoadBalancerAttributes where
toQuery LoadBalancerAttributes'{..}
= mconcat
["CrossZoneLoadBalancing" =:
_lbaCrossZoneLoadBalancing,
"AccessLog" =: _lbaAccessLog,
"AdditionalAttributes" =:
toQuery
(toQueryList "member" <$> _lbaAdditionalAttributes),
"ConnectionSettings" =: _lbaConnectionSettings,
"ConnectionDraining" =: _lbaConnectionDraining]
-- | Information about a load balancer.
--
-- /See:/ 'loadBalancerDescription' smart constructor.
data LoadBalancerDescription = LoadBalancerDescription'
{ _lbdSourceSecurityGroup :: !(Maybe SourceSecurityGroup)
, _lbdCanonicalHostedZoneName :: !(Maybe Text)
, _lbdSecurityGroups :: !(Maybe [Text])
, _lbdHealthCheck :: !(Maybe HealthCheck)
, _lbdLoadBalancerName :: !(Maybe Text)
, _lbdCreatedTime :: !(Maybe ISO8601)
, _lbdVPCId :: !(Maybe Text)
, _lbdSubnets :: !(Maybe [Text])
, _lbdAvailabilityZones :: !(Maybe [Text])
, _lbdBackendServerDescriptions :: !(Maybe [BackendServerDescription])
, _lbdCanonicalHostedZoneNameId :: !(Maybe Text)
, _lbdInstances :: !(Maybe [Instance])
, _lbdScheme :: !(Maybe Text)
, _lbdListenerDescriptions :: !(Maybe [ListenerDescription])
, _lbdDNSName :: !(Maybe Text)
, _lbdPolicies :: !(Maybe Policies)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'LoadBalancerDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbdSourceSecurityGroup'
--
-- * 'lbdCanonicalHostedZoneName'
--
-- * 'lbdSecurityGroups'
--
-- * 'lbdHealthCheck'
--
-- * 'lbdLoadBalancerName'
--
-- * 'lbdCreatedTime'
--
-- * 'lbdVPCId'
--
-- * 'lbdSubnets'
--
-- * 'lbdAvailabilityZones'
--
-- * 'lbdBackendServerDescriptions'
--
-- * 'lbdCanonicalHostedZoneNameId'
--
-- * 'lbdInstances'
--
-- * 'lbdScheme'
--
-- * 'lbdListenerDescriptions'
--
-- * 'lbdDNSName'
--
-- * 'lbdPolicies'
loadBalancerDescription
:: LoadBalancerDescription
loadBalancerDescription =
LoadBalancerDescription'
{ _lbdSourceSecurityGroup = Nothing
, _lbdCanonicalHostedZoneName = Nothing
, _lbdSecurityGroups = Nothing
, _lbdHealthCheck = Nothing
, _lbdLoadBalancerName = Nothing
, _lbdCreatedTime = Nothing
, _lbdVPCId = Nothing
, _lbdSubnets = Nothing
, _lbdAvailabilityZones = Nothing
, _lbdBackendServerDescriptions = Nothing
, _lbdCanonicalHostedZoneNameId = Nothing
, _lbdInstances = Nothing
, _lbdScheme = Nothing
, _lbdListenerDescriptions = Nothing
, _lbdDNSName = Nothing
, _lbdPolicies = Nothing
}
-- | The security group that you can use as part of your inbound rules for
-- your load balancer\'s back-end application instances. To only allow
-- traffic from load balancers, add a security group rule to your back end
-- instance that specifies this source security group as the inbound
-- source.
lbdSourceSecurityGroup :: Lens' LoadBalancerDescription (Maybe SourceSecurityGroup)
lbdSourceSecurityGroup = lens _lbdSourceSecurityGroup (\ s a -> s{_lbdSourceSecurityGroup = a});
-- | The Amazon Route 53 hosted zone associated with the load balancer.
--
-- For more information, see
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-domain-names-with-elb.html Using Domain Names With Elastic Load Balancing>
-- in the /Elastic Load Balancing Developer Guide/.
lbdCanonicalHostedZoneName :: Lens' LoadBalancerDescription (Maybe Text)
lbdCanonicalHostedZoneName = lens _lbdCanonicalHostedZoneName (\ s a -> s{_lbdCanonicalHostedZoneName = a});
-- | The security groups for the load balancer. Valid only for load balancers
-- in a VPC.
lbdSecurityGroups :: Lens' LoadBalancerDescription [Text]
lbdSecurityGroups = lens _lbdSecurityGroups (\ s a -> s{_lbdSecurityGroups = a}) . _Default . _Coerce;
-- | Information about the health checks conducted on the load balancer.
lbdHealthCheck :: Lens' LoadBalancerDescription (Maybe HealthCheck)
lbdHealthCheck = lens _lbdHealthCheck (\ s a -> s{_lbdHealthCheck = a});
-- | The name of the load balancer.
lbdLoadBalancerName :: Lens' LoadBalancerDescription (Maybe Text)
lbdLoadBalancerName = lens _lbdLoadBalancerName (\ s a -> s{_lbdLoadBalancerName = a});
-- | The date and time the load balancer was created.
lbdCreatedTime :: Lens' LoadBalancerDescription (Maybe UTCTime)
lbdCreatedTime = lens _lbdCreatedTime (\ s a -> s{_lbdCreatedTime = a}) . mapping _Time;
-- | The ID of the VPC for the load balancer.
lbdVPCId :: Lens' LoadBalancerDescription (Maybe Text)
lbdVPCId = lens _lbdVPCId (\ s a -> s{_lbdVPCId = a});
-- | The IDs of the subnets for the load balancer.
lbdSubnets :: Lens' LoadBalancerDescription [Text]
lbdSubnets = lens _lbdSubnets (\ s a -> s{_lbdSubnets = a}) . _Default . _Coerce;
-- | The Availability Zones for the load balancer.
lbdAvailabilityZones :: Lens' LoadBalancerDescription [Text]
lbdAvailabilityZones = lens _lbdAvailabilityZones (\ s a -> s{_lbdAvailabilityZones = a}) . _Default . _Coerce;
-- | Information about the back-end servers.
lbdBackendServerDescriptions :: Lens' LoadBalancerDescription [BackendServerDescription]
lbdBackendServerDescriptions = lens _lbdBackendServerDescriptions (\ s a -> s{_lbdBackendServerDescriptions = a}) . _Default . _Coerce;
-- | The ID of the Amazon Route 53 hosted zone name associated with the load
-- balancer.
lbdCanonicalHostedZoneNameId :: Lens' LoadBalancerDescription (Maybe Text)
lbdCanonicalHostedZoneNameId = lens _lbdCanonicalHostedZoneNameId (\ s a -> s{_lbdCanonicalHostedZoneNameId = a});
-- | The IDs of the instances for the load balancer.
lbdInstances :: Lens' LoadBalancerDescription [Instance]
lbdInstances = lens _lbdInstances (\ s a -> s{_lbdInstances = a}) . _Default . _Coerce;
-- | The type of load balancer. Valid only for load balancers in a VPC.
--
-- If 'Scheme' is 'internet-facing', the load balancer has a public DNS
-- name that resolves to a public IP address.
--
-- If 'Scheme' is 'internal', the load balancer has a public DNS name that
-- resolves to a private IP address.
lbdScheme :: Lens' LoadBalancerDescription (Maybe Text)
lbdScheme = lens _lbdScheme (\ s a -> s{_lbdScheme = a});
-- | The listeners for the load balancer.
lbdListenerDescriptions :: Lens' LoadBalancerDescription [ListenerDescription]
lbdListenerDescriptions = lens _lbdListenerDescriptions (\ s a -> s{_lbdListenerDescriptions = a}) . _Default . _Coerce;
-- | The external DNS name of the load balancer.
lbdDNSName :: Lens' LoadBalancerDescription (Maybe Text)
lbdDNSName = lens _lbdDNSName (\ s a -> s{_lbdDNSName = a});
-- | The policies defined for the load balancer.
lbdPolicies :: Lens' LoadBalancerDescription (Maybe Policies)
lbdPolicies = lens _lbdPolicies (\ s a -> s{_lbdPolicies = a});
instance FromXML LoadBalancerDescription where
parseXML x
= LoadBalancerDescription' <$>
(x .@? "SourceSecurityGroup") <*>
(x .@? "CanonicalHostedZoneName")
<*>
(x .@? "SecurityGroups" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "HealthCheck")
<*> (x .@? "LoadBalancerName")
<*> (x .@? "CreatedTime")
<*> (x .@? "VPCId")
<*>
(x .@? "Subnets" .!@ mempty >>=
may (parseXMLList "member"))
<*>
(x .@? "AvailabilityZones" .!@ mempty >>=
may (parseXMLList "member"))
<*>
(x .@? "BackendServerDescriptions" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "CanonicalHostedZoneNameID")
<*>
(x .@? "Instances" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "Scheme")
<*>
(x .@? "ListenerDescriptions" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "DNSName")
<*> (x .@? "Policies")
-- | The policies for a load balancer.
--
-- /See:/ 'policies' smart constructor.
data Policies = Policies'
{ _pOtherPolicies :: !(Maybe [Text])
, _pLBCookieStickinessPolicies :: !(Maybe [LBCookieStickinessPolicy])
, _pAppCookieStickinessPolicies :: !(Maybe [AppCookieStickinessPolicy])
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Policies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pOtherPolicies'
--
-- * 'pLBCookieStickinessPolicies'
--
-- * 'pAppCookieStickinessPolicies'
policies
:: Policies
policies =
Policies'
{ _pOtherPolicies = Nothing
, _pLBCookieStickinessPolicies = Nothing
, _pAppCookieStickinessPolicies = Nothing
}
-- | The policies other than the stickiness policies.
pOtherPolicies :: Lens' Policies [Text]
pOtherPolicies = lens _pOtherPolicies (\ s a -> s{_pOtherPolicies = a}) . _Default . _Coerce;
-- | The stickiness policies created using CreateLBCookieStickinessPolicy.
pLBCookieStickinessPolicies :: Lens' Policies [LBCookieStickinessPolicy]
pLBCookieStickinessPolicies = lens _pLBCookieStickinessPolicies (\ s a -> s{_pLBCookieStickinessPolicies = a}) . _Default . _Coerce;
-- | The stickiness policies created using CreateAppCookieStickinessPolicy.
pAppCookieStickinessPolicies :: Lens' Policies [AppCookieStickinessPolicy]
pAppCookieStickinessPolicies = lens _pAppCookieStickinessPolicies (\ s a -> s{_pAppCookieStickinessPolicies = a}) . _Default . _Coerce;
instance FromXML Policies where
parseXML x
= Policies' <$>
(x .@? "OtherPolicies" .!@ mempty >>=
may (parseXMLList "member"))
<*>
(x .@? "LBCookieStickinessPolicies" .!@ mempty >>=
may (parseXMLList "member"))
<*>
(x .@? "AppCookieStickinessPolicies" .!@ mempty >>=
may (parseXMLList "member"))
-- | Information about a policy attribute.
--
-- /See:/ 'policyAttribute' smart constructor.
data PolicyAttribute = PolicyAttribute'
{ _paAttributeValue :: !(Maybe Text)
, _paAttributeName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PolicyAttribute' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'paAttributeValue'
--
-- * 'paAttributeName'
policyAttribute
:: PolicyAttribute
policyAttribute =
PolicyAttribute'
{ _paAttributeValue = Nothing
, _paAttributeName = Nothing
}
-- | The value of the attribute.
paAttributeValue :: Lens' PolicyAttribute (Maybe Text)
paAttributeValue = lens _paAttributeValue (\ s a -> s{_paAttributeValue = a});
-- | The name of the attribute.
paAttributeName :: Lens' PolicyAttribute (Maybe Text)
paAttributeName = lens _paAttributeName (\ s a -> s{_paAttributeName = a});
instance ToQuery PolicyAttribute where
toQuery PolicyAttribute'{..}
= mconcat
["AttributeValue" =: _paAttributeValue,
"AttributeName" =: _paAttributeName]
-- | Information about a policy attribute.
--
-- /See:/ 'policyAttributeDescription' smart constructor.
data PolicyAttributeDescription = PolicyAttributeDescription'
{ _padAttributeValue :: !(Maybe Text)
, _padAttributeName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PolicyAttributeDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'padAttributeValue'
--
-- * 'padAttributeName'
policyAttributeDescription
:: PolicyAttributeDescription
policyAttributeDescription =
PolicyAttributeDescription'
{ _padAttributeValue = Nothing
, _padAttributeName = Nothing
}
-- | The value of the attribute.
padAttributeValue :: Lens' PolicyAttributeDescription (Maybe Text)
padAttributeValue = lens _padAttributeValue (\ s a -> s{_padAttributeValue = a});
-- | The name of the attribute.
padAttributeName :: Lens' PolicyAttributeDescription (Maybe Text)
padAttributeName = lens _padAttributeName (\ s a -> s{_padAttributeName = a});
instance FromXML PolicyAttributeDescription where
parseXML x
= PolicyAttributeDescription' <$>
(x .@? "AttributeValue") <*> (x .@? "AttributeName")
-- | Information about a policy attribute type.
--
-- /See:/ 'policyAttributeTypeDescription' smart constructor.
data PolicyAttributeTypeDescription = PolicyAttributeTypeDescription'
{ _patdAttributeType :: !(Maybe Text)
, _patdCardinality :: !(Maybe Text)
, _patdDefaultValue :: !(Maybe Text)
, _patdAttributeName :: !(Maybe Text)
, _patdDescription :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PolicyAttributeTypeDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'patdAttributeType'
--
-- * 'patdCardinality'
--
-- * 'patdDefaultValue'
--
-- * 'patdAttributeName'
--
-- * 'patdDescription'
policyAttributeTypeDescription
:: PolicyAttributeTypeDescription
policyAttributeTypeDescription =
PolicyAttributeTypeDescription'
{ _patdAttributeType = Nothing
, _patdCardinality = Nothing
, _patdDefaultValue = Nothing
, _patdAttributeName = Nothing
, _patdDescription = Nothing
}
-- | The type of the attribute. For example, 'Boolean' or 'Integer'.
patdAttributeType :: Lens' PolicyAttributeTypeDescription (Maybe Text)
patdAttributeType = lens _patdAttributeType (\ s a -> s{_patdAttributeType = a});
-- | The cardinality of the attribute.
--
-- Valid values:
--
-- - ONE(1) : Single value required
-- - ZERO_OR_ONE(0..1) : Up to one value can be supplied
-- - ZERO_OR_MORE(0..*) : Optional. Multiple values are allowed
-- - ONE_OR_MORE(1..*0) : Required. Multiple values are allowed
patdCardinality :: Lens' PolicyAttributeTypeDescription (Maybe Text)
patdCardinality = lens _patdCardinality (\ s a -> s{_patdCardinality = a});
-- | The default value of the attribute, if applicable.
patdDefaultValue :: Lens' PolicyAttributeTypeDescription (Maybe Text)
patdDefaultValue = lens _patdDefaultValue (\ s a -> s{_patdDefaultValue = a});
-- | The name of the attribute.
patdAttributeName :: Lens' PolicyAttributeTypeDescription (Maybe Text)
patdAttributeName = lens _patdAttributeName (\ s a -> s{_patdAttributeName = a});
-- | A description of the attribute.
patdDescription :: Lens' PolicyAttributeTypeDescription (Maybe Text)
patdDescription = lens _patdDescription (\ s a -> s{_patdDescription = a});
instance FromXML PolicyAttributeTypeDescription where
parseXML x
= PolicyAttributeTypeDescription' <$>
(x .@? "AttributeType") <*> (x .@? "Cardinality") <*>
(x .@? "DefaultValue")
<*> (x .@? "AttributeName")
<*> (x .@? "Description")
-- | Information about a policy.
--
-- /See:/ 'policyDescription' smart constructor.
data PolicyDescription = PolicyDescription'
{ _pdPolicyName :: !(Maybe Text)
, _pdPolicyAttributeDescriptions :: !(Maybe [PolicyAttributeDescription])
, _pdPolicyTypeName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PolicyDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pdPolicyName'
--
-- * 'pdPolicyAttributeDescriptions'
--
-- * 'pdPolicyTypeName'
policyDescription
:: PolicyDescription
policyDescription =
PolicyDescription'
{ _pdPolicyName = Nothing
, _pdPolicyAttributeDescriptions = Nothing
, _pdPolicyTypeName = Nothing
}
-- | The name of the policy.
pdPolicyName :: Lens' PolicyDescription (Maybe Text)
pdPolicyName = lens _pdPolicyName (\ s a -> s{_pdPolicyName = a});
-- | The policy attributes.
pdPolicyAttributeDescriptions :: Lens' PolicyDescription [PolicyAttributeDescription]
pdPolicyAttributeDescriptions = lens _pdPolicyAttributeDescriptions (\ s a -> s{_pdPolicyAttributeDescriptions = a}) . _Default . _Coerce;
-- | The name of the policy type.
pdPolicyTypeName :: Lens' PolicyDescription (Maybe Text)
pdPolicyTypeName = lens _pdPolicyTypeName (\ s a -> s{_pdPolicyTypeName = a});
instance FromXML PolicyDescription where
parseXML x
= PolicyDescription' <$>
(x .@? "PolicyName") <*>
(x .@? "PolicyAttributeDescriptions" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "PolicyTypeName")
-- | Information about a policy type.
--
-- /See:/ 'policyTypeDescription' smart constructor.
data PolicyTypeDescription = PolicyTypeDescription'
{ _ptdPolicyTypeName :: !(Maybe Text)
, _ptdDescription :: !(Maybe Text)
, _ptdPolicyAttributeTypeDescriptions :: !(Maybe [PolicyAttributeTypeDescription])
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'PolicyTypeDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ptdPolicyTypeName'
--
-- * 'ptdDescription'
--
-- * 'ptdPolicyAttributeTypeDescriptions'
policyTypeDescription
:: PolicyTypeDescription
policyTypeDescription =
PolicyTypeDescription'
{ _ptdPolicyTypeName = Nothing
, _ptdDescription = Nothing
, _ptdPolicyAttributeTypeDescriptions = Nothing
}
-- | The name of the policy type.
ptdPolicyTypeName :: Lens' PolicyTypeDescription (Maybe Text)
ptdPolicyTypeName = lens _ptdPolicyTypeName (\ s a -> s{_ptdPolicyTypeName = a});
-- | A description of the policy type.
ptdDescription :: Lens' PolicyTypeDescription (Maybe Text)
ptdDescription = lens _ptdDescription (\ s a -> s{_ptdDescription = a});
-- | The description of the policy attributes associated with the policies
-- defined by Elastic Load Balancing.
ptdPolicyAttributeTypeDescriptions :: Lens' PolicyTypeDescription [PolicyAttributeTypeDescription]
ptdPolicyAttributeTypeDescriptions = lens _ptdPolicyAttributeTypeDescriptions (\ s a -> s{_ptdPolicyAttributeTypeDescriptions = a}) . _Default . _Coerce;
instance FromXML PolicyTypeDescription where
parseXML x
= PolicyTypeDescription' <$>
(x .@? "PolicyTypeName") <*> (x .@? "Description")
<*>
(x .@? "PolicyAttributeTypeDescriptions" .!@ mempty
>>= may (parseXMLList "member"))
-- | Information about a source security group.
--
-- /See:/ 'sourceSecurityGroup' smart constructor.
data SourceSecurityGroup = SourceSecurityGroup'
{ _ssgOwnerAlias :: !(Maybe Text)
, _ssgGroupName :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'SourceSecurityGroup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ssgOwnerAlias'
--
-- * 'ssgGroupName'
sourceSecurityGroup
:: SourceSecurityGroup
sourceSecurityGroup =
SourceSecurityGroup'
{ _ssgOwnerAlias = Nothing
, _ssgGroupName = Nothing
}
-- | The owner of the security group.
ssgOwnerAlias :: Lens' SourceSecurityGroup (Maybe Text)
ssgOwnerAlias = lens _ssgOwnerAlias (\ s a -> s{_ssgOwnerAlias = a});
-- | The name of the security group.
ssgGroupName :: Lens' SourceSecurityGroup (Maybe Text)
ssgGroupName = lens _ssgGroupName (\ s a -> s{_ssgGroupName = a});
instance FromXML SourceSecurityGroup where
parseXML x
= SourceSecurityGroup' <$>
(x .@? "OwnerAlias") <*> (x .@? "GroupName")
-- | Information about a tag.
--
-- /See:/ 'tag' smart constructor.
data Tag = Tag'
{ _tagValue :: !(Maybe Text)
, _tagKey :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'Tag' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tagValue'
--
-- * 'tagKey'
tag
:: Text -- ^ 'tagKey'
-> Tag
tag pKey_ =
Tag'
{ _tagValue = Nothing
, _tagKey = pKey_
}
-- | The value of the tag.
tagValue :: Lens' Tag (Maybe Text)
tagValue = lens _tagValue (\ s a -> s{_tagValue = a});
-- | The key of the tag.
tagKey :: Lens' Tag Text
tagKey = lens _tagKey (\ s a -> s{_tagKey = a});
instance FromXML Tag where
parseXML x
= Tag' <$> (x .@? "Value") <*> (x .@ "Key")
instance ToQuery Tag where
toQuery Tag'{..}
= mconcat ["Value" =: _tagValue, "Key" =: _tagKey]
-- | The tags associated with a load balancer.
--
-- /See:/ 'tagDescription' smart constructor.
data TagDescription = TagDescription'
{ _tdLoadBalancerName :: !(Maybe Text)
, _tdTags :: !(Maybe (List1 Tag))
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TagDescription' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tdLoadBalancerName'
--
-- * 'tdTags'
tagDescription
:: TagDescription
tagDescription =
TagDescription'
{ _tdLoadBalancerName = Nothing
, _tdTags = Nothing
}
-- | The name of the load balancer.
tdLoadBalancerName :: Lens' TagDescription (Maybe Text)
tdLoadBalancerName = lens _tdLoadBalancerName (\ s a -> s{_tdLoadBalancerName = a});
-- | The tags.
tdTags :: Lens' TagDescription (Maybe (NonEmpty Tag))
tdTags = lens _tdTags (\ s a -> s{_tdTags = a}) . mapping _List1;
instance FromXML TagDescription where
parseXML x
= TagDescription' <$>
(x .@? "LoadBalancerName") <*>
(x .@? "Tags" .!@ mempty >>=
may (parseXMLList1 "member"))
-- | The key of a tag.
--
-- /See:/ 'tagKeyOnly' smart constructor.
newtype TagKeyOnly = TagKeyOnly'
{ _tkoKey :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'TagKeyOnly' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tkoKey'
tagKeyOnly
:: TagKeyOnly
tagKeyOnly =
TagKeyOnly'
{ _tkoKey = Nothing
}
-- | The name of the key.
tkoKey :: Lens' TagKeyOnly (Maybe Text)
tkoKey = lens _tkoKey (\ s a -> s{_tkoKey = a});
instance ToQuery TagKeyOnly where
toQuery TagKeyOnly'{..} = mconcat ["Key" =: _tkoKey]
| olorin/amazonka | amazonka-elb/gen/Network/AWS/ELB/Types/Product.hs | mpl-2.0 | 51,270 | 0 | 24 | 10,544 | 8,921 | 5,160 | 3,761 | 850 | 1 |
module Darkdown
( module Darkdown.Parser
) where
import Darkdown.Parser
| davdar/maam | src/Darkdown.hs | bsd-3-clause | 77 | 0 | 5 | 14 | 17 | 11 | 6 | 3 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : System.Environment
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Miscellaneous information about the system environment.
--
-----------------------------------------------------------------------------
module System.Environment
(
getArgs, -- :: IO [String]
getProgName, -- :: IO String
getEnv, -- :: String -> IO String
#ifndef __NHC__
withArgs,
withProgName,
#endif
#ifdef __GLASGOW_HASKELL__
getEnvironment,
#endif
) where
import Prelude
#ifdef __GLASGOW_HASKELL__
import Foreign
import Foreign.C
import Control.Exception ( bracket )
import Control.Monad
import GHC.IOBase
#endif
#ifdef __HUGS__
import Hugs.System
#endif
#ifdef __NHC__
import System
( getArgs
, getProgName
, getEnv
)
#endif
-- ---------------------------------------------------------------------------
-- getArgs, getProgName, getEnv
-- | Computation 'getArgs' returns a list of the program's command
-- line arguments (not including the program name).
#ifdef __GLASGOW_HASKELL__
getArgs :: IO [String]
getArgs =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
getProgArgv p_argc p_argv
p <- fromIntegral `liftM` peek p_argc
argv <- peek p_argv
peekArray (p - 1) (advancePtr argv 1) >>= mapM peekCString
foreign import ccall unsafe "getProgArgv"
getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()
{-|
Computation 'getProgName' returns the name of the program as it was
invoked.
However, this is hard-to-impossible to implement on some non-Unix
OSes, so instead, for maximum portability, we just return the leafname
of the program as invoked. Even then there are some differences
between platforms: on Windows, for example, a program invoked as foo
is probably really @FOO.EXE@, and that is what 'getProgName' will return.
-}
getProgName :: IO String
getProgName =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
getProgArgv p_argc p_argv
argv <- peek p_argv
unpackProgName argv
unpackProgName :: Ptr (Ptr CChar) -> IO String -- argv[0]
unpackProgName argv = do
s <- peekElemOff argv 0 >>= peekCString
return (basename s)
where
basename :: String -> String
basename f = go f f
where
go acc [] = acc
go acc (x:xs)
| isPathSeparator x = go xs xs
| otherwise = go acc xs
isPathSeparator :: Char -> Bool
isPathSeparator '/' = True
#ifdef mingw32_HOST_OS
isPathSeparator '\\' = True
#endif
isPathSeparator _ = False
-- | Computation 'getEnv' @var@ returns the value
-- of the environment variable @var@.
--
-- This computation may fail with:
--
-- * 'System.IO.Error.isDoesNotExistError' if the environment variable
-- does not exist.
getEnv :: String -> IO String
getEnv name =
withCString name $ \s -> do
litstring <- c_getenv s
if litstring /= nullPtr
then peekCString litstring
else ioException (IOError Nothing NoSuchThing "getEnv"
"no environment variable" (Just name))
foreign import ccall unsafe "getenv"
c_getenv :: CString -> IO (Ptr CChar)
{-|
'withArgs' @args act@ - while executing action @act@, have 'getArgs'
return @args@.
-}
withArgs :: [String] -> IO a -> IO a
withArgs xs act = do
p <- System.Environment.getProgName
withArgv (p:xs) act
{-|
'withProgName' @name act@ - while executing action @act@,
have 'getProgName' return @name@.
-}
withProgName :: String -> IO a -> IO a
withProgName nm act = do
xs <- System.Environment.getArgs
withArgv (nm:xs) act
-- Worker routine which marshals and replaces an argv vector for
-- the duration of an action.
withArgv :: [String] -> IO a -> IO a
withArgv new_args act = do
pName <- System.Environment.getProgName
existing_args <- System.Environment.getArgs
bracket (setArgs new_args)
(\argv -> do setArgs (pName:existing_args); freeArgv argv)
(const act)
freeArgv :: Ptr CString -> IO ()
freeArgv argv = do
size <- lengthArray0 nullPtr argv
sequence_ [peek (argv `advancePtr` i) >>= free | i <- [size, size-1 .. 0]]
free argv
setArgs :: [String] -> IO (Ptr CString)
setArgs argv = do
vs <- mapM newCString argv >>= newArray0 nullPtr
setArgsPrim (length argv) vs
return vs
foreign import ccall unsafe "setProgArgv"
setArgsPrim :: Int -> Ptr CString -> IO ()
-- |'getEnvironment' retrieves the entire environment as a
-- list of @(key,value)@ pairs.
--
-- If an environment entry does not contain an @\'=\'@ character,
-- the @key@ is the whole entry and the @value@ is the empty string.
getEnvironment :: IO [(String, String)]
getEnvironment = do
pBlock <- getEnvBlock
if pBlock == nullPtr then return []
else do
stuff <- peekArray0 nullPtr pBlock >>= mapM peekCString
return (map divvy stuff)
where
divvy str =
case break (=='=') str of
(xs,[]) -> (xs,[]) -- don't barf (like Posix.getEnvironment)
(name,_:value) -> (name,value)
foreign import ccall unsafe "__hscore_environ"
getEnvBlock :: IO (Ptr CString)
#endif /* __GLASGOW_HASKELL__ */
| alekar/hugs | packages/base/System/Environment.hs | bsd-3-clause | 5,303 | 12 | 14 | 1,122 | 1,189 | 621 | 568 | 8 | 0 |
module Numeric.Band.Class
( Band
, pow1pBand
, powBand
) where
import Numeric.Algebra.Idempotent
| athanclark/algebra | src/Numeric/Band/Class.hs | bsd-3-clause | 106 | 0 | 4 | 21 | 24 | 16 | 8 | 5 | 0 |
module Database.Redis (
-- * How To Use This Module
-- |
-- Connect to a Redis server:
--
-- @
-- -- connects to localhost:6379
-- conn <- 'connect' 'defaultConnectInfo'
-- @
--
-- Send commands to the server:
--
-- @
-- {-\# LANGUAGE OverloadedStrings \#-}
-- ...
-- 'runRedis' conn $ do
-- 'set' \"hello\" \"hello\"
-- set \"world\" \"world\"
-- hello <- 'get' \"hello\"
-- world <- get \"world\"
-- liftIO $ print (hello,world)
-- @
-- ** Command Type Signatures
-- |Redis commands behave differently when issued in- or outside of a
-- transaction. To make them work in both contexts, most command functions
-- have a type signature similar to the following:
--
-- @
-- 'echo' :: ('RedisCtx' m f) => ByteString -> m (f ByteString)
-- @
--
-- Here is how to interpret this type signature:
--
-- * The argument types are independent of the execution context. 'echo'
-- always takes a 'ByteString' parameter, whether in- or outside of a
-- transaction. This is true for all command functions.
--
-- * All Redis commands return their result wrapped in some \"container\".
-- The type @f@ of this container depends on the commands execution
-- context @m@. The 'ByteString' return type in the example is specific
-- to the 'echo' command. For other commands, it will often be another
-- type.
--
-- * In the \"normal\" context 'Redis', outside of any transactions,
-- results are wrapped in an @'Either' 'Reply'@.
--
-- * Inside a transaction, in the 'RedisTx' context, results are wrapped in
-- a 'Queued'.
--
-- In short, you can view any command with a 'RedisCtx' constraint in the
-- type signature, to \"have two types\". For example 'echo' \"has both
-- types\":
--
-- @
-- echo :: ByteString -> Redis (Either Reply ByteString)
-- echo :: ByteString -> RedisTx (Queued ByteString)
-- @
--
-- [Exercise] What are the types of 'expire' inside a transaction and
-- 'lindex' outside of a transaction? The solutions are at the very
-- bottom of this page.
-- ** Lua Scripting
-- |Lua values returned from the 'eval' and 'evalsha' functions will be
-- converted to Haskell values by the 'decode' function from the
-- 'RedisResult' type class.
--
-- @
-- Lua Type | Haskell Type | Conversion Example
-- --------------|--------------------|-----------------------------
-- Number | Integer | 1.23 => 1
-- String | ByteString, Double | \"1.23\" => \"1.23\" or 1.23
-- Boolean | Bool | false => False
-- Table | List | {1,2} => [1,2]
-- @
--
-- Additionally, any of the Haskell types from the table above can be
-- wrapped in a 'Maybe':
--
-- @
-- 42 => Just 42 :: Maybe Integer
-- nil => Nothing :: Maybe Integer
-- @
--
-- Note that Redis imposes some limitations on the possible conversions:
--
-- * Lua numbers can only be converted to Integers. Only Lua strings can be
-- interpreted as Doubles.
--
-- * Associative Lua tables can not be converted at all. Returned tables
-- must be \"arrays\", i.e. indexed only by integers.
--
-- The Redis Scripting website (<http://redis.io/commands/eval>)
-- documents the exact semantics of the scripting commands and value
-- conversion.
-- ** Automatic Pipelining
-- |Commands are automatically pipelined as much as possible. For example,
-- in the above \"hello world\" example, all four commands are pipelined.
-- Automatic pipelining makes use of Haskell's laziness. As long as a
-- previous reply is not evaluated, subsequent commands can be pipelined.
--
-- Automatic pipelining also works across several calls to 'runRedis', as
-- long as replies are only evaluated /outside/ the 'runRedis' block.
--
-- To keep memory usage low, the number of requests \"in the pipeline\" is
-- limited (per connection) to 1000. After that number, the next command is
-- sent only when at least one reply has been received. That means, command
-- functions may block until there are less than 1000 outstanding replies.
--
-- ** Error Behavior
-- |
-- [Operations against keys holding the wrong kind of value:] Outside of a
-- transaction, if the Redis server returns an 'Error', command functions
-- will return 'Left' the 'Reply'. The library user can inspect the error
-- message to gain information on what kind of error occured.
--
-- [Connection to the server lost:] In case of a lost connection, command
-- functions throw a 'ConnectionLostException'. It can only be caught
-- outside of 'runRedis'.
--
-- [Exceptions:] Any exceptions can only be caught /outside/ of 'runRedis'.
-- This way the connection pool can properly close the connection, making
-- sure it is not left in an unusable state, e.g. closed or inside a
-- transaction.
--
-- * The Redis Monad
Redis(), runRedis,
RedisCtx(), MonadRedis(),
-- * Connection
Connection, connect,
ConnectInfo(..),defaultConnectInfo,
HostName,PortID(..),
-- * Commands
module Database.Redis.Commands,
-- * Transactions
module Database.Redis.Transactions,
-- * Pub\/Sub
module Database.Redis.PubSub,
-- * Low-Level Command API
sendRequest,
Reply(..),Status(..),RedisResult(..),ConnectionLostException(..),
-- |[Solution to Exercise]
--
-- Type of 'expire' inside a transaction:
--
-- > expire :: ByteString -> Integer -> RedisTx (Queued Bool)
--
-- Type of 'lindex' outside of a transaction:
--
-- > lindex :: ByteString -> Integer -> Redis (Either Reply ByteString)
--
) where
import Database.Redis.Core
import Database.Redis.PubSub
import Database.Redis.Protocol
import Database.Redis.ProtocolPipelining
(HostName, PortID(..), ConnectionLostException(..))
import Database.Redis.Transactions
import Database.Redis.Types
import Database.Redis.Commands
| gyfarkas/hedis | src/Database/Redis.hs | bsd-3-clause | 6,399 | 0 | 6 | 1,767 | 308 | 255 | 53 | 25 | 0 |
{-# LANGUAGE NoMonomorphismRestriction #-}
class Show a where
show :: a -> String
class Read a where
read :: String -> a
readShow x = read (show x)
showRead s = show (read s)
showReadMono s = let y = read s
in (y, show y)
-- read' s = let y = read s in y
| themattchan/tandoori | input/class-sink-simple.hs | bsd-3-clause | 283 | 0 | 9 | 85 | 104 | 51 | 53 | 9 | 1 |
-----------------------------------------------------------------------------------------
-- |
-- Module : FRP.Yampa.Diagnostics
-- Copyright : (c) Antony Courtney and Henrik Nilsson, Yale University, 2003
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : nilsson@cs.yale.edu
-- Stability : provisional
-- Portability : portable
--
-- Standardized error-reporting for Yampa
-----------------------------------------------------------------------------------------
module FRP.Yampa.Diagnostics where
usrErr :: String -> String -> String -> a
usrErr mn fn msg = error (mn ++ "." ++ fn ++ ": " ++ msg)
intErr :: String -> String -> String -> a
intErr mn fn msg = error ("[internal error] " ++ mn ++ "." ++ fn ++ ": "
++ msg)
| ony/Yampa-core | src/FRP/Yampa/Diagnostics.hs | bsd-3-clause | 806 | 0 | 11 | 156 | 125 | 71 | 54 | 6 | 1 |
{-# OPTIONS_GHC -cpp -fno-warn-unused-imports #-}
{-# LANGUAGE CPP #-}
#include "hs_src_config.h"
-- Useful instances that don't belong anywhere else.
module Util.Inst() where
import Control.Applicative
import Control.Monad.Identity(Identity(..))
import Data.Foldable(Foldable(..))
import Data.Monoid(Monoid(..))
import Data.Traversable(Traversable(..), foldMapDefault, fmapDefault)
import qualified Data.IntMap as IM
import qualified Data.Map as Map
#if !HAS_SHOW_IDENTITY
instance Show a => Show (Identity a) where
show x = show $ runIdentity x
#endif
#if !HAS_TRAVERSABLE_INTMAP
instance Traversable IM.IntMap where
traverse f mp = (IM.fromAscList . Map.toAscList) `fmap` (traverse f . Map.fromAscList . IM.toAscList $ mp)
#endif
#if !HAS_FOLDABLE_TUPLE
instance Foldable ((,) a) where
foldMap = foldMapDefault
instance Traversable ((,) a) where
traverse f (x,y) = (,) x <$> f y
#endif
#if !HAS_FUNCTOR_TUPLE3
instance Functor ((,,) a b) where
fmap = fmapDefault
#endif
#if !HAS_FOLDABLE_TUPLE3
instance Foldable ((,,) a b) where
foldMap = foldMapDefault
instance Traversable ((,,) a b) where
traverse f (x,y,z) = (,,) x y <$> f z
#endif
| hvr/jhc | src/Util/Inst.hs | mit | 1,181 | 5 | 11 | 190 | 388 | 218 | 170 | 24 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>Plug-n-Hack | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_ro_RO/helpset_ro_RO.hs | apache-2.0 | 972 | 78 | 68 | 158 | 419 | 212 | 207 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ja-JP">
<title>Sequence Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_ja_JP/helpset_ja_JP.hs | apache-2.0 | 977 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-# LANGUAGE PatternGuards, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances, ParallelListComp, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.AvoidFloats
-- Copyright : (c) 2014 Anders Engstrom <ankaan@gmail.com>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : (c) Anders Engstrom <ankaan@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
-- Find a maximum empty rectangle around floating windows and use that area
-- to display non-floating windows.
--
-----------------------------------------------------------------------------
module XMonad.Layout.AvoidFloats (
-- * Usage
-- $usage
avoidFloats,
avoidFloats',
AvoidFloatMsg(..),
AvoidFloatItemMsg(..),
) where
import XMonad
import XMonad.Layout.LayoutModifier
import qualified XMonad.StackSet as W
import Data.List
import Data.Ord
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S
-- $usage
-- You can use this module with the following in your ~\/.xmonad\/xmonad.hs file:
--
-- > import XMonad.Layout.AvoidFloats
--
-- and modify the layouts to call avoidFloats on the layouts where you want the
-- non-floating windows to not be behind floating windows.
--
-- > layoutHook = ... ||| avoidFloats Full ||| ...
--
-- For more detailed instructions on editing the layoutHook see:
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
--
-- Then add appropriate key bindings, for example:
--
-- > ,((modm .|. shiftMask, xK_b), sendMessage AvoidFloatToggle)
-- > ,((modm .|. controlMask, xK_b), withFocused $ sendMessage . AvoidFloatToggleItem)
-- > ,((modm .|. shiftMask .|. controlMask, xK_b), sendMessage (AvoidFloatSet False) >> sendMessage AvoidFloatClearItems)
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
--
-- Note that this module is incompatible with an old way of configuring
-- "XMonad.Actions.FloatSnap". If you are having problems, please update your
-- configuration.
-- | Avoid floating windows unless the resulting area for windows would be too small.
-- In that case, use the whole screen as if this layout modifier wasn't there.
-- No windows are avoided by default, they need to be added using signals.
avoidFloats
:: l a -- ^ Layout to modify.
-> ModifiedLayout AvoidFloats l a
avoidFloats = avoidFloats' 100 100 False
-- | Avoid floating windows unless the resulting area for windows would be too small.
-- In that case, use the whole screen as if this layout modifier wasn't there.
avoidFloats'
:: Int -- ^ Minimum width of the area used for non-floating windows.
-> Int -- ^ Minimum height of the area used for non-floating windows.
-> Bool -- ^ If floating windows should be avoided by default.
-> l a -- ^ Layout to modify.
-> ModifiedLayout AvoidFloats l a
avoidFloats' w h act = ModifiedLayout (AvoidFloats Nothing S.empty w h act)
data AvoidFloats a = AvoidFloats
{ cache :: Maybe ((M.Map a W.RationalRect, Rectangle), Rectangle)
, chosen :: S.Set a
, minw :: Int
, minh :: Int
, avoidAll :: Bool
} deriving (Read, Show)
-- | Change the state of the whole avoid float layout modifier.
data AvoidFloatMsg
= AvoidFloatToggle -- ^ Toggle between avoiding all or only selected.
| AvoidFloatSet Bool -- ^ Set if all all floating windows should be avoided.
| AvoidFloatClearItems -- ^ Clear the set of windows to specifically avoid.
deriving (Typeable)
-- | Change the state of the avoid float layout modifier conserning a specific window.
data AvoidFloatItemMsg a
= AvoidFloatAddItem a -- ^ Add a window to always avoid.
| AvoidFloatRemoveItem a -- ^ Stop always avoiding selected window.
| AvoidFloatToggleItem a -- ^ Toggle between always avoiding selected window.
deriving (Typeable)
instance Message AvoidFloatMsg
instance Typeable a => Message (AvoidFloatItemMsg a)
instance LayoutModifier AvoidFloats Window where
modifyLayoutWithUpdate lm w r = withDisplay $ \d -> do
floating <- gets $ W.floating . windowset
case cache lm of
Just (key, mer) | key == (floating,r) -> flip (,) Nothing `fmap` runLayout w mer
_ -> do rs <- io $ map toRect `fmap` mapM (getWindowAttributes d) (filter shouldAvoid $ M.keys floating)
let mer = maximumBy (comparing area) $ filter bigEnough $ maxEmptyRectangles r rs
flip (,) (Just $ pruneWindows $ lm { cache = Just ((floating,r),mer) }) `fmap` runLayout w mer
where
toRect :: WindowAttributes -> Rectangle
toRect wa = let b = fi $ wa_border_width wa
in Rectangle (fi $ wa_x wa) (fi $ wa_y wa) (fi $ wa_width wa + 2*b) (fi $ wa_height wa + 2*b)
bigEnough :: Rectangle -> Bool
bigEnough rect = rect_width rect >= fi (minw lm) && rect_height rect >= fi (minh lm)
shouldAvoid a = avoidAll lm || a `S.member` chosen lm
pureMess lm m
| Just (AvoidFloatToggle) <- fromMessage m = Just $ lm { avoidAll = not (avoidAll lm), cache = Nothing }
| Just (AvoidFloatSet s) <- fromMessage m, s /= avoidAll lm = Just $ lm { avoidAll = s, cache = Nothing }
| Just (AvoidFloatClearItems) <- fromMessage m = Just $ lm { chosen = S.empty, cache = Nothing }
| Just (AvoidFloatAddItem a) <- fromMessage m, a `S.notMember` chosen lm = Just $ lm { chosen = S.insert a (chosen lm), cache = Nothing }
| Just (AvoidFloatRemoveItem a) <- fromMessage m, a `S.member` chosen lm = Just $ lm { chosen = S.delete a (chosen lm), cache = Nothing }
| Just (AvoidFloatToggleItem a) <- fromMessage m = let op = if a `S.member` chosen lm then S.delete else S.insert
in Just $ lm { chosen = op a (chosen lm), cache = Nothing }
| otherwise = Nothing
pruneWindows :: AvoidFloats Window -> AvoidFloats Window
pruneWindows lm = case cache lm of
Nothing -> lm
Just ((floating,_),_) -> lm { chosen = S.filter (flip M.member floating) (chosen lm) }
-- | Find all maximum empty rectangles (MERs) that are axis aligned. This is
-- done in O(n^2) time using a modified version of the algoprithm MERAlg 1
-- described in \"On the maximum empty rectangle problem\" by A. Naamad, D.T.
-- Lee and W.-L HSU. Published in Discrete Applied Mathematics 8 (1984.)
maxEmptyRectangles :: Rectangle -> [Rectangle] -> [Rectangle]
maxEmptyRectangles br rectangles = filter (\a -> area a > 0) $ upAndDownEdge ++ noneOrUpEdge ++ downEdge
where
upAndDownEdge = findGaps br rectangles
noneOrUpEdge = concat $ map (everyLower br bottoms) bottoms
downEdge = concat $ map maybeToList $ map (bottomEdge br bottoms) bottoms
bottoms = sortBy (comparing bottom) $ splitContainers rectangles
everyLower :: Rectangle -> [Rectangle] -> Rectangle -> [Rectangle]
everyLower br bottoms r = let (rs, boundLeft, boundRight, boundRects) = foldr (everyUpper r) ([], left br, right br, reverse bottoms) bottoms
(boundLeft', boundRight', _) = shrinkBounds boundLeft boundRight boundRects r (top br)
in mkRect boundLeft' boundRight' (top br) (top r) ?: rs
everyUpper
:: Rectangle -- ^ The current rectangle where the top edge is used.
-> Rectangle -- ^ The current rectangle where the bottom edge is used.
-> ([Rectangle],Int,Int,[Rectangle]) -- ^ List of MERs found so far, left bound, right bound and list of rectangles used for bounds.
-> ([Rectangle],Int,Int,[Rectangle])
everyUpper lower upper (rs, boundLeft, boundRight, boundRects) = (r?:rs, boundLeft', boundRight', boundRects')
where
r = mkRect boundLeft' boundRight' (bottom upper) (top lower)
(boundLeft', boundRight', boundRects') = shrinkBounds boundLeft boundRight boundRects lower (bottom upper)
shrinkBounds :: Int -> Int -> [Rectangle] -> Rectangle -> Int -> (Int, Int, [Rectangle])
shrinkBounds boundLeft boundRight boundRects lower upperLimit = (boundLeft', boundRight', boundRects')
where
(shrinkers, boundRects') = span (\a -> bottom a > upperLimit) boundRects
(boundLeft', boundRight') = foldr (shrinkBounds' lower) (boundLeft, boundRight) $ filter (\a -> top a < top lower) shrinkers
shrinkBounds' :: Rectangle -> Rectangle -> (Int, Int) -> (Int, Int)
shrinkBounds' mr r (boundLeft, boundRight)
| right r < right mr = (max boundLeft $ right r, boundRight)
| left r > left mr = (boundLeft, min boundRight $ left r)
| otherwise = (right r, left r) -- r is horizontally covering all of mr; make sure the area of this rectangle will always be 0.
bottomEdge :: Rectangle -> [Rectangle] -> Rectangle -> Maybe Rectangle
bottomEdge br bottoms r = let rs = filter (\a -> bottom r < bottom a && top a < bottom br) bottoms
boundLeft = maximum $ left br : (filter (< right r) $ map right rs)
boundRight = minimum $ right br : (filter (> left r) $ map left rs)
in if any (\a -> left a <= left r && right r <= right a) rs
then Nothing
else mkRect boundLeft boundRight (bottom r) (bottom br)
-- | Split rectangles that horizontally fully contains another rectangle
-- without sharing either the left or right side.
splitContainers :: [Rectangle] -> [Rectangle]
splitContainers rects = splitContainers' [] $ sortBy (comparing rect_width) rects
where
splitContainers' :: [Rectangle] -> [Rectangle] -> [Rectangle]
splitContainers' res [] = res
splitContainers' res (r:rs) = splitContainers' (r:res) $ concat $ map (doSplit r) rs
doSplit :: Rectangle -> Rectangle -> [Rectangle]
doSplit guide r
| left guide <= left r || right r <= right guide = [r]
| otherwise = let w0 = fi (rect_x guide - rect_x r) + (rect_width guide `div` 2)
w1 = rect_width r - w0
in [ Rectangle (rect_x r) (rect_y r) w0 (rect_height r)
, Rectangle (rect_x r + fi w0) (rect_y r) w1 (rect_height r)
]
-- | Find all horizontal gaps that are left empty from top to bottom of screen.
findGaps
:: Rectangle -- ^ Bounding rectangle.
-> [Rectangle] -- ^ List of all rectangles that can cover areas in the bounding rectangle.
-> [Rectangle]
findGaps br rs = let (gaps,end) = foldr findGaps' ([], left br) $ sortBy (flip $ comparing left) $ filter inBounds rs
lastgap = mkRect end (right br) (top br) (bottom br)
in lastgap?:gaps
where
findGaps' :: Rectangle -> ([Rectangle], Int) -> ([Rectangle], Int)
findGaps' r (gaps, end) = let gap = mkRect end (left r) (top br) (bottom br)
in (gap?:gaps, max end (right r))
inBounds :: Rectangle -> Bool
inBounds r = left r < right br && left br < right r
fi :: (Integral a, Num b) => a -> b
fi x = fromIntegral x
(?:) :: Maybe a -> [a] -> [a]
Just x ?: xs = x:xs
_ ?: xs = xs
left, right, top, bottom, area :: Rectangle -> Int
left r = fi (rect_x r)
right r = fi (rect_x r) + fi (rect_width r)
top r = fi (rect_y r)
bottom r = fi (rect_y r) + fi (rect_height r)
area r = fi (rect_width r * rect_height r)
mkRect :: Int -> Int -> Int -> Int -> Maybe Rectangle
mkRect l r t b = let rect = Rectangle (fi l) (fi t) (fi $ max 0 $ r-l) (fi $ max 0 $ b-t)
in if area rect > 0
then Just rect
else Nothing
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Layout/AvoidFloats.hs | bsd-2-clause | 12,255 | 36 | 26 | 3,397 | 2,959 | 1,605 | 1,354 | 145 | 2 |
{-# LANGUAGE CPP, QuasiQuotes, TemplateHaskell, TypeFamilies, MultiParamTypeClasses, OverloadedStrings #-}
module YesodCoreTest.WaiSubsite (specs, Widget) where
import YesodCoreTest.YesodTest
import Yesod.Core
import qualified Network.HTTP.Types as H
myApp :: Application
myApp _ f = f $ responseLBS H.status200 [("Content-type", "text/plain")] "WAI"
getApp :: a -> WaiSubsite
getApp _ = WaiSubsite myApp
data Y = Y
mkYesod "Y" [parseRoutes|
/ RootR GET
/sub WaiSubsiteR WaiSubsite getApp
|]
instance Yesod Y
app :: Session () -> IO ()
app = yesod Y
getRootR :: Handler ()
getRootR = return ()
specs :: Spec
specs = describe "WaiSubsite" $ do
it "root" $ app $ do
res <- request defaultRequest { pathInfo = [] }
assertStatus 200 res
assertBodyContains "" res
it "subsite" $ app $ do
res <- request defaultRequest { pathInfo = ["sub", "foo"] }
assertStatus 200 res
assertBodyContains "WAI" res
| Daniel-Diaz/yesod | yesod-core/test/YesodCoreTest/WaiSubsite.hs | mit | 946 | 0 | 15 | 189 | 285 | 146 | 139 | 26 | 1 |
{-# LANGUAGE MagicHash, UnboxedTuples #-}
import GHC.Exts
import System.Environment
main = do
[n] <- fmap (fmap read) getArgs
case g n of
(# a, b, c, d, e, f, g, h, i #) -> print a
-- a deep stack in which each frame is an unboxed tuple-return, to exercise
-- the stack underflow machinery.
g :: Int -> (# Int,Float,Double,Int#,Float#,Double#,Int,Float,Double #)
g 0 = (# 1, 2.0, 3.0, 1#, 2.0#, 3.0##, 1, 2.0, 3.0 #)
g x = case g (x-1) of
(# a, b, c, d, e, f, g, h, i #) ->
(# a+1, b, c, d, e, f, g, h, i #)
| urbanslug/ghc | testsuite/tests/rts/stack003.hs | bsd-3-clause | 537 | 0 | 10 | 135 | 238 | 140 | 98 | 12 | 1 |
{-# LANGUAGE ScopedTypeVariables, ViewPatterns, BangPatterns #-}
{-|
Module : Labyrinth.Flood
Description : flood filling
Copyright : (c) deweyvm 2014
License : MIT
Maintainer : deweyvm
Stability : experimental
Portability : unknown
Implementation of flood fill for arbitrary graphs.
-}
module Labyrinth.Flood(
floodFill,
floodAll,
getNode,
computeBorder,
getDiameter
) where
import Control.Applicative
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import qualified Data.List as List
import qualified Labyrinth.Pathing.Dijkstra as D
import Labyrinth.Util
import Labyrinth.Graph
import Labyrinth.Maze
data Flood a b = Flood (Set.Set a) (Seq.Seq b)
mkFlood :: a -> b -> Flood a b
mkFlood x y = Flood (Set.singleton x) (Seq.singleton y)
floodMaze :: (Maze a b c, Ord b, Ord c)
=> a b
-> c
-> Set.Set (Node b c)
floodMaze g pt = floodMazeHelper g $ mkFlood (getNode g pt) pt
floodMazeHelper :: (Maze a b c, Ord b, Ord c)
=> a b
-> Flood (Node b c) c -- b == Bool, c == Point
-> Set.Set (Node b c)
floodMazeHelper _ (Flood pts (Seq.viewl -> Seq.EmptyL)) = pts
floodMazeHelper graph (Flood pts (Seq.viewl -> pt Seq.:< work)) =
floodMazeHelper graph (Flood full q)
where q = (Seq.fromList (getCoord <$> newWork)) Seq.>< work
full = Set.union pts (Set.fromList (fst <$> adj))
newWork = filter notMember $ fst <$> open
open= List.filter (isNode.fst) adj
adj = getAdjacent graph pt
notMember x = Set.notMember x pts
-- | Floods a graph starting from the given node.
floodFill :: (Graph a b c, Ord c)
=> a b -- ^ the graph to be flooded
-> c -- ^ the seed point
-> Set.Set c -- ^ the set of flooded nodes
floodFill graph pt = floodHelper graph $ mkFlood pt pt
floodHelper :: (Graph a b c, Ord c)
=> a b
-> Flood c c
-> Set.Set c
floodHelper _ (Flood pts (Seq.viewl -> Seq.EmptyL)) = pts
floodHelper graph (Flood pts (Seq.viewl -> pt Seq.:< work)) =
floodHelper graph (Flood full q)
where q = (Seq.fromList ns) Seq.>< work
full = Set.union pts (Set.fromList ns)
ns = filter notMember $ fst <$> getNeighbors graph pt
notMember x = Set.notMember x pts
-- | Floods all given passable regions on a given graph.
floodAll :: (Graph a b c, Ord c)
=> a b -- ^ the graph to be flooded
-> Set.Set c -- ^ the set of all open nodes
-> [Set.Set c] -- ^ the resulting flooded regions
floodAll graph open = floodAllHelper graph open []
floodAllHelper :: (Graph a b c, Ord c)
=> a b
-> Set.Set c
-> [Set.Set c]
-> [Set.Set c]
floodAllHelper graph open sofar =
case Set.minView open of
Just (x, _) -> let filled = floodFill graph x in
let newOpen = Set.difference open filled in
floodAllHelper graph newOpen (filled:sofar)
Nothing -> sofar
{- | Compute the border of a maze. The border is defined to be any open
space touching an impassable node, where that impassable node has a
chain of impassable nodes leading out of bounds. -}
computeBorder :: (Border a b c, Maze a b c, Invertible b, Ord b, Ord c)
=> a b
-> b
-> c
-> Set.Set c
computeBorder m blank seed =
let (c, revert) = addBorder m blank in
let nodes = floodMaze (invert <$> c) seed in
let mapped = catMaybes $ Set.foldr (\node acc -> f node : acc) [] nodes in
Set.fromList $ map revert mapped
where f (Node _ _) = Nothing
f (OutOfBounds p) = Just p
f (Solid p) = Just p
getDiameter :: (Invertible b, Ord b, Ord c, Border a b c, Maze a b c)
=> a b
-> b
-> c
-> (Int, c, c, [c])
getDiameter g blank pt =
let borders = Set.toList $ computeBorder g blank pt in
let pairs = [ (x, y) | x <- borders, y <- borders, x /= y] in
--let !_ = myTrace $ pairs in
--fixme, do not ignore failures as they should be impossible!
let e = catEithers $ (\(start, goal) -> D.pfind g start goal) <$> pairs in
let paths = snd e in
let lengths = (\(l, path) -> (l, head path, last path, path)) <$> zip (length <$> paths) paths in
List.maximumBy (\(l, _, _, _) (r, _, _, _) -> l `compare` r) lengths
| deweyvm/labyrinth | src/Labyrinth/Flood.hs | mit | 4,517 | 0 | 21 | 1,392 | 1,536 | 795 | 741 | 94 | 3 |
module Test where
import qualified Data.Set as Set
import qualified Data.Map as Map
infixr 5 :-:
data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord)
infixr 5 .++
(.++) :: List a -> List a -> List a
Empty .++ ys = ys
(x:-:xs) .++ ys = x :-: (xs .++ ys)
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
data NewTree a = NewEmptyTree | NewNode {dataPart :: a, leftSubTree :: NewTree a, rightSubTree :: NewTree a} deriving (Show, Read, Eq)
singletonTree :: a -> Tree a
singletonTree x = Node x EmptyTree EmptyTree
newSingletonTree :: a -> NewTree a
newSingletonTree x = NewNode x NewEmptyTree NewEmptyTree
getData :: NewTree a -> a
getData (NewNode a leftSub rightSub) = a
getTreeData :: Tree a -> a
getTreeData (Node a leftSub rightSub) = a
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singletonTree x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
treeElem :: (Ord a) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
| x == a = True
| x < a = treeElem x left
| x > a = treeElem x right
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x leftSub rightSub) = Node (f x) (fmap f leftSub) (fmap f rightSub)
firstSpace :: String -> String
firstSpace = dropWhile (==' ') . dropWhile (/=' ')
tokenize :: String -> (String, String)
tokenize xs = (a,b)
where a = takeWhile (/=' ') xs
b = firstSpace xs
sum'' :: (Num a) => [a] -> a
sum'' xs = foldl (\acc x -> acc + x) 0 xs
numLongChains :: Int
numLongChains = length (filter (\xs -> length xs > 15) (map chain [1..100]))
chain :: (Integral a) => a -> [a]
chain 1 = [1]
chain n
| even n = n:chain(n `div` 2)
| odd n = n:chain(n*3+1)
largestDivisible :: (Integral a) => a
largestDivisible = head (filter p [100000,99999..])
where p x = x `mod` 3829 == 0
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' f (x:xs)
| f x = x : filter' f xs
| otherwise = filter' f xs
map'' :: (a -> b) -> [a] -> [b]
map'' f xs = foldr (\x acc -> f x : acc) [] xs
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
flip' :: (a -> b -> c) -> (b -> a -> c)
flip' f x y = f y x
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
multThree :: (Num a) => a -> a
multThree = (*3)
quicksort :: (Eq a, Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let small = quicksort [a | a <- xs, a <=x]
big = quicksort [a | a <- xs, a > x]
in small ++ [x] ++ big
elem'' :: (Eq a) => a -> [a] -> Bool
elem'' y ys = foldl (\acc x -> if x == y then True else acc) False ys
elem' :: (Eq a) => a -> [a] -> Bool
elem' _ [] = False
elem' e (x:xs)
| x==e = True
| otherwise = elem' e xs
zip' :: [a] -> [b] -> [(a,b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys
repeat' :: (Eq a) => a -> [a]
repeat' x = x:repeat' x
reverse' :: (Eq a) => [a] -> [a]
reverse' (x:xs) = case (x:xs) of
(x:[]) -> [x]
_ -> reverse' xs ++ [x]
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' _ [] = []
take' n (x:xs)
| n <= 0 = []
| otherwise = x:(take' (n-1) xs)
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| n > 0 = x:replicate' (n-1) x
maxi' :: (Ord a) => [a] -> a
maxi' [] = error "no maximum of empty list"
maxi' [x] = x
maxi' (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maxi' xs
fib :: (Eq a, Num a) => a -> a
fib 0 = 0
fib 1 = 1
fib x = fib (x-1) + fib (x-2)
combineTriple :: (Num a) => (a,a,a) -> a
combineTriple (x,y,z) = let a=x; b=y; c=z in a+b+c
cylinder :: (RealFloat a) => a -> a -> a
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^2
in sideArea + 2 * topArea
calcBmis :: (RealFloat a) => [(a,a)] -> [a]
calcBmis xs = [bmi w h | (w,h) <- xs]
where bmi weight height = weight / height ^ 2
initials :: [Char] -> [Char] -> [Char]
initials firstname lastname = [f] ++ ". " ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
myCompare :: (Ord a) => a -> a -> Ordering
myCompare a b
| a > b = GT
| a == b = EQ
| otherwise = LT
tellMe :: (Integral a, Show a) => a -> [Char]
tellMe something
| something > 0 = "Greater than Zero."
| something < 0 = "Less than Zero."
| otherwise = "Zero."
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum xs
length' :: (Num b) => [a] -> b
length' [] = 0
length' (x:xs) = 1 + length' xs
head' :: [a] -> a
head' [] = error "Empty list has no head."
head' (x:_) = x
factorial :: Integral a => a -> a
factorial n = if n == 0 then 1 else n * factorial (n -1)
sayHello :: String -> IO ()
sayHello x = putStrLn ("Hello, " ++ x ++ "!")
myLength :: [z] -> Int
myLength x = length x
trp :: (x,y,z) -> z
trp (x,y,z) = z
myOrder :: (Ord a, Num a) => a -> a -> Ordering
myOrder a b = if a - b >= 0 then GT else LT
doFunc f a = f a
addOne x =
x + 1
makeEqual x y =
if (not ( x == y ) && (x < y)) then
makeEqual (addOne x) y
else
if x < y then
"Y is larger!"
else
"Equal"
simple y = if (snd y == ()) then fst y else snd y
x = (+)
easyFunction :: Num a => a -> a
easyFunction a = a
myFst :: (a,b) -> a
myFst (a,b) = a
firstOne :: [a] -> a
firstOne (x:xs) = x
myId x = x
-- F :: [Char] -> Integer
legnthPlusOne xd = w `x` 1
where w = length xd
--F xs = w + 1
-- where w = length xs
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome (a:x)
| (length x) == 0 = True
| a /= (x !! (length x - 1)) = False
| a == (x !! (length x - 1)) = isPalindrome (take (length x -1) x)
myAbs :: Integer -> Integer
myAbs x = if x >= 0 then x else (x * (-1))
f :: (a,b) -> (c,d) -> ((b,d) , (a,c))
f (a,b) (c,d) = ((b,d) , (a,c))
cutString :: (Eq n, Num n) => n -> String -> String
cutString n str = case n of
0 -> tail str
n -> cutString (n-1) (tail str)
| doylew/practice | haskell/test.hs | mit | 6,041 | 0 | 13 | 1,605 | 3,581 | 1,885 | 1,696 | 189 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module ElmodoroType
( Elmodoro(..)
, migrateAll
) where
import ElmodoroStatusType
import Data.Int
import Data.Time.Clock
import Database.Persist.TH
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Elmodoro
workStartTime UTCTime
workEndTime UTCTime Maybe
breakStartTime UTCTime Maybe
breakEndTime UTCTime Maybe
workLength Int64
breakLength Int64
tags [String]
status ElmodoroStatus
deriving Eq Show
|]
| ryandv/elmodoro | backend/ElmodoroType.hs | mit | 765 | 0 | 7 | 212 | 66 | 43 | 23 | 14 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE PatternGuards #-}
module Database.Persist.Quasi
( parse
, PersistSettings (..)
, upperCaseSettings
, lowerCaseSettings
, stripId
, nullable
#if TEST
, Token (..)
, tokenize
, parseFieldType
#endif
) where
import Prelude hiding (lines)
import Database.Persist.Types
import Data.Char
import Data.Maybe (mapMaybe, fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Control.Arrow ((&&&))
import qualified Data.Map as M
import Data.List (foldl')
data ParseState a = PSDone | PSFail | PSSuccess a Text
parseFieldType :: Text -> Maybe FieldType
parseFieldType t0 =
case go t0 of
PSSuccess ft t'
| T.all isSpace t' -> Just ft
_ -> Nothing
where
go t =
case goMany id t of
PSSuccess (ft:fts) t' -> PSSuccess (foldl' FTApp ft fts) t'
PSSuccess [] _ -> PSFail
PSFail -> PSFail
PSDone -> PSDone
go1 t =
case T.uncons t of
Nothing -> PSDone
Just (c, t')
| isSpace c -> go1 $ T.dropWhile isSpace t'
| c == '(' ->
case go t' of
PSSuccess ft t'' ->
case T.uncons $ T.dropWhile isSpace t'' of
Just (')', t''') -> PSSuccess ft t'''
_ -> PSFail
_ -> PSFail
| c == '[' ->
case go t' of
PSSuccess ft t'' ->
case T.uncons $ T.dropWhile isSpace t'' of
Just (']', t''') -> PSSuccess (FTList ft) t'''
_ -> PSFail
_ -> PSFail
| isUpper c ->
let (a, b) = T.break (\x -> isSpace x || x `elem` "()[]") t
in PSSuccess (getCon a) b
| otherwise -> PSFail
getCon t =
case T.breakOnEnd "." t of
(_, "") -> FTTypeCon Nothing t
("", _) -> FTTypeCon Nothing t
(a, b) -> FTTypeCon (Just $ T.init a) b
goMany front t =
case go1 t of
PSSuccess x t' -> goMany (front . (x:)) t'
_ -> PSSuccess (front []) t
data PersistSettings = PersistSettings
{ psToDBName :: !(Text -> Text)
, psStrictFields :: !Bool
-- ^ Whether fields are by default strict. Default value: @True@.
--
-- Since 1.2
}
upperCaseSettings :: PersistSettings
upperCaseSettings = PersistSettings
{ psToDBName = id
, psStrictFields = True
}
lowerCaseSettings :: PersistSettings
lowerCaseSettings = PersistSettings
{ psToDBName =
let go c
| isUpper c = T.pack ['_', toLower c]
| otherwise = T.singleton c
in T.dropWhile (== '_') . T.concatMap go
, psStrictFields = True
}
-- | Parses a quasi-quoted syntax into a list of entity definitions.
parse :: PersistSettings -> Text -> [EntityDef ()]
parse ps = parseLines ps
. removeSpaces
. filter (not . empty)
. map tokenize
. T.lines
-- | A token used by the parser.
data Token = Spaces !Int -- ^ @Spaces n@ are @n@ consecutive spaces.
| Token Text -- ^ @Token tok@ is token @tok@ already unquoted.
deriving (Show, Eq)
-- | Tokenize a string.
tokenize :: Text -> [Token]
tokenize t
| T.null t = []
| "--" `T.isPrefixOf` t = [] -- Comment until the end of the line.
| "#" `T.isPrefixOf` t = [] -- Also comment to the end of the line, needed for a CPP bug (#110)
| T.head t == '"' = quotes (T.tail t) id
| T.head t == '(' = parens 1 (T.tail t) id
| isSpace (T.head t) =
let (spaces, rest) = T.span isSpace t
in Spaces (T.length spaces) : tokenize rest
| otherwise =
let (token, rest) = T.break isSpace t
in Token token : tokenize rest
where
quotes t' front
| T.null t' = error $ T.unpack $ T.concat $
"Unterminated quoted string starting with " : front []
| T.head t' == '"' = Token (T.concat $ front []) : tokenize (T.tail t')
| T.head t' == '\\' && T.length t' > 1 =
quotes (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):))
| otherwise =
let (x, y) = T.break (`elem` "\\\"") t'
in quotes y (front . (x:))
parens count t' front
| T.null t' = error $ T.unpack $ T.concat $
"Unterminated parens string starting with " : front []
| T.head t' == ')' =
if count == (1 :: Int)
then Token (T.concat $ front []) : tokenize (T.tail t')
else parens (count - 1) (T.tail t') (front . (")":))
| T.head t' == '(' =
parens (count + 1) (T.tail t') (front . ("(":))
| T.head t' == '\\' && T.length t' > 1 =
parens count (T.drop 2 t') (front . (T.take 1 (T.drop 1 t'):))
| otherwise =
let (x, y) = T.break (`elem` "\\()") t'
in parens count y (front . (x:))
-- | A string of tokens is empty when it has only spaces. There
-- can't be two consecutive 'Spaces', so this takes /O(1)/ time.
empty :: [Token] -> Bool
empty [] = True
empty [Spaces _] = True
empty _ = False
-- | A line. We don't care about spaces in the middle of the
-- line. Also, we don't care about the ammount of indentation.
data Line = Line { lineIndent :: Int
, tokens :: [Text]
}
-- | Remove leading spaces and remove spaces in the middle of the
-- tokens.
removeSpaces :: [[Token]] -> [Line]
removeSpaces =
map toLine
where
toLine (Spaces i:rest) = toLine' i rest
toLine xs = toLine' 0 xs
toLine' i = Line i . mapMaybe fromToken
fromToken (Token t) = Just t
fromToken Spaces{} = Nothing
-- | Divide lines into blocks and make entity definitions.
parseLines :: PersistSettings -> [Line] -> [EntityDef ()]
parseLines ps lines =
toEnts lines
where
toEnts (Line indent (name:entattribs) : rest) =
let (x, y) = span ((> indent) . lineIndent) rest
in mkEntityDef ps name entattribs x : toEnts y
toEnts (Line _ []:rest) = toEnts rest
toEnts [] = []
-- | Construct an entity definition.
mkEntityDef :: PersistSettings
-> Text -- ^ name
-> [Attr] -- ^ entity attributes
-> [Line] -- ^ indented lines
-> EntityDef ()
mkEntityDef ps name entattribs lines =
EntityDef
(HaskellName name')
(DBName $ getDbName ps name' entattribs)
(DBName $ idName entattribs)
entattribs cols uniqs derives
extras
isSum
where
(isSum, name') =
case T.uncons name of
Just ('+', x) -> (True, x)
_ -> (False, name)
(attribs, extras) = splitExtras lines
idName [] = "id"
idName (t:ts) =
case T.stripPrefix "id=" t of
Nothing -> idName ts
Just s -> s
uniqs = mapMaybe (takeUniqs ps cols) attribs
derives = concat $ mapMaybe takeDerives attribs
cols :: [FieldDef ()]
cols = mapMaybe (takeCols ps) attribs
splitExtras :: [Line] -> ([[Text]], M.Map Text [[Text]])
splitExtras [] = ([], M.empty)
splitExtras (Line indent [name]:rest)
| not (T.null name) && isUpper (T.head name) =
let (children, rest') = span ((> indent) . lineIndent) rest
(x, y) = splitExtras rest'
in (x, M.insert name (map tokens children) y)
splitExtras (Line _ ts:rest) =
let (x, y) = splitExtras rest
in (ts:x, y)
takeCols :: PersistSettings -> [Text] -> Maybe (FieldDef ())
takeCols _ ("deriving":_) = Nothing
takeCols ps (n':typ:rest)
| not (T.null n) && isLower (T.head n) =
case parseFieldType typ of
Nothing -> error $ "Invalid field type: " ++ show typ
Just ft -> Just FieldDef
{ fieldHaskell = HaskellName n
, fieldDB = DBName $ getDbName ps n rest
, fieldType = ft
, fieldSqlType = ()
, fieldAttrs = rest
, fieldStrict = fromMaybe (psStrictFields ps) mstrict
, fieldEmbedded = Nothing
}
where
(mstrict, n)
| Just x <- T.stripPrefix "!" n' = (Just True, x)
| Just x <- T.stripPrefix "~" n' = (Just False, x)
| otherwise = (Nothing, n')
takeCols _ _ = Nothing
getDbName :: PersistSettings -> Text -> [Text] -> Text
getDbName ps n [] = psToDBName ps n
getDbName ps n (a:as) =
case T.stripPrefix "sql=" a of
Nothing -> getDbName ps n as
Just s -> s
takeUniqs :: PersistSettings
-> [FieldDef a]
-> [Text]
-> Maybe UniqueDef
takeUniqs ps defs (n:rest)
| not (T.null n) && isUpper (T.head n)
= Just $ UniqueDef
(HaskellName n)
(DBName $ psToDBName ps n)
(map (HaskellName &&& getDBName defs) fields)
attrs
where
(fields,attrs) = break ("!" `T.isPrefixOf`) rest
getDBName [] t = error $ "Unknown column in unique constraint: " ++ show t
getDBName (d:ds) t
| fieldHaskell d == HaskellName t = fieldDB d
| otherwise = getDBName ds t
takeUniqs _ _ _ = Nothing
takeDerives :: [Text] -> Maybe [Text]
takeDerives ("deriving":rest) = Just rest
takeDerives _ = Nothing
stripId :: FieldType -> Maybe Text
stripId (FTTypeCon Nothing t) = T.stripSuffix "Id" t
stripId _ = Nothing
nullable :: [Text] -> IsNullable
nullable s
| "Maybe" `elem` s = Nullable ByMaybeAttr
| "nullable" `elem` s = Nullable ByNullableAttr
| otherwise = NotNullable
| gbwey/persistentold | persistent/Database/Persist/Quasi.hs | mit | 9,748 | 0 | 20 | 3,315 | 3,426 | 1,746 | 1,680 | 242 | 13 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
import Core.Program
import Core.Text
import TechniqueUser
( commandCheckTechnique,
commandFormatTechnique,
)
#ifdef __GHCIDE__
version :: Version
version = "0"
#else
version :: Version
version = $(fromPackage)
#endif
main :: IO ()
main = do
context <-
configure
version
None
( complex
[ Command
"check"
"Syntax- and type-check the given procedure"
[ Option
"watch"
Nothing
Empty
[quote|
Watch the given procedure file and recompile if changes are detected.
|],
Argument
"filename"
[quote|
The file containing the code for the procedure you want to type-check.
|]
],
Command
"format"
"Format the given procedure"
[ Option
"raw-control-chars"
(Just 'R')
Empty
[quote|
Emit ANSI escape codes for syntax highlighting even if output
is redirected to a pipe or file.
|],
Argument
"filename"
[quote|
The file containing the code for the procedure you want to format.
|]
]
]
)
executeWith context program
program :: Program None ()
program = do
params <- getCommandLine
case commandNameFrom params of
Nothing -> do
write "Illegal state?"
terminate 2
Just command -> case command of
"check" -> commandCheckTechnique
"format" -> commandFormatTechnique
_ -> do
write "Unknown command?"
terminate 3
event "Done"
| oprdyn/technique | src/TechniqueMain.hs | mit | 1,950 | 0 | 16 | 830 | 266 | 140 | 126 | 55 | 4 |
-- TypeLevel Operations
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ExplicitForAll #-}
-- a ≡ b
data Eql a b where
Refl :: Eql a a
-- Congruence
-- (f : A → B) {x y} → x ≡ y → f x ≡ f y
cong :: Eql a b -> Eql (f a) (f b)
cong Refl = Refl
-- Symmetry
-- {a b : A} → a ≡ b → a ≡ b
sym :: Eql a b -> Eql b a
sym Refl = Refl
-- Transitivity
-- {a b c : A} → a ≡ b → b ≡ c → a ≡ c
trans :: Eql a b -> Eql b c -> Eql a c
trans Refl Refl = Refl
-- Coerce one type to another given a proof of their equality.
-- {a b : A} → a ≡ b → a → b
castWith :: Eql a b -> a -> b
castWith Refl = id
-- Trivial cases
a :: forall n. Eql n n
a = Refl
b :: forall. Eql () ()
b = Refl
-- Another DataKinds implementation
-- ref: https://stackoverflow.com/questions/22082852/erratic-hole-type-resolution
{-# LANGUAGE
DataKinds, PolyKinds, TypeFamilies,
UndecidableInstances, GADTs, TypeOperators #-}
data (==) :: k -> k -> * where
Refl :: x == x
sym :: a == b -> b == a
sym Refl = Refl
data Nat = Zero | Succ Nat
data SNat :: Nat -> * where
SZero :: SNat Zero
SSucc :: SNat n -> SNat (Succ n)
type family a + b where
Zero + b = b
Succ a + b = Succ (a + b)
addAssoc :: SNat a -> SNat b -> SNat c -> (a + (b + c)) == ((a + b) + c)
addAssoc SZero b c = Refl
addAssoc (SSucc a) b c = case addAssoc a b c of Refl -> Refl
addComm :: SNat a -> SNat b -> (a + b) == (b + a)
addComm SZero SZero = Refl
addComm (SSucc a) SZero = case addComm a SZero of Refl -> Refl
addComm SZero (SSucc b) = case addComm SZero b of Refl -> Refl
addComm sa@(SSucc a) sb@(SSucc b) =
case addComm a sb of
Refl -> case addComm b sa of
Refl -> case addComm a b of
Refl -> Refl | Airtnp/Freshman_Simple_Haskell_Lib | Intro/WIW/Interpreter/TypeLevel.hs | mit | 1,743 | 1 | 13 | 483 | 636 | 333 | 303 | -1 | -1 |
{-|
Module : Main
Description : A simulator for neutron beamlines
Copyright : (c) Adam Washington, 2014
License : MIT
Maintainer : adam.l.washington@gmail.com
Stability : experimental
Portability : POSIX
This module performs a monte-carlo simulation of a neutron beamline.-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Main (main) where
import Neutron (getEnergy,Neutron,position,direction,advance)
import Momentum (Energy(Energy),Momentum)
import Pipes
import qualified Pipes.Prelude as P
import Slits (slit)
import Detector (dumpToConsole,liftBuilder,plotter,dumpToFile)
import Source (simpleSource,producer)
import Samples (scatter,spheres)
import Control.Applicative
import Data.Random
import Data.Random.Source.PureMT
import Data.IORef
import Control.Comonad(extract)
import Linear (V3(V3),Epsilon,nearZero,norm)
import Control.Monad (liftM)
import Data.Vector.Unboxed as V
import Data.Random.Distribution.Uniform (doubleUniform)
import Data.Random.Distribution.Normal (doubleStdNormal)
--import Data.Random.Distribution (rVarT)
-- Step 1: Define the beamline
-- Make a beamline function with parameters for every random value
instance Num (V.Vector Double) where
(+) = V.zipWith (+)
(-) = V.zipWith (-)
(*) = V.zipWith (*)
abs = V.map abs
signum = V.map signum
fromInteger = V.replicate chunksize . fromInteger
instance Fractional (V.Vector Double) where
(/) = V.zipWith (/)
fromRational = V.replicate chunksize . fromRational
instance Floating (V.Vector Double) where
sin = V.map sin
cos = V.map cos
log = V.map log
exp = V.map exp
asin = V.map asin
atan = V.map atan
acos = V.map acos
sinh = V.map sinh
cosh = V.map cosh
asinh = V.map asinh
acosh = V.map acosh
atanh = V.map atanh
pi = V.replicate chunksize pi
instance Epsilon (V.Vector Double) where
nearZero = const False
instance Distribution Uniform (Vector Double)
where rvarT (Uniform a b) = V.zipWithM doubleUniform a b
instance Distribution Normal (Vector Double)
where
rvarT StdNormal = V.replicateM chunksize doubleStdNormal
rvarT (Normal m s) = V.zipWith3 <$> pure (\ a b c -> a*b+c) <*> pure s <*> x <*> pure m
where
x = V.replicateM chunksize doubleStdNormal
chunksize :: Int
chunksize = 1
startSlit :: Neutron (V.Vector Double) -> Maybe (Neutron (V.Vector Double))
startSlit = slit (V3 0 0 (-10)) (V3 0.4 0.9 10)
beamline :: (Momentum m) => V3 (V.Vector Double) -> V3 (V.Vector Double) -> m (V.Vector Double) -> V.Vector Double -> V.Vector Double -> Maybe (Neutron (V.Vector Double))
beamline start target momentum angle q = liftM ({- advance 1 . -}scatter q angle) . startSlit $ simpleSource start target momentum
--beamline = error "Fail"
-- Step 2: Define Random Variables
-- Make a random variable for each of the values
startbox :: RVar (V3 (V.Vector Double))
startbox = pure $ V3 0 0 0
targetbox :: RVar (V3 (V.Vector Double))
targetbox = pure $ V3 0 0 1
mySpread :: RVar (Energy (V.Vector Double))
--mySpread = liftM Energy $ normal 1.0 0.5
mySpread = liftM Energy $ spheres 20
-- Step 3: Make a random beamline
-- This should have NO parameters and a type of RVar (Maybe (Neutron Double))
beam :: RVar (Maybe (Neutron (V.Vector Double)))
beam = beamline <$> startbox <*> targetbox <*> mySpread <*> uniform 0 (2*pi) <*> spheres 1
-- Step 4: Run the beamline!
x :: V3 a -> a
x (V3 n _ _) = n
y :: V3 a -> a
y (V3 _ n _) = n
z :: V3 a -> a
z (V3 _ _ n) = n
norm2d (V3 x y _) = sqrt $ x*x+y*y
xAndy n = show (V.head $ x $ d) Prelude.++ " " Prelude.++ show (V.head $ y $ d)
where
d = direction n
main' :: (RandomSource IO s) => s -> IO ()
-- | Simulate the beamline
main' src = runEffect $ producer src beam >->
P.take 5000000 >->
P.map xAndy >->
-- liftBuilder (norm2d.position) 200 (0,10) 50000 >->
dumpToFile "values.dat"
-- plotter
-- dumpToConsole
-- --main' :: RandomSource IO s => s -> IO ()
-- main' s = runEffect $ P.repeatM (runRVar (spheres (1 :: Double)) s) >->
-- P.take 500000 >->
-- dumpToFile "values.dat"
main :: IO ()
main = do
src <- newIORef (pureMT 1234)
main' src
| rprospero/NeutronPipe | Main.hs | mit | 4,267 | 0 | 16 | 910 | 1,364 | 724 | 640 | 84 | 1 |
import FPPrac
extrX :: Number -> Number -> Number -> Number
extrX a b c = (-b) / (2*a)
extrY :: Number -> Number -> Number -> Number
extrY a b c = a * x ^ 2 + b * x + c
where x = extrX a b c | tcoenraad/functioneel-programmeren | practica/serie1/5.extreme-values.hs | mit | 194 | 0 | 9 | 54 | 112 | 58 | 54 | 6 | 1 |
module Out.Roman
( romanizeWord
, romanizeSyllables
, romanizePhoneme
) where
import ClassyPrelude hiding (Word)
import Data.Text (toTitle)
import HelperFunctions
import Data.Language
import Data.Phoneme
import Data.Word
import Data.Inflection
import Out.IPA
import Out.Syllable
romanizeWord :: Language -> Word -> Text
romanizeWord lang (MorphemeS _ _ syllables) = toTitle $ romanizeSyllables lang syllables []
romanizeWord lang (MorphemeP _ _ phonemes) = toTitle $ romanizePhonemes phonemes
romanizeWord lang (MorphemeC _ _ phonemess) = toTitle $ intercalate "–" (map romanizePhonemes phonemess)
romanizeWord lang (MorphemeV _ _ patts) = toTitle $ intercalate "–" (map (romanizeSyllable lang) patts)
romanizeWord lang word = fromMaybe "!!ERROR!!" (toTitle <$> (romanizeSyllables lang <$> syllabifyWord lang word <*> return []))
romanizeSyllables :: Language -> [Syllable] -> [Phoneme] -> Text
romanizeSyllables lang [] [] = ""
romanizeSyllables lang [] [Vowel{}] = ""
romanizeSyllables lang [] [Diphthong{}] = ""
romanizeSyllables lang [] ps = romanizePhonemes ps
romanizeSyllables lang (s@(Syllable onset nucleus coda tone stress):ss) ps = f ++ n ++ l where
f | (\case [Vowel{}] -> True; [Diphthong{}] -> True; _ -> False) ps && null onset = "\'"
| (\case [Vowel{}] -> True; [Diphthong{}] -> True; _ -> False) ps = romanizePhonemes onset
| otherwise = romanizePhonemes (ps ++ onset)
n_ | length (getTones lang) > 1 = romanizePhoneme nucleus ++ writeToneDiacritic tone
| length (getStresses lang) > 1 = romanizePhoneme nucleus ++ writeStressDiacritic stress
| otherwise = romanizePhoneme nucleus
n | (\case Just 'e' -> True; _ -> False) (lastMay n_) = n_ ++ "\776"
| otherwise = n_
l | null coda = romanizeSyllables lang ss [nucleus]
| otherwise = romanizeSyllables lang ss coda
romanizeSyllable :: Language -> Syllable -> Text
romanizeSyllable lang (Syllable onset nucleus coda tone stress) = out where
out
| length (getTones lang) > 1 = romanizePhonemes onset ++ romanizePhoneme nucleus ++ writeToneDiacritic tone ++ romanizePhonemes coda
| length (getStresses lang) > 1 = romanizePhonemes onset ++ romanizePhoneme nucleus ++ writeStressDiacritic stress ++ romanizePhonemes coda
| otherwise = romanizePhonemes onset ++ romanizePhoneme nucleus ++ romanizePhonemes coda
romanizePhonemes :: [Phoneme] -> Text
romanizePhonemes ps = intercalate "\'" $ map (concatMap romanizePhoneme) $ groupBy (\x y -> not (isVowel x && isVowel y)) ps
-- these rules suck, need diacritics and a pool to pull from as needed
romanizePhoneme :: Phoneme -> Text
romanizePhoneme cns@(Consonant p m h a)
-- Coarticulated
| p == COARTICULATED BILABIAL VELAR && m == APPROXIMANT = "w"
| (\case COARTICULATED{} -> True; _ -> False) p = romanizePhoneme (Consonant (getPlaceA p) m h a) ++ romanizePhoneme (Consonant (getPlaceB p) m h a)
-- Airstream
| m == CLICK && a == LINGUAL = writePhonemeIPA cns
| a == EJECTIVE = romanizePhoneme (Consonant p m h PULMONIC) ++ "'"
| a == IMPLOSIVE = romanizePhoneme (Consonant p m h PULMONIC)
-- Phonation
| h == ASPIRATED = romanizePhoneme (Consonant p m MODAL a) ++ "h"
| h == BREATHY = romanizePhoneme (Consonant p m VOICELESS a)
| h == SLACK = romanizePhoneme (Consonant p m VOICELESS a)
| h == STIFF = romanizePhoneme (Consonant p m MODAL a)
| h == CREAKY = romanizePhoneme (Consonant p m MODAL a)
-- Places
| p == INTERDENTAL = romanizePhoneme (Consonant DENTAL m h a)
| p `elem` [LAMINALALVEOLAR, APICOALVEOLAR] = romanizePhoneme (Consonant ALVEOLAR m h a)
| p == PALATOALVEOLAR = romanizePhoneme (Consonant POSTALVEOLAR m h a)
| p == APICALRETROFLEX = romanizePhoneme (Consonant RETROFLEX m h a)
| p == ALVEOLOPALATAL = romanizePhoneme (Consonant PALATAL m h a)
-- Specific stuff
| p == BILABIAL && m == NASAL && h == MODAL = "m"
| p `elem` [DENTIALVEOLAR, ALVEOLAR] && m == NASAL && h == MODAL = "n"
| p == VELAR && m == NASAL && h == MODAL = "ng"
| p `elem` [BILABIAL, LABIODENTAL] && m == STOP && h == VOICELESS = "p"
| p `elem` [BILABIAL, LABIODENTAL] && m == STOP && h == MODAL = "b"
| p `elem` [DENTIALVEOLAR, ALVEOLAR] && m == STOP && h == VOICELESS = "t"
| p `elem` [DENTIALVEOLAR, ALVEOLAR] && m == STOP && h == MODAL = "d"
| p == VELAR && m == STOP && h == VOICELESS = "k"
| p == VELAR && m == STOP && h == MODAL = "g"
| p == LABIODENTAL && m `elem` [FRICATIVE, SILIBANT] && h == VOICELESS = "f"
| p == LABIODENTAL && m `elem` [FRICATIVE, SILIBANT] && h == MODAL = "v"
| p == DENTAL && m `elem` [FRICATIVE, SILIBANT] && h `elem` [MODAL, VOICELESS] = "th"
| p `elem`[DENTIALVEOLAR, ALVEOLAR] && m `elem` [FRICATIVE, SILIBANT] && h == VOICELESS = "s"
| p `elem`[DENTIALVEOLAR, ALVEOLAR] && m `elem` [FRICATIVE, SILIBANT] && h == MODAL = "z"
| p == POSTALVEOLAR && m `elem` [FRICATIVE, SILIBANT] && h == VOICELESS = "sh"
| p == POSTALVEOLAR && m `elem` [FRICATIVE, SILIBANT] && h == MODAL = "zh"
| p == GLOTTAL && m == FRICATIVE && h == VOICELESS = "h"
| p `elem`[DENTIALVEOLAR, ALVEOLAR] && m `elem` [SAFFRICATE, AFFRICATE] && h == VOICELESS = "ts"
| p == POSTALVEOLAR && m `elem` [SAFFRICATE, AFFRICATE] && h == VOICELESS = "ch"
| p == POSTALVEOLAR && m `elem` [SAFFRICATE, AFFRICATE] && h == MODAL = "j"
| p `elem`[DENTIALVEOLAR, ALVEOLAR] && m `elem` [APPROXIMANT, TRILL] && h == MODAL = "r"
| p `elem`[DENTIALVEOLAR, ALVEOLAR] && m == LAPPROXIMANT && h == MODAL = "l"
| p `elem` [ALVEOLOPALATAL, PALATAL] && m == APPROXIMANT = "y"
| p == VELAR && m == APPROXIMANT = "w"
| ((p <= PALATAL || p == UVULAR) && m == APPROXIMANT) || ((p <= PALATAL || p == UVULAR) && m `elem` [APPROXIMANT, TRILL, FLAP] ) = "r"
| m `elem` [LAPPROXIMANT, LFRICATIVE, LAFFRICATE, LFLAP] = "l"
| p `elem` [UVULAR, PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL] && m == STOP = "g"
| p `elem` [PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = "h"
-- Last resort
| m == NASAL = "n"
| p == VELAR && m == STOP = "k"
| m == AFFRICATE = romanizePhoneme (Consonant p STOP h a) ++ romanizePhoneme (Consonant p FRICATIVE h a)
| m == SAFFRICATE = romanizePhoneme (Consonant p STOP h a) ++ romanizePhoneme (Consonant p SILIBANT h a)
| p == PALATAL = romanizePhoneme (Consonant VELAR m h a)
| p == VELAR = romanizePhoneme (Consonant UVULAR m h a)
| p == RETROFLEX = romanizePhoneme (Consonant ALVEOLAR m h a)
| p == DENTAL = romanizePhoneme (Consonant ALVEOLAR m h a)
-- Otherwise "h"
| otherwise = "h"
romanizePhoneme (Vowel h b r l)
-- Specific stuff
| h == NEAROPEN && b == FRONT && r == UNROUNDED = "a"
| h == CLOSEMID && b == FRONT && r == UNROUNDED = "e"
| h == CLOSE && b == FRONT && r == UNROUNDED = "e"
| h == NEARCLOSE && b == NEARFRONT && r == UNROUNDED = "i"
| h == OPEN && b == BACK && r == ROUNDED = "o"
| h == CLOSE && b == BACK && r == ROUNDED && l == LONG = "o"
| h == OPENMID && b == BACK && r == ROUNDED = "u"
-- Length
| l == LONG = romanizePhoneme (Vowel h b r NORMAL) ++ romanizePhoneme (Vowel h b r NORMAL)
| l == SHORT = romanizePhoneme (Vowel h b r NORMAL)
-- Last resort
| h `elem` [NEARCLOSE, CLOSEMID, MID, OPENMID] && b == BACK = "o"
| h `elem` [CLOSEMID, MID, OPENMID] && b == FRONT = "e"
| h `elem` [OPENMID, NEAROPEN, OPEN] = "a"
| h `elem` [CLOSE, NEARCLOSE] && b `elem` [FRONT, NEARFRONT] = "i"
| h `elem` [CLOSE, NEARCLOSE] && b `elem` [BACK, NEARBACK, CENTRAL] = "o"
| h `elem` [CLOSEMID, MID, OPENMID] && b `elem` [CENTRAL, NEARFRONT, NEARBACK] = "u"
-- Otherwise "u"
| otherwise = "u"
romanizePhoneme (Diphthong h b r h2 b2 r2 l) = romanizePhoneme (Vowel h b r l) ++ romanizePhoneme (Vowel h2 b2 r2 l)
romanizePhoneme Blank = ""
-- Tone diacritics
writeToneDiacritic :: Tone -> Text
writeToneDiacritic t
| t == NONET = ""
| t == TOPT = "\779"
| t == HIGHT = "\769"
| t == MIDT = "\772"
| t == LOWT = "\768"
| t == BOTTOMT = "\783"
| t == FALLT = "\770"
| t == HFALLT = "\7623"
| t == LFALLT = "\7622"
| t == RISET = "\780"
| t == HRISET = "\7620"
| t == LRISET = "\7621"
| t == DIPT = "\7625"
| t == PEAKT = "\7624"
-- Stress diacritics
writeStressDiacritic :: Stress -> Text
writeStressDiacritic s
| s == NONES = ""
| s == PRIMARYS = "\769"
| s == SECONDARYS = "\779"
| Brightgalrs/con-lang-gen | src/Out/Roman.hs | mit | 8,266 | 0 | 17 | 1,733 | 3,590 | 1,823 | 1,767 | -1 | -1 |
{-# LANGUAGE ConstrainedClassMethods #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-
This module implements functions managing Client Connections inside a bigger state-type.
The state-type has to be kept within an TVar variable and the update functions are done using IO
For instances, it is only necessary to TODO
Note: this is used for preventing mutually recursive modules.
TODO: write about what is exported and how to use this module
-}
module App.ConnectionMgnt (
ConnectionId,
ClientConnections(..),
HasConnections,
Conn,
connectClient,
disconnectClient,
getConnections,
setConnections,
findConnectionById,
withoutClient,
IsConnection,
Pending,
sendMsg,
sendSendableMsg,
recvMsg,
acceptRequest,
multicastMsg
) where
import ClassyPrelude
import Network.Protocol
type ConnectionId = Int
-- TODO: instance MonoFoldable & MonoTraversable for ClientConnections
data ClientConnections conn =
ClientConnections
{ connections :: Map ConnectionId conn
, nextId :: ConnectionId
}
class IsConnection c where
type Pending c :: *
sendMsg :: c -> MessageForClient -> IO ()
recvMsg :: c -> IO (Maybe MessageForServer)
sendSendableMsg :: SendableToClient msg => c -> msg -> IO ()
sendSendableMsg c msg = sendMsg c $ wrapSendable msg
acceptRequest :: Pending c -> IO c
-- TODO: optimal multicast signature if ClientConnections was MonoFoldable
-- multicastMsg ::
-- (SendableToClient msg, MonoFoldable f, IsConnection c, c ~ Element f)
-- => f -> msg -> IO ()
multicastMsg :: (SendableToClient msg) => ClientConnections c -> msg -> IO ()
multicastMsg cs msg = omapM_ (`sendSendableMsg` msg) $ connections cs
class HasConnections state where
type Conn state :: *
getConnections :: state -> ClientConnections (Conn state)
setConnections :: ClientConnections (Conn state) -> state -> state
connectClient :: Conn state -> TVar state -> IO ConnectionId
connectClient conn stateVar = do
clientId <- atomically $ addClient conn stateVar
putStrLn $ "connect " ++ tshow clientId
return clientId
disconnectClient :: ConnectionId -> TVar state -> IO ()
disconnectClient clientId stateVar = do
atomically $ removeClient clientId stateVar
putStrLn $ "disconnect " ++ tshow clientId
-- implement HasConnections for ClientConnections themselves
instance IsConnection conn => HasConnections (ClientConnections conn) where
type Conn (ClientConnections conn) = conn
getConnections = id
setConnections = const
-- extra functions
findConnectionById :: ConnectionId -> ClientConnections conn -> Maybe conn
findConnectionById cId =
lookup cId . connections
withoutClient :: ConnectionId -> ClientConnections conn -> ClientConnections conn
withoutClient cId conns =
conns
{ connections = deleteMap cId . connections $ conns
}
-- helper functions (not exported)
addClient :: HasConnections state => Conn state -> TVar state -> STM ConnectionId
addClient conn stateVar = do -- update connection list
state <- readTVar stateVar
let conns = getConnections state
let newConnections =
conns
{ connections =
insertMap (nextId conns) conn $
connections conns
, nextId = 1 + nextId conns
}
writeTVar stateVar (setConnections newConnections state)
return $ nextId conns
removeClient :: HasConnections state => ConnectionId -> TVar state -> STM ()
removeClient cId stateVar = do
state <- readTVar stateVar
let connections = getConnections state
writeTVar stateVar (setConnections (withoutClient cId connections) state)
| Haskell-Praxis/core-catcher | src/App/ConnectionMgnt.hs | mit | 4,028 | 0 | 15 | 988 | 817 | 417 | 400 | 82 | 1 |
import Data.List
import Data.Ord
is_co_prime a b = gcd a b == 1
triangles2 p = [(a,b,c) | n <- [1..floor (sqrt $ fromIntegral p)], m <- [n+1..floor (sqrt $ fromIntegral p)], k <- [1..100], let a = (k * (m^2 - n^2)), let b = (k * (2*m*n)), let c = (k * (m^2 + n^2)), m > n, a+b+c==p, is_co_prime m n, (m-n) `mod` 2 == 1 ]
ans = maximumBy (comparing snd) $ [(p, length $ triangles2 p) | p <- [1..1000]]cabal | stefan-j/ProjectEuler | q39.hs | mit | 413 | 4 | 15 | 92 | 319 | 167 | 152 | 5 | 1 |
module ReaderPractice where
import Control.Applicative
import Data.Maybe
import Data.Monoid
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
-- from Data.List
-- lookup :: Eq a => a -> [(a,b)] -> Maybe b
--zip x and y using 3 as the lookup key
xs :: Maybe Integer
xs = lookup 3 $ zip x y
--zip y and z using 6 as the lookup key
ys :: Maybe Integer
ys = lookup 6 $ zip y z
-- it's also nice to have one that
-- will return Nothing, like this one
-- zip x and y using 4 as the lookup key
zs :: Maybe Integer
zs = lookup 4 $ zip x y
-- now zip x and z using a variable lookup key
z' :: Integer -> Maybe Integer
z' n = lookup n $ zip x z
-- tuple of xs, ys
x1 :: Maybe (Integer, Integer)
x1 = (,) <$> xs <*> ys
-- tuple of ys, zs
x2 :: Maybe (Integer, Integer)
x2 = (,) <$> ys <*> zs
x3 :: Integer -> (Maybe Integer, Maybe Integer)
x3 i = (z' i, z' i)
-- uncurry :: (a -> b -> c) -> (a, b) -> c
-- that first argument is a function
-- in this case, we want it to be addition
-- summed is just uncurry with addition as
-- the first argument
summed :: Num c => (c, c) -> c
summed = uncurry (+)
-- use &&, >3, <8
bolt :: Integer -> Bool
bolt = (&&) <$> (> 3) <*> (< 8)
main :: IO ()
main = do
print $ sequenceA [Just 3, Just 2, Just 1]
print $ sequenceA [x, y]
print $ sequenceA [xs, ys]
print $ summed <$> ((,) <$> xs <*> ys)
print $ fmap summed ((,) <$> xs <*> zs)
print $ bolt 7
print $ fmap bolt z
print $ sequenceA [(>3), (<8), even] 7
sequA :: Integral a => a -> [Bool]
sequA m = sequenceA [(>3), (<8), even] m
s' :: Maybe Integer
s' = summed <$> ((,) <$> xs <*> ys)
-- fold the boolean conjunction operator over the
-- list of results of sequaA
-- apply sequA to s'
main2 :: IO ()
main2 = do
print $ foldMap All (sequA 5)
print $ sequA (fromMaybe 0 s')
print $ bolt (fromMaybe 0 ys)
print $ bolt (fromMaybe 0 (z' 3))
| mitochon/hexercise | src/haskellbook/ch22/ch22.warmup.hs | mit | 1,853 | 0 | 12 | 453 | 702 | 379 | 323 | 45 | 1 |
-- |
-- Module : $Header$
-- Description : Definition of an abstract expression language as the first IR for the Ohua compiler.
-- Copyright : (c) Sebastian Ertel, Justus Adam 2017. All Rights Reserved.
-- License : EPL-1.0
-- Maintainer : dev@justus.science, sebastian.ertel@gmail.com
-- Stability : experimental
-- Portability : portable
-- This source code is licensed under the terms described in the associated LICENSE.TXT file
module Ohua.DAGLang.Passes where
--
-- Passes that transform a DFLang expression into a DAGLang expression.
-- The basic passes put every DFLang.SFLOW call onto a separate task.
--
| ohua-dev/ohua-core | core/src/Ohua/DAGLang/Passes.hs | epl-1.0 | 630 | 0 | 3 | 111 | 20 | 18 | 2 | 1 | 0 |
module H36 where
isPrime :: (Integral i) => i -> Bool
isPrime 1 = False
isPrime n = all (\x -> n `mod` x /= 0) [2..floor $ sqrt $ fromIntegral n]
primeFactors :: (Integral i) => i -> [i]
primeFactors n
| isPrime n = [n]
| otherwise = let f = head $ filter (\n' -> and [isPrime n', n `mod` n' == 0]) [2..n]
in
f : (primeFactors $ n `div` f)
prime_factors_mult :: (Integral i) => i -> [(i, i)]
prime_factors_mult n = groupIt $ primeFactors n
where
groupIt' n x [] = [(x, n)]
groupIt' n x (x':xs)
| x == x' = groupIt' (n+1) x xs
| otherwise = (x, n) : groupIt' 1 x' xs
groupIt [] = []
groupIt (x:xs) = groupIt' 1 x xs
| hsinhuang/codebase | h99/H36.hs | gpl-2.0 | 729 | 0 | 17 | 247 | 369 | 194 | 175 | 17 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Model.EventExplosion
( EventExplosion (..)
) where
import Data.Aeson
import GHC.Generics
import Test.QuickCheck
import Model.Event
import Model.Number
import Model.RobotInfo
data EventExplosion = EventExplosion
{ eventType :: Number
, activationTime :: Float
, robot :: RobotInfo
, hitRobot :: RobotInfo
, damage :: Float
} deriving (Show, Eq, Generic)
instance FromJSON EventExplosion
instance ToJSON EventExplosion
instance Arbitrary EventExplosion where
arbitrary = EventExplosion <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
| massimo-zaniboni/netrobots | robot_examples/haskell-servant/rest_api/lib/Model/EventExplosion.hs | gpl-3.0 | 770 | 0 | 10 | 132 | 151 | 89 | 62 | 24 | 0 |
module Types where
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
deriving Eq
-- this is better done with the 'show' type class
showVal :: LispVal -> String
showVal (Atom s) = s
showVal (String s) = "\"" ++ s ++ "\""
showVal (Number n) = show n
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList x xs) = "(" ++ unwordsList x ++ " . " ++ showVal xs ++ ")"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
-- make instance of the Show type class
instance Show LispVal where show = showVal
-- instance Eq LispVal where show = showVal
| quakehead/haskell-scheme | Types.hs | gpl-3.0 | 796 | 0 | 9 | 218 | 242 | 128 | 114 | 19 | 1 |
module Main (main) where
import Monite.Interpret
import System.Environment (getArgs)
import System.Console.Haskeline
import System.Directory
import System.FilePath
import Control.Exception (AsyncException(..))
import Control.Monad.Except ( ExceptT, runExceptT )
import Control.Monad.State.Lazy ( MonadState, StateT, evalStateT, get, modify, lift )
import Control.Monad.IO.Class ( liftIO, MonadIO )
import Control.Monad (forM, liftM)
import Data.List (isPrefixOf)
import qualified Data.Map as M
-- | Starting the shell main loop with a possible script file as argument.
main :: IO ()
main = do
args <- getArgs
env <- initEnv
case args of
-- File mode
[file] -> do
s <- readFile file -- read the script file
path <- getCurrentDirectory
run (interpret s) (Env [M.empty] path) -- interpret the script file
return ()
-- Shell mode
_ -> do
setCurrentDirectory (path env) -- defaults to $HOME
inputLoop env -- get user commands
-- | Get commands from the user
inputLoop :: Env -> IO ()
inputLoop env = do
-- Get settings
settings <- mySettings
-- Get preferences
prefs <- myPrefs
-- Run the input loop
runInputTWithPrefs prefs settings $ withInterrupt $ loop env
-- | The main loop of the program, interprets the user input.
loop :: Env -> InputT IO ()
loop env = do
let prompt = path env -- TODO: /h/d/s/directory : 2015-03-03 - 16:52:39 (John)
-- get user command
minput <- handleInterrupt (return $ Just "") (getInputLine ("λ> "))
case minput of
Nothing -> exitLoop
Just input -> if isExitCode input then exitLoop else runLoop input
where
-- exit the loop
exitLoop = return ()
-- interpert entered command, and loop
runLoop inp = do env <- withInterrupt $ liftIO $ run (interpret inp) env
loop env
-- | Run the MoniteM monad, with a given environment
run :: MoniteM a -> Env -> IO a
run m env = do
res <- runExceptT $ evalStateT (runMonite m) env
case res of
Left err -> fail $ "error"
Right a -> return a
-- | Set the history file, and the custom completion function
mySettings :: IO (Settings IO)
mySettings = do
home <- getHomeDirectory
return $ setComplete myComplete $
defaultSettings { historyFile = Just $ home ++ "/.monitehistory" }
-- | Read the end-user preferences from file
myPrefs :: IO Prefs
myPrefs = do
home <- getHomeDirectory
readPrefs (home ++ "/.moniterc") -- TODO: Document config file : 2015-03-11 - 10:14:25 (John)
-- | Check if the input is an exit code
isExitCode :: String -> Bool
isExitCode s = s `elem` ["quit", "exit", ":q"]
-- | Custom completion function for hskeline, which will consider the first word
-- on the input line as a binary, and thus, suggest completions from the users
-- $PATH in the enviroment, otherwise it will be considered as a file, and will
-- suggest completions depending on the files in the current directory of
-- moniteshell.
myComplete :: (MonadIO m) => CompletionFunc m
myComplete line@(left, right)
| isBinaryCommand left =
completeWord (Just '\\') ("\"\'" ++ filenameWordBreakChars) listBinFiles $ line
| otherwise =
completeWord (Just '\\') ("\"\'" ++ filenameWordBreakChars) listFiles $ line
-- | Check if it is a binary command, i.e., the first word on the input line,
-- which can not be followed by a white space
isBinaryCommand :: String -> Bool
isBinaryCommand [] = True
isBinaryCommand cmd = l == 1 && (not b1) && (not b2)
where rcmd = reverse cmd
b1 = last rcmd == ' '
b2 = head rcmd == '.'
l = length (words rcmd)
-------------------------------------------------------------------------------
--
-- TODO: Extend haskeline with this completion function : 2015-03-11 - 11:25:27 (John)
-- | Given the input of the first word to be completed, it will return the
-- matching completions found in the users path.
listBinFiles :: (MonadIO m) => FilePath -> m [Completion]
listBinFiles path = liftIO $ do
binPaths <- liftM (map (++ "/" ++ path)) getSearchPath -- TODO: Get path other way : 2015-03-10 - 13:03:29 (John)
comps <- mapM listBinFiles' binPaths
return (concat comps)
-- | List all of the files or folders beginning with this path.
listBinFiles' :: MonadIO m => FilePath -> m [Completion]
listBinFiles' path = liftIO $ do
fixedDir <- fixPath dir
dirExists <- doesDirectoryExist fixedDir
binFiles <- if not dirExists
then return []
else fmap (map completion . filterPrefix)
$ getDirectoryContents fixedDir
let allFiles = binFiles
-- The replacement text should include the directory part, and also
-- have a trailing slash if it's itself a directory.
forM allFiles $ \c -> do
isDir <- doesDirectoryExist (fixedDir </> replacement c)
return $ c -- setReplacement fullName $ alterIfDir isDir c
where
(dir, file) = splitFileName path
filterPrefix = filter (\f -> notElem f [".",".."]
&& file `isPrefixOf` f)
-- turn a user-visible path into an internal version useable by System.FilePath.
fixPath :: String -> IO String
-- For versions of filepath < 1.2
fixPath "" = return "."
fixPath ('~':c:path) | isPathSeparator c = do
home <- getHomeDirectory
return (home </> path)
fixPath path = return path
completion :: String -> Completion
completion str = Completion str str False
| sebiva/monite | src/Main.hs | gpl-3.0 | 5,505 | 0 | 16 | 1,296 | 1,309 | 675 | 634 | 99 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudHSM.DeleteHapg
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a high-availability partition group.
--
-- <http://docs.aws.amazon.com/cloudhsm/latest/dg/API_DeleteHapg.html>
module Network.AWS.CloudHSM.DeleteHapg
(
-- * Request
DeleteHapg
-- ** Request constructor
, deleteHapg
-- ** Request lenses
, dhHapgArn
-- * Response
, DeleteHapgResponse
-- ** Response constructor
, deleteHapgResponse
-- ** Response lenses
, dhrStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CloudHSM.Types
import qualified GHC.Exts
newtype DeleteHapg = DeleteHapg
{ _dhHapgArn :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteHapg' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dhHapgArn' @::@ 'Text'
--
deleteHapg :: Text -- ^ 'dhHapgArn'
-> DeleteHapg
deleteHapg p1 = DeleteHapg
{ _dhHapgArn = p1
}
-- | The ARN of the high-availability partition group to delete.
dhHapgArn :: Lens' DeleteHapg Text
dhHapgArn = lens _dhHapgArn (\s a -> s { _dhHapgArn = a })
newtype DeleteHapgResponse = DeleteHapgResponse
{ _dhrStatus :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteHapgResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dhrStatus' @::@ 'Text'
--
deleteHapgResponse :: Text -- ^ 'dhrStatus'
-> DeleteHapgResponse
deleteHapgResponse p1 = DeleteHapgResponse
{ _dhrStatus = p1
}
-- | The status of the action.
dhrStatus :: Lens' DeleteHapgResponse Text
dhrStatus = lens _dhrStatus (\s a -> s { _dhrStatus = a })
instance ToPath DeleteHapg where
toPath = const "/"
instance ToQuery DeleteHapg where
toQuery = const mempty
instance ToHeaders DeleteHapg
instance ToJSON DeleteHapg where
toJSON DeleteHapg{..} = object
[ "HapgArn" .= _dhHapgArn
]
instance AWSRequest DeleteHapg where
type Sv DeleteHapg = CloudHSM
type Rs DeleteHapg = DeleteHapgResponse
request = post "DeleteHapg"
response = jsonResponse
instance FromJSON DeleteHapgResponse where
parseJSON = withObject "DeleteHapgResponse" $ \o -> DeleteHapgResponse
<$> o .: "Status"
| dysinger/amazonka | amazonka-cloudhsm/gen/Network/AWS/CloudHSM/DeleteHapg.hs | mpl-2.0 | 3,258 | 0 | 9 | 765 | 449 | 272 | 177 | 56 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Books.MyLibrary.Bookshelves.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 a list of bookshelves belonging to the authenticated user.
--
-- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.mylibrary.bookshelves.list@.
module Network.Google.Resource.Books.MyLibrary.Bookshelves.List
(
-- * REST Resource
MyLibraryBookshelvesListResource
-- * Creating a Request
, myLibraryBookshelvesList
, MyLibraryBookshelvesList
-- * Request Lenses
, mlblXgafv
, mlblUploadProtocol
, mlblAccessToken
, mlblUploadType
, mlblSource
, mlblCallback
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.mylibrary.bookshelves.list@ method which the
-- 'MyLibraryBookshelvesList' request conforms to.
type MyLibraryBookshelvesListResource =
"books" :>
"v1" :>
"mylibrary" :>
"bookshelves" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "source" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Bookshelves
-- | Retrieves a list of bookshelves belonging to the authenticated user.
--
-- /See:/ 'myLibraryBookshelvesList' smart constructor.
data MyLibraryBookshelvesList =
MyLibraryBookshelvesList'
{ _mlblXgafv :: !(Maybe Xgafv)
, _mlblUploadProtocol :: !(Maybe Text)
, _mlblAccessToken :: !(Maybe Text)
, _mlblUploadType :: !(Maybe Text)
, _mlblSource :: !(Maybe Text)
, _mlblCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MyLibraryBookshelvesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mlblXgafv'
--
-- * 'mlblUploadProtocol'
--
-- * 'mlblAccessToken'
--
-- * 'mlblUploadType'
--
-- * 'mlblSource'
--
-- * 'mlblCallback'
myLibraryBookshelvesList
:: MyLibraryBookshelvesList
myLibraryBookshelvesList =
MyLibraryBookshelvesList'
{ _mlblXgafv = Nothing
, _mlblUploadProtocol = Nothing
, _mlblAccessToken = Nothing
, _mlblUploadType = Nothing
, _mlblSource = Nothing
, _mlblCallback = Nothing
}
-- | V1 error format.
mlblXgafv :: Lens' MyLibraryBookshelvesList (Maybe Xgafv)
mlblXgafv
= lens _mlblXgafv (\ s a -> s{_mlblXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
mlblUploadProtocol :: Lens' MyLibraryBookshelvesList (Maybe Text)
mlblUploadProtocol
= lens _mlblUploadProtocol
(\ s a -> s{_mlblUploadProtocol = a})
-- | OAuth access token.
mlblAccessToken :: Lens' MyLibraryBookshelvesList (Maybe Text)
mlblAccessToken
= lens _mlblAccessToken
(\ s a -> s{_mlblAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
mlblUploadType :: Lens' MyLibraryBookshelvesList (Maybe Text)
mlblUploadType
= lens _mlblUploadType
(\ s a -> s{_mlblUploadType = a})
-- | String to identify the originator of this request.
mlblSource :: Lens' MyLibraryBookshelvesList (Maybe Text)
mlblSource
= lens _mlblSource (\ s a -> s{_mlblSource = a})
-- | JSONP
mlblCallback :: Lens' MyLibraryBookshelvesList (Maybe Text)
mlblCallback
= lens _mlblCallback (\ s a -> s{_mlblCallback = a})
instance GoogleRequest MyLibraryBookshelvesList where
type Rs MyLibraryBookshelvesList = Bookshelves
type Scopes MyLibraryBookshelvesList =
'["https://www.googleapis.com/auth/books"]
requestClient MyLibraryBookshelvesList'{..}
= go _mlblXgafv _mlblUploadProtocol _mlblAccessToken
_mlblUploadType
_mlblSource
_mlblCallback
(Just AltJSON)
booksService
where go
= buildClient
(Proxy :: Proxy MyLibraryBookshelvesListResource)
mempty
| brendanhay/gogol | gogol-books/gen/Network/Google/Resource/Books/MyLibrary/Bookshelves/List.hs | mpl-2.0 | 4,850 | 0 | 18 | 1,104 | 711 | 414 | 297 | 104 | 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.ReplicaPoolUpdater.RollingUpdates.Cancel
-- 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)
--
-- Cancels an update. The update must be PAUSED before it can be cancelled.
-- This has no effect if the update is already CANCELLED.
--
-- /See:/ <https://cloud.google.com/compute/docs/instance-groups/manager/#applying_rolling_updates_using_the_updater_service Google Compute Engine Instance Group Updater API Reference> for @replicapoolupdater.rollingUpdates.cancel@.
module Network.Google.Resource.ReplicaPoolUpdater.RollingUpdates.Cancel
(
-- * REST Resource
RollingUpdatesCancelResource
-- * Creating a Request
, rollingUpdatesCancel
, RollingUpdatesCancel
-- * Request Lenses
, rucRollingUpdate
, rucProject
, rucZone
) where
import Network.Google.Prelude
import Network.Google.ReplicaPoolUpdater.Types
-- | A resource alias for @replicapoolupdater.rollingUpdates.cancel@ method which the
-- 'RollingUpdatesCancel' request conforms to.
type RollingUpdatesCancelResource =
"replicapoolupdater" :>
"v1beta1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"rollingUpdates" :>
Capture "rollingUpdate" Text :>
"cancel" :>
QueryParam "alt" AltJSON :> Post '[JSON] Operation
-- | Cancels an update. The update must be PAUSED before it can be cancelled.
-- This has no effect if the update is already CANCELLED.
--
-- /See:/ 'rollingUpdatesCancel' smart constructor.
data RollingUpdatesCancel = RollingUpdatesCancel'
{ _rucRollingUpdate :: !Text
, _rucProject :: !Text
, _rucZone :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RollingUpdatesCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rucRollingUpdate'
--
-- * 'rucProject'
--
-- * 'rucZone'
rollingUpdatesCancel
:: Text -- ^ 'rucRollingUpdate'
-> Text -- ^ 'rucProject'
-> Text -- ^ 'rucZone'
-> RollingUpdatesCancel
rollingUpdatesCancel pRucRollingUpdate_ pRucProject_ pRucZone_ =
RollingUpdatesCancel'
{ _rucRollingUpdate = pRucRollingUpdate_
, _rucProject = pRucProject_
, _rucZone = pRucZone_
}
-- | The name of the update.
rucRollingUpdate :: Lens' RollingUpdatesCancel Text
rucRollingUpdate
= lens _rucRollingUpdate
(\ s a -> s{_rucRollingUpdate = a})
-- | The Google Developers Console project name.
rucProject :: Lens' RollingUpdatesCancel Text
rucProject
= lens _rucProject (\ s a -> s{_rucProject = a})
-- | The name of the zone in which the update\'s target resides.
rucZone :: Lens' RollingUpdatesCancel Text
rucZone = lens _rucZone (\ s a -> s{_rucZone = a})
instance GoogleRequest RollingUpdatesCancel where
type Rs RollingUpdatesCancel = Operation
type Scopes RollingUpdatesCancel =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/replicapool"]
requestClient RollingUpdatesCancel'{..}
= go _rucProject _rucZone _rucRollingUpdate
(Just AltJSON)
replicaPoolUpdaterService
where go
= buildClient
(Proxy :: Proxy RollingUpdatesCancelResource)
mempty
| rueshyna/gogol | gogol-replicapool-updater/gen/Network/Google/Resource/ReplicaPoolUpdater/RollingUpdates/Cancel.hs | mpl-2.0 | 4,146 | 0 | 17 | 957 | 469 | 280 | 189 | 76 | 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.Blogger.Posts.Revert
-- 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)
--
-- Reverts a published or scheduled post to draft state.
--
-- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.posts.revert@.
module Network.Google.Resource.Blogger.Posts.Revert
(
-- * REST Resource
PostsRevertResource
-- * Creating a Request
, postsRevert
, PostsRevert
-- * Request Lenses
, prXgafv
, prUploadProtocol
, prAccessToken
, prUploadType
, prBlogId
, prPostId
, prCallback
) where
import Network.Google.Blogger.Types
import Network.Google.Prelude
-- | A resource alias for @blogger.posts.revert@ method which the
-- 'PostsRevert' request conforms to.
type PostsRevertResource =
"v3" :>
"blogs" :>
Capture "blogId" Text :>
"posts" :>
Capture "postId" Text :>
"revert" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Post'
-- | Reverts a published or scheduled post to draft state.
--
-- /See:/ 'postsRevert' smart constructor.
data PostsRevert =
PostsRevert'
{ _prXgafv :: !(Maybe Xgafv)
, _prUploadProtocol :: !(Maybe Text)
, _prAccessToken :: !(Maybe Text)
, _prUploadType :: !(Maybe Text)
, _prBlogId :: !Text
, _prPostId :: !Text
, _prCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PostsRevert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'prXgafv'
--
-- * 'prUploadProtocol'
--
-- * 'prAccessToken'
--
-- * 'prUploadType'
--
-- * 'prBlogId'
--
-- * 'prPostId'
--
-- * 'prCallback'
postsRevert
:: Text -- ^ 'prBlogId'
-> Text -- ^ 'prPostId'
-> PostsRevert
postsRevert pPrBlogId_ pPrPostId_ =
PostsRevert'
{ _prXgafv = Nothing
, _prUploadProtocol = Nothing
, _prAccessToken = Nothing
, _prUploadType = Nothing
, _prBlogId = pPrBlogId_
, _prPostId = pPrPostId_
, _prCallback = Nothing
}
-- | V1 error format.
prXgafv :: Lens' PostsRevert (Maybe Xgafv)
prXgafv = lens _prXgafv (\ s a -> s{_prXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
prUploadProtocol :: Lens' PostsRevert (Maybe Text)
prUploadProtocol
= lens _prUploadProtocol
(\ s a -> s{_prUploadProtocol = a})
-- | OAuth access token.
prAccessToken :: Lens' PostsRevert (Maybe Text)
prAccessToken
= lens _prAccessToken
(\ s a -> s{_prAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
prUploadType :: Lens' PostsRevert (Maybe Text)
prUploadType
= lens _prUploadType (\ s a -> s{_prUploadType = a})
prBlogId :: Lens' PostsRevert Text
prBlogId = lens _prBlogId (\ s a -> s{_prBlogId = a})
prPostId :: Lens' PostsRevert Text
prPostId = lens _prPostId (\ s a -> s{_prPostId = a})
-- | JSONP
prCallback :: Lens' PostsRevert (Maybe Text)
prCallback
= lens _prCallback (\ s a -> s{_prCallback = a})
instance GoogleRequest PostsRevert where
type Rs PostsRevert = Post'
type Scopes PostsRevert =
'["https://www.googleapis.com/auth/blogger"]
requestClient PostsRevert'{..}
= go _prBlogId _prPostId _prXgafv _prUploadProtocol
_prAccessToken
_prUploadType
_prCallback
(Just AltJSON)
bloggerService
where go
= buildClient (Proxy :: Proxy PostsRevertResource)
mempty
| brendanhay/gogol | gogol-blogger/gen/Network/Google/Resource/Blogger/Posts/Revert.hs | mpl-2.0 | 4,556 | 0 | 19 | 1,154 | 779 | 452 | 327 | 110 | 1 |
import Control.Applicative ((<$>))
import Control.Monad (forM_)
import Data.Aeson (eitherDecode)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy.Char8 as BLC
import qualified Data.Yaml as Y
import System.Environment (getArgs)
import System.Exit (exitFailure)
helpMessage :: IO ()
helpMessage = putStrLn "Usage: json2yaml <FILE> [<FILE> ..]\nFor stdin input, use - as FILE" >> exitFailure
printYAML :: Show a => Either a Y.Value -> IO B.ByteString
printYAML x = case x of
Left err -> print err >> exitFailure
Right v -> return $ Y.encode (v :: Y.Value)
main :: IO ()
main = do
args <- getArgs
case args of
[] -> helpMessage
_ ->
forM_ args $ \arg ->
case arg of
"-" -> B.getContents >>= printYAML . Y.decodeEither' >>= B.putStr
_ -> eitherDecode <$> BLC.readFile arg >>= printYAML >>= B.writeFile (arg ++ ".yaml")
| rayqiu/jsonyaml | src/json2yaml.hs | apache-2.0 | 1,031 | 0 | 19 | 321 | 301 | 160 | 141 | 24 | 3 |
module PolygonSizes.A328787 (a328787) where
import Data.Set (size)
import Helpers.PolygonSizes (triangleSizes)
a328787_list :: [Int]
a328787_list = map size triangleSizes
a328787 :: Int -> Int
a328787 n = a328787_list !! (n - 2)
| peterokagey/haskellOEIS | src/PolygonSizes/A328787.hs | apache-2.0 | 231 | 0 | 7 | 33 | 77 | 44 | 33 | 7 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
import Criterion.Main
import System.Environment
import LogicGrowsOnTrees
import LogicGrowsOnTrees.Checkpoint
import LogicGrowsOnTrees.Utils.PerfectTree (trivialPerfectTree)
import LogicGrowsOnTrees.Utils.WordSum
import qualified LogicGrowsOnTrees.Parallel.Adapter.Threads as Threads
import LogicGrowsOnTrees.Parallel.Adapter.Threads (setNumberOfWorkers)
import LogicGrowsOnTrees.Parallel.Common.Worker (exploreTreeGeneric)
import LogicGrowsOnTrees.Parallel.ExplorationMode (ExplorationMode(AllMode))
import LogicGrowsOnTrees.Parallel.Main
import LogicGrowsOnTrees.Parallel.Purity (Purity(Pure))
main :: IO ()
main = defaultMain
[bench "list" $ nf (getWordSum . mconcat . trivialPerfectTree 2) depth
,bench "tree" $ nf (getWordSum . exploreTree . trivialPerfectTree 2) depth
,bench "tree w/ checkpointing" $
nf (getWordSum . exploreTreeStartingFromCheckpoint Unexplored . trivialPerfectTree 2) depth
,bench "tree using worker" $ nfIO $
exploreTreeGeneric AllMode Pure (trivialPerfectTree 2 depth)
,bench "tree using single thread (direct)" $ nfIO $
Threads.exploreTree (setNumberOfWorkers 1) (trivialPerfectTree 2 depth)
,bench "tree using single thread (main)" $ nfIO $
withArgs ["-n1"] $
simpleMainForExploreTree
Threads.driver
mempty
(const $ return ())
(trivialPerfectTree 2 depth)
]
where depth = 15
| gcross/LogicGrowsOnTrees | LogicGrowsOnTrees/benchmarks/tree-versus-list-trivial-tree.hs | bsd-2-clause | 1,479 | 0 | 12 | 278 | 341 | 185 | 156 | 31 | 1 |
{-# LANGUAGE Haskell2010 #-}
module Visible where
visible :: Int -> Int
visible a = a
| haskell/haddock | html-test/src/Visible.hs | bsd-2-clause | 86 | 0 | 5 | 16 | 22 | 13 | 9 | 4 | 1 |
{-# LANGUAGE Haskell2010 #-}
-- Just like Bug308 module but here we test that referring to anchors
-- from other modules works.
module Bug308CrossModule where
import Bug308
{-|
start "Bug308#startAnchor"
startOldStyle "Bug308\#startAnchor"
middle "Bug308#middleAnchor"
end "Bug308#middleAnchor"
-}
h :: ()
h = ()
| haskell/haddock | html-test/src/Bug308CrossModule.hs | bsd-2-clause | 318 | 0 | 5 | 48 | 25 | 17 | 8 | 5 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : dave.laing.80@gmail.com
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Fragment.TmApp.Ast.Term (
TmFApp
, AsTmApp(..)
) where
import Data.Functor.Classes (showsBinaryWith)
import Bound (Bound(..))
import Control.Lens.Prism (Prism')
import Control.Lens.Wrapped (_Wrapped, _Unwrapped)
import Control.Lens.TH (makePrisms)
import Data.Deriving (deriveEq1, deriveOrd1, deriveShow1)
import Ast.Term
import Data.Bitransversable
import Data.Functor.Rec
import Util.Prisms
data TmFApp (ki :: (* -> *) -> * -> *) (ty :: ((* -> *) -> * -> *) -> (* -> *) -> * -> *) (pt :: (* -> *) -> * -> *) k a =
TmAppF (k a) (k a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
makePrisms ''TmFApp
deriveEq1 ''TmFApp
deriveOrd1 ''TmFApp
deriveShow1 ''TmFApp
instance EqRec (TmFApp ki ty pt) where
liftEqRec eR _ (TmAppF x1 y1) (TmAppF x2 y2) =
eR x1 x2 && eR y1 y2
instance OrdRec (TmFApp ki ty pt) where
liftCompareRec cR _ (TmAppF x1 y1) (TmAppF x2 y2) =
case cR x1 x2 of
EQ -> cR y1 y2
z -> z
instance ShowRec (TmFApp ki ty pt) where
liftShowsPrecRec sR _ _ _ n (TmAppF x y) =
showsBinaryWith sR sR "TmAppF" n x y
instance Bound (TmFApp ki ty pt) where
TmAppF x y >>>= f = TmAppF (x >>= f) (y >>= f)
instance Bitransversable (TmFApp ki ty pt) where
bitransverse fT fL (TmAppF x y) = TmAppF <$> fT fL x <*> fT fL y
class (TmAstBound ki ty pt tm, TmAstTransversable ki ty pt tm) => AsTmApp ki ty pt tm where
_TmAppP :: Prism' (tm ki ty pt f a) (TmFApp ki ty pt f a)
_TmApp :: Prism' (Term ki ty pt tm a) (Term ki ty pt tm a, Term ki ty pt tm a)
_TmApp = _Wrapped . _TmAstTerm . _TmAppP . _TmAppF . mkPair _Unwrapped _Unwrapped
instance (Bound ki, Bound (ty ki), Bound pt, Bitransversable ki, Bitransversable (ty ki), Bitransversable pt) => AsTmApp ki ty pt TmFApp where
_TmAppP = id
instance {-# OVERLAPPABLE #-} (Bound (x ki ty pt), Bitransversable (x ki ty pt), AsTmApp ki ty pt (TmSum xs)) => AsTmApp ki ty pt (TmSum (x ': xs)) where
_TmAppP = _TmNext . _TmAppP
instance {-# OVERLAPPING #-} (Bound ki, Bound (ty ki), Bound pt, Bound (TmSum xs ki ty pt), Bitransversable ki, Bitransversable (ty ki), Bitransversable pt, Bitransversable (TmSum xs ki ty pt)) => AsTmApp ki ty pt (TmSum (TmFApp ': xs)) where
_TmAppP = _TmNow . _TmAppP
| dalaing/type-systems | src/Fragment/TmApp/Ast/Term.hs | bsd-3-clause | 2,713 | 0 | 10 | 533 | 1,047 | 552 | 495 | 55 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -Wall #-}
-- | An interface to bitcoind's available raw transaction-related RPC calls.
-- The implementation of these functions can be found at
-- <https://github.com/bitcoin/bitcoin/blob/master/src/rpcrawtransaction.cpp>.
--
-- If any APIs are missing, patches are always welcome. If you look at the
-- source of this module, you'll see that the interface code is trivial.
--
-- Also, documentation for this module is scarce. I would love the addition
-- of more documentation by anyone who knows what these things are.
module Network.Bitcoin.RawTransaction ( Client
, getClient
, RawTransaction
, getRawTransaction
, TxIn(..)
, TxnOutputType(..)
, ScriptPubKey(..)
, ScriptSig(..)
, TxOut(..)
, BlockInfo(..)
, RawTransactionInfo(..)
, getRawTransactionInfo
, UnspentTransaction(..)
, listUnspent
, createRawTransaction
, DecodedRawTransaction(..)
, decodeRawTransaction
, WhoCanPay(..)
, RawSignedTransaction(..)
, signRawTransaction
, sendRawTransaction
) where
import Control.Applicative
import Control.Monad
import Data.Aeson as A
import Data.Aeson.Types as AT
import Data.Maybe
import qualified Data.Vector as V
import Network.Bitcoin.Internal
-- | Just like most binary data retrieved from bitcoind, a raw transaction is
-- represented by a hexstring.
--
-- This is a serialized, hex-encoded transaction.
type RawTransaction = HexString
-- | Get a raw transaction from its unique ID.
getRawTransaction :: Client -> TransactionID -> IO RawTransaction
getRawTransaction client txid =
callApi client "getrawtransaction" [ tj txid, tj verbose ]
where verbose = 0 :: Int
-- | A transaction into an account. This can either be a coinbase transaction,
-- or a standard transaction with another account.
data TxIn = TxCoinbase { txCoinbase :: HexString
}
| TxIn { -- | This transaction's ID.
txInId :: TransactionID
, numOut :: Integer
, scriptSig :: ScriptSig
-- | A transaction sequence number.
, txSequence :: Integer
}
deriving ( Show, Read, Ord, Eq )
instance FromJSON TxIn where
parseJSON (Object o) = parseCB <|> parseTxIn
where
parseCB = TxCoinbase <$> o .: "coinbase"
parseTxIn = TxIn <$> o .: "txid"
<*> o .: "vout"
<*> o .: "scriptSig"
<*> o .: "sequence"
parseJSON _ = mzero
-- | The type of a transaction out.
--
-- More documentation is needed here. Submit a patch if you know what this is
-- about!
data TxnOutputType = TxnPubKey -- ^ JSON of "pubkey" received.
| TxnPubKeyHash -- ^ JSON of "pubkeyhash" received.
| TxnScriptHash -- ^ JSON of "scripthash" received.
| TxnMultisig -- ^ JSON of "multisig" received.
deriving ( Show, Read, Ord, Eq )
instance FromJSON TxnOutputType where
parseJSON (A.String s) | s == "pubkey" = return TxnPubKey
| s == "pubkeyhash" = return TxnPubKeyHash
| s == "scripthash" = return TxnScriptHash
| s == "multisig" = return TxnMultisig
| otherwise = mzero
parseJSON _ = mzero
-- | A transaction out of an account.
data TxOut =
TxOut { -- | The amount of bitcoin transferred out.
txoutVal :: BTC
-- | The public key of the account we sent the money to.
, scriptPubKey :: ScriptPubKey
}
deriving ( Show, Read, Ord, Eq )
instance FromJSON TxOut where
parseJSON (Object o) = TxOut <$> o .: "value"
<*> o .: "scriptPubKey"
parseJSON _ = mzero
-- * Scripts
-- A script is a complex bitcoin construct that provides the creation
-- of Contracts.
-- See <https://en.bitcoin.it/wiki/Script> and <https://en.bitcoin.it/wiki/Contracts>.
-- It consists of two parts - a public key and a signature.
-- | A public key of someone we sent money to.
data ScriptPubKey = NonStandardScriptPubKey { -- | The JSON "asm" field.
nspkAsm :: HexString
-- | The JSON "hex" field.
, nspkHex :: HexString
}
| StandardScriptPubKey { -- | The JSON "asm" field.
sspkAsm :: HexString
-- | The JSON "hex" field.
, sspkHex :: HexString
-- | The number of required signatures.
, requiredSigs :: Integer
-- | The type of the transaction.
, sspkType :: TxnOutputType
-- | The addresses associated with this key.
, sspkAddresses :: Vector Address
}
deriving ( Show, Read, Ord, Eq )
instance FromJSON ScriptPubKey where
parseJSON (Object o) = parseStandard <|> parseNonstandard
where
parseStandard = StandardScriptPubKey <$> o .: "asm"
<*> o .: "hex"
<*> o .: "reqSigs"
<*> o .: "type"
<*> o .: "addresses"
parseNonstandard = NonStandardScriptPubKey <$> o .: "asm"
<*> o .: "hex"
parseJSON _ = mzero
-- | A script signature.
data ScriptSig = ScriptSig { sigAsm :: HexString
, sigHex :: HexString
}
deriving ( Show, Read, Ord, Eq )
instance FromJSON ScriptSig where
parseJSON (Object o) = ScriptSig <$> o .: "asm"
<*> o .: "hex"
parseJSON _ = mzero
-- | Information on a single block.
data BlockInfo = ConfirmedBlock { -- | The number of confirmations a block has.
-- This will always be >= 1.
confirmations :: Integer
-- The JSON "time" field".
, cbTime :: Integer
-- | The JSON "blocktime" field.
, blockTime :: Integer
}
| UnconfirmedBlock
-- ^ An unconfirmed block is boring, but a possibility.
deriving ( Show, Read, Ord, Eq )
instance FromJSON BlockInfo where
parseJSON (Object o) = parseConfirmed <|> parseUnconfirmed
where
parseConfirmed = ConfirmedBlock <$> o .: "confirmations"
<*> o .: "time"
<*> o .: "blocktime"
parseUnconfirmed = do c <- o .: "confirmations" :: AT.Parser Integer
guard $ c == 0
return UnconfirmedBlock
parseJSON _ = mzero
-- | The raw transaction info for a given transaction ID.
data RawTransactionInfo =
RawTransactionInfo { -- | The raw transaction.
raw :: RawTransaction
-- | The transaction version number.
, txnVersion :: Integer
, txnLockTime :: Integer
-- | The vector of transactions in.
, vin :: Vector TxIn
-- | The vector of transactions out.
, vout :: Vector TxOut
-- | The hash of the block that was used for this
-- transaction.
, rawTxBlockHash :: HexString
-- | The transaction's block's info.
, rawBlockInfo :: BlockInfo
}
deriving ( Show, Read, Ord, Eq )
instance FromJSON RawTransactionInfo where
parseJSON v@(Object o) = RawTransactionInfo <$> o .: "hex"
<*> o .: "version"
<*> o .: "locktime"
<*> o .: "vin"
<*> o .: "vout"
<*> o .: "blockhash"
<*> parseJSON v
parseJSON _ = mzero
-- | Get raw transaction info for a given transaction ID. The data structure
-- returned is quite sprawling and undocumented, so any patches to help
-- simplify things would be greatly appreciated.
getRawTransactionInfo :: Client -> TransactionID -> IO RawTransactionInfo
getRawTransactionInfo client txid =
callApi client "getrawtransaction" [ tj txid, tj verbose ]
where verbose = 1 :: Int
data UnspentTransaction =
UnspentTransaction { unspentTransactionId :: TransactionID
, outIdx :: Integer
, unspentAddress :: Address
, unspentScriptPubKey :: HexString
, redeemScript :: Maybe HexString
, unspentAmount :: BTC
, usConfirmations :: Integer
} deriving ( Show, Eq )
instance FromJSON UnspentTransaction where
parseJSON (Object o) = UnspentTransaction <$> o .: "txid"
<*> o .: "vout"
<*> o .: "address"
<*> o .: "scriptPubKey"
<*> o .:? "redeemScript"
<*> o .: "amount"
<*> o .: "confirmations"
parseJSON _ = mzero
-- Instance used in 'createRawTransaction'.
instance ToJSON UnspentTransaction where
toJSON (UnspentTransaction{..}) = object [ "txid" .= unspentTransactionId
, "vout" .= outIdx
]
-- | Returns an array of unspent transaction outputs with between minconf and
-- maxconf (inclusive) confirmations. If addresses are given, the result will
-- be filtered to include only those addresses.
listUnspent :: Client
-> Maybe Int -- ^ minconf. Defaults to 1 if 'Nothing'.
-> Maybe Int -- ^ maxconf. Defaults to 9999999 if 'Nothing'.
-> Vector Address -- ^ Use 'Data.Vector.empty' for no filtering.
-> IO (Vector UnspentTransaction)
listUnspent client mmin mmax vaddrs =
let min' = fromMaybe 1 mmin
max' = fromMaybe 9999999 mmax
in callApi client "listunspent" [ tj min', tj max', tj vaddrs ]
-- | Create a transaction spending given inputs, sending to given addresses.
--
-- Note that the transaction's inputs are not signed, and it is not stored
-- in the wallet or transmitted to the network.
--
-- Also, there is no checking to see if it's possible to send that much to
-- the targets specified. In the future, such a scenario might throw an
-- exception.
createRawTransaction :: Client
-> Vector UnspentTransaction
-- ^ The unspent transactions we'll be using as our output.
-> Vector (Address, BTC)
-- ^ The addresses we're sending money to, along with how
-- much each of them gets.
-> IO HexString
createRawTransaction client us tgts =
callApi client "createrawtransaction" [ tj us, tj $ AA tgts ]
-- | A successfully decoded raw transaction, from a given serialized,
-- hex-encoded transaction.
data DecodedRawTransaction =
DecodedRawTransaction { -- | The raw transaction.
decRaw :: RawTransaction
-- | The transaction version number.
, decTxnVersion :: Integer
, decTxnLockTime :: Integer
-- | The vector of transactions in.
, decVin :: Vector TxIn
-- | The vector of transactions out.
, decVout :: Vector TxOut
}
instance FromJSON DecodedRawTransaction where
parseJSON (Object o) = DecodedRawTransaction <$> o .: "hex"
<*> o .: "version"
<*> o .: "locktime"
<*> o .: "vin"
<*> o .: "vout"
parseJSON _ = mzero
-- | Decodes a raw transaction into a more accessible data structure.
decodeRawTransaction :: Client -> RawTransaction -> IO DecodedRawTransaction
decodeRawTransaction client tx = callApi client "decoderawtransaction" [ tj tx ]
-- | Used internally to give a new 'ToJSON' instance for 'UnspentTransaction'.
newtype UnspentForSigning = UFS UnspentTransaction
instance ToJSON UnspentForSigning where
toJSON (UFS (UnspentTransaction{..}))
| isNothing redeemScript =
object [ "txid" .= unspentTransactionId
, "vout" .= outIdx
, "scriptPubKey" .= unspentScriptPubKey
]
| otherwise =
object [ "txid" .= unspentTransactionId
, "vout" .= outIdx
, "scriptPubKey" .= unspentScriptPubKey
, "redeemScript" .= fromJust redeemScript
]
-- | Who can pay for a given transaction.
data WhoCanPay = All
| AllOrAnyoneCanPay
| None
| NoneOrAnyoneCanPay
| Single
| SingleOrAnyoneCanPay
toString :: WhoCanPay -> Text
toString All = "ALL"
toString AllOrAnyoneCanPay = "ALL|ANYONECANPAY"
toString None = "NONE"
toString NoneOrAnyoneCanPay = "NONE|ANYONECANPAY"
toString Single = "SINGLE"
toString SingleOrAnyoneCanPay = "SINGLE|ANYONECANPAY"
-- | A raw signed transaction contains the raw, signed hexstring and whether or
-- not this transaction has a complete signature set.
data RawSignedTransaction =
RawSignedTransaction { rawSigned :: HexString
, hasCompleteSigSet :: Bool
}
instance FromJSON RawSignedTransaction where
parseJSON (Object o) = RawSignedTransaction <$> o .: "hex"
<*> o .: "complete"
parseJSON _ = mzero
-- | Sign inputs for a raw transaction.
signRawTransaction :: Client
-> RawTransaction
-- ^ The raw transaction whose inputs we're signing.
-> Maybe (Vector UnspentTransaction)
-- ^ An optional list of previous transaction outputs that
-- this transaction depends on but may not yet be in the
-- block chain.
-> Maybe (Vector HexString)
-- ^ An array of base58-encoded private keys that, if given,
-- will be the only keys used to sign the transaction.
-> Maybe WhoCanPay
-- ^ Who can pay for this transaction? 'All' by default.
-> IO RawSignedTransaction
-- ^ Returns 'Nothing' if the transaction has a complete set
-- of signatures, and the raw signed transa
signRawTransaction client rt us' privkeys wcp =
let us = V.map UFS <$> us' :: Maybe (Vector UnspentForSigning)
in callApi client "signrawtransaction" [ tj rt
, tj us
, tj privkeys
, tj . toString $ fromMaybe All wcp
]
sendRawTransaction :: Client -> RawTransaction -> IO TransactionID
sendRawTransaction client rt = callApi client "sendrawtransaction" [ tj rt ]
| cgaebel/network-bitcoin | src/Network/Bitcoin/RawTransaction.hs | bsd-3-clause | 17,379 | 0 | 19 | 7,573 | 2,291 | 1,273 | 1,018 | 235 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
-- |
-- Additional data types
module Data.Protobuf.Internal.Types (
-- * Double map
DMap
, emptyDMap
, fromL2Map
, lookupDMap
, lookupDMap2
, insertDMapM
, insertDMap2
) where
import Data.Data (Typeable,Data)
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Foldable as F
import qualified Data.Traversable as T
----------------------------------------------------------------
-- Double map
----------------------------------------------------------------
-- | Map which maps first set of key to second one. This is needed
-- either to preserve sharing or when first set of keys could be
-- larger than second and wee want to avoid keeping duplicates.
data DMap k1 k2 v = DMap (Map k1 k2) (Map k2 v)
deriving (Typeable,Data,Functor,F.Foldable,T.Traversable)
-- | Empty map
emptyDMap :: DMap k1 k2 v
emptyDMap = DMap Map.empty Map.empty
fromL2Map :: (Ord k1, Ord k2) => Map k2 v -> DMap k1 k2 v
fromL2Map m2 = DMap Map.empty m2
-- | Lookup value in the map.
lookupDMap :: (Ord k1, Ord k2) => k1 -> DMap k1 k2 v -> Maybe v
lookupDMap k1 (DMap m1 m2) =
case k1 `Map.lookup` m1 of
Nothing -> Nothing
Just k2 -> case k2 `Map.lookup` m2 of
Nothing -> error "Internal error in Data.Protobuf.Types.DMap"
r -> r
lookupDMap2 :: (Ord k2) => k2 -> DMap k1 k2 v -> Maybe v
lookupDMap2 k2 (DMap _ m2) =
k2 `Map.lookup` m2
-- | Insert value into double map using monadic action.
insertDMapM :: (Ord k1, Ord k2, Monad m)
=> (k1 -> m k2) -- ^ Mapping from first key to second
-> (k2 -> m v) -- ^ Mapping from second key to value
-> k1 -- ^ Key to insert
-> DMap k1 k2 v
-> m (Maybe v,DMap k1 k2 v)
insertDMapM fKey fVal k1 m@(DMap m1 m2)
| k1 `Map.member` m1 = return (Nothing,m)
| otherwise = do
k2 <- fKey k1
if k2 `Map.member` m2
then return (Nothing, DMap (Map.insert k1 k2 m1) m2)
else do v <- fVal k2
return ( Just v
, DMap (Map.insert k1 k2 m1)
(Map.insert k2 v m2)
)
insertDMap2 :: (Ord k2) => k2 -> v -> DMap k1 k2 v -> DMap k1 k2 v
insertDMap2 k v (DMap m1 m2) = DMap m1 $ Map.insert k v m2
| Shimuuar/protobuf | Data/Protobuf/Internal/Types.hs | bsd-3-clause | 2,528 | 0 | 16 | 772 | 729 | 390 | 339 | 51 | 3 |
-- | HUnit expriments
-- tutoralial located at: <https://leiffrenzel.de/papers/getting-started-with-hunit.html>
module FindIdentifier_Test where
import FindIdentifier (findIdentifier)
import Test.HUnit
borderCases = TestLabel "Border test cases" (TestList [ testEmpty, testNegCursor, testComment ])
testEmpty = TestCase $ assertEqual
"Should get Nothing from an empty string" Nothing ( findIdentifier "" (1, 1) )
testNegCursor = TestCase $ assertEqual
"Should get Nothing whe cursor is negative" Nothing (findIdentifier "a" (-1,-1))
testComment = TestCase $ assertEqual
"Should get Nothing on Comment" Nothing (findIdentifier "-- a" (1, 3))
simpleCases = TestLabel "Simple, but serious cases" (TestList [ testMinimal, testData ])
testMinimal = TestCase $ assertEqual
"Minimal program" (Just "main") (findIdentifier "main = print 42" (1,2))
testData = TestCase $ assertEqual
"Data declarations"
(Just "Bli")
(findIdentifier "main = print 42\ndata Bli | Blubb" (2,7))
main = runTestTT $ TestList [ borderCases, simpleCases ]
| emaphis/Haskell-Practice | testing-project/test/FindIdentifier_Test.hs | bsd-3-clause | 1,051 | 0 | 10 | 162 | 250 | 137 | 113 | 18 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Foundation where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings.Development (development)
import Settings.StaticFiles
import Settings (widgetFile, Extra (..))
import Text.Jasmine (minifym)
import Text.Hamlet (hamletFile)
import Yesod.Core.Types (Logger)
import Yesod.MangoPay
import Web.MangoPay
import Data.IORef (IORef)
import Yesod.Form.Jquery (YesodJquery)
import Network.Wai (pathInfo,Request)
import Data.Text as T (Text)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, httpManager :: Manager
, appLogger :: Logger
, appToken :: IORef (Maybe MangoPayToken) -- ^ the currently valid access token, if any
, appEvents :: IORef [Event] -- ^ the received events, for the moment stored into a list
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- | use relative links unless if to register hook or for card registration
-- this is useful when developing since the external address may not be the local address
approotRequest :: App -> Request -> Text
approotRequest master request
| pathInfo request==["runFakeHandler", "pathInfo"] = appRoot $ settings master
| (not $ null $ pathInfo request) && (head (pathInfo request) == "card") = appRoot $ settings master
| otherwise= ""
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootRequest approotRequest
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = fmap Just $ defaultClientSessionBackend
(120 * 60) -- 120 minutes
"config/client_session_key.aes"
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_normalize_css
, css_bootstrap_css
])
$(widgetFile "default-layout")
giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent =
addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute [])
where
-- Generate a unique filename based on the content itself
genFileName lbs
| development = "autogen-" ++ base64md5 lbs
| otherwise = base64md5 lbs
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. Since this is a test app, log everything.
shouldLog _ _ _ = True
makeLogger = return . appLogger
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- | use JQuery form widgets
instance YesodJquery App
-- | MangoPay support
instance YesodMangoPay App where
mpCredentials app=let
extra=appExtra $ settings app
in Credentials (mpID extra) (mpName extra) (mpEmail extra) (Just $ mpSecret extra)
mpHttpManager=httpManager
mpUseSandbox=mpSandbox . appExtra . settings
mpToken=appToken
-- | show an error page on a mangopay error
catchW :: (Yesod site, RenderMessage site AppMessage) =>
HandlerT site IO Html -> HandlerT site IO Html
catchW a=catchMP a (\e->
defaultLayout $ do
$(logError) "in error handler"
let exception=show e
setTitleI MsgRequestFail
$(widgetFile "request_fail"))
| prowdsponsor/mangopay | yesod-mangopay/app/Foundation.hs | bsd-3-clause | 6,597 | 0 | 15 | 1,398 | 977 | 533 | 444 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
module SymbolicDifferentiation.SExp where
import SymbolicDifferentiation.AlphaSyntax (Exp(N, V, Plus, Times))
import qualified Data.SCargot as S
import Data.SCargot.Language.Basic (basicParser)
import Data.SCargot.Repr.WellFormed
(WellFormedSExpr(WFSList, WFSAtom), fromWellFormed)
import qualified Data.Text as Text
import Data.Text (Text)
import Data.Text.Read (signed, decimal)
import Data.String.Here (i)
-- | Error when parsing.
type Error = String
-- | For simplicity, we use 'basicParser' which just treats every atom
-- as 'Text', which we parse later rather than up front.
parse :: Text -> Either Error Exp
parse text = parseOneSexp text >>= toExp
parseOneSexp :: Text -> Either Error (WellFormedSExpr Text)
parseOneSexp = S.decodeOne (S.asWellFormed basicParser)
toExp :: WellFormedSExpr Text -> Either Error Exp
toExp (WFSAtom text) = fromAtom text
toExp (WFSList [WFSAtom operatorText, sexp1, sexp2]) = do
operator <- fromOperator operatorText
e1 <- toExp sexp1
e2 <- toExp sexp2
return (operator e1 e2)
toExp list@(WFSList _) = Left [i|${list} should have exactly 3 elements|]
fromOperator :: Text -> Either Error (Exp -> Exp -> Exp)
fromOperator "+" = return Plus
fromOperator "*" = return Times
fromOperator text = Left [i|${text} is not a valid operator|]
-- | Either an integer or a variable.
fromAtom :: Text -> Either Error Exp
fromAtom text =
case signed decimal text of
Right (n, "") ->
return (N n)
Right (_, _) ->
Left [i|extra garbage after numeric in ${text}|]
Left _ ->
return (V (Text.unpack text))
fromExp :: Exp -> WellFormedSExpr Text
fromExp (N n) = WFSAtom (Text.pack (show n))
fromExp (V x) = WFSAtom (Text.pack x)
fromExp (Plus e1 e2) = WFSList [WFSAtom "+", fromExp e1, fromExp e2]
fromExp (Times e1 e2) = WFSList [WFSAtom "*", fromExp e1, fromExp e2]
prettyPrint :: Exp -> Text
prettyPrint =
S.encodeOne (S.setFromCarrier fromWellFormed (S.basicPrint id))
. fromExp
| FranklinChen/twenty-four-days2015-of-hackage | src/SymbolicDifferentiation/SExp.hs | bsd-3-clause | 2,030 | 0 | 13 | 355 | 665 | 355 | 310 | 47 | 3 |
module Problem89 where
import Data.List
import Data.Maybe
main :: IO ()
main = readFile "txt/89.txt" >>= print . sum . map characterSaved . lines
characterSaved :: String -> Int
characterSaved x = length x - length (write . value $ x)
where
value [] = 0
value xs =
(\(pre, val) -> val + value (fromJust $ stripPrefix pre xs))
. head
. filter (flip isPrefixOf xs . fst)
$ romanSymbolValues
write 0 = ""
write n =
(\(pre, val) -> pre ++ write (n - val))
. head
. filter ((<= n) . snd)
$ romanSymbolValues
romanSymbolValues =
[ ("M" , 1000)
, ("CM", 900)
, ("D" , 500)
, ("CD", 400)
, ("C" , 100)
, ("XC", 90)
, ("L" , 50)
, ("XL", 40)
, ("X" , 10)
, ("IX", 9)
, ("V" , 5)
, ("IV", 4)
, ("I" , 1)
]
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem89.hs | bsd-3-clause | 921 | 0 | 16 | 371 | 361 | 206 | 155 | 33 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
HsImpExp: Abstract syntax: imports, exports, interfaces
-}
{-# LANGUAGE DeriveDataTypeable #-}
module HsImpExp where
import Module ( ModuleName )
import HsDoc ( HsDocString )
import OccName ( HasOccName(..), isTcOcc, isSymOcc )
import BasicTypes ( SourceText, StringLiteral(..) )
import FieldLabel ( FieldLbl(..) )
import Outputable
import FastString
import SrcLoc
import Data.Data
{-
************************************************************************
* *
\subsection{Import and export declaration lists}
* *
************************************************************************
One per \tr{import} declaration in a module.
-}
type LImportDecl name = Located (ImportDecl name)
-- ^ When in a list this may have
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi'
-- For details on above see note [Api annotations] in ApiAnnotation
-- | A single Haskell @import@ declaration.
data ImportDecl name
= ImportDecl {
ideclSourceSrc :: Maybe SourceText,
-- Note [Pragma source text] in BasicTypes
ideclName :: Located ModuleName, -- ^ Module name.
ideclPkgQual :: Maybe StringLiteral, -- ^ Package qualifier.
ideclSource :: Bool, -- ^ True <=> {-\# SOURCE \#-} import
ideclSafe :: Bool, -- ^ True => safe import
ideclQualified :: Bool, -- ^ True => qualified
ideclImplicit :: Bool, -- ^ True => implicit import (of Prelude)
ideclAs :: Maybe ModuleName, -- ^ as Module
ideclHiding :: Maybe (Bool, Located [LIE name])
-- ^ (True => hiding, names)
}
-- ^
-- 'ApiAnnotation.AnnKeywordId's
--
-- - 'ApiAnnotation.AnnImport'
--
-- - 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnClose' for ideclSource
--
-- - 'ApiAnnotation.AnnSafe','ApiAnnotation.AnnQualified',
-- 'ApiAnnotation.AnnPackageName','ApiAnnotation.AnnAs',
-- 'ApiAnnotation.AnnVal'
--
-- - 'ApiAnnotation.AnnHiding','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose' attached
-- to location in ideclHiding
-- For details on above see note [Api annotations] in ApiAnnotation
deriving (Data, Typeable)
simpleImportDecl :: ModuleName -> ImportDecl name
simpleImportDecl mn = ImportDecl {
ideclSourceSrc = Nothing,
ideclName = noLoc mn,
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False,
ideclImplicit = False,
ideclQualified = False,
ideclAs = Nothing,
ideclHiding = Nothing
}
instance (OutputableBndr name, HasOccName name) => Outputable (ImportDecl name) where
ppr (ImportDecl { ideclName = mod', ideclPkgQual = pkg
, ideclSource = from, ideclSafe = safe
, ideclQualified = qual, ideclImplicit = implicit
, ideclAs = as, ideclHiding = spec })
= hang (hsep [text "import", ppr_imp from, pp_implicit implicit, pp_safe safe,
pp_qual qual, pp_pkg pkg, ppr mod', pp_as as])
4 (pp_spec spec)
where
pp_implicit False = empty
pp_implicit True = ptext (sLit ("(implicit)"))
pp_pkg Nothing = empty
pp_pkg (Just (StringLiteral _ p)) = doubleQuotes (ftext p)
pp_qual False = empty
pp_qual True = text "qualified"
pp_safe False = empty
pp_safe True = text "safe"
pp_as Nothing = empty
pp_as (Just a) = text "as" <+> ppr a
ppr_imp True = text "{-# SOURCE #-}"
ppr_imp False = empty
pp_spec Nothing = empty
pp_spec (Just (False, (L _ ies))) = ppr_ies ies
pp_spec (Just (True, (L _ ies))) = text "hiding" <+> ppr_ies ies
ppr_ies [] = text "()"
ppr_ies ies = char '(' <+> interpp'SP ies <+> char ')'
{-
************************************************************************
* *
\subsection{Imported and exported entities}
* *
************************************************************************
-}
type LIE name = Located (IE name)
-- ^ When in a list this may have
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Imported or exported entity.
data IE name
= IEVar (Located name)
-- ^ - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnType'
-- For details on above see note [Api annotations] in ApiAnnotation
-- See Note [Located RdrNames] in HsExpr
| IEThingAbs (Located name) -- ^ Class/Type (can't tell)
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern',
-- 'ApiAnnotation.AnnType','ApiAnnotation.AnnVal'
-- For details on above see note [Api annotations] in ApiAnnotation
-- See Note [Located RdrNames] in HsExpr
| IEThingAll (Located name) -- ^ Class/Type plus all methods/constructors
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnType'
-- For details on above see note [Api annotations] in ApiAnnotation
-- See Note [Located RdrNames] in HsExpr
| IEThingWith (Located name)
IEWildcard
[Located name]
[Located (FieldLbl name)]
-- ^ Class/Type plus some methods/constructors
-- and record fields; see Note [IEThingWith]
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnType'
-- For details on above see note [Api annotations] in ApiAnnotation
| IEModuleContents (Located ModuleName) -- ^ (Export Only)
--
-- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnModule'
-- For details on above see note [Api annotations] in ApiAnnotation
| IEGroup Int HsDocString -- ^ Doc section heading
| IEDoc HsDocString -- ^ Some documentation
| IEDocNamed String -- ^ Reference to named doc
deriving (Eq, Data, Typeable)
data IEWildcard = NoIEWildcard | IEWildcard Int deriving (Eq, Data, Typeable)
{-
Note [IEThingWith]
~~~~~~~~~~~~~~~~~~
A definition like
module M ( T(MkT, x) ) where
data T = MkT { x :: Int }
gives rise to
IEThingWith T [MkT] [FieldLabel "x" False x)] (without DuplicateRecordFields)
IEThingWith T [MkT] [FieldLabel "x" True $sel:x:MkT)] (with DuplicateRecordFields)
See Note [Representing fields in AvailInfo] in Avail for more details.
-}
ieName :: IE name -> name
ieName (IEVar (L _ n)) = n
ieName (IEThingAbs (L _ n)) = n
ieName (IEThingWith (L _ n) _ _ _) = n
ieName (IEThingAll (L _ n)) = n
ieName _ = panic "ieName failed pattern match!"
ieNames :: IE a -> [a]
ieNames (IEVar (L _ n) ) = [n]
ieNames (IEThingAbs (L _ n) ) = [n]
ieNames (IEThingAll (L _ n) ) = [n]
ieNames (IEThingWith (L _ n) _ ns _) = n : map unLoc ns
ieNames (IEModuleContents _ ) = []
ieNames (IEGroup _ _ ) = []
ieNames (IEDoc _ ) = []
ieNames (IEDocNamed _ ) = []
pprImpExp :: (HasOccName name, OutputableBndr name) => name -> SDoc
pprImpExp name = type_pref <+> pprPrefixOcc name
where
occ = occName name
type_pref | isTcOcc occ && isSymOcc occ = text "type"
| otherwise = empty
instance (HasOccName name, OutputableBndr name) => Outputable (IE name) where
ppr (IEVar var) = pprPrefixOcc (unLoc var)
ppr (IEThingAbs thing) = pprImpExp (unLoc thing)
ppr (IEThingAll thing) = hcat [pprImpExp (unLoc thing), text "(..)"]
ppr (IEThingWith thing wc withs flds)
= pprImpExp (unLoc thing) <> parens (fsep (punctuate comma
(ppWiths ++
map (ppr . flLabel . unLoc) flds)))
where
ppWiths =
case wc of
NoIEWildcard ->
map (pprImpExp . unLoc) withs
IEWildcard pos ->
let (bs, as) = splitAt pos (map (pprImpExp . unLoc) withs)
in bs ++ [text ".."] ++ as
ppr (IEModuleContents mod')
= text "module" <+> ppr mod'
ppr (IEGroup n _) = text ("<IEGroup: " ++ show n ++ ">")
ppr (IEDoc doc) = ppr doc
ppr (IEDocNamed string) = text ("<IEDocNamed: " ++ string ++ ">")
| GaloisInc/halvm-ghc | compiler/hsSyn/HsImpExp.hs | bsd-3-clause | 9,411 | 0 | 19 | 3,161 | 1,705 | 924 | 781 | 115 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FunctionalDependencies, FlexibleInstances, DeriveDataTypeable #-}
-- | A CoherentWorker is one that doesn't need to return everything at once...
module Rede.MainLoop.CoherentWorker(
getHeaderFromFlatList
, waitRequestBody
, Headers
, Request
, Footers
, CoherentWorker
, PrincipalStream
, PushedStreams
, PushedStream
, DataAndConclussion
, InputDataStream
, StreamCancelledException(..)
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Builder as Bu
import qualified Data.ByteString.Lazy as LB
import Data.Conduit
import Data.Foldable (find)
import qualified Data.Monoid as M
import Control.Exception
import Data.Typeable
type Headers = [(B.ByteString, B.ByteString)]
type InputDataStream = Source IO B.ByteString
-- A request is a set of headers and a request body....
-- which will normally be empty
type Request = (Headers, Maybe InputDataStream)
-- This will be raised inside a Coherent worker when the underlying
-- stream is cancelled.
data StreamCancelledException = StreamCancelledException
deriving (Show, Typeable)
instance Exception StreamCancelledException
type FinalizationHeaders = Headers
-- Thanks to Luis Cobian for the name...
type Footers = FinalizationHeaders
type CoherentWorker = Request -> IO PrincipalStream
type PrincipalStream = (Headers, PushedStreams, DataAndConclussion)
-- We can use this type in the future...
-- type DataAndConclussion = ConduitM () B.ByteString IO Footers
-- This type could possibly return footers but ...
-- Update: there is functionality now to support this....
type DataAndConclussion = Source IO B.ByteString
type PushedStreams = [ IO PushedStream ]
type PushedStream = (Headers, DataAndConclussion)
getHeaderFromFlatList :: Headers -> B.ByteString -> Maybe B.ByteString
getHeaderFromFlatList unvl bs =
case find (\ (x,_) -> x==bs ) unvl of
Just (_, found_value) -> Just found_value
Nothing -> Nothing
-- | Consumes the request body and returns it.... this can be
-- happily done in the threadlets of Haskell without any further
-- brain-burning.....
waitRequestBody :: InputDataStream -> IO B.ByteString
waitRequestBody source =
let
consumer b = do
maybe_bytes <- await
case maybe_bytes of
Just bytes -> do
-- liftIO $ putStrLn $ "Got bytes " ++ (show $ B.length bytes)
consumer $ b `M.mappend` (Bu.byteString bytes)
Nothing -> do
-- liftIO $ putStrLn "Finishing"
return b
in do
full_builder <- (source $$ consumer "") :: IO Bu.Builder
return $ (LB.toStrict . Bu.toLazyByteString) full_builder
| loadimpact/http2-test | hs-src/Rede/MainLoop/CoherentWorker.hs | bsd-3-clause | 2,909 | 0 | 19 | 696 | 496 | 288 | 208 | 55 | 2 |
{-# LANGUAGE LambdaCase #-}
module Language.Brainfuck.Internals.Optim.CopyLoop where
import Language.Brainfuck.Internals.Instructions
import qualified Data.Map as M
import Control.Monad.State
-- | Loop is optimizable only if it contains only basic operations:
-- * Incr
-- * Decr
-- * MoveLeft
-- * MoveRight
optimizableLoop :: [Instr] -> Bool
optimizableLoop [] = True
optimizableLoop (Incr _:t) = True && optimizableLoop t
optimizableLoop (Decr _:t) = True && optimizableLoop t
optimizableLoop (MoveLeft _:t) = True && optimizableLoop t
optimizableLoop (MoveRight _:t) = True && optimizableLoop t
optimizableLoop _ = False
-- | Interpret loop and keep track of `ptr` and `memory` to detect copy
data Interpreter = Interpreter
{ memory:: M.Map Int Int
, ptr::Int}
defaultInterpreter :: Interpreter
defaultInterpreter = Interpreter {memory = M.empty, ptr = 0}
interpret :: Instr -> State Interpreter ()
interpret (Incr i) = modify' (\s -> s { memory=M.alter (\case { Nothing -> Just i; Just v -> Just (v + i) }) (ptr s) (memory s) })
interpret (Decr i) = modify' (\s -> s { memory=M.alter (\case { Nothing -> Just (-1 * i); Just v -> Just (v - i) }) (ptr s) (memory s) })
interpret (MoveRight n) = modify' (\s -> s { ptr=n + ptr s })
interpret (MoveLeft n) = modify' (\s -> s { ptr=(-n) + ptr s})
interpret _ = return ()
optim :: Program -> Program
optim [] = []
optim (Loop body:t)
| optimizableLoop body =
let s = execState (mapM_ interpret body) defaultInterpreter
in if ptr s == 0 && M.findWithDefault 0 0 (memory s) == -1
then [Mul p val | (p, val) <- M.toAscList (memory s), p /= 0] ++ Set 0 :optim t
else Loop body : optim t
| otherwise = Loop (optim body) : optim t
optim (instr:t) = instr:optim t
| remusao/Hodor | src/Language/Brainfuck/Internals/Optim/CopyLoop.hs | bsd-3-clause | 1,776 | 0 | 18 | 368 | 748 | 390 | 358 | 33 | 3 |
{- |
Main Datatype to hold information about a job, and function
to calculate thread delay
-}
module TinyScheduler.Jobs
( Job(..)
, makeJob
, timeAtomToJob
) where
import Data.Time
import Prelude hiding (id)
import TinyScheduler.Time
import TinyScheduler.TimeAtom
import TinyScheduler.Utils (calculateDelay)
-- | Main datatype to hold job Information
data Job a = Job
{ id :: Int
, delay :: UTCTime -> [Int]
, job :: IO a
}
-- | Convert time atom to Job
timeAtomToJob :: Int -> IO a -> UTCTime -> TimeAtom -> Job a
timeAtomToJob id job start atom = Job {id = id, delay = (delay_ atom start), job = job}
-- | Function to generate job from information about id, no of hits, interval
-- | startTine and the a function with side effects
makeJob :: Int -> Int -> Interval -> UTCTime -> IO a -> Job a
makeJob id hits interval startTime job = Job id (calculateDelay interval hits startTime) job
| functor-soup/tiny-scheduler | TinyScheduler/Jobs.hs | bsd-3-clause | 912 | 0 | 10 | 184 | 231 | 131 | 100 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Blackbox.App where
------------------------------------------------------------------------------
import Prelude hiding (lookup)
------------------------------------------------------------------------------
import Control.Applicative
import Control.Lens
import Control.Monad.Trans
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Configurator
import Snap.Core
import Snap.Util.FileServe
------------------------------------------------------------------------------
import Data.Map.Syntax ((##))
import Snap.Snaplet
import Snap.Snaplet.Heist
import qualified Snap.Snaplet.HeistNoClass as HNC
import Heist
import Heist.Interpreted
------------------------------------------------------------------------------
import Blackbox.Common
import Blackbox.BarSnaplet
import Blackbox.FooSnaplet
import Blackbox.EmbeddedSnaplet
import Blackbox.Types
import Snap.Snaplet.Session
import Snap.Snaplet.Session.Backends.CookieSession
--------------------
-- THE SNAPLET --
--------------------
------------------------------------------------------------------------------
app :: SnapletInit App App
app = makeSnaplet "app" "Test application" Nothing $ do
hs <- nestSnaplet "heist" heist $ heistInit "templates"
fs <- nestSnaplet "foo" foo $ fooInit hs
bs <- nestSnaplet "" bar $ nameSnaplet "baz" $ barInit hs foo
sm <- nestSnaplet "session" session $
initCookieSessionManager "sitekey.txt" "_session" (Just (30 * 60))
ns <- embedSnaplet "embed" embedded embeddedInit
_lens <- getLens
addConfig hs $ mempty
{ hcInterpretedSplices = do
"appsplice" ## textSplice "contents of the app splice"
"appconfig" ## shConfigSplice _lens }
addRoutes [ ("/hello", writeText "hello world")
, ("/routeWithSplice", routeWithSplice)
, ("/routeWithConfig", routeWithConfig)
, ("/public", serveDirectory "public")
, ("/sessionDemo", sessionDemo)
, ("/sessionTest", sessionTest)
]
wrapSite (<|> heistServe)
return $ App hs (over snapletValue fooMod fs) bs sm ns
-------------------------------------------------------------------------------
routeWithSplice :: Handler App App ()
routeWithSplice = do
str <- with foo getFooField
writeText $ T.pack $ "routeWithSplice: "++str
------------------------------------------------------------------------------
routeWithConfig :: Handler App App ()
routeWithConfig = do
cfg <- getSnapletUserConfig
val <- liftIO $ lookup cfg "topConfigField"
writeText $ "routeWithConfig: " `T.append` fromJust val
------------------------------------------------------------------------------
sessionDemo :: Handler App App ()
sessionDemo = withSession session $ do
with session $ do
curVal <- getFromSession "foo"
case curVal of
Nothing -> setInSession "foo" "bar"
Just _ -> return ()
list <- with session $ (T.pack . show) `fmap` sessionToList
csrf <- with session $ (T.pack . show) `fmap` csrfToken
HNC.renderWithSplices heist "session" $ do
"session" ## textSplice list
"csrf" ## textSplice csrf
------------------------------------------------------------------------------
sessionTest :: Handler App App ()
sessionTest = withSession session $ do
q <- getParam "q"
val <- case q of
Just x -> do
let x' = T.decodeUtf8 x
with session $ setInSession "test" x'
return x'
Nothing -> fromMaybe "" `fmap` with session (getFromSession "test")
writeText val
fooMod :: FooSnaplet -> FooSnaplet
fooMod f = f { fooField = fooField f ++ "z" }
| 23Skidoo/snap-templates | test/suite/Blackbox/App.hs | bsd-3-clause | 3,980 | 1 | 18 | 763 | 897 | 465 | 432 | 85 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE KindSignatures, DataKinds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Geometry.Math.Numerical
-- Copyright : Copyright (C) 2015 Artem M. Chirkin <chirkin@arch.ethz.ch>
-- License : BSD3
--
-- Maintainer : Artem M. Chirkin <chirkin@arch.ethz.ch>
-- Stability : Experimental
--
-- Numerical algorithms, such as optimization, root-finding, etc
--
-----------------------------------------------------------------------------
module Geometry.Math.Optimization where
import Control.Monad (liftM)
import GHC.TypeLits (Nat)
import Geometry.Space
import Geometry.Math.Calculus
--import Debug.Trace (traceShow)
-- | If we do not know initial step to select second point
-- we choose @ x1 = x0 * (1 - signum x0 * min 1 (eps*startEmult)) - startEmult*eps @
startEmult :: RealFloat a => a
startEmult = 10
-- | If x1 is newer point and x0 is older point,
-- then @ x2 = convergeRatio*x0 + (1-convergeRatio)*x1 @
convergeRatio :: RealFloat a => a
convergeRatio = 0.1
class Optimization (r :: Nat) where
-- | Rn -> R1 function defenition, with derivatives if necessary
data NumericFunction (r::Nat) (n::Nat) x
-- | R1 -> R1 function defenition, with derivatives if necessary
data NumericFunction1D (r::Nat) x
-- | Construct a function together with its derivatives up to order `r`
estimateFunction :: ( Floating x
, TensorMath n n
, TensorMath n 1
, TensorMath 1 n
, Ord (Vector n x))
=> ApproximationType -> x -> (Vector n x -> x) -> NumericFunction r n x
-- | Construct a function together with its derivatives up to order `r`
estimateFunction1D :: (Floating x) => ApproximationType -> x -> (x -> x) -> NumericFunction1D r x
-- | Minimize 1D function w.r.t. its argument within an interval
minimize1Dbounded :: (Floating x, Ord x) => NumericFunction1D r x -> (x,x) -> Approximately x x
minimize1D :: (RealFloat x) => NumericFunction1D r x -> x -> Approximately x x
-- | Minimize function of multiple arguments
minimize :: ( RealFloat x
, SquareMatrix n
, TensorMath n 1
, TensorMath 1 n )
=> NumericFunction r n x -> Vector n x -> Approximately x (Vector n x)
instance Optimization 0 where
data NumericFunction 0 n x = F0 (Vector n x -> x)
data NumericFunction1D 0 x = F0D1 (x -> x)
estimateFunction _ _ = F0
estimateFunction1D _ _ = F0D1
-- | Golden section search https://en.wikipedia.org/wiki/Golden_section_search
minimize1Dbounded (F0D1 f) start = liftM (safe start) getEps
where phi = (sqrt 5 - 1) / 2
opt (a,_,c) _ e | abs (c-a) <= e * (abs a + abs c) = (c+a)/2
opt (a,Right b,c) fb e | x <- c - phi * (c-a)
, fx <- f x = if fx < fb then opt (a,Right x,b) fx e
else opt (x,Left b, c) fb e
opt (a,Left b ,c) fb e | x <- a + phi * (c-a)
, fx <- f x = if fx < fb then opt (b,Left x ,c) fx e
else opt (a,Right b,x) fb e
safe (a,b) e | a == b = a
| a < b, c <- b - phi*(b-a) = opt (a,Left c, b) (f c) e
| otherwise = safe (b,a) e
minimize1D (F0D1 _) _ = undefined
minimize (F0 _) _ = undefined
instance Optimization 1 where
data NumericFunction 1 n x = F1 (Vector n x -> x) (Vector n x -> Vector n x)
data NumericFunction1D 1 x = F1D1 (x -> x) (x -> x)
estimateFunction a d f = F1 f (gradient a d f)
estimateFunction1D a d f = F1D1 f (derivative' a d f)
minimize1Dbounded (F1D1 _ _) _ = undefined
-- | https://en.wikipedia.org/wiki/Successive_parabolic_interpolation (mine is modified version)
minimize1D (F1D1 f df) x00 = liftM (\e -> opt (fun x00) (fun $ x' e) e) getEps
where fun x = (f x, df x, x)
x' e = let s = signum (df x00)
in x00 * (1 - signum x00 * s * min 1 (e*startEmult)) - s*e*startEmult
opt (f0,g0,x0)
(f1,g1,x1)
e | abs (x1-x0) <= e * (abs x1 + abs x0) = (x1+x0)/2
| isInfinite x0 || isNaN x0 = x0
| isInfinite x1 || isNaN x1 = x1
| d <- x1 - x0
, a <- (g1-g0)/2/d
, b <- g0 - 2*a*x0
, (f0',g0',x0') <- if f1 > f0 then (f0,g0,x0) else (f1,g1,x1)
, (fgx0,fgx1) <- if a > 0
then let xt = -b / 2 / a in (fun xt, fun $ (1-convergeRatio)*xt + convergeRatio*x0')
else (fun $ x0' - signum g0' * 2 * abs d, (f0', g0', x0'))
= opt fgx0 fgx1 e
-- | https://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method
minimize (F1 f df) x0 = isSmall (df x0) >>= \small ->
if small
then return x0
else opt zeros (normL2Squared $ df x0) x0 False
where opt so go xn thesame
| any isInfinite xn || any isNaN xn = return xn
| ngrad <- neg $ df xn
, gn <- normL2Squared ngrad
, sn <- ngrad .+ (gn / go) ..* so
, xp <- (xn .+) . (sn *..)
, fp <- f . xp = do
te <- liftM (findBound fp) getEps
xn1 <- liftM xp $ minimize1Dbounded (F0D1 fp) (0, te)
near <- areClose xn1 xn
flat <- isSmall' gn
if near && (flat || thesame)
then return $ (xn1.+xn)/..2
else opt sn gn xn1 near
instance Optimization 2 where
data NumericFunction 2 n x = F2 (Vector n x -> x) (Vector n x -> Vector n x) (Vector n x -> Tensor n n x)
data NumericFunction1D 2 x = F2D1 (x -> x) (x -> x) (x -> x)
estimateFunction a d f = F2 f (gradient a d f) (hessian d f)
estimateFunction1D a d f = F2D1 f (derivative' a d f) (derivative2' a d f)
minimize1Dbounded F2D1{} _ = undefined
minimize1D F2D1{} _ = undefined
-- | Damped Newton. Similar, but not equal to
-- https://en.wikipedia.org/wiki/Levenberg–Marquardt_algorithm
minimize (F2 f df ddf) x0 = isSmall (df x0) >>= \small ->
if small
then return x0
else getEps >>= opt (f x0) x0 g0 False . (startEmult *)
where g0 = foldDiag max (abs <$> ddf x0) * 8
opt fn xn gn thesame dn
| any isInfinite xn || any isNaN xn = return xn
| grad <- neg $ df xn
, dir <- unit $ invert (ddf xn .+ gn ..* eye) `prod` grad
, xp <- (xn .+) . (dir *..)
, fp <- f . xp
, te <- findBound fp dn = do
xn1 <- liftM xp $ minimize1Dbounded (F0D1 fp) (0, te)
near <- areClose xn1 xn
flat <- isSmall grad
let fn1 = f xn1
case (near && (flat || thesame), fn1 <= fn) of
(False, True) -> opt fn1 xn1 (gn/2) near (dn/2)
(False, False) -> opt fn xn (gn*2) near (dn*2)
(True, _) -> return $ (xn1.+xn)/..2
-- | Supplementary function.
-- Finds the upper bound on argument assuming @ x0 = 0 @ and @ f' <= 0 @.
findBound :: RealFloat a
=> (a -> a) -- ^ non-increasing at 0 funcion
-> a -- ^ starting delta
-> a -- ^ boundary where function starts increasing
findBound f = opt 0
where opt e0 e1 | isInfinite e1 || isNaN e1 = e1
| f e0 <= f e1 = e1
| otherwise = opt e1 (e1*2)
| achirkin/fgeom | src/Geometry/Math/Optimization.hs | bsd-3-clause | 7,994 | 0 | 21 | 2,914 | 2,702 | 1,387 | 1,315 | 125 | 1 |
module Main where
import Database.Relational.Query (relationalQuery)
import Database.HDBC.Session (withConnectionIO, handleSqlError')
import Database.HDBC.Record.Query (runQuery)
import DataSource
import HrrDatatypeTest
main :: IO ()
main = handleSqlError' $ withConnectionIO connect $ \conn -> do
runQuery conn (relationalQuery hrrDatatypeTest) () >>= print
| amutake/haskell-relational-record-driver-oracle | example/src/main.hs | bsd-3-clause | 366 | 0 | 12 | 45 | 100 | 57 | 43 | 9 | 1 |
module SSAReduce where
import SSA
import Syntax
import qualified Data.Map as Map
reduceFundef :: SSAFundef -> SSAFundef
reduceFundef fundef@(SSAFundef {blocks = blks} ) =
mapEndoBlock (reduceBlock (map blkID blks)) fundef
where blkID (Block x _ _ _) = x
reduceBlock :: [BlockID] -> Block -> Block
reduceBlock blkIDs (Block blkId phi insts term) = Block blkId (f phi) (map g insts) (h term)
where
f (Phi vars cols) =
let meanful = Map.filterWithKey (\x _ -> elem x blkIDs) cols in
Phi vars meanful
g (Inst dest op) = Inst dest $ case op of
SArithBin Add x (OpConst (IntConst 0)) -> SId x
SArithBin Sub x (OpConst (IntConst 0)) -> SId x
SArithBin Mul _ (OpConst (IntConst 0)) -> SId (OpConst (IntConst 0))
SArithBin Mul x (OpConst (IntConst 1)) -> SId x
SArithBin Mul x (OpConst (IntConst 2)) -> SArithBin Add x x
SArithBin Add (OpConst t) (OpVar x) -> SArithBin Add (OpVar x) (OpConst t)
SArithBin Mul (OpConst t) (OpVar x) -> SArithBin Mul (OpVar x) (OpConst t)
e -> e
h (TBr _ blk1 blk2) | blk1 == blk2 = TJmp blk1
h (TBr (OpConst (IntConst x)) blk1 blk2) = case x of
1 -> TJmp blk1
0 -> TJmp blk2
_ -> error $ "condition must be 0 or 1, but got:" ++ show x
h t = t
{- Performs operator strength reduction -}
reduce :: [SSAFundef] -> [SSAFundef]
reduce = map reduceFundef
| koba-e964/hayashii-mcc | SSAReduce.hs | bsd-3-clause | 1,387 | 0 | 15 | 352 | 623 | 308 | 315 | 30 | 12 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Database.Concelo.Crypto
( derivePrivate
, derivePublic
, fromPublic
, toPublic
, fromPrivate
, toPrivate
, dummyKey
, fromSymmetric
, toSymmetric
, newSymmetric
, decryptPrivate
, decryptAsymmetric
, encryptAsymmetric
, decryptSymmetric
, encryptSymmetric
, PublicKey()
, PrivateKey()
, SymmetricKey()
, PRNG()
, makePRNG
, randomBytes
, seedSize
, sign
, verify
, hash ) where
import Data.Functor ((<$>))
import Data.Foldable (Foldable())
import qualified Crypto.Error as E
import qualified Crypto.Random as R
import qualified Crypto.Cipher.Types as CT
import qualified Crypto.Cipher.AES as AES
import qualified Crypto.Hash as H
import qualified Crypto.PubKey.RSA as RSA
import qualified Crypto.PubKey.RSA.Types as RSAT
import qualified Crypto.PubKey.RSA.PKCS15 as PKCS15
import qualified Crypto.KDF.PBKDF2 as PBKDF2
import qualified Data.Foldable as F
import qualified Data.ByteString as BS
import qualified Data.ByteArray as BA
import qualified Control.Lens as L
import qualified Control.Monad as M
import qualified Control.Monad.State as S
import qualified Database.Concelo.Bytes as B
import qualified Database.Concelo.Control as C
newtype PRNG = PRNG R.ChaChaDRG
newtype PrivateKey = PrivateKey { getPrivateKey :: RSAT.PrivateKey }
deriving Show
newtype PublicKey = PublicKey { _getPublicKey :: RSAT.PublicKey }
instance Show PublicKey where
show = show . fromPublic
newtype SymmetricKey = SymmetricKey { fromSymmetric :: BS.ByteString }
newtype ParseState = ParseState { getParseStateString :: BS.ByteString }
parseStateString :: L.Lens' ParseState BS.ByteString
parseStateString =
L.lens getParseStateString (\x v -> x { getParseStateString = v })
instance C.ParseState ParseState where
parseString = parseStateString
type Cipher = AES.AES256
hashAlgorithm = H.SHA256
-- todo: does WebCrypto support Scrypt or Bcrypt? If so, use one of them.
prf = PBKDF2.prfHMAC hashAlgorithm
iterations = 4096
-- This only determines the size of email/password derived keys; keys
-- generated from different sources may be of any size. Ideally, we'd
-- use e.g. 1920 byte (15360 bit) keys here so as to achieve a 256-bit
-- equivalent strength, but those are prohibitively slow to generate.
-- TODO: Switch to elliptic curves and use ECDH to agree on a key and
-- use that to encrypt stuff like the keys used to encrypt each tree.
asymmetricKeySize = 512
symmetricKeySize = 32
seedSize = 40
defaultExponent = 65537
makePRNG = PRNG . R.drgNewTest . toSeed
toSymmetric = SymmetricKey
newSymmetric = toSymmetric <$> randomBytes symmetricKeySize
-- todo: use standard serialization formats for public and private keys
decryptPrivate password privateKey =
decryptSymmetric
(SymmetricKey $ deriveKey symmetricKeySize password privateKey) privateKey
>>= C.eitherToAction . toPrivate
fromPrivate (PrivateKey key) =
BS.concat [fromPublic $ PublicKey $ RSAT.private_pub key,
B.fromInteger $ RSAT.private_d key]
parsePrivate = do
public <- parsePublic
d <- B.toInteger
return $ PrivateKey $ RSAT.PrivateKey public d 0 0 0 0 0
toPrivate s = C.eval parsePrivate $ ParseState s
fromPublic (PublicKey key) =
BS.concat [B.fromInteger $ RSAT.public_size key,
B.fromInteger $ RSAT.public_n key,
B.fromInteger $ RSAT.public_e key]
parsePublic =
M.liftM3 RSAT.PublicKey
B.toInteger
B.toInteger
B.toInteger
toPublic s = PublicKey <$> C.eval parsePublic (ParseState s)
decryptAsymmetric (PrivateKey key) ciphertext = do
PRNG drg <- S.get
let (result, drg') = R.withDRG drg $ PKCS15.decryptSafer key ciphertext
S.put $ PRNG drg'
case result of
Left error -> C.exception $ show error
Right plaintext -> return plaintext
encryptAsymmetric (PublicKey key) plaintext = do
PRNG drg <- S.get
let (result, drg') = R.withDRG drg $ PKCS15.encrypt key plaintext
S.put $ PRNG drg'
case result of
Left error -> C.exception $ show error
Right ciphertext -> return ciphertext
decryptSymmetric (SymmetricKey key) ciphertext = do
let (nonce, tail) = BS.splitAt 16 ciphertext
case CT.cipherInit key :: E.CryptoFailable Cipher of
E.CryptoPassed cipher -> case CT.makeIV nonce of
Nothing -> C.exception "unable to make initialization vector"
Just iv -> return $ CT.ctrCombine cipher iv tail
E.CryptoFailed message -> C.exception $ show message
encryptSymmetric (SymmetricKey key) plaintext = do
nonce <- randomBytes 16
case CT.cipherInit key :: E.CryptoFailable Cipher of
E.CryptoPassed cipher -> case CT.makeIV nonce of
Nothing -> C.exception "unable to make initialization vector"
Just iv -> return $ nonce `BS.append` CT.ctrCombine cipher iv plaintext
E.CryptoFailed error -> C.exception $ show error
withRandomBytes :: R.DRG g => g -> Int -> (BS.ByteString, g)
withRandomBytes drg count = R.withRandomBytes drg count id
randomBytes count = do
PRNG drg <- S.get
let (result, drg') = withRandomBytes drg count
S.put $ PRNG drg'
return result
toSeed s = (B.toWord64 a,
B.toWord64 b,
B.toWord64 c,
B.toWord64 d,
B.toWord64 e)
where (a, as) = BS.splitAt 8 s
(b, bs) = BS.splitAt 8 as
(c, cs) = BS.splitAt 8 bs
(d, ds) = BS.splitAt 8 cs
(e, _) = BS.splitAt 8 ds
deriveSeed password salt = toSeed $ deriveKey seedSize password salt
deriveKey size = PBKDF2.generate prf $ PBKDF2.Parameters iterations size
derivePrivate password salt =
PrivateKey $ snd $ fst $ R.withDRG (R.drgNewTest $ deriveSeed password salt)
$ RSA.generate asymmetricKeySize defaultExponent
dummyKey = derivePrivate
("secret" :: BS.ByteString)
("trust@every.one" :: BS.ByteString)
derivePublic = PublicKey . RSAT.private_pub . getPrivateKey
sign (PrivateKey key) text = do
PRNG drg <- S.get
let (result, drg') =
R.withDRG drg $ PKCS15.signSafer (Just hashAlgorithm) key text
S.put $ PRNG drg'
case result of
Left error -> C.exception $ show error
Right s -> return s
verify (PublicKey key) signature text =
PKCS15.verify (Just hashAlgorithm) key text signature
hash :: Foldable t => t BS.ByteString -> BS.ByteString
hash = BA.convert . H.hashFinalize
. F.foldr (flip H.hashUpdate) (H.hashInitWith hashAlgorithm)
| Concelo/concelo | src/Database/Concelo/Crypto.hs | bsd-3-clause | 6,516 | 0 | 15 | 1,306 | 1,861 | 983 | 878 | 171 | 3 |
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
module OpenCV.Internal.Core.Types.Rect.TH
( mkRectType
) where
import "base" Data.Monoid ( (<>) )
import "base" Foreign.Marshal.Utils ( toBool )
import "base" System.IO.Unsafe ( unsafePerformIO )
import qualified "inline-c" Language.C.Inline.Unsafe as CU
import "linear" Linear.Vector ( (^+^) )
import "linear" Linear.V2 ( V2(..) )
import "template-haskell" Language.Haskell.TH
import "template-haskell" Language.Haskell.TH.Quote ( quoteExp )
import "this" OpenCV.Core.Types.Point
import "this" OpenCV.Core.Types.Size
import "this" OpenCV.Internal
import "this" OpenCV.Internal.Core.Types.Rect
import "this" OpenCV.Internal.C.PlacementNew.TH ( mkPlacementNewInstance )
import "this" OpenCV.Internal.C.Types
--------------------------------------------------------------------------------
mkRectType
:: String -- ^ Rectangle type name, for both Haskell and C
-> Name -- ^ Depth type name in Haskell
-> String -- ^ Depth type name in C
-> String -- ^ Point type name in C
-> String -- ^ Size type name in C
-> Q [Dec]
mkRectType rTypeNameStr depthTypeName cDepthTypeStr cPointTypeStr cSizeTypeStr =
fmap concat . sequence $
[ (:[]) <$> rectTySynD
, fromPtrDs
, isRectOpenCVInstanceDs
, isRectHaskellInstanceDs
, mkPlacementNewInstance rTypeName
]
where
rTypeName :: Name
rTypeName = mkName rTypeNameStr
cRectTypeStr :: String
cRectTypeStr = rTypeNameStr
rTypeQ :: Q Type
rTypeQ = conT rTypeName
depthTypeQ :: Q Type
depthTypeQ = conT depthTypeName
rectTySynD :: Q Dec
rectTySynD =
tySynD rTypeName [] ([t|Rect|] `appT` depthTypeQ)
fromPtrDs :: Q [Dec]
fromPtrDs =
[d|
instance FromPtr $(rTypeQ) where
fromPtr = objFromPtr Rect $ $(finalizerExpQ)
|]
where
finalizerExpQ :: Q Exp
finalizerExpQ = do
ptr <- newName "ptr"
lamE [varP ptr] $
quoteExp CU.exp $
"void { delete $(" <> cRectTypeStr <> " * " <> nameBase ptr <> ") }"
isRectOpenCVInstanceDs :: Q [Dec]
isRectOpenCVInstanceDs =
[d|
instance IsRect Rect $(depthTypeQ) where
toRect = id
fromRect = id
rectTopLeft rect = unsafePerformIO $ fromPtr $ withPtr rect $ $(rectTopLeftExpQ)
rectBottomRight rect = unsafePerformIO $ fromPtr $ withPtr rect $ $(rectBottomRightExpQ)
rectSize rect = unsafePerformIO $ fromPtr $ withPtr rect $ $(rectSizeExpQ)
rectArea rect = unsafePerformIO $ withPtr rect $ $(rectAreaExpQ)
rectContains = $(rectContainsExpQ)
|]
where
rectTopLeftExpQ :: Q Exp
rectTopLeftExpQ = do
rectPtr <- newName "rectPtr"
lamE [varP rectPtr] $ quoteExp CU.exp $
cPointTypeStr <> " * { new " <> cPointTypeStr <> "($(" <> cRectTypeStr <> " * rectPtr)->tl()) }"
rectBottomRightExpQ :: Q Exp
rectBottomRightExpQ = do
rectPtr <- newName "rectPtr"
lamE [varP rectPtr] $ quoteExp CU.exp $
cPointTypeStr <> " * { new " <> cPointTypeStr <> "($(" <> cRectTypeStr <> " * rectPtr)->br()) }"
rectSizeExpQ :: Q Exp
rectSizeExpQ = do
rectPtr <- newName "rectPtr"
lamE [varP rectPtr] $ quoteExp CU.exp $
cSizeTypeStr <> " * { new " <> cSizeTypeStr <> "($(" <> cRectTypeStr <> " * rectPtr)->size()) }"
rectAreaExpQ :: Q Exp
rectAreaExpQ = do
rectPtr <- newName "rectPtr"
lamE [varP rectPtr] $ quoteExp CU.exp $
cDepthTypeStr <> " { $(" <> cRectTypeStr <> " * rectPtr)->area() }"
rectContainsExpQ :: Q Exp
rectContainsExpQ = do
point <- newName "point"
rect <- newName "rect"
pointPtr <- newName "pointPtr"
rectPtr <- newName "rectPtr"
lamE [varP point, varP rect]
$ appE [e|toBool|]
$ appE [e|unsafePerformIO|]
$ appE ([e|withPtr|] `appE` ([e|toPoint|] `appE` varE point))
$ lamE [varP pointPtr]
$ appE ([e|withPtr|] `appE` (varE rect))
$ lamE [varP rectPtr]
$ quoteExp CU.exp
$ "int { $(" <> cRectTypeStr <> " * rectPtr)->contains(*$(" <> cPointTypeStr <> " * pointPtr)) }"
isRectHaskellInstanceDs :: Q [Dec]
isRectHaskellInstanceDs =
[d|
instance IsRect HRect $(depthTypeQ) where
toRect hr = unsafePerformIO $ toRectIO hr
fromRect rect = HRect
{ hRectTopLeft = fromPoint $ rectTopLeft rect
, hRectSize = fromSize $ rectSize rect
}
toRectIO = $(toRectIOExpQ)
rectTopLeft hr = hRectTopLeft hr
rectBottomRight hr = hRectTopLeft hr ^+^ hRectSize hr
rectSize hr = hRectSize hr
rectArea hr = let V2 w h = hRectSize hr
in w * h
rectContains (V2 px py) (HRect (V2 rx ry) (V2 rw rh)) =
px >= rx && px < rx + rw
&& py >= ry && py < ry + rh
|]
where
toRectIOExpQ :: Q Exp
toRectIOExpQ = do
x <- newName "x"
y <- newName "y"
w <- newName "w"
h <- newName "h"
lamE [conP 'HRect [conP 'V2 [varP x, varP y], conP 'V2 [varP w, varP h]]] $
appE [e|fromPtr|] $
quoteExp CU.exp $ concat
[ cRectTypeStr <> " * { "
, "new cv::Rect_<" <> cDepthTypeStr <> ">("
, "$(" <> cDepthTypeStr <> " x), "
, "$(" <> cDepthTypeStr <> " y), "
, "$(" <> cDepthTypeStr <> " w), "
, "$(" <> cDepthTypeStr <> " h)"
, ")}"
]
| Cortlandd/haskell-opencv | src/OpenCV/Internal/Core/Types/Rect/TH.hs | bsd-3-clause | 5,922 | 0 | 26 | 1,965 | 1,159 | 632 | 527 | -1 | -1 |
{-#LANGUAGE MultiParamTypeClasses #-}
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE ViewPatterns #-}
module Twilio.AuthorizedConnectApp
( -- * Resource
AuthorizedConnectApp(..)
, ConnectAppSID
, Twilio.AuthorizedConnectApp.get
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Data.Aeson
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock
import Network.URI
import Control.Monad.Twilio
import Twilio.Internal.Parser
import Twilio.Internal.Request
import Twilio.Internal.Resource as Resource
import Twilio.Types
{- Resource -}
data AuthorizedConnectApp = AuthorizedConnectApp
{ dateCreated :: !UTCTime
, dateUpdated :: !UTCTime
, accountSID :: !AccountSID
-- , permissions :: !Permissions
, sid :: !ConnectAppSID
, friendlyName :: !Text
, description :: !Text
, companyName :: !Text
, homepageURL :: !(Maybe URI)
, uri :: !URI
} deriving (Show, Eq)
instance FromJSON AuthorizedConnectApp where
parseJSON (Object v) = AuthorizedConnectApp
<$> (v .: "date_created" >>= parseDateTime)
<*> (v .: "date_updated" >>= parseDateTime)
<*> v .: "account_sid"
-- <*> v .: "permissions"
<*> v .: "connect_app_sid"
<*> v .: "connect_app_friendly_name"
<*> v .: "connect_app_description"
<*> v .: "connect_app_company_name"
<*> (v .: "connect_app_homepage_url" <&> fmap filterEmpty
<&> fmap (fmap $ parseURI . T.unpack)
>>= maybeReturn'')
<*> (v .: "uri" <&> parseRelativeReference
>>= maybeReturn)
parseJSON _ = mzero
instance Get1 ConnectAppSID AuthorizedConnectApp where
get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest
("/AuthorizedConnectApps/" <> sid <> ".json")
-- | Get an 'AuthorizedConnectApp' by 'ConnectAppSID'.
get :: MonadThrow m => ConnectAppSID -> TwilioT m AuthorizedConnectApp
get = Resource.get
| seagreen/twilio-haskell | src/Twilio/AuthorizedConnectApp.hs | bsd-3-clause | 2,078 | 0 | 22 | 488 | 442 | 249 | 193 | 71 | 1 |
{-# LANGUAGE RankNTypes #-}
module Graphics.Rendering.GLPlot.Types where
import Linear
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL.GL hiding (Points, Lines, Rect)
import qualified Data.Vector.Storable as V
import Control.Concurrent (ThreadId)
import Control.Concurrent.STM
-- | A main loop context
data Context = Context { _ctxTasks :: !(TQueue (IO ()))
}
data Curve = Curve { _cParams :: !CurveParams
, _cBuffer :: !BufferObject
, _cPoints :: !(TVar Int)
, _cPlot :: !Plot
}
data Style = Lines | Points
data CurveParams = CurveParams { _cColor :: !(Color4 GLfloat)
, _cStyle :: !Style
, _cName :: !(Maybe String)
}
defaultCurve :: CurveParams
defaultCurve = CurveParams { _cColor = Color4 0 0 0 0
, _cStyle = Points
, _cName = Nothing
}
data Rect a = Rect (V2 a) (V2 a)
data Plot = Plot { _pWindow :: !(TMVar Window)
, _pCurves :: !(TVar [Curve])
, _pLimits :: !(TVar (Rect GLdouble))
, _pMainloop :: !Context
, _pRedrawScheduled :: !(TVar Bool)
, _pLegendPos :: !(TVar (Maybe (V2 GLfloat)))
, _pLegend :: !(TVar (Maybe TextureObject))
, _pProgram :: Program
, _pFrameCount :: !(TVar Int)
}
| bgamari/gl-plot | Graphics/Rendering/GLPlot/Types.hs | bsd-3-clause | 1,602 | 0 | 15 | 666 | 393 | 227 | 166 | 63 | 1 |
import Control.Arrow ((&&&))
import Test.Hspec (Spec, it, shouldBe, shouldNotBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import qualified Data.Vector as Vector (fromList)
import Matrix
( Matrix
, cols
, column
, flatten
, fromList
, fromString
, reshape
, row
, rows
, shape
, transpose
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
let intMatrix = fromString :: String -> Matrix Int
let vector = Vector.fromList
it "extract first row" $ do
row 0 (intMatrix "1 2\n10 20") `shouldBe` vector [1, 2]
row 0 (intMatrix "9 7\n8 6" ) `shouldBe` vector [9, 7]
it "extract second row" $ do
row 1 (intMatrix "9 8 7\n19 18 17") `shouldBe` vector [19, 18, 17]
row 1 (intMatrix "1 4 9\n16 25 36") `shouldBe` vector [16, 25, 36]
it "extract first column" $ do
column 0 (intMatrix "1 2 3\n4 5 6\n7 8 9\n 8 7 6")
`shouldBe` vector [1, 4, 7, 8]
column 1 (intMatrix "89 1903 3\n18 3 1\n9 4 800")
`shouldBe` vector [1903, 3, 4]
it "shape" $ do
shape (intMatrix "" ) `shouldBe` (0, 0)
shape (intMatrix "1" ) `shouldBe` (1, 1)
shape (intMatrix "1\n2" ) `shouldBe` (2, 1)
shape (intMatrix "1 2" ) `shouldBe` (1, 2)
shape (intMatrix "1 2\n3 4") `shouldBe` (2, 2)
it "rows & cols" $
(rows &&& cols) (intMatrix "1 2") `shouldBe` (1, 2)
it "eq" $ do
intMatrix "1 2" `shouldBe` intMatrix "1 2"
intMatrix "2 3" `shouldNotBe` intMatrix "1 2 3"
it "fromList" $ do
fromList [[1 , 2]] `shouldBe` intMatrix "1 2"
fromList [[1], [2]] `shouldBe` intMatrix "1\n2"
it "transpose" $ do
transpose (intMatrix "1\n2\n3" ) `shouldBe` intMatrix "1 2 3"
transpose (intMatrix "1 4\n2 5\n3 6") `shouldBe` intMatrix "1 2 3\n4 5 6"
it "reshape" $
reshape (2, 2) (intMatrix "1 2 3 4") `shouldBe` intMatrix "1 2\n3 4"
it "flatten" $
flatten (intMatrix "1 2\n3 4") `shouldBe` vector [1, 2, 3, 4]
| c19/Exercism-Haskell | matrix/test/Tests.hs | mit | 2,094 | 0 | 13 | 588 | 784 | 414 | 370 | 54 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>Forced Browse Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/bruteforce/src/main/javahelp/org/zaproxy/zap/extension/bruteforce/resources/help_ro_RO/helpset_ro_RO.hs | apache-2.0 | 966 | 79 | 67 | 158 | 415 | 210 | 205 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="bs-BA">
<title>Customizable HTML Report</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_bs_BA/helpset_bs_BA.hs | apache-2.0 | 970 | 79 | 66 | 158 | 411 | 208 | 203 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Module : Documentation.Haddock.Parser
-- Copyright : (c) Mateusz Kowalczyk 2013-2014,
-- Simon Hengel 2013
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Parser used for Haddock comments. For external users of this
-- library, the most commonly used combination of functions is going
-- to be
--
-- @'toRegular' . 'parseParas'@
module Documentation.Haddock.Parser ( parseString, parseParas
, overIdentifier, toRegular, Identifier
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Char (chr, isAsciiUpper)
import Data.List (stripPrefix, intercalate, unfoldr)
import Data.Maybe (fromMaybe)
import Data.Monoid
import Documentation.Haddock.Doc
import Documentation.Haddock.Parser.Monad hiding (take, endOfLine)
import Documentation.Haddock.Parser.Util
import Documentation.Haddock.Types
import Documentation.Haddock.Utf8
import Prelude hiding (takeWhile)
-- $setup
-- >>> :set -XOverloadedStrings
-- | Identifier string surrounded with opening and closing quotes/backticks.
type Identifier = (Char, String, Char)
-- | Drops the quotes/backticks around all identifiers, as if they
-- were valid but still 'String's.
toRegular :: DocH mod Identifier -> DocH mod String
toRegular = fmap (\(_, x, _) -> x)
-- | Maps over 'DocIdentifier's over 'String' with potentially failing
-- conversion using user-supplied function. If the conversion fails,
-- the identifier is deemed to not be valid and is treated as a
-- regular string.
overIdentifier :: (String -> Maybe a)
-> DocH mod Identifier
-> DocH mod a
overIdentifier f d = g d
where
g (DocIdentifier (o, x, e)) = case f x of
Nothing -> DocString $ o : x ++ [e]
Just x' -> DocIdentifier x'
g DocEmpty = DocEmpty
g (DocAppend x x') = DocAppend (g x) (g x')
g (DocString x) = DocString x
g (DocParagraph x) = DocParagraph $ g x
g (DocIdentifierUnchecked x) = DocIdentifierUnchecked x
g (DocModule x) = DocModule x
g (DocWarning x) = DocWarning $ g x
g (DocEmphasis x) = DocEmphasis $ g x
g (DocMonospaced x) = DocMonospaced $ g x
g (DocBold x) = DocBold $ g x
g (DocUnorderedList x) = DocUnorderedList $ fmap g x
g (DocOrderedList x) = DocOrderedList $ fmap g x
g (DocDefList x) = DocDefList $ fmap (\(y, z) -> (g y, g z)) x
g (DocCodeBlock x) = DocCodeBlock $ g x
g (DocHyperlink x) = DocHyperlink x
g (DocPic x) = DocPic x
g (DocAName x) = DocAName x
g (DocProperty x) = DocProperty x
g (DocExamples x) = DocExamples x
g (DocHeader (Header l x)) = DocHeader . Header l $ g x
parse :: Parser a -> BS.ByteString -> (ParserState, a)
parse p = either err id . parseOnly (p <* endOfInput)
where
err = error . ("Haddock.Parser.parse: " ++)
-- | Main entry point to the parser. Appends the newline character
-- to the input string.
parseParas :: String -- ^ String to parse
-> MetaDoc mod Identifier
parseParas input = case parseParasState input of
(state, a) -> MetaDoc { _meta = Meta { _version = parserStateSince state }
, _doc = a
}
parseParasState :: String -> (ParserState, DocH mod Identifier)
parseParasState = parse (p <* skipSpace) . encodeUtf8 . (++ "\n")
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> paragraph `sepBy` many (skipHorizontalSpace *> "\n")
parseParagraphs :: String -> Parser (DocH mod Identifier)
parseParagraphs input = case parseParasState input of
(state, a) -> setParserState state >> return a
-- | Parse a text paragraph. Actually just a wrapper over 'parseStringBS' which
-- drops leading whitespace and encodes the string to UTF8 first.
parseString :: String -> DocH mod Identifier
parseString = parseStringBS . encodeUtf8 . dropWhile isSpace
parseStringBS :: BS.ByteString -> DocH mod Identifier
parseStringBS = snd . parse p
where
p :: Parser (DocH mod Identifier)
p = docConcat <$> many (monospace <|> anchor <|> identifier <|> moduleName
<|> picture <|> markdownImage <|> hyperlink <|> bold
<|> emphasis <|> encodedChar <|> string'
<|> skipSpecialChar)
-- | Parses and processes
-- <https://en.wikipedia.org/wiki/Numeric_character_reference Numeric character references>
--
-- >>> parseString "A"
-- DocString "A"
encodedChar :: Parser (DocH mod a)
encodedChar = "&#" *> c <* ";"
where
c = DocString . return . chr <$> num
num = hex <|> decimal
hex = ("x" <|> "X") *> hexadecimal
-- | List of characters that we use to delimit any special markup.
-- Once we have checked for any of these and tried to parse the
-- relevant markup, we can assume they are used as regular text.
specialChar :: [Char]
specialChar = "_/<@\"&'`# "
-- | Plain, regular parser for text. Called as one of the last parsers
-- to ensure that we have already given a chance to more meaningful parsers
-- before capturing their characers.
string' :: Parser (DocH mod a)
string' = DocString . unescape . decodeUtf8 <$> takeWhile1_ (`notElem` specialChar)
where
unescape "" = ""
unescape ('\\':x:xs) = x : unescape xs
unescape (x:xs) = x : unescape xs
-- | Skips a single special character and treats it as a plain string.
-- This is done to skip over any special characters belonging to other
-- elements but which were not deemed meaningful at their positions.
skipSpecialChar :: Parser (DocH mod a)
skipSpecialChar = DocString . return <$> satisfy (`elem` specialChar)
-- | Emphasis parser.
--
-- >>> parseString "/Hello world/"
-- DocEmphasis (DocString "Hello world")
emphasis :: Parser (DocH mod Identifier)
emphasis = DocEmphasis . parseStringBS <$>
mfilter ('\n' `BS.notElem`) ("/" *> takeWhile1_ (/= '/') <* "/")
-- | Bold parser.
--
-- >>> parseString "__Hello world__"
-- DocBold (DocString "Hello world")
bold :: Parser (DocH mod Identifier)
bold = DocBold . parseStringBS <$> disallowNewline ("__" *> takeUntil "__")
disallowNewline :: Parser BS.ByteString -> Parser BS.ByteString
disallowNewline = mfilter ('\n' `BS.notElem`)
-- | Like `takeWhile`, but unconditionally take escaped characters.
takeWhile_ :: (Char -> Bool) -> Parser BS.ByteString
takeWhile_ p = scan False p_
where
p_ escaped c
| escaped = Just False
| not $ p c = Nothing
| otherwise = Just (c == '\\')
-- | Like `takeWhile1`, but unconditionally take escaped characters.
takeWhile1_ :: (Char -> Bool) -> Parser BS.ByteString
takeWhile1_ = mfilter (not . BS.null) . takeWhile_
-- | Text anchors to allow for jumping around the generated documentation.
--
-- >>> parseString "#Hello world#"
-- DocAName "Hello world"
anchor :: Parser (DocH mod a)
anchor = DocAName . decodeUtf8 <$>
disallowNewline ("#" *> takeWhile1_ (/= '#') <* "#")
-- | Monospaced strings.
--
-- >>> parseString "@cruel@"
-- DocMonospaced (DocString "cruel")
monospace :: Parser (DocH mod Identifier)
monospace = DocMonospaced . parseStringBS
<$> ("@" *> takeWhile1_ (/= '@') <* "@")
-- | Module names: we try our reasonable best to only allow valid
-- Haskell module names, with caveat about not matching on technically
-- valid unicode symbols.
moduleName :: Parser (DocH mod a)
moduleName = DocModule <$> (char '"' *> modid <* char '"')
where
modid = intercalate "." <$> conid `sepBy1` "."
conid = (:)
<$> satisfy isAsciiUpper
-- NOTE: According to Haskell 2010 we should actually only
-- accept {small | large | digit | ' } here. But as we can't
-- match on unicode characters, this is currently not possible.
-- Note that we allow ‘#’ to suport anchors.
<*> (decodeUtf8 <$> takeWhile (`notElem` (" .&[{}(=*)+]!|@/;,^?\"\n"::String)))
-- | Picture parser, surrounded by \<\< and \>\>. It's possible to specify
-- a title for the picture.
--
-- >>> parseString "<<hello.png>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Nothing})
-- >>> parseString "<<hello.png world>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Just "world"})
picture :: Parser (DocH mod a)
picture = DocPic . makeLabeled Picture . decodeUtf8
<$> disallowNewline ("<<" *> takeUntil ">>")
markdownImage :: Parser (DocH mod a)
markdownImage = fromHyperlink <$> ("!" *> linkParser)
where
fromHyperlink (Hyperlink url label) = DocPic (Picture url label)
-- | Paragraph parser, called by 'parseParas'.
paragraph :: Parser (DocH mod Identifier)
paragraph = examples <|> skipSpace *> (
since
<|> unorderedList
<|> orderedList
<|> birdtracks
<|> codeblock
<|> property
<|> header
<|> textParagraphThatStartsWithMarkdownLink
<|> definitionList
<|> docParagraph <$> textParagraph
)
since :: Parser (DocH mod a)
since = ("@since " *> version <* skipHorizontalSpace <* endOfLine) >>= setSince >> return DocEmpty
where
version = decimal `sepBy1'` "."
-- | Headers inside the comment denoted with @=@ signs, up to 6 levels
-- deep.
--
-- >>> snd <$> parseOnly header "= Hello"
-- Right (DocHeader (Header {headerLevel = 1, headerTitle = DocString "Hello"}))
-- >>> snd <$> parseOnly header "== World"
-- Right (DocHeader (Header {headerLevel = 2, headerTitle = DocString "World"}))
header :: Parser (DocH mod Identifier)
header = do
let psers = map (string . encodeUtf8 . concat . flip replicate "=") [6, 5 .. 1]
pser = foldl1 (<|>) psers
delim <- decodeUtf8 <$> pser
line <- skipHorizontalSpace *> nonEmptyLine >>= return . parseString
rest <- paragraph <|> return DocEmpty
return $ DocHeader (Header (length delim) line) `docAppend` rest
textParagraph :: Parser (DocH mod Identifier)
textParagraph = parseString . intercalate "\n" <$> many1 nonEmptyLine
textParagraphThatStartsWithMarkdownLink :: Parser (DocH mod Identifier)
textParagraphThatStartsWithMarkdownLink = docParagraph <$> (docAppend <$> markdownLink <*> optionalTextParagraph)
where
optionalTextParagraph :: Parser (DocH mod Identifier)
optionalTextParagraph = (docAppend <$> whitespace <*> textParagraph) <|> pure DocEmpty
whitespace :: Parser (DocH mod a)
whitespace = DocString <$> (f <$> takeHorizontalSpace <*> optional "\n")
where
f :: BS.ByteString -> Maybe BS.ByteString -> String
f xs (fromMaybe "" -> x)
| BS.null (xs <> x) = ""
| otherwise = " "
-- | Parses unordered (bullet) lists.
unorderedList :: Parser (DocH mod Identifier)
unorderedList = DocUnorderedList <$> p
where
p = ("*" <|> "-") *> innerList p
-- | Parses ordered lists (numbered or dashed).
orderedList :: Parser (DocH mod Identifier)
orderedList = DocOrderedList <$> p
where
p = (paren <|> dot) *> innerList p
dot = (decimal :: Parser Int) <* "."
paren = "(" *> decimal <* ")"
-- | Generic function collecting any further lines belonging to the
-- list entry and recursively collecting any further lists in the
-- same paragraph. Usually used as
--
-- > someListFunction = listBeginning *> innerList someListFunction
innerList :: Parser [DocH mod Identifier] -> Parser [DocH mod Identifier]
innerList item = do
c <- takeLine
(cs, items) <- more item
let contents = docParagraph . parseString . dropNLs . unlines $ c : cs
return $ case items of
Left p -> [contents `docAppend` p]
Right i -> contents : i
-- | Parses definition lists.
definitionList :: Parser (DocH mod Identifier)
definitionList = DocDefList <$> p
where
p = do
label <- "[" *> (parseStringBS <$> takeWhile1 (`notElem` ("]\n" :: String))) <* ("]" <* optional ":")
c <- takeLine
(cs, items) <- more p
let contents = parseString . dropNLs . unlines $ c : cs
return $ case items of
Left x -> [(label, contents `docAppend` x)]
Right i -> (label, contents) : i
-- | Drops all trailing newlines.
dropNLs :: String -> String
dropNLs = reverse . dropWhile (== '\n') . reverse
-- | Main worker for 'innerList' and 'definitionList'.
-- We need the 'Either' here to be able to tell in the respective functions
-- whether we're dealing with the next list or a nested paragraph.
more :: Monoid a => Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
more item = innerParagraphs <|> moreListItems item
<|> moreContent item <|> pure ([], Right mempty)
-- | Used by 'innerList' and 'definitionList' to parse any nested paragraphs.
innerParagraphs :: Parser ([String], Either (DocH mod Identifier) a)
innerParagraphs = (,) [] . Left <$> ("\n" *> indentedParagraphs)
-- | Attempts to fetch the next list if possibly. Used by 'innerList' and
-- 'definitionList' to recursively grab lists that aren't separated by a whole
-- paragraph.
moreListItems :: Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
moreListItems item = (,) [] . Right <$> (skipSpace *> item)
-- | Helper for 'innerList' and 'definitionList' which simply takes
-- a line of text and attempts to parse more list content with 'more'.
moreContent :: Monoid a => Parser a
-> Parser ([String], Either (DocH mod Identifier) a)
moreContent item = first . (:) <$> nonEmptyLine <*> more item
-- | Parses an indented paragraph.
-- The indentation is 4 spaces.
indentedParagraphs :: Parser (DocH mod Identifier)
indentedParagraphs = (concat <$> dropFrontOfPara " ") >>= parseParagraphs
-- | Grab as many fully indented paragraphs as we can.
dropFrontOfPara :: Parser BS.ByteString -> Parser [String]
dropFrontOfPara sp = do
currentParagraph <- some (sp *> takeNonEmptyLine)
followingParagraphs <-
skipHorizontalSpace *> nextPar -- we have more paragraphs to take
<|> skipHorizontalSpace *> nlList -- end of the ride, remember the newline
<|> endOfInput *> return [] -- nothing more to take at all
return (currentParagraph ++ followingParagraphs)
where
nextPar = (++) <$> nlList <*> dropFrontOfPara sp
nlList = "\n" *> return ["\n"]
nonSpace :: BS.ByteString -> Parser BS.ByteString
nonSpace xs
| not $ any (not . isSpace) $ decodeUtf8 xs = fail "empty line"
| otherwise = return xs
-- | Takes a non-empty, not fully whitespace line.
--
-- Doesn't discard the trailing newline.
takeNonEmptyLine :: Parser String
takeNonEmptyLine = do
(++ "\n") . decodeUtf8 <$> (takeWhile1 (/= '\n') >>= nonSpace) <* "\n"
-- | Blocks of text of the form:
--
-- >> foo
-- >> bar
-- >> baz
--
birdtracks :: Parser (DocH mod a)
birdtracks = DocCodeBlock . DocString . intercalate "\n" . stripSpace <$> many1 line
where
line = skipHorizontalSpace *> ">" *> takeLine
stripSpace :: [String] -> [String]
stripSpace = fromMaybe <*> mapM strip'
where
strip' (' ':xs') = Just xs'
strip' "" = Just ""
strip' _ = Nothing
-- | Parses examples. Examples are a paragraph level entitity (separated by an empty line).
-- Consecutive examples are accepted.
examples :: Parser (DocH mod a)
examples = DocExamples <$> (many (skipHorizontalSpace *> "\n") *> go)
where
go :: Parser [Example]
go = do
prefix <- decodeUtf8 <$> takeHorizontalSpace <* ">>>"
expr <- takeLine
(rs, es) <- resultAndMoreExamples
return (makeExample prefix expr rs : es)
where
resultAndMoreExamples :: Parser ([String], [Example])
resultAndMoreExamples = moreExamples <|> result <|> pure ([], [])
where
moreExamples :: Parser ([String], [Example])
moreExamples = (,) [] <$> go
result :: Parser ([String], [Example])
result = first . (:) <$> nonEmptyLine <*> resultAndMoreExamples
makeExample :: String -> String -> [String] -> Example
makeExample prefix expression res =
Example (strip expression) result
where
result = map (substituteBlankLine . tryStripPrefix) res
tryStripPrefix xs = fromMaybe xs (stripPrefix prefix xs)
substituteBlankLine "<BLANKLINE>" = ""
substituteBlankLine xs = xs
nonEmptyLine :: Parser String
nonEmptyLine = mfilter (any (not . isSpace)) takeLine
takeLine :: Parser String
takeLine = decodeUtf8 <$> takeWhile (/= '\n') <* endOfLine
endOfLine :: Parser ()
endOfLine = void "\n" <|> endOfInput
-- | Property parser.
--
-- >>> snd <$> parseOnly property "prop> hello world"
-- Right (DocProperty "hello world")
property :: Parser (DocH mod a)
property = DocProperty . strip . decodeUtf8 <$> ("prop>" *> takeWhile1 (/= '\n'))
-- |
-- Paragraph level codeblock. Anything between the two delimiting \@ is parsed
-- for markup.
codeblock :: Parser (DocH mod Identifier)
codeblock =
DocCodeBlock . parseStringBS . dropSpaces
<$> ("@" *> skipHorizontalSpace *> "\n" *> block' <* "@")
where
dropSpaces xs =
let rs = decodeUtf8 xs
in case splitByNl rs of
[] -> xs
ys -> case last ys of
' ':_ -> case mapM dropSpace ys of
Nothing -> xs
Just zs -> encodeUtf8 $ intercalate "\n" zs
_ -> xs
-- This is necessary because ‘lines’ swallows up a trailing newline
-- and we lose information about whether the last line belongs to @ or to
-- text which we need to decide whether we actually want to be dropping
-- anything at all.
splitByNl = unfoldr (\x -> case x of
'\n':s -> Just (span (/= '\n') s)
_ -> Nothing)
. ('\n' :)
dropSpace "" = Just ""
dropSpace (' ':xs) = Just xs
dropSpace _ = Nothing
block' = scan False p
where
p isNewline c
| isNewline && c == '@' = Nothing
| isNewline && isSpace c = Just isNewline
| otherwise = Just $ c == '\n'
hyperlink :: Parser (DocH mod a)
hyperlink = DocHyperlink . makeLabeled Hyperlink . decodeUtf8
<$> disallowNewline ("<" *> takeUntil ">")
<|> autoUrl
<|> markdownLink
markdownLink :: Parser (DocH mod a)
markdownLink = DocHyperlink <$> linkParser
linkParser :: Parser Hyperlink
linkParser = flip Hyperlink <$> label <*> (whitespace *> url)
where
label :: Parser (Maybe String)
label = Just . strip . decode <$> ("[" *> takeUntil "]")
whitespace :: Parser ()
whitespace = skipHorizontalSpace <* optional ("\n" *> skipHorizontalSpace)
url :: Parser String
url = rejectWhitespace (decode <$> ("(" *> takeUntil ")"))
rejectWhitespace :: MonadPlus m => m String -> m String
rejectWhitespace = mfilter (all (not . isSpace))
decode :: BS.ByteString -> String
decode = removeEscapes . decodeUtf8
-- | Looks for URL-like things to automatically hyperlink even if they
-- weren't marked as links.
autoUrl :: Parser (DocH mod a)
autoUrl = mkLink <$> url
where
url = mappend <$> ("http://" <|> "https://" <|> "ftp://") <*> takeWhile1 (not . isSpace)
mkLink :: BS.ByteString -> DocH mod a
mkLink s = case unsnoc s of
Just (xs, x) | x `elem` (",.!?" :: String) -> DocHyperlink (Hyperlink (decodeUtf8 xs) Nothing) `docAppend` DocString [x]
_ -> DocHyperlink (Hyperlink (decodeUtf8 s) Nothing)
-- | Parses strings between identifier delimiters. Consumes all input that it
-- deems to be valid in an identifier. Note that it simply blindly consumes
-- characters and does no actual validation itself.
parseValid :: Parser String
parseValid = p some
where
idChar = satisfy (`elem` ("_.!#$%&*+/<=>?@\\|-~:^"::String))
<|> digit <|> letter_ascii
p p' = do
vs' <- p' $ utf8String "⋆" <|> return <$> idChar
let vs = concat vs'
c <- peekChar'
case c of
'`' -> return vs
'\'' -> (\x -> vs ++ "'" ++ x) <$> ("'" *> p many') <|> return vs
_ -> fail "outofvalid"
-- | Parses UTF8 strings from ByteString streams.
utf8String :: String -> Parser String
utf8String x = decodeUtf8 <$> string (encodeUtf8 x)
-- | Parses identifiers with help of 'parseValid'. Asks GHC for
-- 'String' from the string it deems valid.
identifier :: Parser (DocH mod Identifier)
identifier = do
o <- idDelim
vid <- parseValid
e <- idDelim
return $ DocIdentifier (o, vid, e)
where
idDelim = char '\'' <|> char '`'
| mrBliss/haddock | haddock-library/src/Documentation/Haddock/Parser.hs | bsd-2-clause | 20,544 | 0 | 20 | 4,725 | 5,270 | 2,776 | 2,494 | 322 | 22 |
-- |
-- Module : Data.ByteString.Search
-- Copyright : Daniel Fischer (2007-2011)
-- Chris Kuklewicz
-- Licence : BSD3
-- Maintainer : Daniel Fischer <daniel.is.fischer@googlemail.com>
-- Stability : Provisional
-- Portability : non-portable (BangPatterns)
--
-- Fast overlapping Boyer-Moore search of strict
-- 'S.ByteString' values. Breaking, splitting and replacing
-- using the Boyer-Moore algorithm.
--
-- Descriptions of the algorithm can be found at
-- <http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140>
-- and
-- <http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm>
--
-- Original authors: Daniel Fischer (daniel.is.fischer at googlemail.com) and
-- Chris Kuklewicz (haskell at list.mightyreason.com).
module Data.ByteString.Search ( -- * Overview
-- $overview
-- ** Performance
-- $performance
-- ** Complexity
-- $complexity
-- ** Partial application
-- $partial
-- * Finding substrings
indices
, nonOverlappingIndices
-- * Breaking on substrings
, breakOn
, breakAfter
-- * Replacing
, replace
-- * Splitting
, split
, splitKeepEnd
, splitKeepFront
) where
import qualified Data.ByteString.Search.Internal.BoyerMoore as BM
import Data.ByteString.Search.Substitution
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
-- $overview
--
-- This module provides functions related to searching a substring within
-- a string, using the Boyer-Moore algorithm with minor modifications
-- to improve the overall performance and avoid the worst case
-- performance degradation of the original Boyer-Moore algorithm for
-- periodic patterns.
--
-- When searching a pattern in a UTF-8-encoded 'S.ByteString', be aware that
-- these functions work on bytes, not characters, so the indices are
-- byte-offsets, not character offsets.
-- $performance
--
-- In general, the Boyer-Moore algorithm is the most efficient method to
-- search for a pattern inside a string. The advantage over other algorithms
-- (e.g. Naïve, Knuth-Morris-Pratt, Horspool, Sunday) can be made
-- arbitrarily large for specially selected patterns and targets, but
-- usually, it's a factor of 2–3 versus Knuth-Morris-Pratt and of
-- 6–10 versus the naïve algorithm. The Horspool and Sunday
-- algorithms, which are simplified variants of the Boyer-Moore algorithm,
-- typically have performance between Boyer-Moore and Knuth-Morris-Pratt,
-- mostly closer to Boyer-Moore. The advantage of the Boyer-moore variants
-- over other algorithms generally becomes larger for longer patterns. For
-- very short patterns (or patterns with a very short period), other
-- algorithms, e.g. "Data.ByteString.Search.DFA" can be faster (my
-- tests suggest that \"very short\" means two, maybe three bytes).
--
-- In general, searching in a strict 'S.ByteString' is slightly faster
-- than searching in a lazy 'L.ByteString', but for long targets, the
-- smaller memory footprint of lazy 'L.ByteString's can make searching
-- those (sometimes much) faster. On the other hand, there are cases
-- where searching in a strict target is much faster, even for long targets.
-- $complexity
--
-- Preprocessing the pattern is /O/(@patternLength@ + σ) in time and
-- space (σ is the alphabet size, 256 here) for all functions.
-- The time complexity of the searching phase for 'indices'
-- is /O/(@targetLength@ \/ @patternLength@) in the best case.
-- For non-periodic patterns, the worst case complexity is
-- /O/(@targetLength@), but for periodic patterns, the worst case complexity
-- is /O/(@targetLength@ * @patternLength@) for the original Boyer-Moore
-- algorithm.
--
-- The searching functions in this module contain a modification which
-- drastically improves the performance for periodic patterns.
-- I believe that for strict target strings, the worst case is now
-- /O/(@targetLength@) also for periodic patterns.
-- I may be wrong, though.
--
-- The other functions don't have to deal with possible overlapping
-- patterns, hence the worst case complexity for the processing phase
-- is /O/(@targetLength@) (respectively /O/(@firstIndex + patternLength@)
-- for the breaking functions if the pattern occurs).
-- $partial
--
-- All functions can usefully be partially applied. Given only a pattern,
-- the pattern is preprocessed only once, allowing efficient re-use.
------------------------------------------------------------------------------
-- Exported Functions --
------------------------------------------------------------------------------
-- | @'indices'@ finds the starting indices of all possibly overlapping
-- occurrences of the pattern in the target string.
-- If the pattern is empty, the result is @[0 .. 'length' target]@.
--
-- In general, @'not' . 'null' $ 'indices' pat target@ is a much more
-- efficient version of 'S.isInfixOf'.
{-# INLINE indices #-}
indices :: S.ByteString -- ^ Pattern to find
-> S.ByteString -- ^ String to search
-> [Int] -- ^ Offsets of matches
indices = BM.matchSS
-- | @'nonOverlappingIndices'@ finds the starting indices of all
-- non-overlapping occurrences of the pattern in the target string.
-- It is more efficient than removing indices from the list produced
-- by 'indices'.
{-# INLINE nonOverlappingIndices #-}
nonOverlappingIndices :: S.ByteString -- ^ Pattern to find
-> S.ByteString -- ^ String to search
-> [Int] -- ^ Offsets of matches
nonOverlappingIndices = BM.matchNOS
-- | @'breakOn' pattern target@ splits @target@ at the first occurrence
-- of @pattern@. If the pattern does not occur in the target, the
-- second component of the result is empty, otherwise it starts with
-- @pattern@. If the pattern is empty, the first component is empty.
--
-- @
-- 'uncurry' 'S.append' . 'breakOn' pattern = 'id'
-- @
{-# INLINE breakOn #-}
breakOn :: S.ByteString -- ^ String to search for
-> S.ByteString -- ^ String to search in
-> (S.ByteString, S.ByteString)
-- ^ Head and tail of string broken at substring
breakOn = BM.breakSubstringS
-- | @'breakAfter' pattern target@ splits @target@ behind the first occurrence
-- of @pattern@. An empty second component means that either the pattern
-- does not occur in the target or the first occurrence of pattern is at
-- the very end of target. To discriminate between those cases, use e.g.
-- 'S.isSuffixOf'.
--
-- @
-- 'uncurry' 'S.append' . 'breakAfter' pattern = 'id'
-- @
{-# INLINE breakAfter #-}
breakAfter :: S.ByteString -- ^ String to search for
-> S.ByteString -- ^ String to search in
-> (S.ByteString, S.ByteString)
-- ^ Head and tail of string broken after substring
breakAfter = BM.breakAfterS
-- | @'replace' pat sub text@ replaces all (non-overlapping) occurrences of
-- @pat@ in @text@ with @sub@. If occurrences of @pat@ overlap, the first
-- occurrence that does not overlap with a replaced previous occurrence
-- is substituted. Occurrences of @pat@ arising from a substitution
-- will not be substituted. For example:
--
-- @
-- 'replace' \"ana\" \"olog\" \"banana\" = \"bologna\"
-- 'replace' \"ana\" \"o\" \"bananana\" = \"bono\"
-- 'replace' \"aab\" \"abaa\" \"aaabb\" = \"aabaab\"
-- @
--
-- The result is a /lazy/ 'L.ByteString',
-- which is lazily produced, without copying.
-- Equality of pattern and substitution is not checked, but
--
-- @
-- ('S.concat' . 'L.toChunks' $ 'replace' pat pat text) == text
-- @
--
-- holds. If the pattern is empty but not the substitution, the result
-- is equivalent to (were they 'String's) @'cycle' sub@.
--
-- For non-empty @pat@ and @sub@ a strict 'S.ByteString',
--
-- @
-- 'L.fromChunks' . 'Data.List.intersperse' sub . 'split' pat = 'replace' pat sub
-- @
--
-- and analogous relations hold for other types of @sub@.
{-# INLINE replace #-}
replace :: Substitution rep
=> S.ByteString -- ^ Substring to replace
-> rep -- ^ Replacement string
-> S.ByteString -- ^ String to modify
-> L.ByteString -- ^ Lazy result
replace = BM.replaceAllS
-- | @'split' pattern target@ splits @target@ at each (non-overlapping)
-- occurrence of @pattern@, removing @pattern@. If @pattern@ is empty,
-- the result is an infinite list of empty 'S.ByteString's, if @target@
-- is empty but not @pattern@, the result is an empty list, otherwise
-- the following relations hold:
--
-- @
-- 'S.concat' . 'Data.List.intersperse' pat . 'split' pat = 'id',
-- 'length' ('split' pattern target) ==
-- 'length' ('nonOverlappingIndices' pattern target) + 1,
-- @
--
-- no fragment in the result contains an occurrence of @pattern@.
{-# INLINE split #-}
split :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ Fragments of string
split = BM.splitDropS
-- | @'splitKeepEnd' pattern target@ splits @target@ after each (non-overlapping)
-- occurrence of @pattern@. If @pattern@ is empty, the result is an
-- infinite list of empty 'S.ByteString's, otherwise the following
-- relations hold:
--
-- @
-- 'S.concat' . 'splitKeepEnd' pattern = 'id',
-- @
--
-- all fragments in the result except possibly the last end with
-- @pattern@, no fragment contains more than one occurrence of @pattern@.
{-# INLINE splitKeepEnd #-}
splitKeepEnd :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ Fragments of string
splitKeepEnd = BM.splitKeepEndS
-- | @'splitKeepFront'@ is like 'splitKeepEnd', except that @target@ is split
-- before each occurrence of @pattern@ and hence all fragments
-- with the possible exception of the first begin with @pattern@.
-- No fragment contains more than one non-overlapping occurrence
-- of @pattern@.
{-# INLINE splitKeepFront #-}
splitKeepFront :: S.ByteString -- ^ Pattern to split on
-> S.ByteString -- ^ String to split
-> [S.ByteString] -- ^ Fragments of string
splitKeepFront = BM.splitKeepFrontS
| seereason/stringsearch | Data/ByteString/Search.hs | bsd-3-clause | 10,918 | 0 | 9 | 2,670 | 525 | 395 | 130 | 55 | 1 |
-- | main entry point for tests
module Main where
import Test.Framework
import Test.Unit
import Test.Pretty
import Test.Diff
import Test.Arbitrary
-- entry point for the test-suite
main = defaultMain tests
tests = [tests_diff
,tests_unit
,test_arbitrary
--,tests_pretty -- disabled the pretty tests until version 1.0
]
| sinelaw/language-ecmascript | test/TestMain.hs | bsd-3-clause | 364 | 0 | 5 | 90 | 54 | 34 | 20 | 10 | 1 |
module Graphics.Wayland.Scanner.Protocol (
readProtocol, parseFile
) where
import Data.Functor
import Data.Maybe
import Data.Char
import Text.XML.Light
import System.Process
import Language.Haskell.TH (mkName)
import Graphics.Wayland.Scanner.Types
import Graphics.Wayland.Scanner.Names
interface = QName "interface" Nothing Nothing
request = QName "request" Nothing Nothing
event = QName "event" Nothing Nothing
enum = QName "enum" Nothing Nothing
entry = QName "entry" Nothing Nothing
arg = QName "arg" Nothing Nothing
namexml = QName "name" Nothing Nothing
version = QName "version" Nothing Nothing
allow_null = QName "allow-null" Nothing Nothing
typexml = QName "type" Nothing Nothing
value = QName "value" Nothing Nothing
parseInterface :: ProtocolName -> Element -> Interface
parseInterface pname elt =
let iname = fromJust $ findAttr namexml elt
parseMessage :: Element -> Maybe Message
parseMessage msgelt = do -- we're gonna do some fancy construction to skip messages we can't deal with yet
let name = fromJust $ findAttr namexml msgelt
arguments <- mapM parseArgument (findChildren arg msgelt)
let destructorVal = findAttr typexml msgelt
let isDestructor = case destructorVal of
Nothing -> False
Just str -> str=="destructor"
return Message {messageName = name, messageArguments = arguments, messageIsDestructor = isDestructor} where
parseArgument argelt = do
let msgname = fromJust $ findAttr namexml argelt
let argtypecode = fromJust $ findAttr typexml argelt
argtype <- case argtypecode of
"object" -> ObjectArg . mkName . interfaceTypeName pname <$> findAttr interface argelt
"new_id" -> (\iname -> NewIdArg (mkName $ interfaceTypeName pname iname) iname) <$> findAttr interface argelt
_ -> lookup argtypecode argConversionTable
let allowNull = fromMaybe False (read <$> capitalize <$> findAttr allow_null argelt)
return (msgname, argtype, allowNull)
parseEnum enumelt =
let enumname = fromJust $ findAttr namexml enumelt
entries = map parseEntry $ findChildren entry enumelt
in WLEnum {enumName = enumname, enumEntries = entries} where
parseEntry entryelt = (fromJust $ findAttr namexml entryelt,
read $ fromJust $ findAttr value entryelt :: Int)
in Interface {
interfaceName = iname,
interfaceVersion = read $ fromJust $ findAttr version elt, -- unused atm
interfaceRequests = mapMaybe parseMessage (findChildren request elt),
interfaceEvents = mapMaybe parseMessage (findChildren event elt),
interfaceEnums = map parseEnum $ findChildren enum elt
}
parseProtocol :: [Content] -> ProtocolSpec
parseProtocol xmlTree =
let subTree = (!!1) $ onlyElems xmlTree -- cut off XML header stuff
pname = fromJust $ findAttr namexml subTree
interfaces = map (parseInterface pname) $ findChildren interface subTree
in ProtocolSpec pname interfaces
parseFile :: FilePath -> IO ProtocolSpec
parseFile filename = do
fileContents <- readFile filename
return $ parseProtocol $ parseXML fileContents
-- | locate wayland.xml on disk and parse it
readProtocol :: IO ProtocolSpec
readProtocol = do
datadir <- figureOutWaylandDataDir
parseFile (datadir ++ "/" ++ protocolFile)
-- TODO move this into some pretty Setup.hs thing as soon as someone complains about portability
figureOutWaylandDataDir :: IO String
figureOutWaylandDataDir =
head <$> lines <$> readProcess "pkg-config" ["wayland-server", "--variable=pkgdatadir"] []
protocolFile = "wayland.xml"
| abooij/haskell-wayland | Graphics/Wayland/Scanner/Protocol.hs | mit | 3,814 | 0 | 23 | 923 | 945 | 481 | 464 | 72 | 4 |
-- It is generally a good idea to keep all your business logic in your library
-- and only use it in the executable. Doing so allows others to use what you
-- wrote in their libraries.
import qualified Example
main :: IO ()
main = Example.main
| wz1000/haskell-webapps | ServantOpaleye/executable/Main.hs | mit | 245 | 0 | 6 | 48 | 25 | 15 | 10 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Trace.Hpc.Coveralls.GitInfo (getGitInfo, GitInfo) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (guard)
import Data.Aeson
import Data.List (nubBy)
import Data.Function (on)
import System.Process (readProcess)
data GitInfo = GitInfo { headRef :: Commit
, branch :: String
, remotes :: [Remote] }
instance ToJSON GitInfo where
toJSON i = object [ "head" .= headRef i
, "branch" .= branch i
, "remotes" .= remotes i]
data Commit = Commit { hash :: String
, authorName :: String
, authorEmail :: String
, committerName :: String
, committerEmail :: String
, message :: String }
instance ToJSON Commit where
toJSON c = object [ "id" .= hash c
, "author_name" .= authorName c
, "author_email" .= authorEmail c
, "committer_name" .= committerName c
, "committer_email" .= committerEmail c
, "message" .= message c ]
data Remote = Remote { name :: String
, url :: String }
instance ToJSON Remote where
toJSON r = object [ "name" .= name r
, "url" .= url r ]
git :: [String] -> IO String
git args = init <$> readProcess "git" args [] -- init to strip trailing \n
-- | Get information about the Git repo in the current directory.
getGitInfo :: IO GitInfo
getGitInfo = GitInfo <$> headRef <*> branch <*> getRemotes where
headRef = Commit <$> git ["rev-parse", "HEAD"]
<*> git ["log", "-1", "--pretty=%aN"] <*> git ["log", "-1", "--pretty=%aE"]
<*> git ["log", "-1", "--pretty=%cN"] <*> git ["log", "-1", "--pretty=%cE"]
<*> git ["log", "-1", "--pretty=%s"]
branch = git ["rev-parse", "--abbrev-ref", "HEAD"]
getRemotes :: IO [Remote]
getRemotes = nubBy ((==) `on` name) <$> parseRemotes <$> git ["remote", "-v"] where
parseRemotes :: String -> [Remote]
parseRemotes input = do
line <- lines input
let fields = words line
guard $ length fields >= 2
return $ Remote (head fields) (fields !! 1)
| jdnavarro/hpc-coveralls | src/Trace/Hpc/Coveralls/GitInfo.hs | bsd-3-clause | 2,381 | 0 | 14 | 836 | 652 | 359 | 293 | 50 | 1 |
module Distribution.Server.Packages.ChangeLog (
isChangeLogFile
) where
import System.FilePath (splitExtension)
import Data.Char as Char
isChangeLogFile :: FilePath -> Bool
isChangeLogFile fname = map Char.toLower base `elem` basenames
&& ext `elem` extensions
where
(base, ext) = splitExtension fname
basenames = ["news", "changelog", "change_log", "changes"]
extensions = ["", ".txt", ".md", ".markdown"]
| agrafix/hackage-server | Distribution/Server/Packages/ChangeLog.hs | bsd-3-clause | 456 | 0 | 9 | 97 | 121 | 73 | 48 | 10 | 1 |
import System.Environment
import System.IO
import Text.ParserCombinators.Parsec
import Control.Monad
import Data.ByteString.Lazy.Char8 as BS hiding (take,drop,filter,head,last,map,zip,repeat)
import Control.Applicative hiding ((<|>), many)
import Data.Char
{--
join2(Open usp Tukubai)
designed by Nobuaki Tounaka
written by Ryuichi Ueda
The MIT License
Copyright (C) 2012 Universal Shell Programming Laboratory
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--}
showUsage :: IO ()
showUsage = do System.IO.hPutStr stderr ("Usage : join2 [+ng] <key=n> <master> <tran>\n" ++
"Sun Jul 28 16:20:53 JST 2013\n" ++
"Open usp Tukubai (LINUX+FREEBSD), Haskell ver.\n")
main :: IO ()
main = do args <- getArgs
case args of
["-h"] -> showUsage
["--help"] -> showUsage
[delim,key,master,tran] -> mainProc delim key master tran
[a,b,c] -> if (a !! 0) == 'k'
then mainProc "" a b c
else mainProc a b c "-"
[key,master] -> mainProc "" key master "-"
mainProc :: String -> String -> String -> String -> IO ()
mainProc delim key master tran = do ms <- readF master
ts <- readF tran
mainProc' (parseKey key) ms ts (readDelim delim)
readF :: String -> IO BS.ByteString
readF "-" = BS.getContents
readF f = BS.readFile f
readDelim :: String -> String
readDelim "" = ""
readDelim ('+':str) = str
readDelim ('-':'d':str) = str
parseKey :: String -> Keys
parseKey str = case parse keys "" str of
Right opt -> opt
Left err -> Error (show err)
mainProc' :: Keys -> BS.ByteString -> BS.ByteString -> String -> IO ()
mainProc' (Keys ks) ms ts delim = out (join2 (makeDummy mlines delim) (head mlines) (drop 1 mlines) tlines)
where mlines = parseMaster ks (BS.lines ms) delim
tlines = parseTran ks (BS.lines ts)
out :: [OutTran] -> IO ()
out [] = do return ()
out (ln:lns) = (BS.putStrLn ln) >> (out lns)
join2 :: [BS.ByteString] -> Master -> [Master] -> [Tran] -> [OutTran]
join2 _ _ _ [] = []
join2 dv (Master mk v) [] ((Tran p tk a):ts)
| mk == tk = makeLine (Master mk v) (Tran p tk a) : join2 dv (Master mk v) [] ts
| otherwise = makeLine (Master tk dv) (Tran p tk a) : join2 dv (Master mk v) [] ts
join2 dv (Master mk v) (m:ms) ((Tran p tk a):ts)
| mk == tk = makeLine (Master mk v) (Tran p tk a) : join2 dv (Master mk v) (m:ms) ts
| mk < tk = join2 dv m ms ((Tran p tk a):ts)
| otherwise = makeLine (Master tk dv) (Tran p tk a) : join2 dv (Master mk v) (m:ms) ts
{--
join2 :: [Master] -> Tran -> OutTran
join2 ms (Tran p k a) = makeLine (pickMaster ms k) (Tran p k a)
--}
makeLine :: Master -> Tran -> OutTran
makeLine (Master [] v) (Tran p k a) = BS.unwords $ p ++ k ++ v ++ a
makeLine (Master k v) (Tran p _ a) = BS.unwords $ p ++ k ++ v ++ a
myWords :: BS.ByteString -> [BS.ByteString]
myWords line = BS.split ' ' line
pickMaster :: [Master] -> [BS.ByteString] -> Master
pickMaster ms k = if Prelude.length matched > 0 then head matched else dummy
where matched = filter ( matchMaster k ) ms
a = last ms
dummy = f a
f (Master _ v) = Master [] v
matchMaster k (Master a b) = k == a
parseMaster :: [Int] -> [BS.ByteString] -> String -> [Master]
parseMaster ks lines delim = [ f (Prelude.length ks) (myWords ln) | ln <- lines ]
where f n ws = Master (take n ws) (drop n ws)
makeDummy :: [Master] -> String -> [BS.ByteString]
makeDummy ms "" = [ BS.pack $ take y ( repeat '*' ) | y <- x ]
where x = maxLengths [ getValueLength m | m <- ms ]
makeDummy ms str = [ BS.pack str | y <- (g (head ms)) ]
where g (Master _ b) = b
maxLengths :: [[Int]] -> [Int]
maxLengths (vsr:vsl:[]) = [ if (fst z) > (snd z) then fst z else snd z | z <- (zip vsr vsl)]
maxLengths (vsr:vsl:vss) = maxLengths (a:vss)
where zs = zip vsr vsl
a = [ if (fst z) > (snd z) then fst z else snd z | z <- zs]
getValueLength :: Master -> [Int]
getValueLength (Master k v) = map ( wc . BS.unpack ) v
parseTran :: [Int] -> [BS.ByteString] -> [Tran]
parseTran ks lines = [ parseTran' ks (myWords ln) | ln <- lines ]
parseTran' :: [Int] -> [BS.ByteString] -> Tran
parseTran' ks ws = Tran (take pre ws) (take (Prelude.length ks) rem) (drop (Prelude.length ks) rem)
where pre = (ks !! 0) - 1
rem = drop pre ws
wc :: String -> Int
wc [] = 0
wc (c:[]) = 1
wc (c:a:[]) = 2
wc (c:a:b:cs) = wc' $ ord c
where wc' n = if n < 128
then 1 + wc (a:b:cs)
else (hanzen (n*256*256+(ord a)*256+(ord b))) + wc cs
hanzen m = if m >= 0xEFBDA1 && m <= 0xEFBE9F then 1 else 2
data Keys = Keys [Int] | Error String
data Master = Master [BS.ByteString] [BS.ByteString] deriving Show -- keys and values
data Tran = Tran [BS.ByteString] [BS.ByteString] [BS.ByteString] deriving Show -- values and keys and values
type OutTran = BS.ByteString
keys = string "key=" >> (try(rangekey) <|> try(singlekey) )
singlekey = do n <- many1 digit
return $ Keys [read n::Int]
rangekey = do n <- many1 digit
char '/'
m <- many1 digit
return $ Keys [(read n::Int)..(read m::Int)]
| ShellShoccar-jpn/Open-usp-Tukubai | COMMANDS.HS/join2.hs | mit | 6,716 | 0 | 16 | 2,032 | 2,401 | 1,236 | 1,165 | 105 | 6 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
module PlaceHolder where
import Type ( Type )
import Outputable
import Name
import NameSet
import RdrName
import Var
import Coercion
import ConLike (ConLike)
import FieldLabel
import SrcLoc (Located)
import TcEvidence ( HsWrapper )
import Data.Data hiding ( Fixity )
import BasicTypes (Fixity)
{-
%************************************************************************
%* *
\subsection{Annotating the syntax}
%* *
%************************************************************************
-}
-- NB: These are intentionally open, allowing API consumers (like Haddock)
-- to declare new instances
-- | used as place holder in PostTc and PostRn values
data PlaceHolder = PlaceHolder
deriving (Data,Typeable)
-- | Types that are not defined until after type checking
type family PostTc id ty -- Note [Pass sensitive types]
type instance PostTc Id ty = ty
type instance PostTc Name ty = PlaceHolder
type instance PostTc RdrName ty = PlaceHolder
-- | Types that are not defined until after renaming
type family PostRn id ty -- Note [Pass sensitive types]
type instance PostRn Id ty = ty
type instance PostRn Name ty = ty
type instance PostRn RdrName ty = PlaceHolder
placeHolderKind :: PlaceHolder
placeHolderKind = PlaceHolder
placeHolderFixity :: PlaceHolder
placeHolderFixity = PlaceHolder
placeHolderType :: PlaceHolder
placeHolderType = PlaceHolder
placeHolderTypeTc :: Type
placeHolderTypeTc = panic "Evaluated the place holder for a PostTcType"
placeHolderNames :: PlaceHolder
placeHolderNames = PlaceHolder
placeHolderNamesTc :: NameSet
placeHolderNamesTc = emptyNameSet
placeHolderHsWrapper :: PlaceHolder
placeHolderHsWrapper = PlaceHolder
{-
Note [Pass sensitive types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Since the same AST types are re-used through parsing,renaming and type
checking there are naturally some places in the AST that do not have
any meaningful value prior to the pass they are assigned a value.
Historically these have been filled in with place holder values of the form
panic "error message"
This has meant the AST is difficult to traverse using standard generic
programming techniques. The problem is addressed by introducing
pass-specific data types, implemented as a pair of open type families,
one for PostTc and one for PostRn. These are then explicitly populated
with a PlaceHolder value when they do not yet have meaning.
In terms of actual usage, we have the following
PostTc id Kind
PostTc id Type
PostRn id Fixity
PostRn id NameSet
TcId and Var are synonyms for Id
-}
type DataId id =
( Data id
, Data (PostRn id NameSet)
, Data (PostRn id Fixity)
, Data (PostRn id Bool)
, Data (PostRn id Name)
, Data (PostRn id (Located Name))
, Data (PostRn id [Name])
-- , Data (PostRn id [id])
, Data (PostRn id id)
, Data (PostTc id Type)
, Data (PostTc id Coercion)
, Data (PostTc id id)
, Data (PostTc id [Type])
, Data (PostTc id ConLike)
, Data (PostTc id [ConLike])
, Data (PostTc id HsWrapper)
, Data (PostTc id [FieldLabel])
)
| tjakway/ghcjvm | compiler/hsSyn/PlaceHolder.hs | bsd-3-clause | 3,361 | 0 | 10 | 710 | 509 | 293 | 216 | 60 | 1 |
module Main where
import Eval
import Parser
import Pretty
import Control.Monad.Trans
import System.Console.Haskeline
process :: String -> IO ()
process line = do
let res = parseExpr line
case res of
Left err -> print err
Right ex -> case eval ex of
Nothing -> putStrLn "Cannot evaluate"
Just result -> putStrLn $ ppexpr result
main :: IO ()
main = runInputT defaultSettings loop
where
loop = do
minput <- getInputLine "Arith> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just input -> (liftIO $ process input) >> loop
| yupferris/write-you-a-haskell | chapter3/calc/Main.hs | mit | 576 | 0 | 15 | 141 | 195 | 95 | 100 | 21 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.