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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- | How big of a sofa can we get around a corner?
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
module Main where
import GHC.Generics ( Generic1 )
import Data.Proxy ( Proxy(..) )
import Data.IORef ( newIORef, readIORef, writeIORef )
import qualified Data.Foldable as F
import Data.Binary
import qualified System.ZMQ4 as ZMQ
import Data.ByteString.Char8 ( pack )
import Data.ByteString.Lazy ( toStrict )
import Dyno.Vectorize
import Dyno.Nlp
import Dyno.NlpUtils
import Dyno.TypeVecs ( Vec )
import qualified Dyno.TypeVecs as TV
import Dyno.Solvers
import Sofa.Common
type NPoints = 81
type NSteps = 61
data X a =
X
{ xR :: a
, xPoints :: Vec NPoints (Point a)
, xStages :: Vec NSteps (Stage a)
} deriving (Functor, Generic1, Show)
data G a =
G
{ gMin90 :: Vec NPoints a
, gEqualR :: Vec NPoints a
, g360s :: Vec NPoints a
, gMean0 :: Point a
, gStages :: Vec NSteps (StageCon a)
, gCloseMean :: Vec NSteps (Point a)
, gCloseTheta :: Vec NSteps a
} deriving (Functor, Generic1, Show)
data Stage a =
Stage
{ sTheta :: a
, sMean :: Point a
, sPhis :: Vec NPoints a
} deriving (Functor, Generic1, Show)
data StageCon a =
StageCon
{ scOuters :: Vec NPoints (Point a)
, scInners :: Vec NPoints a
} deriving (Functor, Generic1, Show)
instance Applicative X where {pure = vpure; (<*>) = vapply}
instance Applicative G where {pure = vpure; (<*>) = vapply}
instance Applicative Stage where {pure = vpure; (<*>) = vapply}
instance Applicative StageCon where {pure = vpure; (<*>) = vapply}
instance Vectorize X
instance Vectorize G
instance Vectorize Stage
instance Vectorize StageCon
npoints :: Int
npoints = vlength (Proxy :: Proxy (Vec NPoints))
nsteps :: Int
nsteps = vlength (Proxy :: Proxy (Vec NSteps))
linspace :: Fractional a => a -> a -> Int -> [a]
linspace x0 xf n =
fmap
(\x -> x0 + (xf - x0)*(fromIntegral x / fromIntegral (n-1)))
$ take n [(0::Int)..]
radius0 :: Fractional a => a
radius0 = 0.3
segment0 :: Floating a => a
segment0 = 2 * radius0 * sin(pi/fromIntegral npoints)
points0 :: Vec NPoints (Point Double)
points0 = TV.mkVec' $ map (\q -> Point (radius0*cos(q)) (radius0*sin(q))) $ take npoints $ linspace 0 (2*pi) (npoints + 1)
atan2' :: RealFloat a => Point a -> a
atan2' (Point x y) = atan2 y x
--data G a =
-- G
-- { gMin90 :: Vec NPoints a
-- , gEqualR :: Vec NPoints a
-- , gMean0 :: Point a
-- , gStages :: Vec NSteps (StageCon a)
-- , gCloseMean :: Vec NSteps (Point a)
-- , gCloseTheta :: Vec NSteps a
-- } deriving (Functor, Generic1, Show)
--(f0,g0) = fg guess undefined
----worst :: Vectorize f => f Double -> Double
----worst = V.toList (fmap abs)
--
--blah :: IO ()
--blah = do
---- putStrLn $ "gmin90: " ++ show (minimum $ F.toList $ gMin90 g0)
---- putStrLn $ "gmin90: " ++ show (maximum $ F.toList $ gMin90 g0)
-- print $ gMean0 g0
-- print $ g360 g0
guess :: X Double
guess =
X
{ xR = segment0
, xPoints = points0
, xStages = TV.tvzipWith (\mean theta ->
Stage { sTheta = theta
, sMean = mean
, sPhis = pure $ min 0 (max (pi/2) (atan2' mean))
}) means0 thetas0
}
where
thetas0 :: Vec NSteps Double
thetas0 = TV.mkVec' $ linspace 0 0 nsteps
means0 :: Vec NSteps (Point Double)
means0 = TV.mkVec' $ map f (linspace (-pi/4) (3*pi/4) nsteps)
-- means0 = TV.mkVec' $ map f (linspace 0 (pi/2) npoints)
where
f :: Double -> Point Double
f q
| q <= pi/4 = fmap (/ (2*px)) p0
| otherwise = fmap (/ (2*py)) p0
where
p0 = Point px py
px = cos q
py = sin q
bx :: X Bounds
bx = X
{ xR = (Just (segment0/2), Nothing)
, xPoints = pure $ Point (Just (-5), Just 5) (Just (-5), Just 5)
, xStages = TV.mkVec' $ stage0 : replicate (nsteps-1) otherStages
}
where
stage0 =
Stage
{ sTheta = (Just 0, Just 0)
, sMean = Point (Just (-3), Just 3) (Just (-3), Just 3)
, sPhis = pure (Just 0, Just (pi/2))
}
otherStages =
Stage
{ sTheta = (Just (-4*pi), Just (4*pi))
, sMean = Point (Just (-3), Just 3) (Just (-3), Just 3)
, sPhis = pure (Just 0, Just (pi/2))
}
bg :: G Bounds
bg = G
{ gMin90 = pure (Just 0.8, Nothing)
, gEqualR = pure (Just 0, Just 0)
, gMean0 = pure (Just 0, Just 0)
, g360s = TV.mkVec' $ map (\q -> (Just (q - pi), Just (q + pi)))
$ linspace 0 (2*pi) npoints
, gStages = TV.mkVec' $ stage0 : replicate (nsteps-2) midStages ++ [stageF]
, gCloseMean = TV.mkVec' $ replicate (nsteps - 1) (pure (Just (-deltaMean), Just deltaMean)) ++ [pure (Nothing, Nothing)]
, gCloseTheta = TV.mkVec' $ replicate (nsteps - 1) (Just (-deltaTheta), Just deltaTheta) ++ [(Nothing, Nothing)]
}
where
deltaTheta = pi / fromIntegral nsteps
deltaMean = 4 / fromIntegral nsteps
stage0 = StageCon
{ scOuters = pure $ Point (Nothing, Just 1) (Nothing, Just 0)
, scInners = pure (Just 0, Nothing)
}
stageF = StageCon
{ scOuters = pure $ Point (Nothing, Just 0) (Nothing, Just 1)
, scInners = pure (Just 0, Nothing)
}
midStages = StageCon
{ scOuters = pure $ Point (Nothing, Just 1) (Nothing, Just 1)
, scInners = pure (Just 0, Nothing)
}
dot :: Num a => Point a -> Point a -> a
dot (Point x0 y0) (Point x1 y1) = x0*x1 + y0*y1
fg :: forall a . Floating a => X a -> (a, G a)
fg (X r points stages) = (f, g)
where
ds :: Vec NPoints (Point a)
ds = zipWithNext (\x0 x1 -> x1 - x0) points
curvatureRegularization = (F.sum (zipWithNext (\x0 x1 -> dot x0 x1) ds)) / (fromIntegral npoints)
f = 1*curvatureRegularization - 0.5 * (F.sum $ zipWithNext cross points)
g = G
{ gMin90 = zipWithNext (\x0 x1 -> dot x0 x1 / ((norm2 x0) * (norm2 x1))) ds
, gEqualR = fmap (\(Point x y) -> x*x + y*y - r*r) ds
, gMean0 = F.sum points / (fromIntegral npoints)
, g360s = TV.mkVec' $
drop 1 $ scanl (+) 0 $
F.toList $
zipWithNext
(\d0 d1 -> asin ((d0 `cross` d1) / ((1e-9 + norm2 d0) * (1e-9 + norm2 d1))))
ds
, gStages = fmap stageCon stages
, gCloseMean = zipWithNext (\(Stage _ mean1 _) (Stage _ mean0 _) -> mean1 - mean0) stages
, gCloseTheta = zipWithNext (\(Stage theta1 _ _) (Stage theta0 _ _) -> theta1 - theta0) stages
}
stageCon :: Stage a -> StageCon a
stageCon (Stage theta mean phis) = StageCon { scOuters = points'
, scInners = TV.tvzipWith inner points' phis
}
where
rot :: Point a -> Point a
rot (Point x y) = mean + Point (x*cos(theta) + y*sin(theta)) (-x*sin(theta) + y*cos(theta))
points' :: Vec NPoints (Point a)
points' = fmap rot points
inner (Point xij' yij') phiij = xij'*cos(phiij) + yij'*sin(phiij)
solver :: Solver
solver =
ipoptSolver
{ options =
[ ("ipopt.ma86_order", GString "metis")
, ("ipopt.max_iter", GInt 1000)
]
}
--solver = snoptSolver { options = [ ("detect_linear", Opt False) ] }
send :: Binary a => ZMQ.Socket ZMQ.Pub -> String -> a -> IO ()
send publisher chanName stuff = do
let bs = toStrict (encode stuff)
ZMQ.send publisher [ZMQ.SendMore] (pack chanName)
ZMQ.send publisher [] bs
-- ZMQ.send publisher [] (toStrict bs)
main :: IO ()
main =
ZMQ.withContext $ \context ->
ZMQ.withSocket context ZMQ.Pub $ \publisher -> do
ZMQ.bind publisher url
putStrLn $ "# design vars: " ++ show (vlength (Proxy :: Proxy X))
putStrLn $ "# constraints: " ++ show (vlength (Proxy :: Proxy G))
iters <- newIORef 0
_ <- solveNlpV "sofa_expando" solver fg bx bg guess $ Just $ \x _ -> do
k <- readIORef iters
writeIORef iters (k + 1)
let msg = SofaMessage
{ smSegmentLength = xR x
, smIters = k
, smPoints = F.toList (xPoints x)
, smMeanThetas = map (\stg -> (sMean stg, sTheta stg)) $ F.toList (xStages x)
}
--mapM_ (\stg -> print (sMean stg, sTheta stg)) $ F.toList (xStages x)
send publisher sofaChannel msg
return True
return ()
| ghorn/dynobud | dynobud/examples/SofaExpando.hs | lgpl-3.0 | 8,581 | 0 | 26 | 2,546 | 3,270 | 1,757 | 1,513 | 191 | 1 |
-- Simple theorem prover for PROP
module Tableau where
import Data.List (nub)
import Control.Monad (msum)
data Formula = Atomic Char
| Negation Formula
| Conjunction Formula Formula
| Disjunction Formula Formula
| Implication Formula Formula
| Equivalence Formula Formula
deriving Eq
instance Show Formula where
show (Atomic c ) = [c]
show (Negation f1 ) = "~" ++ (show f1)
show (Conjunction f1 f2) = '(':(show f1) ++ "^" ++ (show f2) ++ ")"
show (Disjunction f1 f2) = '(':(show f1) ++ "v" ++ (show f2) ++ ")"
show (Implication f1 f2) = '(':(show f1) ++ "->" ++ (show f2) ++ ")"
show (Equivalence f1 f2) = '(':(show f1) ++ "=" ++ (show f2) ++ ")"
data Tree a = Leaf a
| SingleBranch a (Tree a)
| MultiBranch a (Tree a) (Tree a)
deriving (Eq)
instance Show a => Show (Tree a) where
show t = schau 0 t
where
schau :: Show a => Int -> Tree a -> String
schau n (Leaf a) = "L: " ++ (show a)
schau n (SingleBranch f t) = (show f) ++ " * " ++ (schau (n+3+(length (show f))) t)
schau n (MultiBranch f t0 t1) = (show f) ++ " # " ++ (schau (n+3+(length (show f))) t0)
++ "\n" ++ (replicate (n+(length (show f))) ' ') ++ " # " ++ (schau (n+3+(length (show f))) t1)
type Path = []
type CounterExample = Path Formula
-- corresponds to (the negation of) the following: (A->B), (B->C) |- (A->C)
-- Since this is a tautology, the code should find a counterexample (and thereby prove the original)
example1 :: Formula
example1 = Conjunction (Conjunction (Implication (Atomic 'A') (Atomic 'B')) (Implication (Atomic 'B') (Atomic 'C'))) (Negation (Implication (Atomic 'A') (Atomic 'C')))
-- corresponds to (the negation of) the following: (P = Q) & (P -> (Not Q))
-- This is not a tautology, the code should be unable to find a counterexample (and hence fail to prove the original)
example2 :: Formula
example2 = Conjunction (Equivalence (Atomic 'P') (Atomic 'Q')) (Implication (Atomic 'P') (Negation (Atomic 'Q')))
-- corresponds to (the negation of) the following: ((P & Q) v (Not P & Not Q)) |- (P = Q)
example3 :: Formula
example3 = Conjunction (Disjunction (Conjunction (Atomic 'P') (Atomic 'Q')) (Conjunction (Negation (Atomic 'P')) (Negation (Atomic 'Q')))) (Negation (Equivalence (Atomic 'P') (Atomic 'Q')))
trp :: Tree a -> Tree a -> Tree a
trp (Leaf f) tn = SingleBranch f tn
trp (SingleBranch f t0) tn = SingleBranch f (t0 `trp` tn)
trp (MultiBranch f t0 t1) tn = MultiBranch f (t0 `trp` tn) (t1 `trp` tn)
treeify :: Formula -> Tree Formula
treeify f@(Atomic c) = Leaf f
treeify f@(Conjunction p q) = (treeify p) `trp` (treeify q)
treeify f@(Disjunction p q) = MultiBranch f (treeify p) (treeify q)
treeify f@(Implication p q) = MultiBranch f (treeify (Negation p)) (treeify q)
treeify f@(Equivalence p q) = MultiBranch f (treeify p `trp` treeify q) (treeify (Negation p) `trp` treeify (Negation q))
treeify f@(Negation n) = case n of
(Atomic c ) -> Leaf (Negation (Atomic c))
(Negation p ) -> treeify p
(Conjunction p q) -> MultiBranch f (treeify (Negation p)) (treeify (Negation q))
(Disjunction p q) -> (treeify (Negation p)) `trp` (treeify (Negation q))
(Implication p q) -> (treeify p) `trp` (treeify q)
(Equivalence p q) -> MultiBranch f ((treeify (Negation p)) `trp` (treeify q)) ((treeify p) `trp` (treeify (Negation q)))
pathify :: Tree Formula -> [Path Formula]
pathify (Leaf (Atomic c)) = [[(Atomic c)]]
pathify (Leaf (Negation (Atomic c))) = [[(Negation (Atomic c))]]
pathify (Leaf _) = error "Non-atomic Leaf"
pathify (SingleBranch (Atomic c) t) = map ((Atomic c):) (pathify t)
pathify (SingleBranch (Negation (Atomic c)) t) = map ((Negation (Atomic c)):) (pathify t)
pathify (SingleBranch _ t) = pathify t
pathify (MultiBranch (Atomic c) t0 t1) = (map ((Atomic c):) (pathify t0)) ++ (map ((Atomic c):) (pathify t1))
pathify (MultiBranch (Negation (Atomic c)) t0 t1) = (map ((Negation (Atomic c)):) (pathify t0)) ++ (map ((Negation (Atomic c)):) (pathify t1))
pathify (MultiBranch _ t0 t1) = (pathify t0) ++ (pathify t1)
checkPath :: Path Formula -> Maybe (Path Formula)
checkPath p = if all (isnotnegatedin p) p then Just p else Nothing
where
isnotnegatedin :: [Formula] -> Formula -> Bool
isnotnegatedin xs (Negation x) = notElem x xs
isnotnegatedin xs f@(Atomic c) = notElem (Negation f) xs
prove :: Formula -> String
prove f = case (msum . (fmap checkPath) . (fmap nub) . pathify . treeify . neg) f of Nothing -> "Tautology!"
(Just x) -> ("Not a tautology: " ++ show x)
neg :: Formula -> Formula
neg f@(Atomic c) = Negation f
neg f@(Negation n) = Negation f
neg (Conjunction p q) = Disjunction (Negation p) (Negation q)
neg (Disjunction p q) = Conjunction (Negation p) (Negation q)
neg (Implication p q) = Disjunction (Negation p) q
neg (Equivalence p q) = Disjunction (Conjunction p q) (Conjunction (Negation p) (Negation q))
| jbetzend/Haskell-playground | Tableau/Tableau.hs | unlicense | 5,375 | 0 | 20 | 1,462 | 2,334 | 1,196 | 1,138 | 78 | 6 |
module HostConfiguration
( WorkspaceNames
, HostConfiguration
, KeyMapping(..)
, workspaces
, workspaceMap
, terminal
, locale
, readHostConfiguration
, keyMappings
, isSlim
, sysInfoBar
, autostartPrograms
) where
import Control.Applicative ((<$>))
import qualified Data.Map.Strict as M
import qualified Data.Maybe as MB
import Data.HashMap.Lazy
import qualified Data.Vector as V
import Graphics.X11.Types
import Network.HostName
import System.Directory
import System.IO
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Text.Toml
import Text.Toml.Types
type NetInterfaceName = String
type ExecuteCommand = ( String, [ String ] )
type UsernameAtHostnameColonPort = String
type Hostname = String
type PortNum = String
data KeyMapping = KeyMapping
{ kmKey :: String
, kmName :: String
, kmExec :: ExecuteCommand
, kmInTerminal :: Bool
} deriving Show
type WorkspaceNames = M.Map Int String
-- | Default desktop locale, if not configured
defaultLocale = "en"
-- | Default set of workspaces, if not configured
defaultWorkspaces = M.fromList $ zip [1..] ["web","com","dev","gfx","ofc","","","",""]
-- | Default terminal to use, if not not configured
defaultTerminal = "xterm"
-- | The mode in which the sysinfobar should be displayed
data SysInfoBarMode = Slim | Full
deriving ( Read, Show, Eq )
-- | General section as read from TOML
data GeneralSection = GeneralSection
{ gen_locale :: String
, gen_terminal :: String
, gen_barMode :: SysInfoBarMode
} deriving Show
-- | Defaults for the general section
defaultGeneralSection :: GeneralSection
defaultGeneralSection = GeneralSection
{ gen_locale = "en"
, gen_terminal = defaultTerminal
, gen_barMode = Full
}
-- | Entire TOML configuration
data HostConfiguration = HostConfiguration
{ general :: GeneralSection
, workspaces :: WorkspaceNames
, autostartPrograms :: [ ExecuteCommand ]
, keyMappings :: [KeyMapping]
}
deriving Show
-- | Helper to check if we deal with a slim desktop variant
isSlim :: HostConfiguration -> Bool
isSlim hc = gen_barMode (general hc) == Slim
-- | Retrieves the current terminal application
terminal :: HostConfiguration -> String
terminal hc = gen_terminal (general hc)
-- | Retrieves the current locale
locale :: HostConfiguration -> String
locale hc = gen_locale (general hc)
-- | Retrieves the current workspace map as a Map
workspaceMap :: HostConfiguration -> M.Map String String
workspaceMap hc = M.foldrWithKey (\k v m -> M.insert v (wsname k v) m) M.empty (workspaces hc)
where wsname i n
| isSlim hc = show i
| otherwise = concat [ show i, ":", n ]
-- | Defaults for the entire TOML configuration
defaultHostConfiguration :: HostConfiguration
defaultHostConfiguration = HostConfiguration
{ general = defaultGeneralSection
, workspaces = defaultWorkspaces
, autostartPrograms = []
, keyMappings = []
}
-- | Reads the TOML general section with fallbacks
parseGeneralSection :: Table -> GeneralSection
parseGeneralSection g =
GeneralSection
(case g ! T.pack "locale" of
VString l -> T.unpack l
_ -> defaultLocale
)
(case g ! T.pack "terminal" of
VString t -> T.unpack t
_ -> defaultTerminal
)
(case g ! T.pack "slimscreen" of
VBoolean bm -> if bm then Slim
else gen_barMode defaultGeneralSection
_ -> gen_barMode defaultGeneralSection
)
-- | Reads the TOML workspaces section with fallback
parseWorkSpaceSection :: Table -> WorkspaceNames
parseWorkSpaceSection w =
M.fromList
[
(num, T.unpack n) | num <- [1..9],
let tnum = T.pack (show num),
member tnum w,
let VString n = w ! T.pack (show num)
]
-- | Parses an exec specification
parseExec :: Node -> Maybe ExecuteCommand
parseExec e =
case e of
VArray v -> let cmd = traverse
(\x -> case x of
VString t -> Just $ T.unpack t
_ -> Nothing
) (V.toList v)
in
case cmd of
Just (bin:args) -> Just (bin, args)
_ -> Nothing
_ -> Nothing
-- | Parses the autostart section, falls back to empty
parseAutostartSection :: Table -> [ExecuteCommand]
parseAutostartSection a =
case a ! T.pack "exec" of
VArray v -> MB.mapMaybe parseExec (V.toList v)
_ -> autostartPrograms defaultHostConfiguration
-- | Parses a key mapping from the mapping section
parseMapping :: Table -> Maybe KeyMapping
parseMapping mt =
let k = case mt ! T.pack "key" of
VString t -> T.unpack t
_ -> ""
e = case mt ! T.pack "exec" of
v@(VArray _) -> parseExec v
_ -> Nothing
n = case mt ! T.pack "name" of
VString n -> T.unpack n
_ -> ""
t = case mt ! T.pack "in_terminal" of
VBoolean b -> b
_ -> False
in
if Prelude.null k || MB.isNothing e
then
Nothing
else
Just $ KeyMapping k n (MB.fromJust e) t
-- | Parses all mappings from the TOML configuration
parseMappingTable :: VTArray -> [KeyMapping]
parseMappingTable a = MB.catMaybes $ V.toList $ V.map parseMapping a
-- | Parses the TOML configuration
parseConfiguration :: Table -> HostConfiguration
parseConfiguration t =
let gen = parseGeneralSection $ case t ! T.pack "general" of
VTable general -> general
_ -> emptyTable
wsp = parseWorkSpaceSection $ case t ! T.pack "workspaces" of
VTable ws -> ws
_ -> emptyTable
auto = parseAutostartSection $ case t ! T.pack "autostart" of
VTable a -> a
_ -> emptyTable
mapping = if mappingkey `member` t then
case t ! mappingkey of
VTArray m -> parseMappingTable m
_ -> []
else
[]
in
HostConfiguration
{ general = gen
, workspaces = wsp
, autostartPrograms = auto
, keyMappings = mapping
}
where mappingkey = T.pack "mapping"
-- | Locates, reads and parses the TOML configuration file
-- | and returns a HostConfiguration for general use
readHostConfiguration :: IO HostConfiguration
readHostConfiguration = do
homedir <- getHomeDirectory
host <- myHostName
let confpath = homedir ++ "/.xmonad/conf/" ++ host ++ ".toml"
confexists <- doesFileExist confpath
hPutStrLn stderr $ "Reading " ++ confpath
if confexists then do
contents <- TIO.readFile confpath
let toml = parseTomlDoc "" contents
case toml of
Left err -> do
hPutStrLn stderr ("failed to parse TOML in " ++ confpath)
hPutStrLn stderr ("\t" ++ show err)
return defaultHostConfiguration
Right t -> return $ parseConfiguration t
else do
hPutStrLn stderr "configuration not found, using defaults."
return defaultHostConfiguration
-- | Helper to retrieve the short portion of the host name
-- | to use it a the filename
myHostName :: IO Hostname
myHostName = takeWhile (/= '.') <$> getHostName
-- | Returns the SysInfoBar execute path
sysInfoBar :: HostConfiguration -> String
sysInfoBar conf =
"xmobar -d .xmonad/" ++ barPrefix ++ "sysinfo_xmobar.rc"
where barPrefix
| isSlim conf = "slim_"
| otherwise = ""
| nakal/xmonad-conf | lib/HostConfiguration.hs | bsd-2-clause | 9,141 | 0 | 20 | 3,700 | 1,870 | 993 | 877 | 182 | 6 |
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Network.MyTardis.RestTypes where
import Prelude hiding (id)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson
import Data.Typeable
data RestExperimentMeta = RestExperimentMeta
{ emLimit :: Integer
, emNext :: Maybe String
, emOffset :: Integer
, emPrevious :: Maybe String
, emTotalCount :: Integer
} deriving (Eq, Show)
instance FromJSON RestExperimentMeta where
parseJSON (Object v) = RestExperimentMeta <$>
v .: "limit" <*>
v .:? "next" <*>
v .: "offset" <*>
v .:? "previous" <*>
v .: "total_count"
parseJSON _ = mzero
-- From tardis/tardis_portal/models/experiment.py:
publicAccessNone, publicAccessMetadata, publicAccessFull :: Integer
publicAccessNone = 1
publicAccessMetadata = 50
publicAccessFull = 100
data RestExperiment = RestExperiment
{ eiApproved :: Bool
, eiCreatedBy :: String
, eiCreatedTime :: String
, eiDescription :: String -- ^ Experiment description.
, eiEndTime :: Maybe String
, eiHandle :: Maybe String
, eiID :: Integer
, eiInstitutionName :: String
, eiParameterSets :: [RestExperimentParameterSet] -- ^ Experiment parameter sets.
, eiLocked :: Bool
, eiPublicAccess :: Integer -- ^ Access level; see PUBLIC_ACCESS_NONE, PUBLIC_ACCESS_METADATA, and PUBLIC_ACCESS_FULL in the MyTARDIS source.
, eiResourceURI :: String -- ^ Experiment resource URI, e.g. \"\/api\/v1\/experiment\/42\/\"
, eiStartTime :: Maybe String
, eiTitle :: String
, eiUpdateTime :: String
, eiURL :: Maybe String
, eiObjectACLs :: [RestObjectACL]
}
deriving (Eq, Ord, Show, Typeable)
instance FromJSON RestExperiment where
parseJSON (Object v) = RestExperiment <$>
v .: "approved" <*>
v .: "created_by" <*>
v .: "created_time" <*>
v .: "description" <*>
v .: "end_time" <*>
v .: "handle" <*>
v .: "id" <*>
v .: "institution_name" <*>
v .: "parameter_sets" <*>
v .: "locked" <*>
v .: "public_access" <*>
v .: "resource_uri" <*>
v .: "start_time" <*>
v .: "title" <*>
v .: "update_time" <*>
v .: "url" <*>
v .: "objectacls"
parseJSON _ = mzero
instance ToJSON RestExperiment where
toJSON e = object
[ ("approved", toJSON $ eiApproved e)
, ("created_by", toJSON $ eiCreatedBy e)
, ("created_time", toJSON $ eiCreatedTime e)
, ("description", toJSON $ eiDescription e)
, ("end_time", toJSON $ eiEndTime e)
, ("handle", toJSON $ eiHandle e)
, ("id", toJSON $ eiID e)
, ("institution_name", toJSON $ eiInstitutionName e)
, ("parameter_sets", toJSON $ eiParameterSets e)
, ("locked", toJSON $ eiLocked e)
, ("public_access", toJSON $ eiPublicAccess e)
, ("resource_uri", toJSON $ eiResourceURI e)
, ("start_time", toJSON $ eiStartTime e)
, ("title", toJSON $ eiTitle e)
, ("update_time", toJSON $ eiUpdateTime e)
, ("url", toJSON $ eiURL e)
, ("objectacls", toJSON $ eiObjectACLs e)
]
data RestParameter = RestParameter
{ epDatetimeValue :: Maybe String
, epID :: Integer
, epName :: String -- ^ URI to parametername, e.g. \"\/api\/v1\/parametername\/63\/\"
, epNameCache :: String -- ^ Actual name, as if we had looked up the parametername URI.
, epNumericalValue :: Maybe Float -- ^ Numerical value.
, epParametersetURL :: String -- ^ URI to parameterset, e.g. \"\/api\/v1\/experimentparameterset\/13\/\"
, epResourceURI :: String -- ^ URI for this parameter, e.g. \"\/api\/v1\/experimentparameter\/33\/\"
, epStringValue :: Maybe String -- ^ String value.
, epValue :: Maybe String
} deriving (Eq, Ord, Show)
instance FromJSON RestParameter where
parseJSON (Object v) = RestParameter <$>
v .: "datetime_value" <*>
v .: "id" <*>
v .: "name" <*>
v .: "name_cache" <*>
v .: "numerical_value" <*>
v .: "parameterset" <*>
v .: "resource_uri" <*>
v .: "string_value" <*>
v .: "value"
parseJSON _ = mzero
instance ToJSON RestParameter where
toJSON (RestParameter datetime id name namecache numval pset uri sval _) = object
[ ("datetime_value", toJSON datetime)
, ("id", toJSON id)
, ("name", toJSON name)
, ("numerical_value", toJSON numval)
, ("parameterset", toJSON pset)
, ("resource_uri", toJSON uri)
, ("string_value", toJSON sval)
]
data RestExperimentParameterSet = RestExperimentParameterSet
{ epsExperimentURL :: String -- ^ URI for the experiment that this parameter set refers to.
, epsID :: Integer
, epsParameters :: [RestParameter] -- ^ List of parameters that are in this parameter set.
, epsResourceURI :: String -- ^ Resource URI for this parameter set.
, epsSchema :: RestSchema -- ^ Schema for this parameter set.
} deriving (Eq, Ord, Show)
instance FromJSON RestExperimentParameterSet where
parseJSON (Object v) = RestExperimentParameterSet <$>
v .: "experiment" <*>
v .: "id" <*>
v .: "parameters" <*>
v .: "resource_uri" <*>
v .: "schema"
parseJSON _ = mzero
instance ToJSON RestExperimentParameterSet where
toJSON (RestExperimentParameterSet e id ps uri schema) = object
[ ("experiment", toJSON e)
, ("id", toJSON id)
, ("parameters", toJSON ps)
, ("resource_uri", toJSON uri)
, ("schema", toJSON schema)
]
data RestDatasetParameterSet = RestDatasetParameterSet
{ dsParamSetDatasetURL :: String
, dsParamSetID :: Integer
, dsParamSetParameters :: [RestParameter]
, dsParamSetResourceURI :: String
, dsParamSetSchema :: RestSchema
}
deriving (Eq, Show)
instance FromJSON RestDatasetParameterSet where
parseJSON (Object v) = RestDatasetParameterSet <$>
v .: "dataset" <*>
v .: "id" <*>
v .: "parameters" <*>
v .: "resource_uri" <*>
v .: "schema"
parseJSON _ = mzero
data RestDatasetFileParameterSet = RestDatasetFileParameterSet
{ dsfParamSetFileURL :: String
, dsfParamSetID :: Integer
, dsfParamSetParameters :: [RestParameter]
, dsfParamSetResourceURI :: String
, dsfParamSetSchema :: RestSchema
}
deriving (Eq, Show)
instance FromJSON RestDatasetFileParameterSet where
parseJSON (Object v) = RestDatasetFileParameterSet <$>
v .: "dataset_file" <*>
v .: "id" <*>
v .: "parameters" <*>
v .: "resource_uri" <*>
v .: "schema"
parseJSON _ = mzero
data RestSchema = RestSchema
{ schemaHidden :: Bool
, schemaID :: Integer
, schemaImmutable :: Bool
, schemaName :: String -- ^ Name, e.g. \"DICOM fields\".
, schemaNamespace :: String -- ^ Namespace (primary key), e.g. \"http:\/\/cai.uq.edu.au\/schema\/metadata\/1\"
, schemaResourceURI :: String -- ^ Resource URI for this schema.
, schemaSubtype :: Maybe String
, schemaType :: Integer -- ^ Schema types, hard coded in the MyTARDIS source: EXPERIMENT = 1, DATASET = 2, DATAFILE = 3, NONE = 4.
} deriving (Eq, Ord, Show)
instance FromJSON RestSchema where
parseJSON (Object v) = RestSchema <$>
v .: "hidden" <*>
v .: "id" <*>
v .: "immutable" <*>
v .: "name" <*>
v .: "namespace" <*>
v .: "resource_uri" <*>
v .: "subtype" <*>
v .: "type"
parseJSON _ = mzero
instance ToJSON RestSchema where
toJSON (RestSchema hidden id immutable name namespace uri subtype t) = object
[ ("hidden", toJSON hidden)
, ("id", toJSON id)
, ("immutable", toJSON immutable)
, ("name", toJSON name)
, ("namespace", toJSON namespace)
, ("resource_uri", toJSON uri)
, ("subtype", toJSON subtype)
, ("type", toJSON t)
]
data RestParameterName = RestParameterName
{ pnChoices :: Maybe String
, pnComparisonType :: Integer
, pnDataType :: Integer
, pnFullName :: String
, pnID :: Integer
, pnImmutable :: Bool
, pnIsSearchable :: Bool
, pnName :: String
, pnOrder :: Integer
, pnResourceURI :: String
, pnSchemaURL :: String
, pnUnits :: Maybe String
} deriving (Eq, Ord, Show)
instance FromJSON RestParameterName where
parseJSON (Object v) = RestParameterName <$>
v .: "choices" <*>
v .: "comparison_type" <*>
v .: "data_type" <*>
v .: "full_name" <*>
v .: "id" <*>
v .: "immutable" <*>
v .: "is_searchable" <*>
v .: "name" <*>
v .: "order" <*>
v .: "resource_uri" <*>
v .: "schema" <*>
v .: "units"
parseJSON _ = mzero
-- The hell does the 'dsi' prefix mean?
data RestDataset = RestDataset
{ dsiDescription :: String
, dsiDirectory :: Maybe String
, dsiExperiments :: [String]
, dsiID :: Integer
, dsiImmutable :: Bool
, dsiParameterSets :: [RestDatasetParameterSet]
, dsiResourceURI :: String
} deriving (Eq, Show)
instance FromJSON RestDataset where
parseJSON (Object v) = RestDataset <$>
v .: "description" <*>
v .: "directory" <*>
v .: "experiments" <*>
v .: "id" <*>
v .: "immutable" <*>
v .: "parameter_sets" <*>
v .: "resource_uri"
parseJSON _ = mzero
data RestDatasetFile = RestDatasetFile
{ dsfCreatedTime :: Maybe String
, dsfDatafile :: Maybe String
, dsfDatasetURL :: String -- ^ URI for dataset that has this file.
, dsfDirectory :: Maybe String -- ^ Directory name (used in the tar file that users can download).
, dsfFilename :: String -- ^ File name. Not the whole path.
, dsfID :: Integer
, dsfMd5sum :: String -- ^ Md5sum.
, dsfMimetype :: String -- ^ Mimetype.
, dsfModificationTime :: Maybe String
, dsfParameterSets :: [RestDatasetFileParameterSet] -- ^ List of parameter sets attached to this file.
, dsfReplicas :: [RestReplica] -- ^ Replicas. Typically these point to a file in the MyTARDIS store directory but could in future be object store etc.
, dsfResourceURI :: String -- ^ Resource URI for this file.
, dsfSha512sum :: String
, dsfSize :: String -- ^ File size. Yes, it is a string!
} deriving (Eq, Show)
instance FromJSON RestDatasetFile where
parseJSON (Object v) = RestDatasetFile <$>
v .: "created_time" <*>
v .: "datafile" <*>
v .: "dataset" <*>
v .: "directory" <*>
v .: "filename" <*>
v .: "id" <*>
v .: "md5sum" <*>
v .: "mimetype" <*>
v .: "modification_time" <*>
v .: "parameter_sets" <*>
v .: "replicas" <*>
v .: "resource_uri" <*>
v .: "sha512sum" <*>
v .: "size"
parseJSON _ = mzero
data RestReplica = RestReplica
{ replicaDatafile :: String -- ^ URI for the file.
, replicaID :: Integer
-- , replicaLocation :: String -- ^ URI for the location where this file is stored (see the Location model in MyTARDIS).
-- , replicaProtocol :: Maybe String
, replicaResourceURI :: String -- ^ URI for this replica.
-- , replicaStayRemote :: Bool
, replicaURL :: String -- ^ URL to this file, not including location, e.g. \"11\/11\/foo.mnc\",
, replicaVerified :: Bool -- ^ Has MyTARDIS verified the file's checksum?
} deriving (Eq, Show)
instance FromJSON RestReplica where
parseJSON (Object v) = RestReplica <$>
v .: "datafile" <*>
v .: "id" <*>
-- v .: "location" <*>
-- v .: "protocol" <*>
v .: "resource_uri" <*>
-- v .: "stay_remote" <*>
v .: "uri" <*>
v .: "verified"
parseJSON _ = mzero
data RestPermission = RestPermission
{ permCodename :: String
, permID :: Integer
, permName :: String
, permResourceURI :: String
} deriving (Eq, Ord, Show)
instance FromJSON RestPermission where
parseJSON (Object v) = RestPermission <$>
v .: "codename" <*>
v .: "id" <*>
v .: "name" <*>
v .: "resource_uri"
parseJSON _ = mzero
instance ToJSON RestPermission where
toJSON (RestPermission codename id name uri) = object
[ ("codename", toJSON codename)
, ("id", toJSON id)
, ("name", toJSON name)
, ("resource_uri", toJSON uri)
]
data RestGroup = RestGroup
{ groupID :: Integer
, groupName :: String
, groupPermissions :: [RestPermission]
, groupResourceURI :: String
} deriving (Eq, Ord, Show)
instance FromJSON RestGroup where
parseJSON (Object v) = RestGroup <$>
v .: "id" <*>
v .: "name" <*>
v .: "permissions" <*>
v .: "resource_uri"
parseJSON _ = mzero
instance ToJSON RestGroup where
toJSON (RestGroup id name perms uri) = object
[ ("id", toJSON id)
, ("name", toJSON name)
, ("permissions", toJSON perms)
, ("resource_uri", toJSON uri)
]
data RestObjectACL = RestObjectACL
{ objectAclOwnershipType :: Integer
, objectCanDelete :: Bool
, objectCanRead :: Bool
, objectCanWrite :: Bool
, objectEffectiveDate :: Maybe String
, objectEntityId :: String -- ^ ID of object that we are referring to, e.g. "RestExperiment".
, objectExpiryDate :: Maybe String
, objectID :: Integer
, objectIsOwner :: Bool
, objectObjectID :: Integer
, objectPluginId :: String -- ^ For example \"django_group\".
, objectRelatedGroup :: Maybe RestGroup
, objectResourceURI :: String
} deriving (Eq, Ord, Show)
instance FromJSON RestObjectACL where
parseJSON (Object v) = RestObjectACL <$>
v .: "aclOwnershipType" <*>
v .: "canDelete" <*>
v .: "canRead" <*>
v .: "canWrite" <*>
v .: "effectiveDate" <*>
v .: "entityId" <*>
v .: "expiryDate" <*>
v .: "id" <*>
v .: "isOwner" <*>
v .: "object_id" <*>
v .: "pluginId" <*>
v .: "related_group" <*>
v .: "resource_uri"
parseJSON _ = mzero
instance ToJSON RestObjectACL where
toJSON (RestObjectACL ownertype candel canread canwrite effdate eid edate id isowner oid pluginid _ _) = object
[ ("aclOwnershipType", toJSON ownertype)
, ("canDelete", toJSON candel)
, ("canRead", toJSON canread)
, ("canWrite", toJSON canwrite)
, ("effectiveDate", toJSON effdate)
, ("entityId", toJSON eid)
, ("expiryDate", toJSON edate)
, ("id", toJSON id)
, ("isOwner", toJSON isowner)
, ("object_id", toJSON oid)
, ("pluginId", toJSON pluginid)
]
data RestUser = RestUser
{ ruserFirstName :: String
, ruserGroups :: [RestGroup]
, ruserLastName :: String
, ruserResourceURI :: String
, ruserUsername :: String
, ruserIsSuperuser :: Bool
} deriving (Eq, Show)
instance FromJSON RestUser where
parseJSON (Object v) = RestUser <$>
v .: "first_name" <*>
v .: "groups" <*>
v .: "last_name" <*>
v .: "resource_uri" <*>
v .: "username" <*>
v .: "is_superuser"
parseJSON _ = mzero
instance ToJSON RestUser where
toJSON (RestUser fname groups lname _ username issuper) = object
[ ("first_name", toJSON fname)
, ("groups", toJSON groups)
, ("last_name", toJSON lname)
, ("username", toJSON username)
, ("is_superuser", toJSON issuper)
]
| carlohamalainen/imagetrove-uploader | src/Network/MyTardis/RestTypes.hs | bsd-2-clause | 20,122 | 0 | 39 | 8,808 | 3,745 | 2,092 | 1,653 | 401 | 1 |
module TB where
import CLaSH.Prelude
type Inp = (Signed 4,Outp)
type Outp = (Maybe (Signed 8,Bool),Bit)
topEntity :: Unbundled' Inp -> Unbundled' Outp
topEntity = transfer <^> initS
transfer s i = (i,o)
where
o = snd s
initS = (0,(Nothing,low))
testInput :: Signal Inp
testInput = stimuliGenerator $(v ([ (1,(Just (4,True), low))
, (3,(Nothing, high))
]::[(Signed 4,(Maybe (Signed 8,Bool),Bit))]))
expectedOutput :: Signal Outp -> Signal Bool
expectedOutput = outputVerifier $(v ([(Nothing,low)
,(Just (4,False), low)
]::[(Maybe (Signed 8,Bool),Bit)]))
| christiaanb/clash-compiler | tests/shouldwork/Testbench/TB.hs | bsd-2-clause | 714 | 0 | 15 | 239 | 297 | 170 | 127 | -1 | -1 |
module Problem48 where
main :: IO ()
main = print . last10 . sum . map (\x -> last10 $ x ^ x) $ [1 .. 1000]
where last10 = read . (\xs -> drop (length xs - 10) xs) . show
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem48.hs | bsd-3-clause | 176 | 0 | 14 | 47 | 98 | 53 | 45 | 4 | 1 |
{-# LANGUAGE PackageImports #-}
module GHC.IORef (module M) where
import "base" GHC.IORef as M
| silkapp/base-noprelude | src/GHC/IORef.hs | bsd-3-clause | 100 | 0 | 4 | 18 | 21 | 15 | 6 | 3 | 0 |
{-# LANGUAGE PolyKinds #-}
-- | Explicit dictionaries.
--
-- When working with compound constraints such as constructed
-- using 'All' or 'All2', GHC cannot always prove automatically
-- what one would expect to hold.
--
-- This module provides a way of explicitly proving
-- conversions between such constraints to GHC. Such conversions
-- still have to be manually applied.
--
-- This module is new and experimental in generics-sop 0.2.
-- It is therefore not yet exported via the main module and
-- has to be imported explicitly. Its interface is to be
-- considered even less stable than that of the rest of the
-- library. Feedback is very welcome though.
--
module Generics.SOP.Dict where
import Data.Proxy
import Generics.SOP.Classes
import Generics.SOP.Constraint
import Generics.SOP.NP
import Generics.SOP.Sing
-- | An explicit dictionary carrying evidence of a
-- class constraint.
--
-- The constraint parameter is separated into a
-- second argument so that @'Dict' c@ is of the correct
-- kind to be used directly as a parameter to e.g. 'NP'.
--
data Dict (c :: k -> Constraint) (a :: k) where
Dict :: c a => Dict c a
-- | A proof that the trivial constraint holds
-- over all type-level lists.
pureAll :: SListI xs => Dict (All Top) xs
pureAll = all_NP (hpure Dict)
-- | A proof that the trivial constraint holds
-- over all type-level lists of lists.
pureAll2 :: All SListI xss => Dict (All2 Top) xss
pureAll2 = all_POP (hpure Dict)
-- | Lifts a dictionary conversion over a type-level list.
mapAll :: forall c d xs .
(forall a . Dict c a -> Dict d a)
-> Dict (All c) xs -> Dict (All d) xs
mapAll f Dict = (all_NP . hmap f . unAll_NP) Dict
-- | Lifts a dictionary conversion over a type-level list
-- of lists.
mapAll2 :: forall c d xss .
(forall a . Dict c a -> Dict d a)
-> Dict (All2 c) xss -> Dict (All2 d) xss
mapAll2 f d @ Dict = (all2 . mapAll (mapAll f) . unAll2) d
-- | If two constraints 'c' and 'd' hold over a type-level
-- list 'xs', then the combination of both constraints holds
-- over that list.
zipAll :: Dict (All c) xs -> Dict (All d) xs -> Dict (All (c `And` d)) xs
zipAll dc @ Dict dd = all_NP (hzipWith (\ Dict Dict -> Dict) (unAll_NP dc) (unAll_NP dd))
-- | If two constraints 'c' and 'd' hold over a type-level
-- list of lists 'xss', then the combination of both constraints
-- holds over that list of lists.
zipAll2 :: All SListI xss => Dict (All2 c) xss -> Dict (All2 d) xss -> Dict (All2 (c `And` d)) xss
zipAll2 dc dd = all_POP (hzipWith (\ Dict Dict -> Dict) (unAll_POP dc) (unAll_POP dd))
-- TODO: I currently don't understand why the All constraint in the beginning
-- cannot be inferred.
-- | If we have a constraint 'c' that holds over a type-level
-- list 'xs', we can create a product containing proofs that
-- each individual list element satisfies 'c'.
unAll_NP :: forall c xs . Dict (All c) xs -> NP (Dict c) xs
unAll_NP Dict = hcpure (Proxy :: Proxy c) Dict
-- | If we have a constraint 'c' that holds over a type-level
-- list of lists 'xss', we can create a product of products
-- containing proofs that all the inner elements satisfy 'c'.
unAll_POP :: forall c xss . Dict (All2 c) xss -> POP (Dict c) xss
unAll_POP Dict = hcpure (Proxy :: Proxy c) Dict
-- | If we have a product containing proofs that each element
-- of 'xs' satisfies 'c', then 'All c' holds for 'xs'.
all_NP :: NP (Dict c) xs -> Dict (All c) xs
all_NP Nil = Dict
all_NP (Dict :* ds) = withDict (all_NP ds) Dict
-- | If we have a product of products containing proofs that
-- each inner element of 'xss' satisfies 'c', then 'All2 c'
-- holds for 'xss'.
all_POP :: SListI xss => POP (Dict c) xss -> Dict (All2 c) xss
all_POP = all2 . all_NP . hmap all_NP . unPOP
-- TODO: Is the constraint necessary?
-- | The constraint 'All2 c' is convertible to 'All (All c)'.
unAll2 :: Dict (All2 c) xss -> Dict (All (All c)) xss
unAll2 Dict = Dict
-- | The constraint 'All (All c)' is convertible to 'All2 c'.
all2 :: Dict (All (All c)) xss -> Dict (All2 c) xss
all2 Dict = Dict
-- | If we have an explicit dictionary, we can unwrap it and
-- pass a function that makes use of it.
withDict :: Dict c a -> (c a => r) -> r
withDict Dict x = x
| phadej/generics-sop | src/Generics/SOP/Dict.hs | bsd-3-clause | 4,217 | 2 | 12 | 873 | 984 | 527 | 457 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts, TypeFamilies, RankNTypes #-}
#ifdef __GHCJS__
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-}
#endif
-- |
module VK.DOM.Router (getLocation
, setLocation
, setLocationHash
, getLocationHash
, onLocationHashChange
, actionRoute
, childRoutePath
, initRouter
, storeRouter
) where
import React.Flux
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as BC
import Control.Monad.IO.Class (liftIO)
import qualified Web.Routes as WR
import Data.Foldable (forM_)
#ifdef __GHCJS__
import Control.Monad (liftM)
import qualified Data.JSString as JSS
import GHCJS.Foreign.Callback
import GHCJS.Types (JSString, JSVal)
import Unsafe.Coerce
#endif
#ifdef __GHCJS__
foreign import javascript unsafe
"window.onhashchange = function() {$1(location.hash.toString());}"
js_attachtLocationHashCb :: (Callback (JSVal -> IO ())) -> IO ()
foreign import javascript unsafe
"window.location.hash = $1"
js_setLocationHash :: JSString -> IO ()
foreign import javascript unsafe
"window.location.hash.toString()"
js_getLocationHash :: IO JSString
foreign import javascript unsafe
"window.location.replace($1)"
js_setLocation :: JSString -> IO ()
foreign import javascript unsafe
"window.location.toString()"
js_getLocation :: IO JSString
setLocation :: String -> IO ()
setLocation = js_setLocation . JSS.pack
getLocation :: IO (Maybe String)
getLocation = do
rt <- liftM JSS.unpack js_getLocation
return $ case rt of
"" -> Nothing
_ -> Just rt
setLocationHash :: String -> IO ()
setLocationHash = js_setLocationHash . JSS.pack
getLocationHash :: IO (Maybe String)
getLocationHash = do
rt <- liftM JSS.unpack js_getLocationHash
return $ case rt of
"" -> Nothing
_ -> Just rt
onLocationHashChange :: (String -> IO ()) -> IO ()
onLocationHashChange fn = do
cb <- syncCallback1 ThrowWouldBlock (fn . JSS.unpack . unsafeCoerce)
js_attachtLocationHashCb cb
# else
getLocation :: IO (Maybe String)
getLocation = return Nothing
setLocation :: String -> IO ()
setLocation _ = return ()
setLocationHash :: String -> IO ()
setLocationHash _ = return ()
getLocationHash :: IO (Maybe String)
getLocationHash = return Nothing
onLocationHashChange :: (String -> IO ()) -> IO ()
onLocationHashChange _ = return ()
#endif
childRoutePath :: WR.PathInfo action => action -> [T.Text]
childRoutePath = WR.toPathSegments
actionRoute :: (StoreData store, WR.PathInfo (StoreAction store)) =>
store -> Maybe ([T.Text] -> T.Text) -> StoreAction store -> T.Text
actionRoute _ mparentRouter action =
frag
where
path = maybe (WR.toPathInfo action) ($ childRoutePath action) mparentRouter
frag = if "#" `T.isPrefixOf` path
then path
else T.cons '#' path
initRouter :: ([T.Text] -> IO ()) -> IO ()
initRouter router =
onLocationHashChange $ router . stripHash . WR.decodePathInfo . BC.pack
where
stripHash ("#":path) = path
stripHash path = path
storeRouter ::
WR.PathInfo action =>
(action -> [SomeStoreAction]) -> ([T.Text] -> IO ())
storeRouter dispatch =
let site = WR.mkSitePI $ WR.runRouteT $ routerExec
in
\rt -> either (const $ return ()) id $ WR.runSite "" site rt
where
routerExec action =
liftIO $ forM_ (dispatch action) executeAction
| eryx67/vk-api-example | src/VK/DOM/Router.hs | bsd-3-clause | 3,604 | 11 | 13 | 855 | 1,018 | 537 | 481 | 50 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Inspection.Data.AuthToken
( AuthToken(..)
, toGithubAuth
) where
import MyLittlePrelude
import qualified Data.Text as Text
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import qualified GitHub as GH
import Web.HttpApiData (FromHttpApiData(..), ToHttpApiData(..))
newtype AuthToken = AuthToken { runAuthToken :: ByteString } deriving (Show, Eq, Generic)
instance Hashable AuthToken
instance FromHttpApiData AuthToken where
parseUrlPiece t = case Text.words t of
["token", token] -> Right (AuthToken (encodeUtf8 token))
_ -> Left "Failed to parse AuthToken"
instance ToHttpApiData AuthToken where
toUrlPiece (AuthToken token) = Text.unwords ["token", decodeUtf8 token]
toGithubAuth :: AuthToken -> GH.Auth
toGithubAuth (AuthToken t) = GH.OAuth t
| zudov/purescript-inspection | src/Inspection/Data/AuthToken.hs | bsd-3-clause | 843 | 0 | 13 | 148 | 234 | 133 | 101 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Graphics.Formats.STL.Printer where
import qualified Data.ByteString as BS
import Data.ByteString.Lazy.Builder
import Data.List (intersperse)
import Data.Monoid
import Data.Text.Encoding (encodeUtf8)
import Graphics.Formats.STL.Types
-- | Convert an @STL@ value to a @Builder@, which can be converted to a
-- @ByteString@ with 'toLazyByteString'
textSTL :: STL -> Builder
textSTL s = vcat [ stringUtf8 "solid " <> (byteString . encodeUtf8 $ name s)
, vcat . map triangle $ triangles s
, stringUtf8 "endsolid " <> (byteString . encodeUtf8 $ name s)
]
triangle :: Triangle -> Builder
triangle (Triangle n (a, b, c)) =
vcat $ stringUtf8 "facet normal " <> maybeNormal n :
map (indent 4) [ stringUtf8 "outer loop"
, indent 4 $ vertex a
, indent 4 $ vertex b
, indent 4 $ vertex c
, stringUtf8 "endloop"
]
++ [stringUtf8 "endfacet"]
maybeNormal :: Maybe Vector -> Builder
maybeNormal n = case n of
Nothing -> v3 (0,0,0)
Just n' -> v3 n'
vertex :: Vector -> Builder
vertex v = stringUtf8 "vertex " <> v3 v
v3 :: Vector -> Builder
v3 (x, y, z) = mconcat $ intersperse space [floatDec x, floatDec y, floatDec z]
where
space = charUtf8 ' '
indent :: Int -> Builder -> Builder
indent i bs = spaces <> bs where
spaces = byteString . BS.replicate i $ 0x20 -- 0x20 is UTF-8 space
vcat :: [Builder] -> Builder
vcat bs = mconcat $ intersperse newline bs where
newline = charUtf8 '\n'
| bergey/STL | src/Graphics/Formats/STL/Printer.hs | bsd-3-clause | 1,705 | 0 | 10 | 539 | 499 | 262 | 237 | 36 | 2 |
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Module : Geography.MapAlgebra
-- Copyright : (c) Colin Woodbury, 2018 - 2020
-- License : BSD3
-- Maintainer: Colin Woodbury <[email protected]>
--
-- This library is an implementation of /Map Algebra/ as described in the book
-- /GIS and Cartographic Modeling/ (GaCM) by Dana Tomlin. The fundamental
-- primitive is the `Raster`, a rectangular grid of data that usually describes
-- some area on the earth. A `Raster` need not contain numerical data, however,
-- and need not just represent satellite imagery. It is essentially a matrix,
-- which of course forms a `Functor`, and thus is available for all the
-- operations we would expect to run on any Functor. /GIS and Cartographic
-- Modeling/ doesn't lean on this fact, and so describes many seemingly custom
-- operations which to Haskell are just applications of `fmap` or `zipWith` with
-- pure functions.
--
-- Here are the main classes of operations ascribed to /Map Algebra/ and their
-- corresponding approach in Haskell:
--
-- * Single-Raster /Local Operations/ -> `fmap` with pure functions
-- * Multi-Raster /Local Operations/ -> `foldl` with `zipWith` and pure functions
-- * /Focal Operations/ -> 'massiv'-based smart `Stencil` operations
-- * /Zonal Operations/ -> Not yet implemented
--
-- Whether it is meaningful to perform operations between two given `Raster`s
-- (i.e. whether the Rasters properly overlap on the earth) is not handled in
-- this library and is left to the application.
--
-- The "colour ramp" generation functions (like `greenRed`) gratefully borrow
-- colour sets from Gretchen N. Peterson's book /Cartographer's Toolkit/.
--
-- === A Word on Massiv: Fused, Parallel Arrays
-- Thanks to the underlying `Array` library
-- [massiv](https://hackage.haskell.org/package/massiv), most operations over
-- and between Rasters are /fused/, meaning that no extra memory is allocated in
-- between each step of a composite operation.
--
-- Take the [Enhanced Vegetation Index](https://en.wikipedia.org/wiki/Enhanced_vegetation_index)
-- calculation:
--
-- @
-- evi :: Raster D p r c Double -> Raster D p r c Double -> Raster D p r c Double -> Raster D p r c Double
-- evi nir red blue = 2.5 * (numer / denom)
-- where numer = nir - red
-- denom = nir + (6 * red) - (7.5 * blue) + 1
-- @
--
-- 8 binary operators are used here, but none allocate new memory. It's only
-- when some `lazy` Raster is made `strict` that calculations occur and memory
-- is allocated.
--
-- Provided your machine has more than 1 CPU, Rasters read by functions like
-- `fromRGBA` will automatically be in `Par`allel mode. This means that forcing
-- calculations with `strict` will cause evaluation to be done with every CPU
-- your machine has. The effect of this is quite potent for Focal Operations,
-- which yield special, cache-friendly windowed (`DW`) Rasters.
--
-- Familiarity with Massiv will help in using this library. A guide
-- [can be found here](https://github.com/lehins/massiv).
--
-- === Compilation Options for Best Performance
-- When using this library, always compile your project with @-threaded@ and
-- @-with-rtsopts=-N@. These will ensure your executables will automatically use
-- all the available CPU cores.
--
-- As always, @-O2@ is your friend. The @{-\# INLINE ... \#-}@ pragma is also
-- very likely to improve the performance of code that uses functions from this
-- library. Make sure to benchmark proactively.
--
-- For particularly mathy operations like `fmean`, compiling with @-fllvm@
-- grants about a 2x speedup.
module Geography.MapAlgebra
(
-- * Types
-- ** Rasters
Raster(..)
, lazy, strict
, RGBARaster(..)
-- *** Creation
, constant, fromFunction, fromVector, fromRGBA, fromGray
-- *** Colouring
-- | To colour a `Raster`:
--
-- 1. Fully evaluate it with `strict` `S`.
-- 2. Use `histogram` to analyse the spread of its values. Currently only `Word8` is supported.
-- 3. Use `breaks` on the `Histogram` to generate a list of "break points".
-- 4. Pass the break points to a function like `greenRed` to generate a "colour ramp" (a `M.Map`).
-- 5. Use this ramp with `classify` to colour your `Raster` in \(\mathcal{O}(n\log(n))\).
-- `invisible` can be used as the default colour for values that fall outside the range
-- of the Map.
--
-- @
-- colourIt :: Raster D p r c Word8 -> Raster S p r c (Pixel RGBA Word8)
-- colourIt (strict S -> r) = strict S . classify invisible cm $ lazy r
-- where cm = blueGreen . breaks $ histogram r
-- @
--
-- If you aren't interested in colour but still want to render your `Raster`,
-- consider `grayscale`. Coloured `Raster`s can be unwrapped with `_array` and
-- then output with functions like `writeImage`.
, grayscale
, Histogram(..), histogram, breaks
, invisible
, greenRed, spectrum, blueGreen, purpleYellow, brownBlue
, grayBrown, greenPurple, brownYellow, purpleGreen, purpleRed
-- *** Output and Display
-- | For coloured output, first use `classify` over your `Raster` to produce a
-- @Raster u p r c (Pixel RGBA Word8)@. Then unwrap it with `_array` and output
-- with something like `writeImage`.
--
-- For quick debugging, you can visualize a `Raster` with `displayImage`:
--
-- @
-- raster :: Raster D p 512 512 Word8
--
-- >>> displayImage . _array . strict S . grayscale
-- @
, writeImage, writeImageAuto
, displayImage
, png
-- ** Projections
, Projection(..)
, reproject
, Sphere, LatLng, WebMercator
, Point(..)
-- * Map Algebra
-- ** Local Operations
-- | Operations between `Raster`s. All operations are element-wise:
--
-- @
-- 1 1 + 2 2 == 3 3
-- 1 1 2 2 3 3
--
-- 2 2 * 3 3 == 6 6
-- 2 2 3 3 6 6
-- @
--
-- If an operation you need isn't available here, use our `zipWith`:
--
-- @
-- zipWith :: (a -> b -> d) -> Raster u p r c a -> Raster u p r c b -> Raster D p r c d
--
-- -- Your operation.
-- foo :: Int -> Int -> Int
--
-- bar :: Raster u p r c Int -> Raster u p r c Int -> Raster D p r c Int
-- bar a b = zipWith foo a b
-- @
, zipWith
-- *** Unary
-- | If you want to do simple unary @Raster -> Raster@ operations (called
-- /LocalCalculation/ in GaCM), `Raster` is a `Functor` so you can use `fmap`
-- as normal:
--
-- @
-- myRaster :: Raster D p r c Int
--
-- -- Add 17 to every value in the Raster.
-- fmap (+ 17) myRaster
-- @
, classify
-- *** Binary
-- | You can safely use these with the `foldl` family on any `Foldable` of
-- `Raster`s. You would likely want @foldl1'@ which is provided by both List
-- and Vector.
--
-- Keep in mind that `Raster` `D` has a `Num` instance, so you can use all the
-- normal math operators with them as well.
, lmax, lmin
-- *** Other
-- | There is no binary form of these functions that exists without
-- producing numerical error, so you can't use the `foldl` family with these.
-- Consider the average operation, where the following is /not/ true:
-- \[
-- \forall abc \in \mathbb{R}. \frac{\frac{a + b}{2} + c}{2} = \frac{a + b + c}{3}
-- \]
, lmean, lvariety, lmajority, lminority, lvariance
-- ** Focal Operations
-- | Operations on one `Raster`, given some polygonal neighbourhood. Your
-- `Raster` must be of a `Manifest` type (i.e. backed by real memory) before
-- you attempt any focal operations. Without this constraint, wayward users
-- run the risk of setting up operations that would perform terribly. Use
-- `strict` to easily convert a lazy `Raster` to a memory-backed one.
--
-- @
-- myRaster :: Raster D p r c Float
--
-- averaged :: Raster DW p r c Float
-- averaged = fmean $ strict P myRaster
-- @
, fsum, fproduct, fmonoid, fmean
, fmax, fmin
, fmajority, fminority, fvariety
, fpercentage, fpercentile
-- *** Lineal
-- | Focal operations that assume that groups of data points represent
-- line-like objects in a `Raster`. GaCM calls these /lineal characteristics/
-- and describes them fully on page 18 and 19.
, Line(..)
, flinkage, flength
-- *** Areal
-- | Focal operations that assume that groups of data points represent 2D
-- areas in a `Raster`. GaCM calls these /areal characteristics/ and describes
-- them fully on page 20 and 21.
, Corners(..), Surround(..)
, fpartition, fshape, ffrontage, farea
-- *** Surficial
-- | Focal operations that work over elevation `Raster`s. GaCM calls elevation
-- features /surficial characteristics/ and describes them fully on page 21
-- and 22.
--
-- Some of these operations require finding a "best-fit plane" that
-- approximates the surficial shape of each pixel. Each pixel has 9 "facet
-- points" calculated for it based on its surrounding pixels. We then use
-- these facets to determine a plane which adheres to this equation:
--
-- \[
-- ax + by + c = z
-- \]
-- This is a linear equation that we can solve for in the form \(Ax = B\).
-- For facet points \((x_i, y_i, z_i)\), we have:
--
-- \[
-- \begin{bmatrix}
-- x_0 & y_0 & 1 \\
-- x_1 & y_1 & 1 \\
-- \vdots & \vdots & \vdots \\
-- x_n & y_n & 1
-- \end{bmatrix} \begin{bmatrix}
-- a\\
-- b\\
-- c
-- \end{bmatrix} = \begin{bmatrix}
-- z_0\\
-- z_1\\
-- \vdots\\
-- z_n
-- \end{bmatrix}
-- \]
--
-- Since this system of equations is "over determined", we rework the above to
-- find the coefficients of the best-fitting plane via:
-- \[
-- \begin{bmatrix}
-- a\\
-- b\\
-- c
-- \end{bmatrix} = \boxed{(A^{T}A)^{-1}A^{T}}B
-- \]
-- The boxed section is called the "left pseudo inverse" and is available as
-- `leftPseudo`. The actual values of \(A\) don't matter for our purposes,
-- hence \(A\) can be fixed to avoid redundant calculations.
, Drain(..), Direction(..)
, direction, directions, drainage
, fvolume, fgradient, faspect, faspect', fdownstream, fupstream
-- * Utilities
, leftPseudo, tau
-- * Massiv Re-exports
-- | For your convenience.
, D(..), DW(..), S(..), P(..), U(..), B(..), N(..)
, Ix2(..), Comp(..)
, Pixel(..), RGBA, Y
) where
import Control.Concurrent (getNumCapabilities)
import Control.DeepSeq (NFData(..), deepseq)
import Control.Monad.ST
import Data.Bits (testBit)
import Data.Bool (bool)
import qualified Data.ByteString.Lazy as BL
import Data.Foldable
import qualified Data.List as L
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import Data.Massiv.Array hiding (zipWith)
import qualified Data.Massiv.Array as A
import Data.Massiv.Array.IO
import qualified Data.Massiv.Array.Manifest.Vector as A
import Data.Massiv.Array.Unsafe as A
import Data.Proxy (Proxy(..))
import Data.Semigroup
import qualified Data.Set as S
import Data.Typeable (Typeable)
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import Data.Word
import GHC.TypeLits
import Graphics.ColorSpace (ColorSpace, Elevator, Pixel(..), RGBA, Y)
import qualified Numeric.LinearAlgebra as LA
import Prelude hiding (zipWith)
import qualified Prelude as P
import Text.Printf (printf)
--
-- | A location on the Earth in some `Projection`.
data Point p = Point { x :: !Double, y :: !Double } deriving (Eq, Show)
-- | The Earth is not a sphere. Various schemes have been invented throughout
-- history that provide `Point` coordinates for locations on the earth, although
-- all are approximations and come with trade-offs. We call these "Projections",
-- since they are a mapping of `Sphere` coordinates to some other approximation.
-- The Projection used most commonly for mapping on the internet is called
-- `WebMercator`.
--
-- A Projection is also known as a Coordinate Reference System (CRS).
--
-- Use `reproject` to convert `Point`s between various Projections.
--
-- __Note:__ Full support for Projections is still pending.
class Projection p where
-- | Convert a `Point` in this Projection to one of radians on a perfect `Sphere`.
toSphere :: Point p -> Point Sphere
-- | Convert a `Point` of radians on a perfect sphere to that of a specific Projection.
fromSphere :: Point Sphere -> Point p
-- | Reproject a `Point` from one `Projection` to another.
reproject :: (Projection p, Projection r) => Point p -> Point r
reproject = fromSphere . toSphere
{-# INLINE reproject #-}
-- | A perfect geometric sphere. The earth isn't actually shaped this way, but
-- it's a convenient middle-ground for converting between various `Projection`s.
data Sphere
instance Projection Sphere where
toSphere = id
fromSphere = id
-- | Latitude (north-south position) and Longitude (east-west position).
data LatLng
-- instance Projection LatLng where
-- toSphere = undefined
-- fromSphere = undefined
-- | The most commonly used `Projection` for mapping in internet applications.
data WebMercator
-- instance Projection WebMercator where
-- toSphere = undefined
-- fromSphere = undefined
-- | A rectangular grid of data representing some area on the earth.
--
-- * @u@: What is the /underlying representation/ of this Raster? (see 'massiv')
-- * @p@: What `Projection` is this Raster in?
-- * @r@: How many rows does this Raster have?
-- * @c@: How many columns does this Raster have?
-- * @a@: What data type is held in this Raster?
--
-- By having explicit p, r, and c, we make impossible any operation between two
-- Rasters of differing size or projection. Conceptually, we consider Rasters of
-- different size and projection to be /entirely different types/. Example:
--
-- @
-- -- | A lazy 256x256 Raster with the value 5 at every index. Uses DataKinds
-- -- and "type literals" to achieve the same-size guarantee.
-- myRaster :: Raster D WebMercator 256 256 Int
-- myRaster = constant D Par 5
--
-- >>> length myRaster
-- 65536
-- @
newtype Raster u p (r :: Nat) (c :: Nat) a = Raster { _array :: Array u Ix2 a }
-- | Warning: This will evaluate (at most) the 10x10 top-left corner of your
-- `Raster` for display. This should only be used for debugging.
instance (Show a, Load (R u) Ix2 a, Extract u Ix2 a) => Show (Raster u p r c a) where
show (Raster a) = show . computeAs B $ extract' zeroIndex (Sz2 (P.min 10 r) (P.min 10 c)) a
where Sz (r :. c) = size a
instance (Eq a, Unbox a) => Eq (Raster U p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance (Eq a, Storable a) => Eq (Raster S p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance (Eq a, Prim a) => Eq (Raster P p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance (Eq a, NFData a) => Eq (Raster N p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance Eq a => Eq (Raster B p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance Eq a => Eq (Raster D p r c a) where
Raster a == Raster b = a == b
{-# INLINE (==) #-}
instance Functor (Raster DW p r c) where
fmap f (Raster a) = Raster $ fmap f a
{-# INLINE fmap #-}
instance Functor (Raster D p r c) where
fmap f (Raster a) = Raster $ fmap f a
{-# INLINE fmap #-}
instance Functor (Raster DI p r c) where
fmap f (Raster a) = Raster $ fmap f a
{-# INLINE fmap #-}
instance (KnownNat r, KnownNat c) => Applicative (Raster D p r c) where
pure = constant D Par
{-# INLINE pure #-}
-- TODO: Use strict ($)?
fs <*> as = zipWith ($) fs as
{-# INLINE (<*>) #-}
instance Semigroup a => Semigroup (Raster D p r c a) where
a <> b = zipWith (<>) a b
{-# INLINE (<>) #-}
instance (Monoid a, KnownNat r, KnownNat c) => Monoid (Raster D p r c a) where
mempty = constant D Par mempty
{-# INLINE mempty #-}
a `mappend` b = zipWith mappend a b
{-# INLINE mappend #-}
instance (Num a, KnownNat r, KnownNat c) => Num (Raster D p r c a) where
a + b = zipWith (+) a b
{-# INLINE (+) #-}
a - b = zipWith (-) a b
{-# INLINE (-) #-}
a * b = zipWith (*) a b
{-# INLINE (*) #-}
abs = fmap abs
{-# INLINE abs #-}
signum = fmap signum
{-# INLINE signum #-}
fromInteger = constant D Par . fromInteger
{-# INLINE fromInteger #-}
instance (Fractional a, KnownNat r, KnownNat c) => Fractional (Raster D p r c a) where
a / b = zipWith (/) a b
{-# INLINE (/) #-}
fromRational = constant D Par . fromRational
{-# INLINE fromRational #-}
-- TODO: more explicit implementations?
-- | `length` has a specialized \(\mathcal{O}(1)\) implementation.
instance Foldable (Raster D p r c) where
foldMap f (Raster a) = foldMap f a
{-# INLINE foldMap #-}
sum (Raster a) = A.sum a
{-# INLINE sum #-}
product (Raster a) = A.product a
{-# INLINE product #-}
-- | \(\mathcal{O}(1)\).
length (Raster a) = (\(Sz2 r c) -> r * c) $ A.size a
{-# INLINE length #-}
-- | \(\mathcal{O}(1)\). Force a `Raster`'s representation to `D`, allowing it
-- to undergo various operations. All operations between `D` `Raster`s are fused
-- and allocate no extra memory.
lazy :: Source u Ix2 a => Raster u p r c a -> Raster D p r c a
lazy (Raster a) = Raster $ delay a
{-# INLINE lazy #-}
-- | Evaluate some lazy (`D`, `DW`, or `DI`) `Raster` to some explicit
-- `Manifest` type (i.e. to a real memory-backed Array). Will follow the
-- `Comp`utation strategy of the underlying 'massiv' `Array`.
--
-- __Note:__ If using the `Par` computation strategy, make sure you're compiling
-- with @-with-rtsopts=-N@ to automatically use all available CPU cores at
-- runtime. Otherwise your "parallel" operations will only execute on one core.
strict :: (Load v Ix2 a, Mutable u Ix2 a) => u -> Raster v p r c a -> Raster u p r c a
strict u (Raster a) = Raster $ computeAs u a
{-# INLINE strict #-}
-- | Create a `Raster` of any size which has the same value everywhere.
constant :: (KnownNat r, KnownNat c, Construct u Ix2 a) => u -> Comp -> a -> Raster u p r c a
constant u c a = fromFunction u c (const a)
{-# INLINE constant #-}
-- | \(\mathcal{O}(1)\). Create a `Raster` from a function of its row and column
-- number respectively.
fromFunction :: forall u p r c a. (KnownNat r, KnownNat c, Construct u Ix2 a) =>
u -> Comp -> (Ix2 -> a) -> Raster u p r c a
fromFunction u c f = Raster $ makeArrayR u c (Sz sh) f
where sh = fromInteger (natVal (Proxy :: Proxy r)) :. fromInteger (natVal (Proxy :: Proxy c))
{-# INLINE fromFunction #-}
-- | \(\mathcal{O}(1)\). Create a `Raster` from the values of any `GV.Vector`
-- type. Will fail if the size of the Vector does not match the declared size of
-- the `Raster`.
fromVector :: forall v p r c a. (KnownNat r, KnownNat c, GV.Vector v a, Mutable (A.ARepr v) Ix2 a, Typeable v) =>
Comp -> v a -> Either String (Raster (A.ARepr v) p r c a)
-- fromVector comp v | (r * c) == GV.length v = Right . Raster $ A.fromVector comp (r :. c) v
fromVector comp v | (r * c) == GV.length v = Right . Raster $ A.fromVector' comp (Sz2 r c) v
| otherwise = Left $ printf "Expected Pixel Count: %d - Actual: %d" (r * c) (GV.length v)
where r = fromInteger $ natVal (Proxy :: Proxy r)
c = fromInteger $ natVal (Proxy :: Proxy c)
{-# INLINE fromVector #-}
-- | An RGBA image whose colour bands are distinct.
data RGBARaster p r c a = RGBARaster { _red :: !(Raster S p r c a)
, _green :: !(Raster S p r c a)
, _blue :: !(Raster S p r c a)
, _alpha :: !(Raster S p r c a) }
-- | Read any image type into a `Raster` of distinct colour bands with the cell
-- type you declare. If the source image stores its values as `Int` but you
-- declare `Double`, the conversion will happen automatically.
--
-- Will fail if the declared size of the `Raster` does not match the actual size
-- of the input image.
fromRGBA :: forall p r c a. (Elevator a, KnownNat r, KnownNat c) => FilePath -> IO (Either String (RGBARaster p r c a))
fromRGBA fp = do
cap <- getNumCapabilities
img <- setComp (bool Par Seq $ cap == 1) <$> readImageAuto fp
let rows = fromInteger $ natVal (Proxy :: Proxy r)
cols = fromInteger $ natVal (Proxy :: Proxy c)
Sz (r :. c) = size img
if r == rows && c == cols
then do
(ar, ag, ab, aa) <- spreadRGBA img
pure . Right $ RGBARaster (Raster ar) (Raster ag) (Raster ab) (Raster aa)
else pure . Left $ printf "Expected Size: %d x %d - Actual Size: %d x %d" rows cols r c
{-# INLINE fromRGBA #-}
spreadRGBA :: (Index ix, Elevator e)
=> A.Array S ix (Pixel RGBA e)
-> IO (A.Array S ix e, A.Array S ix e, A.Array S ix e, A.Array S ix e)
spreadRGBA arr = do
let sz = A.size arr
mr <- A.unsafeNew sz
mb <- A.unsafeNew sz
mg <- A.unsafeNew sz
ma <- A.unsafeNew sz
flip A.imapM_ arr $ \i (PixelRGBA r g b a) -> do
A.unsafeWrite mr i r
A.unsafeWrite mg i g
A.unsafeWrite mb i b
A.unsafeWrite ma i a
ar <- A.unsafeFreeze (getComp arr) mr
ag <- A.unsafeFreeze (getComp arr) mg
ab <- A.unsafeFreeze (getComp arr) mb
aa <- A.unsafeFreeze (getComp arr) ma
return (ar, ag, ab, aa)
{-# INLINE spreadRGBA #-}
-- | Read a grayscale image. If the source file has more than one colour band,
-- they'll be combined automatically.
fromGray :: forall p r c a. (Elevator a, KnownNat r, KnownNat c) => FilePath -> IO (Either String (Raster S p r c a))
fromGray fp = do
cap <- getNumCapabilities
img <- setComp (bool Par Seq $ cap == 1) <$> readImageAuto fp
let rows = fromInteger $ natVal (Proxy :: Proxy r)
cols = fromInteger $ natVal (Proxy :: Proxy c)
Sz (r :. c) = size img
pure . bool (Left $ printf "Expected Size: %d x %d - Actual Size: %d x %d" rows cols r c) (Right $ f img) $ r == rows && c == cols
where f :: Image S Y a -> Raster S p r c a
f img = Raster . A.fromVector' (getComp img) (size img) . VS.unsafeCast $ A.toVector img
{-# INLINE fromGray #-}
-- | An invisible pixel (alpha channel set to 0).
invisible :: Pixel RGBA Word8
invisible = PixelRGBA 0 0 0 0
-- | Construct a colour ramp.
-- ramp :: Ord k => [(Word8, Word8, Word8)] -> [k] -> M.Map k PixelRGBA8
ramp :: Ord k => [(Word8, Word8, Word8)] -> [k] -> M.Map k (Pixel RGBA Word8)
ramp colours bs = M.fromList . P.zip bs $ P.map (\(r,g,b) -> PixelRGBA r g b maxBound) colours
{-# INLINE ramp #-}
-- | From page 32 of /Cartographer's Toolkit/.
greenRed :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
greenRed = ramp colours
where colours = [ (0, 48, 0), (31, 79, 20), (100, 135, 68), (148, 193, 28), (193, 242, 3)
, (241, 255, 159), (249, 228, 227), (202, 145, 150), (153, 101, 97), (142, 38 ,18) ]
-- | From page 33 of /Cartographer's Toolkit/.
spectrum :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
spectrum = ramp colours
where colours = [ (0, 22, 51), (51, 18, 135), (150, 0, 204), (242, 13, 177), (255, 61, 61)
, (240, 152, 56), (248, 230, 99), (166, 249, 159), (184, 249, 212), (216, 230, 253) ]
-- | From page 34 of /Cartographer's Toolkit/.
blueGreen :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
blueGreen = ramp colours
where colours = [ (29, 43, 53), (37, 44, 95), (63, 70, 134), (89, 112, 147), (87, 124, 143)
, (117, 160, 125), (188, 219, 173), (239, 253, 163), (222, 214, 67), (189, 138, 55) ]
-- | From page 35 of /Cartographer's Toolkit/.
purpleYellow :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
purpleYellow = ramp colours
where colours = [ (90, 89, 78), (73, 65, 132), (107, 86, 225), (225, 67, 94), (247, 55, 55)
, (251, 105, 46), (248, 174, 66), (249, 219, 25), (255, 255, 0), (242, 242, 242) ]
-- | From page 36 of /Cartographer's Toolkit/.
brownBlue :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
brownBlue = ramp colours
where colours = [ (27, 36, 43), (86, 52, 42), (152, 107, 65), (182, 176, 152), (215, 206, 191)
, (198, 247, 0), (53, 227, 0), (30, 158, 184), (22, 109, 138), (12, 47, 122) ]
-- | From page 37 of /Cartographer's Toolkit/.
grayBrown :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
grayBrown = ramp colours
where colours = [ (64, 57, 88), (95, 96, 116), (158, 158, 166), (206, 208, 197), (215, 206, 191)
, (186, 164, 150), (160, 124, 98), (117, 85, 72), (90, 70, 63), (39, 21, 17) ]
-- | From page 38 of /Cartographer's Toolkit/.
greenPurple :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
greenPurple = ramp colours
where colours = [ (89, 168, 15), (158, 213, 76), (196, 237, 104), (226, 255, 158), (240, 242, 221)
, (248, 202, 140), (233, 161, 137), (212, 115, 132), (172, 67, 123), (140, 40, 110) ]
-- | From page 39 of /Cartographer's Toolkit/.
brownYellow :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
brownYellow = ramp colours
where colours = [ (96, 72, 96), (120, 72, 96), (168, 96, 96), (192, 120, 96), (240, 168, 72)
, (248, 202, 140), (254, 236, 174), (255, 244, 194), (255, 247, 219), (255, 252, 246) ]
-- | From page 40 of /Cartographer's Toolkit/.
purpleGreen :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
purpleGreen = ramp colours
where colours = [ (80, 73, 113), (117, 64, 152), (148, 116, 180), (199, 178, 214), (223, 204, 228)
, (218, 234, 193), (171, 214, 155), (109, 192, 103), (13, 177, 75), (57, 99, 83) ]
-- | From page 41 of /Cartographer's Toolkit/.
purpleRed :: Ord k => [k] -> M.Map k (Pixel RGBA Word8)
purpleRed = ramp colours
where colours = [ (51, 60, 255), (76, 60, 233), (99, 60, 211), (121, 60, 188), (155, 60, 155)
, (166, 60, 143), (188, 60, 121), (206, 60, 94), (217, 60, 83), (255, 60, 76) ]
-- | Convert a `Raster` into grayscale pixels, suitable for easy output with
-- functions like `writeImage`.
grayscale :: Functor (Raster u p r c) => Raster u p r c a -> Raster u p r c (Pixel Y a)
grayscale = fmap PixelY
{-# INLINE grayscale #-}
-- | Render a PNG-encoded `BL.ByteString` from a coloured `Raster`. Useful for
-- returning a `Raster` from a webserver endpoint.
png :: (Source u Ix2 (Pixel cs a), ColorSpace cs a) => Raster u p r c (Pixel cs a) -> BL.ByteString
png (Raster a) = encode PNG def a
{-# INLINE png #-}
-- | Called /LocalClassification/ in GaCM. The first argument is the value to
-- give to any index whose value is less than the lowest break in the `M.Map`.
--
-- This is a glorified `fmap` operation, but we expose it for convenience.
classify :: (Ord a, Functor f) => b -> M.Map a b -> f a -> f b
classify d m r = fmap f r
where f a = maybe d snd $ M.lookupLE a m
{-# INLINE classify #-}
-- | Finds the minimum value at each index between two `Raster`s.
lmin :: (Ord a, Source u Ix2 a) => Raster u p r c a -> Raster u p r c a -> Raster D p r c a
lmin = zipWith P.min
{-# INLINE lmin #-}
-- | Finds the maximum value at each index between two `Raster`s.
lmax :: (Ord a, Source u Ix2 a) => Raster u p r c a -> Raster u p r c a -> Raster D p r c a
lmax = zipWith P.max
{-# INLINE lmax #-}
-- | Averages the values per-index of all `Raster`s in a collection.
lmean :: (Real a, Fractional b, KnownNat r, KnownNat c) => NonEmpty (Raster D p r c a) -> Raster D p r c b
lmean (a :| [b]) = Raster $ A.zipWith (\n m -> realToFrac (n + m) / 2) (_array a) (_array b)
lmean (a :| [b,c]) = Raster $ A.zipWith3 (\n m o -> realToFrac (n + m + o) / 3) (_array a) (_array b) (_array c)
lmean (a :| as) = (\n -> realToFrac n / len) <$> foldl' (+) a as
where len = 1 + fromIntegral (length as)
{-# INLINE lmean #-}
-- | The count of unique values at each shared index.
lvariety :: (KnownNat r, KnownNat c, Eq a) => NonEmpty (Raster D p r c a) -> Raster D p r c Word
lvariety = fmap (fromIntegral . length . NE.nub) . P.sequenceA
{-# INLINE lvariety #-}
-- | The most frequently appearing value at each shared index.
lmajority :: (KnownNat r, KnownNat c, Ord a) => NonEmpty (Raster D p r c a) -> Raster D p r c a
lmajority = fmap majo . P.sequenceA
{-# INLINE lmajority #-}
-- | Find the most common value in some `Foldable`.
majo :: forall t a. (Foldable t, Ord a) => t a -> a
majo = fst . g . f
where
f :: t a -> M.Map a Int
f = foldl' (\m a -> M.insertWith (+) a 1 m) M.empty
g :: M.Map a Int -> (a, Int)
g = L.foldl1' (\(a,c) (k,v) -> if c < v then (k,v) else (a,c)) . M.toList
{-# INLINE majo #-}
-- | The least frequently appearing value at each shared index.
lminority :: (KnownNat r, KnownNat c, Ord a) => NonEmpty (Raster D p r c a) -> Raster D p r c a
lminority = fmap mino . P.sequenceA
{-# INLINE lminority #-}
-- | Find the least common value in some `Foldable`.
mino :: forall t a. (Foldable t, Ord a) => t a -> a
mino = fst . g . f
where
f :: t a -> M.Map a Int
f = foldl' (\m a -> M.insertWith (+) a 1 m) M.empty
g :: M.Map a Int -> (a, Int)
g = L.foldl1' (\(a,c) (k,v) -> if c > v then (k,v) else (a,c)) . M.toList
{-# INLINE mino #-}
-- | A measure of how spread out a dataset is. This calculation will fail with
-- `Nothing` if a length 1 list is given.
lvariance
:: forall p a r c. (Real a, KnownNat r, KnownNat c)
=> NonEmpty (Raster D p r c a) -> Maybe (Raster D p r c Double)
lvariance (_ :| []) = Nothing
lvariance rs = Just (f <$> P.sequenceA rs)
where
len :: Double
len = realToFrac $ length rs
avg :: NonEmpty a -> Double
avg ns = (\z -> realToFrac z / len) $ foldl' (+) 0 ns
f :: NonEmpty a -> Double
f os@(n :| ns) = num / (len - 1)
where
num = foldl' (\acc m -> acc + ((realToFrac m - av) ^ (2 :: Int))) ((realToFrac n - av) ^ (2 :: Int)) ns
av = avg os
{-# INLINE lvariance #-}
-- Old implementation that was replaced with `sequenceA` usage above. I wonder if this is faster?
-- Leaving it here in case we feel like comparing later.
--listEm :: (Projection p, KnownNat r, KnownNat c) => NonEmpty (Raster p r c a) -> Raster p r c (NonEmpty a)
--listEm = sequenceA
--listEm (r :| rs) = foldl' (\acc s -> zipWith cons s acc) z rs
-- where z = (\a -> a :| []) <$> r
--{-# INLINE [2] listEm #-}
-- | Combine two `Raster`s, element-wise, with a binary operator.
zipWith :: (Source u Ix2 a, Source u Ix2 b) =>
(a -> b -> d) -> Raster u p r c a -> Raster u p r c b -> Raster D p r c d
zipWith f (Raster a) (Raster b) = Raster $ A.zipWith f a b
{-# INLINE zipWith #-}
-- | Focal Addition.
fsum :: (Num a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fsum (Raster a) = Raster $ mapStencil (Fill 0) (sumStencil $ Sz2 3 3) a
{-# INLINE fsum #-}
-- | Focal Product.
fproduct :: (Num a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fproduct (Raster a) = Raster $ mapStencil (Fill 1) (productStencil $ Sz2 3 3) a
{-# INLINE fproduct #-}
-- | Focal Monoid - combine all elements of a neighbourhood via their `Monoid`
-- instance. In terms of precedence, the neighbourhood focus is the "left-most",
-- and all other elements are "added" to it.
--
-- This is not mentioned in GaCM, but seems useful nonetheless.
fmonoid :: (Monoid a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fmonoid (Raster a) = Raster $ mapStencil (Fill mempty) (foldStencil $ Sz2 3 3) a
{-# INLINE fmonoid #-}
-- | Focal Mean.
fmean :: (Fractional a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fmean (Raster a) = Raster $ mapStencil (Fill 0) (avgStencil $ Sz2 3 3) a
{-# INLINE fmean #-}
-- | Focal Maximum.
fmax :: (Ord a, Bounded a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fmax (Raster a) = Raster $ mapStencil Edge (maxStencil $ Sz2 3 3) a
{-# INLINE fmax #-}
-- | Focal Minimum.
fmin :: (Ord a, Bounded a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fmin (Raster a) = Raster $ mapStencil Edge (minStencil $ Sz2 3 3) a
{-# INLINE fmin #-}
-- | Focal Variety - the number of unique values in each neighbourhood.
fvariety :: (Ord a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Word
fvariety (Raster a) = Raster $ mapStencil Edge (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = fromIntegral . length $ L.nub [ nw, no, ne, we, fo, ea, sw, so, se ]
{-# INLINE fvariety #-}
-- | Focal Majority - the most frequently appearing value in each neighbourhood.
fmajority :: (Ord a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fmajority (Raster a) = Raster $ mapStencil Continue (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = majo [ nw, no, ne, we, fo, ea, sw, so, se ]
{-# INLINE fmajority #-}
-- | Focal Minority - the least frequently appearing value in each neighbourhood.
fminority :: (Ord a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fminority (Raster a) = Raster $ mapStencil Continue (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = mino [ nw, no, ne, we, fo, ea, sw, so, se ]
{-# INLINE fminority #-}
-- | Focal Percentage - the percentage of neighbourhood values that are equal to
-- the neighbourhood focus. Not to be confused with `fpercentile`.
fpercentage :: (Eq a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Double
fpercentage (Raster a) = Raster $ mapStencil Continue (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = ( bool 0 1 (nw == fo)
+ bool 0 1 (no == fo)
+ bool 0 1 (ne == fo)
+ bool 0 1 (we == fo)
+ bool 0 1 (ea == fo)
+ bool 0 1 (sw == fo)
+ bool 0 1 (so == fo)
+ bool 0 1 (se == fo) ) / 8
{-# INLINE fpercentage #-}
-- | Focal Percentile - the percentage of neighbourhood values that are /less/
-- than the neighbourhood focus. Not to be confused with `fpercentage`.
fpercentile :: (Ord a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Double
fpercentile (Raster a) = Raster $ mapStencil Continue (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = ( bool 0 1 (nw < fo)
+ bool 0 1 (no < fo)
+ bool 0 1 (ne < fo)
+ bool 0 1 (we < fo)
+ bool 0 1 (ea < fo)
+ bool 0 1 (sw < fo)
+ bool 0 1 (so < fo)
+ bool 0 1 (se < fo) ) / 8
{-# INLINE fpercentile #-}
-- `Fill def` has the highest chance of the edge pixel and the off-the-edge pixel
-- having a different value. This is until the following is addressed:
-- https://github.com/fosskers/mapalgebra/pull/3#issuecomment-379943208
-- | Focal Linkage - a description of how each neighbourhood focus is connected
-- to its neighbours. Foci of equal value to none of their neighbours will have
-- a value of 0.
flinkage :: (Default a, Eq a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Line
flinkage (Raster a) = Raster $ mapStencil (Fill def) (neighbourhoodStencil linkage) a
{-# INLINE flinkage #-}
-- | A description of lineal directions with the same encoding as `Drain`.
-- See `flinkage` and `flength`.
newtype Line = Line { _line :: Word8 }
deriving stock (Eq, Ord, Show)
deriving newtype (Storable, Prim, Default)
instance NFData Line where
rnf (Line a) = deepseq a ()
linkage :: Eq a => a -> a -> a -> a -> a -> a -> a -> a -> a -> Line
linkage nw no ne we fo ea sw so se = Line $ axes + diags
where axes = bool 0 2 (no == fo) + bool 0 8 (we == fo) + bool 0 16 (ea == fo) + bool 0 64 (so == fo)
diags = bool 0 1 (nw == fo && not (testBit axes 1 || testBit axes 3))
+ bool 0 4 (ne == fo && not (testBit axes 1 || testBit axes 4))
+ bool 0 32 (sw == fo && not (testBit axes 3 || testBit axes 6))
+ bool 0 128 (se == fo && not (testBit axes 4 || testBit axes 6))
{-# INLINE linkage #-}
-- | Directions that neighbourhood foci can be connected by.
data Direction = East | NorthEast | North | NorthWest | West | SouthWest | South | SouthEast
deriving (Eq, Ord, Enum, Show)
-- | Focal Length - the length of the lineal structure at every location. The
-- result is in "pixel units", where 1 is the height/width of one pixel.
flength :: Functor (Raster u p r c) => Raster u p r c Line -> Raster u p r c Double
flength = fmap f
where half = 1 / 2
root = 1 / sqrt 2
f (Line a) = bool 0 half (testBit a 1)
+ bool 0 half (testBit a 3)
+ bool 0 half (testBit a 4)
+ bool 0 half (testBit a 6)
+ bool 0 root (testBit a 0)
+ bool 0 root (testBit a 2)
+ bool 0 root (testBit a 5)
+ bool 0 root (testBit a 7)
{-# INLINE flength #-}
-- | A layout of the areal conditions of a single `Raster` pixel. It describes
-- whether each pixel corner is occupied by the same "areal zone" as the pixel
-- centre.
data Corners = Corners { _topLeft :: !Surround
, _bottomLeft :: !Surround
, _bottomRight :: !Surround
, _topRight :: !Surround } deriving (Eq, Show)
instance NFData Corners where
rnf (Corners tl bl br tr) = tl `deepseq` bl `deepseq` br `deepseq` tr `deepseq` ()
-- | A state of surroundedness of a pixel corner. For the examples below, the
-- bottom-left pixel is considered the focus and we're wondering about the
-- surroundedness of its top-right corner.
data Surround = Complete -- ^ A corner has three of the same opponent against it.
--
-- The corner is considered "occupied" by the opponent value,
-- thus forming a diagonal areal edge.
--
-- @
-- [ 1 1 ]
-- [ 0 1 ]
-- @
| OneSide -- ^ One edge of a corner is touching an opponent, but
-- the other edge touches a friend.
--
-- @
-- [ 1 1 ] or [ 0 1 ]
-- [ 0 0 ] [ 0 1 ]
-- @
| Open -- ^ A corner is surrounded by friends.
--
-- @
-- [ 0 0 ] or [ 0 0 ] or [ 1 0 ]
-- [ 0 0 ] [ 0 1 ] [ 0 0 ]
-- @
| RightAngle -- ^ Similar to `Complete`, except that the diagonal
-- opponent doesn't match the other two. The corner
-- is considered surrounded, but not "occupied".
--
-- @
-- [ 1 2 ]
-- [ 0 1 ]
-- @
| OutFlow -- ^ Similar to `Complete`, except that the area of the
-- focus surrounds the diagonal neighbour.
--
-- @
-- [ 0 1 ]
-- [ 0 0 ]
-- @
deriving (Eq, Ord, Show)
instance NFData Surround where
rnf s = case s of
Complete -> ()
OneSide -> ()
Open -> ()
RightAngle -> ()
OutFlow -> ()
-- | Imagining a 2x2 neighbourhood with its focus in the bottom-left, what
-- `Surround` relationship does the focus have with the other pixels?
surround :: Eq a => a -> a -> a -> a -> Surround
surround fo tl tr br
| up && tl == tr && tr == br = Complete
| up && right = RightAngle
| (up && diag) || (diag && right) = OneSide
| diag && fo == tl && fo == br = OutFlow
| otherwise = Open
where up = fo /= tl
diag = fo /= tr
right = fo /= br
{-# INLINE surround #-}
-- | What is the total length of the areal edges (if there are any) at a given
-- pixel?
frontage :: Corners -> Double
frontage (Corners tl bl br tr) = f tl + f bl + f br + f tr
where f Complete = 1 / sqrt 2
f OneSide = 1 / 2
f Open = 0
f RightAngle = 1
f OutFlow = 1 / sqrt 2
-- | Focal Partition - the areal form of each location, only considering the
-- top-right edge.
fpartition :: (Default a, Eq a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Corners
fpartition (Raster a) = Raster $ mapStencil Reflect partStencil a
{-# INLINE fpartition #-}
partStencil :: (Eq a, Default a) => Stencil Ix2 a Corners
partStencil = makeStencil (Sz2 2 2) (1 :. 0) $ \f -> do
tl <- f (-1 :. 0)
tr <- f (-1 :. 1)
br <- f (0 :. 1)
fo <- f (0 :. 0)
pure $ Corners (surround fo tl tl fo) Open (surround fo fo br br) (surround fo tl tr br)
{-# INLINE partStencil #-}
-- | Like `fpartition`, but considers the `Surround` of all corners. Is alluded
-- to in GaCM but isn't given its own operation name.
--
-- If preparing for `ffrontage` or `farea`, you almost certainly want this
-- function and not `fpartition`.
fshape :: (Default a, Eq a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c Corners
fshape (Raster a) = Raster $ mapStencil Reflect (neighbourhoodStencil f) a
where f nw no ne we fo ea sw so se = Corners (surround fo no nw we)
(surround fo so sw we)
(surround fo so se ea)
(surround fo no ne ea)
{-# INLINE fshape #-}
-- | Focal Frontage - the length of areal edges between each pixel and its
-- neighbourhood.
--
-- Usually, the output of `fshape` is the appropriate input for this function.
ffrontage :: Functor (Raster u p r c) => Raster u p r c Corners -> Raster u p r c Double
ffrontage = fmap frontage
{-# INLINE ffrontage #-}
-- | The area of a 1x1 square is 1. It has 8 right-triangular sections,
-- each with area 1/8.
area :: Corners -> Double
area (Corners tl bl br tr) = 1 - f tl - f bl - f br - f tr
where f Complete = 1/8
f OutFlow = -1/8 -- For areas that "invade" their neighbours.
f _ = 0
{-# INLINE area #-}
-- | Focal Area - the area of the shape made up by a neighbourhood focus and its
-- surrounding pixels. Each pixel is assumed to have length and width of 1.
--
-- Usually, the output of `fshape` is the appropriate input for this function.
farea :: Functor (Raster u p r c) => Raster u p r c Corners -> Raster u p r c Double
farea = fmap area
{-# INLINE farea #-}
-- | Focal Volume - the surficial volume under each pixel, assuming the `Raster`
-- represents elevation in some way.
fvolume :: (Fractional a, Default a, Manifest u Ix2 a) => Raster u p r c a -> Raster DW p r c a
fvolume (Raster a) = Raster $ mapStencil Reflect (neighbourhoodStencil volume) a
{-# INLINE fvolume #-}
volume :: Fractional a => a -> a -> a -> a -> a -> a -> a -> a -> a -> a
volume tl up tr le fo ri bl bo br =
((fo * 8) -- Simple algebra to reorganize individual volume calculations for each subtriangle.
+ nw + no
+ no + ne
+ ne + ea
+ ea + se
+ se + so
+ so + sw
+ sw + we
+ we + nw) / 24
where nw = (tl + up + le + fo) / 4
no = (up + fo) / 2
ne = (up + tr + fo + ri) / 4
we = (le + fo) / 2
ea = (fo + ri) / 2
sw = (le + fo + bl + bo) / 4
so = (fo + bo) / 2
se = (fo + ri + bo + br) / 4
{-# INLINE volume #-}
-- | Direct access to the entire neighbourhood.
neighbourhood :: Applicative f => (a -> a -> a -> a -> a -> a -> a -> a -> a -> b) -> (Ix2 -> f a) -> f b
neighbourhood g f = g <$> f (-1 :. -1) <*> f (-1 :. 0) <*> f (-1 :. 1)
<*> f (0 :. -1) <*> f (0 :. 0) <*> f (0 :. 1)
<*> f (1 :. -1) <*> f (1 :. 0) <*> f (1 :. 1)
{-# INLINE neighbourhood #-}
neighbourhoodStencil :: Default a => (a -> a -> a -> a -> a -> a -> a -> a -> a -> b) -> Stencil Ix2 a b
neighbourhoodStencil f = makeStencil (Sz2 3 3) (1 :. 1) (neighbourhood f)
{-# INLINE neighbourhoodStencil #-}
-- | Get the surficial facets for each pixel and apply some function to them.
facetStencil :: (Fractional a, Default a) => (a -> a -> a -> a -> a -> a -> a -> a -> a -> b) -> Stencil Ix2 a b
facetStencil f = makeStencil (Sz2 3 3) (1 :. 1) (neighbourhood g)
where g nw no ne we fo ea sw so se = f ((nw + no + we + fo) / 4)
((no + fo) / 2)
((no + ne + fo + ea) / 4)
((we + fo) / 2)
fo
((fo + ea) / 2)
((we + fo + sw + so) / 4)
((fo + so) / 2)
((fo + ea + so + se) / 4)
{-# INLINE facetStencil #-}
-- | The first part to the "left pseudo inverse" needed to calculate
-- a best-fitting plane of 9 points.
leftPseudo :: LA.Matrix Double
leftPseudo = LA.inv (aT <> a) <> aT
where aT = LA.tr' a
a = LA.matrix 3 [ -0.5, -0.5, 1
, -0.5, 0, 1
, -0.5, 0.5, 1
, 0, -0.5, 1
, 0, 0, 1
, 0, 0.5, 1
, 0.5, -0.5, 1
, 0.5, 0, 1
, 0.5, 0.5, 1 ]
-- TODO: newtype wrapper for `Radians`?
-- | Focal Gradient - a measurement of surficial slope for each pixel relative to
-- the horizonal cartographic plane. Results are in radians, with a flat plane
-- having a slope angle of 0 and a near-vertical plane approaching \(\tau / 4\).
fgradient :: (Manifest u Ix2 Double) => Raster u p r c Double -> Raster DW p r c Double
fgradient (Raster a) = Raster $ mapStencil Reflect (facetStencil gradient) a
{-# INLINE fgradient #-}
-- | \(\tau\). One full rotation of the unit circle.
tau :: Double
tau = 6.283185307179586
-- | Given a list of \(z\) values, find the slope of the best-fit plane that
-- matches those points.
--
-- See: https://stackoverflow.com/a/16669463/643684
gradient :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double
gradient nw no ne we fo ea sw so se = (tau / 2) - acos (normal vs LA.! 2)
where vs = [ nw, no, ne, we, fo, ea, sw, so, se ]
-- | Given a list of \(z\) values, find a normal vector that /points down/ from
-- a best-fit plane toward the cartographic plane.
normal :: [Double] -> LA.Vector Double
normal = LA.normalize . zcoord (-1) . normal'
-- | A non-normalized, non-Z-corrected normal. Handy for `faspect`,
-- which needs to drop the Z and renormalize.
normal' :: [Double] -> LA.Vector Double
normal' vs = leftPseudo LA.#> LA.vector vs
-- | Replace the Z-coordinate of a Vector.
zcoord :: Double -> LA.Vector Double -> LA.Vector Double
zcoord n v = LA.vector [ v LA.! 0, v LA.! 1, n ]
-- | Focal Aspect - the compass direction toward which the surface descends most
-- rapidly. Results are in radians, with 0 or \(\tau\) being North, \(\tau / 4\)
-- being East, and so on. For areas that are essentially flat, their aspect will
-- be `Nothing`.
faspect :: Manifest u Ix2 Double => Raster u p r c Double -> Raster DW p r c (Maybe Double)
faspect (Raster a) = Raster $ mapStencil Reflect (facetStencil f) a
where f nw no ne we fo ea sw so se = case normal' [ nw, no, ne, we, fo, ea, sw, so, se ] of
n | ((n LA.! 0) =~ 0) && ((n LA.! 1) =~ 0) -> Nothing
| otherwise -> Just $ angle (LA.normalize $ zcoord 0 n) axis
axis = LA.vector [1, 0, 0]
{-# INLINE faspect #-}
-- | Like `faspect`, but slightly faster. Beware of nonsense results when the
-- plane is flat.
faspect' :: Manifest u Ix2 Double => Raster u p r c Double -> Raster DW p r c Double
faspect' (Raster a) = Raster $ mapStencil Reflect (facetStencil f) a
where f nw no ne we fo ea sw so se = angle (LA.normalize $ zcoord 0 $ normal' [ nw, no, ne, we, fo, ea, sw, so , se ]) axis
axis = LA.vector [1, 0, 0]
{-# INLINE faspect' #-}
-- | Approximate Equality. Considers two `Double` to be equal if they are less
-- than \(/tau / 1024\) apart.
(=~) :: Double -> Double -> Bool
a =~ b = abs (a - b) < 0.0061359
-- | Given two normalized (length 1) vectors in R3, find the angle between them.
angle :: LA.Vector Double -> LA.Vector Double -> Double
angle u v = acos $ LA.dot u v
-- | The main type for `fdownstream` and `fupstream`, used to calculate Focal
-- Drainage. This scheme for encoding drainage patterns is described on page 81
-- of GaCM.
--
-- ==== __Full Explanation__
--
-- Fluid can flow in or out of a square pixel in one of 256 ways. Imagine a pit,
-- whose neighbours are all higher in elevation: liquid would flow in from all
-- eight compass directions, but no liquid would flow out. Consider then a
-- neighbourhood of random heights - fluid might flow in or out of the focus in
-- any permutation of the eight directions.
--
-- The scheme for encoding these permutations in a single `Word8` as described
-- in GaCM is this:
--
-- Flow in a particular direction is represented by a power of 2:
--
-- @
-- [ 1 2 4 ]
-- [ 8 16 ]
-- [ 32 64 128 ]
-- @
--
-- Direction values are summed to make the encoding. If there were drainage to
-- the North, East, and SouthEast, we'd see a sum of \(2 + 16 + 128 = 146\) to
-- uniquely represent this.
--
-- Analysing a drainage pattern from a `Drain` is just as easy: check if the bit
-- corresponding to the desired direction is flipped. The `direction` function
-- handles this.
newtype Drain = Drain { _drain :: Word8 }
deriving stock (Eq, Ord, Show)
deriving newtype (Storable, Prim, Default)
instance NFData Drain where
rnf (Drain a) = deepseq a ()
-- | Focal Drainage - downstream portion. This indicates the one or more compass
-- directions of steepest descent from each location. Appropriate as the input
-- to `fupstream`.
--
-- __Note:__ Peak-like surfaces will not flow equally in all 8 directions.
-- Consider this neighbourhood:
--
-- @
-- [ 1 1 1 ]
-- [ 1 3 1 ]
-- [ 1 1 1 ]
-- @
--
-- According to the rules in GaCM for calculating the intermediate surficial
-- "facet" points for the focus, 3, we arrive at the following facet height
-- matrix:
--
-- @
-- [ 1.5 2 1.5 ]
-- [ 2 3 2 ]
-- [ 1.5 2 1.5 ]
-- @
--
-- With these numbers it's clear that the corners would yield a steeper angle,
-- so our resulting `Drain` would only contain the directions of the diagonals.
fdownstream :: Manifest u Ix2 Double => Raster u p r c Double -> Raster DW p r c Drain
fdownstream (Raster a) = Raster $ mapStencil Reflect (facetStencil downstream) a
{-# INLINE fdownstream #-}
downstream :: Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Drain
downstream nw no ne we fo ea sw so se = Drain . snd $ foldl' f (0, 0) angles
where f (!curr, !s) (!a, !d) | a =~ curr = (curr, s + d)
| a > curr = (a, d)
| otherwise = (curr, s)
angles = [ (fo - nw, 1)
, (fo - no, 2)
, (fo - ne, 4)
, (fo - we, 8)
, (fo - ea, 16)
, (fo - sw, 32)
, (fo - so, 64)
, (fo - se, 128) ]
-- | Focal Drainage - upstream portion. This indicates the one of more compass
-- directions from which liquid would flow into each surface location. See also
-- `fdownstream`.
fupstream :: Manifest u Ix2 Drain => Raster u p r c Drain -> Raster DW p r c Drain
fupstream (Raster a) = Raster $ mapStencil (Fill $ Drain 0) (neighbourhoodStencil f) a
where f nw no ne we _ ea sw so se = Drain $ bool 0 1 (testBit (_drain nw) 7)
+ bool 0 2 (testBit (_drain no) 6)
+ bool 0 4 (testBit (_drain ne) 5)
+ bool 0 8 (testBit (_drain we) 4)
+ bool 0 16 (testBit (_drain ea) 3)
+ bool 0 32 (testBit (_drain sw) 2)
+ bool 0 64 (testBit (_drain so) 1)
+ bool 0 128 (testBit (_drain se) 0)
{-# INLINE fupstream #-}
-- | Does a given `Drain` indicate flow in a certain `Direction`?
direction :: Direction -> Drain -> Bool
direction dir (Drain d) = case dir of
NorthWest -> testBit d 0
North -> testBit d 1
NorthEast -> testBit d 2
West -> testBit d 3
East -> testBit d 4
SouthWest -> testBit d 5
South -> testBit d 6
SouthEast -> testBit d 7
-- | All `Direction`s that a `Drain` indicates flow toward.
directions :: Drain -> S.Set Direction
directions d = S.fromList $ foldl' (\acc dir -> bool acc (dir : acc) $ direction dir d) [] dirs
where dirs = [NorthWest, North, NorthEast, West, East, SouthWest, South, SouthEast]
-- | The opposite of `directions`.
drainage :: S.Set Direction -> Drain
drainage = Drain . S.foldl' f 0
where f acc d = case d of
NorthWest -> acc + 1
North -> acc + 2
NorthEast -> acc + 4
West -> acc + 8
East -> acc + 16
SouthWest -> acc + 32
South -> acc + 64
SouthEast -> acc + 128
-- | A count of `Word8` values across some `Raster`.
newtype Histogram = Histogram { _histogram :: VS.Vector Word } deriving (Eq, Show)
-- | Given a `Raster` of byte data, efficiently produce a `Histogram` that
-- describes value counts across the image. To be passed to `breaks`.
histogram :: Source u Ix2 Word8 => Raster u p r c Word8 -> Histogram
histogram (Raster a) = runST $ do
acc <- VSM.replicate 256 0
A.mapM_ (VSM.unsafeModify acc succ . fromIntegral) a
Histogram <$> VS.unsafeFreeze acc
{-# INLINE histogram #-}
-- | Given a `Histogram`, produce a list of "colour breaks" as needed by
-- functions like `greenRed`.
breaks :: Histogram -> [Word8]
breaks (Histogram h) = take 10 . (1 :) . P.reverse . snd . VS.ifoldl' f (binWidth, []) . VS.postscanl' (+) 0 $ VS.tail h
where binWidth = VS.sum (VS.tail h) `div` 11 -- Yes, 11 and not 10.
f a@(goal, acc) i n | n > goal = (next n goal, (fromIntegral i + 1) : acc)
| otherwise = a
next n goal | (n - goal) > binWidth = goal + (binWidth * (((n - goal) `div` binWidth) + 1))
| otherwise = goal + binWidth
| fosskers/mapalgebra | lib/Geography/MapAlgebra.hs | bsd-3-clause | 55,449 | 0 | 24 | 15,363 | 14,596 | 8,034 | 6,562 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, ForeignFunctionInterface #-}
-- | Duck interpreter values
-- For now, duck values are layed out in the following naive manner:
--
-- 1. All types are pointer sized. In particular, there are no zero size types as yet.
-- 2. Int and Char are stored as unboxed integers.
-- 3. Algebraic datatypes are always boxed (even ()). The first word is the tag, and
-- the remaining words are the data constructor arguments. Even tuples have tags.
module Memory
( Value
, Convert(..)
, valCons
, unsafeTag, UnsafeUnvalCons(..), unsafeUnvalConsN, unsafeUnvalConsNth
, Box, unbox, box, unsafeCastBox
, Vol, ToVol(..), readVol
, Ref, newRef, readRef, writeRef, unsafeCastRef, unsafeFreeze
, wordSize
) where
import Data.Char
import Data.Functor
import Foreign.Ptr
import Foreign.Storable
import System.IO.Unsafe
import Util
-- | Opaque type representing any Duck value (either boxed or unboxed)
type Value = Ptr WordPtr
-- | Runtime system functions
foreign import ccall "runtime.h duck_malloc" malloc :: WordPtr -> IO Value
foreign import ccall "runtime.h duck_print_int" debug_int :: WordPtr -> IO ()
_ignore = debug_int
wordSize :: Int
wordSize = sizeOf (undefined :: WordPtr)
valCons :: Int -> [Value] -> Value
valCons c args = unsafePerformIO $ do
p <- malloc $ fromIntegral $ (1 + length args) * wordSize
let c' = fromIntegral c :: WordPtr
poke p c'
mapM_ (\(i,a) -> pokeElemOff p i $ ptrToWordPtr a) (zip [1..] args)
return p
unsafeTag :: Value -> Int
unsafeTag p = fromIntegral $ unsafePerformIO $ peek p
unsafeUnvalConsN :: Int -> Value -> [Value]
unsafeUnvalConsN n p = unsafePerformIO $ mapM (\i -> peekElemOff p i >.= wordPtrToPtr) [1..n]
unsafeUnvalConsNth :: Value -> Int -> Value
unsafeUnvalConsNth p n = unsafePerformIO $ peekElemOff p (succ n) >.= wordPtrToPtr
class UnsafeUnvalCons t where
unsafeUnvalCons' :: Value -> IO t
unsafeUnvalCons :: Value -> t
unsafeUnvalCons p = unsafePerformIO (unsafeUnvalCons' p)
instance UnsafeUnvalCons Value where
unsafeUnvalCons' p = peekElemOff p 1 >.= wordPtrToPtr
instance UnsafeUnvalCons (Value,Value) where
unsafeUnvalCons' p = do
a <- peekElemOff p 1 >.= wordPtrToPtr
b <- peekElemOff p 2 >.= wordPtrToPtr
return (a,b)
instance UnsafeUnvalCons (Value,Value,Value) where
unsafeUnvalCons' p = do
(a,b) <- unsafeUnvalCons' p
c <- peekElemOff p 3 >.= wordPtrToPtr
return (a,b,c)
instance UnsafeUnvalCons (Value,Value,Value,Value) where
unsafeUnvalCons' p = do
(a,b,c) <- unsafeUnvalCons' p
d <- peekElemOff p 4 >.= wordPtrToPtr
return (a,b,c,d)
instance UnsafeUnvalCons (Value,Value,Value,Value,Value) where
unsafeUnvalCons' p = do
(a,b,c,d) <- unsafeUnvalCons' p
e <- peekElemOff p 5 >.= wordPtrToPtr
return (a,b,c,d,e)
-- | Conversion between Duck and Haskell memory representations
class Convert t where
value :: t -> Value
unsafeUnvalue :: Value -> t
instance Convert Value where
value = id
unsafeUnvalue = id
instance Convert Int where
value = intPtrToPtr . fromIntegral
unsafeUnvalue = fromIntegral . ptrToIntPtr
instance Convert Char where
value = value . ord
unsafeUnvalue = chr . unsafeUnvalue
instance Convert Bool where
value v = valCons (fromEnum v) []
unsafeUnvalue = toEnum . unsafeTag
instance Convert a => Convert [a] where
value [] = valCons 0 []
value (x:l) = valCons 1 [value x,value l]
unsafeUnvalue p = case unsafeTag p of
0 -> []
1 -> unsafeUnvalue x : unsafeUnvalue l where (x,l) = unsafeUnvalCons p
_ -> error "Convert [a]"
instance Convert a => Convert (Maybe a) where
value Nothing = valCons 0 []
value (Just x) = valCons 1 [value x]
unsafeUnvalue p = case unsafeTag p of
0 -> Nothing
1 -> Just (unsafeUnvalue x) where x = unsafeUnvalCons p
_ -> error "Convert (Maybe a)"
instance (Convert a, Convert b) => Convert (a,b) where
value (a,b) = valCons 0 [value a, value b]
unsafeUnvalue p = (unsafeUnvalue a, unsafeUnvalue b) where (a,b) = unsafeUnvalCons p
instance (Convert a, Convert b, Convert c) => Convert (a,b,c) where
value (a,b,c) = valCons 0 [value a, value b, value c]
unsafeUnvalue p = (unsafeUnvalue a, unsafeUnvalue b, unsafeUnvalue c) where (a,b,c) = unsafeUnvalCons p
-- | Version of Value with a known corresponding Haskell type
{-
newtype KnownValue t = KnownValue (Ptr (KnownValue t))
instance Convert (KnownValue t) where
value (KnownValue v) = castPtr v
unsafeUnvalue = KnownValue . castPtr
unvalue :: Convert t => KnownValue t -> t
unvalue (KnownValue v) = unsafeUnvalue $ castPtr v
-}
-- | An immutable boxed cell of known type
newtype Box t = Box (Ptr (Box t))
instance Convert (Box t) where
value (Box v) = castPtr v
unsafeUnvalue = Box . castPtr
unbox :: Convert t => Box t -> t
unbox (Box v) = unsafeUnvalue $ unsafePerformIO $ peek $ castPtr v
box :: Convert t => t -> Box t
box v = unsafePerformIO $ do
p <- malloc $ fromIntegral wordSize
poke p $ ptrToWordPtr $ value v
return $ Box $ castPtr p
-- |Cast a box to a different type
unsafeCastBox :: Box s -> Box t
unsafeCastBox (Box v) = Box $ castPtr v
-- | A mutable boxed cell of known type
newtype Ref t = Ref (Ptr (Ref t))
instance Convert (Ref t) where
value (Ref v) = castPtr v
unsafeUnvalue = Ref . castPtr
newRef :: Convert t => t -> IO (Ref t)
newRef v = do
p <- malloc $ fromIntegral wordSize
poke p $ ptrToWordPtr $ value v
return $ Ref $ castPtr p
readRef :: Convert t => Ref t -> IO t
readRef (Ref m) = unsafeUnvalue . castPtr <$> peek (castPtr m)
writeRef :: Convert t => Ref t -> t -> IO ()
writeRef (Ref m) v = poke (castPtr m) (value v)
-- |Cast a mutable cell to a different type
unsafeCastRef :: Ref s -> IO (Ref t)
unsafeCastRef (Ref m) = return $ Ref $ castPtr m
-- |Declare a mutable cell forever frozen
unsafeFreeze :: Ref t -> IO (Box t)
unsafeFreeze (Ref m) = return $ Box $ castPtr m
-- |"Volatile" boxed cell of indeterminate mutability
newtype Vol t = Vol (Ptr (Vol t))
instance Convert (Vol t) where
value (Vol v) = castPtr v
unsafeUnvalue = Vol . castPtr
class ToVol b where
toVol :: b t -> Vol t
instance ToVol Box where
toVol (Box v) = Vol $ castPtr v
instance ToVol Ref where
toVol (Ref m) = Vol $ castPtr m
readVol :: Convert t => Vol t -> IO t
readVol (Vol v) = unsafeUnvalue . castPtr <$> peek (castPtr v)
| girving/duck | duck/Memory.hs | bsd-3-clause | 6,382 | 0 | 13 | 1,304 | 2,209 | 1,132 | 1,077 | 138 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
import Data.Proxy
import Data.Monoid
import GHC.Types
type UnaryCounter = [()]
class CounterLike a where
zero :: a
incr :: a -> a
toInt :: a -> Int
instance CounterLike Int where
zero = 0
incr = (+1)
toInt = id
instance CounterLike UnaryCounter where
zero = []
incr = (():)
toInt = length
-- DeMorgan's Law
newtype Exists c = Exists (forall b. (forall a. c a => a -> b) -> b)
pack :: forall c a. c a => a -> Exists c
modify :: forall c. (forall a. c a => a -> a) -> Exists c -> Exists c
apply :: forall c b. (forall a. c a => a -> b) -> Exists c -> b
pack x = Exists (\f -> f x)
modify g (Exists k) = Exists (\f -> k (\x -> f . g $ x))
apply f (Exists k) = k f
mylilcounter :: Exists CounterLike
mylilcounter = pack (100 :: Int)
double :: Exists CounterLike -> Exists CounterLike
double = modify (\x -> d x x)
where
d x = appEndo . mconcat $ replicate (toInt x) (Endo incr)
| sleexyz/haskell-fun | ExistentialsForFree2.hs | bsd-3-clause | 1,072 | 0 | 12 | 248 | 452 | 244 | 208 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Test.Sandbox.Compose
import Options.Applicative
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T
import Shelly hiding (command,run,FilePath)
import Network.HTTP.Conduit
import Control.Monad
import Control.Concurrent
default (T.Text)
type Port=Int
data Command
= Up [String]
| Status [String]
| Conf
| Kill [String]
| Logs [String]
| Destroy
| Daemon FilePath
deriving Show
up :: Parser Command
up = Up <$> many (argument str (metavar "TARGET..."))
status :: Parser Command
status = Status <$> many (argument str (metavar "TARGET..."))
conf :: Parser Command
conf = pure Conf
kill :: Parser Command
kill = Kill <$> many (argument str (metavar "TARGET..."))
logs :: Parser Command
logs = Logs <$> many (argument str (metavar "TARGET..."))
destroy :: Parser Command
destroy = pure Destroy
daemon :: Parser Command
daemon = Daemon <$> strOption (long "conf" <> value "test-sandbox-compose.yml" <> metavar "CONFFILE(Yaml)")
parse :: Parser Command
parse = subparser $ foldr1 (<>) [
command "up" (info up (progDesc "up registered service"))
, command "status" (info status (progDesc "show sandbox-state"))
, command "conf" (info conf (progDesc "show internal-conf-file"))
, command "kill" (info kill (progDesc "kill service"))
, command "logs" (info logs (progDesc "show logs"))
, command "destroy" (info destroy (progDesc "destroy deamon"))
, command "daemon" (info daemon (progDesc "start daemon"))
]
setup :: IO Port
setup = shelly $ do
unlessM (test_e ".sandbox/port") $
liftIO $ do
runServer "test-sandbox-compose.yml" False
threadDelay $ 1*1000*1000
content <- readfile ".sandbox/port"
return $ read $ T.unpack content
runCmd' :: [String] -> String -> IO ()
runCmd' xs cmd' = do
port' <- setup
case xs of
[] -> simpleHttp ("http://localhost:" <> show port' <> "/" <> cmd') >>= L.putStr
xs' -> forM_ xs' $ \x ->
simpleHttp ("http://localhost:" <> show port' <> "/" <> cmd' <> "/" <> x) >>= L.putStr
runCmd :: Command -> IO ()
runCmd (Up targets) = runCmd' targets "up"
runCmd (Status targets) = runCmd' targets "status"
runCmd (Kill targets) = runCmd' targets "kill"
runCmd (Logs targets) = runCmd' targets "logs"
runCmd Conf = runCmd' [] "conf"
runCmd Destroy = runCmd' [] "destroy"
runCmd (Daemon conf) = runServer conf True
opts :: ParserInfo Command
opts = info (parse <**> helper) idm
main :: IO ()
main = execParser opts >>= runCmd
| junjihashimoto/test-sandbox-compose | Main.hs | bsd-3-clause | 2,625 | 0 | 20 | 514 | 918 | 470 | 448 | 72 | 2 |
module HsImport.Utils
( srcLine
, declSrcLoc
, importDecls
) where
import qualified Language.Haskell.Exts as HS
type SrcLine = Int
srcLine :: HS.ImportDecl -> SrcLine
srcLine = HS.srcLine . HS.importLoc
declSrcLoc :: HS.Decl -> Maybe HS.SrcLoc
declSrcLoc decl =
case decl of
HS.TypeDecl srcLoc _ _ _ -> Just srcLoc
HS.TypeFamDecl srcLoc _ _ _ -> Just srcLoc
HS.ClosedTypeFamDecl srcLoc _ _ _ _ -> Just srcLoc
HS.DataDecl srcLoc _ _ _ _ _ _ -> Just srcLoc
HS.GDataDecl srcLoc _ _ _ _ _ _ _ -> Just srcLoc
HS.DataFamDecl srcLoc _ _ _ _ -> Just srcLoc
HS.TypeInsDecl srcLoc _ _ -> Just srcLoc
HS.DataInsDecl srcLoc _ _ _ _ -> Just srcLoc
HS.GDataInsDecl srcLoc _ _ _ _ _ -> Just srcLoc
HS.ClassDecl srcLoc _ _ _ _ _ -> Just srcLoc
HS.InstDecl srcLoc _ _ _ _ _ _ -> Just srcLoc
HS.DerivDecl srcLoc _ _ _ _ _ -> Just srcLoc
HS.InfixDecl srcLoc _ _ _ -> Just srcLoc
HS.DefaultDecl srcLoc _ -> Just srcLoc
HS.SpliceDecl srcLoc _ -> Just srcLoc
HS.TypeSig srcLoc _ _ -> Just srcLoc
HS.FunBind _ -> Nothing
HS.PatBind srcLoc _ _ _ -> Just srcLoc
HS.ForImp srcLoc _ _ _ _ _ -> Just srcLoc
HS.ForExp srcLoc _ _ _ _ -> Just srcLoc
HS.RulePragmaDecl srcLoc _ -> Just srcLoc
HS.DeprPragmaDecl srcLoc _ -> Just srcLoc
HS.WarnPragmaDecl srcLoc _ -> Just srcLoc
HS.InlineSig srcLoc _ _ _ -> Just srcLoc
HS.InlineConlikeSig srcLoc _ _ -> Just srcLoc
HS.SpecSig srcLoc _ _ _ -> Just srcLoc
HS.SpecInlineSig srcLoc _ _ _ _ -> Just srcLoc
HS.InstSig srcLoc _ _ _ _ -> Just srcLoc
HS.AnnPragma srcLoc _ -> Just srcLoc
HS.MinimalPragma srcLoc _ -> Just srcLoc
importDecls :: HS.Module -> [HS.ImportDecl]
importDecls (HS.Module _ _ _ _ _ imports _) = imports
| jystic/hsimport | lib/HsImport/Utils.hs | bsd-3-clause | 2,162 | 0 | 9 | 827 | 733 | 345 | 388 | 43 | 30 |
{-# LANGUAGE NoImplicitPrelude, FlexibleInstances, MultiParamTypeClasses #-}
module Network.NineP.Server.Utils
( getQid, fromStat, toWStat, toMode, walk, sendRMsg, convertPerm
) where
import Prelude hiding (lookup)
import Control.Monad (liftM)
import Control.Monad.Trans (MonadIO(..))
import Data.Bits (shiftL, complement, (.&.), (.|.))
import Data.Word (Word8, Word16, Word32, Word64)
import System.IO (Handle, hFlush)
import qualified Data.Map as M
import Data.Accessor(Accessor, (^=))
import Data.Binary.Put (runPut)
import Data.Time(UTCTime)
import Data.Time.Clock.POSIX(utcTimeToPOSIXSeconds, posixSecondsToUTCTime)
import qualified Data.ByteString.Lazy as L
import Data.NineP.Mode
import Data.NineP.Stat
import Network.NineP.Server.File.Internal
import qualified Network.NineP.Binary as B
class Convertable a b where
convert :: a -> b
(^>=) :: Convertable a b => Accessor r b -> a -> r -> r
(^>=) t a = t ^= convert a
instance Convertable Word32 (Maybe Permission) where
convert w | w == maxBound = Nothing
| True = Just w
instance Convertable Word32 (Maybe UTCTime) where
convert w | w == maxBound = Nothing
| True = Just $ posixSecondsToUTCTime . fromIntegral $ w
instance Convertable Word64 (Maybe Word64) where
convert w | w == maxBound = Nothing
| True = Just w
instance Convertable String (Maybe String) where
convert s | s == "" = Nothing
| True = Just s
sendRMsg :: MonadIO m => Handle -> Word16 -> B.RMsgBody -> m ()
sendRMsg h tag msgBody =
liftIO $ L.hPutStr h (runPut $ B.put $ B.Msg tag msgBody) >> hFlush h
getQid :: File a s => a -> NineP s B.Qid
getQid file =
do
path <- qidPath file
ver <- qidVersion file
stat' <- stat file
return $ B.Qid (fromIntegral $ (st_perm stat') `shiftL` 24) ver path
convertPerm :: File a s => a -> Word32 -> NineP s Permission
convertPerm dir perm =
do
let perm' = fromIntegral perm
let mask = if (perm' .&. permDir /= 0) then 0o666 else 0o777
let comask = complement mask
stat' <- stat dir
return $ perm' .&. (comask .|. (st_perm stat' .&. mask))
toWStat :: B.Stat -> WStat
toWStat (B.Stat _ _ _ mode atime mtime size name uid gid muid) =
wst_perm ^>= mode $ wst_size ^>= size
$ wst_atime ^>= atime $ wst_mtime ^>= mtime
$ wst_name ^>= name $ wst_uid ^>= uid
$ wst_gid ^>= gid $ wst_muid ^>= muid
$ emptyWStat
toMode :: Word8 -> Mode
toMode mode =
let m = fromIntegral mode
in fromIntegral $ (1 `shiftL` (m .&. 0xF)) .|. (m .&. (complement 0xF))
fromStat :: File' s -> NineP s B.Stat
fromStat (File' file _) =
do
Stat mode atime mtime size name uid guid muid <- stat file
qid <- getQid file
return $ B.Stat 0 0 qid mode
(liftM round utcTimeToPOSIXSeconds atime)
(liftM round utcTimeToPOSIXSeconds mtime)
size name uid guid muid
walk :: File a s => a -> [String] -> NineP s (File' s, [B.Qid])
walk file (wname : wnames) = do
mp <- lookup file
case M.lookup wname mp of
Just (File' f _) -> do
(rf, qids) <- walk f wnames
qid <- getQid f
return (rf, qid : qids)
Nothing -> return (file' file, [])
walk file [] = return (file' file, [])
| Elemir/network-ninep | src/Network/NineP/Server/Utils.hs | bsd-3-clause | 3,269 | 0 | 20 | 793 | 1,284 | 663 | 621 | 83 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : AERN2.WithGlobalParam.Elementary
Description : elementary functions on sequences
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Elementary functions on fast converging sequences.
-}
module AERN2.WithGlobalParam.Elementary
()
where
import MixedTypesNumPrelude
-- import qualified Prelude as P
-- import Control.Arrow
import Control.CollectErrors
import AERN2.MP.Dyadic
import AERN2.QA.Protocol
import AERN2.WithGlobalParam.Type
import AERN2.WithGlobalParam.Helpers
import AERN2.WithGlobalParam.Ring ()
import AERN2.WithGlobalParam.Field ()
{- exp -}
instance
(QAArrow to, CanExp a
, SuitableForWGParam prm a, SuitableForWGParam prm (ExpType a))
=>
CanExp (WithGlobalParamA to prm a)
where
type ExpType (WithGlobalParamA to prm a) = WithGlobalParamA to prm (ExpType a)
exp = unaryOp "exp" exp
{- log -}
instance
(QAArrow to, CanLog a
, SuitableForWGParam prm a, SuitableForWGParam prm (LogType a))
=>
CanLog (WithGlobalParamA to prm a)
where
type LogType (WithGlobalParamA to prm a) = WithGlobalParamA to prm (LogType a)
log = unaryOp "log" log
{- power -}
instance
(QAArrow to, CanPow a e
, SuitableForWGParam prm a, SuitableForWGParam prm e
, SuitableForWGParam prm (PowTypeNoCN a e)
, SuitableForWGParam prm (PowType a e))
=>
CanPow (WithGlobalParamA to prm a) (WithGlobalParamA to prm e)
where
type PowTypeNoCN (WithGlobalParamA to prm a) (WithGlobalParamA to prm e) = WithGlobalParamA to prm (PowTypeNoCN a e)
powNoCN = binaryOp "^!" powNoCN
type PowType (WithGlobalParamA to prm a) (WithGlobalParamA to prm e) = WithGlobalParamA to prm (PowType a e)
pow = binaryOp "^" pow
instance
(CanPow (WithGlobalParamA to prm a) b
, CanEnsureCE es b
, CanEnsureCE es (PowTypeNoCN (WithGlobalParamA to prm a) b)
, CanEnsureCE es (PowType (WithGlobalParamA to prm a) b)
, CanBeErrors es)
=>
CanPow (WithGlobalParamA to prm a) (CollectErrors es b)
where
type PowTypeNoCN (WithGlobalParamA to prm a) (CollectErrors es b) =
EnsureCE es (PowTypeNoCN (WithGlobalParamA to prm a) b)
powNoCN = lift2TLCE powNoCN
type PowType (WithGlobalParamA to prm a) (CollectErrors es b) =
EnsureCE es (PowType (WithGlobalParamA to prm a) b)
pow = lift2TLCE pow
instance
(CanPow a (WithGlobalParamA to prm b)
, CanEnsureCE es a
, CanEnsureCE es (PowType a (WithGlobalParamA to prm b))
, CanEnsureCE es (PowTypeNoCN a (WithGlobalParamA to prm b))
, CanBeErrors es)
=>
CanPow (CollectErrors es a) (WithGlobalParamA to prm b)
where
type PowTypeNoCN (CollectErrors es a) (WithGlobalParamA to prm b) =
EnsureCE es (PowTypeNoCN a (WithGlobalParamA to prm b))
powNoCN = lift2TCE powNoCN
type PowType (CollectErrors es a) (WithGlobalParamA to prm b) =
EnsureCE es (PowType a (WithGlobalParamA to prm b))
pow = lift2TCE pow
$(declForTypes
[[t| Integer |], [t| Int |], [t| Dyadic |], [t| Rational |]]
(\ t -> [d|
instance
(QAArrow to, CanPow a $t
, SuitableForWGParam prm a
, SuitableForWGParam prm (PowTypeNoCN a $t)
, SuitableForWGParam prm (PowType a $t))
=>
CanPow (WithGlobalParamA to prm a) $t where
type PowTypeNoCN (WithGlobalParamA to prm a) $t =
WithGlobalParamA to prm (PowTypeNoCN a $t)
powNoCN = binaryOpWithPureArg "^" powNoCN
type PowType (WithGlobalParamA to prm a) $t =
WithGlobalParamA to prm (PowType a $t)
pow = binaryOpWithPureArg "^" pow
instance
(QAArrow to, CanPow $t a
, SuitableForWGParam prm a
, SuitableForWGParam prm (PowTypeNoCN $t a)
, SuitableForWGParam prm (PowType $t a))
=>
CanPow $t (WithGlobalParamA to prm a) where
type PowTypeNoCN $t (WithGlobalParamA to prm a) =
WithGlobalParamA to prm (PowTypeNoCN $t a)
powNoCN = flip $ binaryOpWithPureArg "^" (flip powNoCN)
type PowType $t (WithGlobalParamA to prm a) =
WithGlobalParamA to prm (PowType $t a)
pow = flip $ binaryOpWithPureArg "^" (flip pow)
|]))
{- sqrt -}
instance
(QAArrow to, CanSqrt a
, CanMinMaxThis a Integer
, SuitableForWGParam prm a, SuitableForWGParam prm (SqrtType a))
=>
CanSqrt (WithGlobalParamA to prm a)
where
type SqrtType (WithGlobalParamA to prm a) = WithGlobalParamA to prm (SqrtType a)
sqrt = unaryOp "sqrt" sqrt
{- sine, cosine -}
instance
(QAArrow to, CanSinCos a
, SuitableForWGParam prm a, SuitableForWGParam prm (SinCosType a))
=>
CanSinCos (WithGlobalParamA to prm a)
where
type SinCosType (WithGlobalParamA to prm a) = WithGlobalParamA to prm (SinCosType a)
cos = unaryOp "cos" cos
sin = unaryOp "sin" sin
| michalkonecny/aern2 | aern2-net/src/AERN2/WithGlobalParam/Elementary.hs | bsd-3-clause | 4,825 | 0 | 10 | 1,065 | 1,204 | 632 | 572 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Events
( events
) where
import IO
import Text
import Network.SimpleIRC
import qualified Data.ByteString.UTF8 as U
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
import Control.Exception
import Control.Monad
import System.IO.Error
events = [Privmsg onMessage,Disconnect onDisconnect,RawMsg onRaw, Quit onQuit]
onRaw s = print
onDisconnect mIrc = do
m <- reconnect mIrc
either (\err -> putStrLn $ "Unable to reconnect: " ++ show err) (\_ -> putStrLn "Successfully reconnected.") m
onQuit s mIrc = do
m <- reconnect s
either (\err -> putStrLn $ "Unable to reconnect: " ++ show err) (\_ -> putStrLn "Successfully reconnected.") m
onMessage :: EventFunc
onMessage s m
| iscmd "?g " = mention <=< getRedirectTitle . googlestr . spaceToPlus . killSpaces . stringDropCmd $ msg
| iscmd "?wik " = mention <=< getRedirectTitle . wikistr . spaceToPlus . killSpaces . stringDropCmd $ msg
| iscmd "?tube " = mention <=< getRedirectTitle . youstr . spaceToPlus . killSpaces . stringDropCmd $ msg
| iscmd "?tell " = mention =<< saveTell msg nick
| iscmd "?h" = say . fromMaybe helpstr . flip lookup helpstrs . takeWhile (/=' ') . stringDropCmd $ msg
| iscmd "?ping" = mention <=< ping $ msg
| iscmd "?d " = mention <=< dice . stringDropCmd $ msg
| iscmd "?t" = mention =<< title msg chan
| otherwise = do
tell s nick
let url = matchUrl . B.unpack $ msg
unless (null url) $ do
title <- getTitle url
unless (null title) $ do
tfile <- getTitleFile chan
writeFile tfile title
where iscmd = flip B.isPrefixOf msg
channel = fromJust $ mChan m
chan = U.toString channel
msg = mMsg m
nik = fromJust $ mNick m
nick = U.toString nik
say = send s m
mention = say . address nick
title :: B.ByteString -> String -> IO String
title msg chan = do
let url = matchUrl . stringDropCmd $ msg
tfile <- getTitleFile chan
e <- tryJust (guard . isDoesNotExistError) (readFile tfile)
unescapeEntities <$> if not . null $ url then getTitle url else
return $ either (const "No title to get") id e
ping :: B.ByteString -> IO String
ping msg = do
let url = matchUrl . stringDropCmd $ msg
if not . null $ url then do
time <- flip stringRegex "(?<=time=)[0-9]*" <$> runCmd "ping" ["-c 2 -w 3", url] ""
return $ if not . null $ time then time ++ "ms" else "Can't connect."
else return "pong!"
dice :: String -> IO String
dice msg = fmap collapseroll $ mapM droll $ wrapDie $ matchDice msg
where droll :: (Int, Int, Int, Int) -> IO [Int]
droll (d, multi, offset, num) = fmap (map (+offset)) $ replicateM num (
fmap sum $ replicateM multi (roll d))
collapseroll :: [[Int]] -> String
collapseroll [] = ""
collapseroll (i:is) = unwords [unwords $ map show i, collapseroll is]
| raposalorx/mssbot | Events.hs | bsd-3-clause | 2,954 | 0 | 15 | 725 | 1,091 | 540 | 551 | -1 | -1 |
{-# LANGUAGE TypeFamilies, OverloadedStrings, FlexibleContexts #-}
--------------------------------------------------------------------
-- |
-- Module : Diagrams.SVG.Tree
-- Copyright : (c) 2015 Tillmann Vogt <[email protected]>
-- License : BSD3
--
-- Maintainer: [email protected]
-- Stability : stable
-- Portability: portable
module Diagrams.SVG.Tree
(
-- * Tree data type
Tag(..)
, HashMaps(..)
-- * Extract data from the tree
, nodes
, Attrs(..)
, NodesMap
, CSSMap
, GradientsMap
, PreserveAR(..)
, AlignSVG(..)
, MeetOrSlice(..)
, Place
, ViewBox(..)
, Gr(..)
, GradientAttributes(..)
, PresentationAttributes(..)
, GradRefId
, expandGradMap
, insertRefs
, preserveAspectRatio
, FontContent(..)
, FontData(..)
, FontFace(..)
, Glyph(..)
, KernDir(..)
, KernMaps(..)
, SvgGlyphs(..)
, Kern(..)
)
where
import Data.Maybe (isJust, fromJust , fromMaybe)
import qualified Data.HashMap.Strict as H
import qualified Data.Text as T
import Data.Text(Text(..))
import Data.Vector(Vector)
import Diagrams.Prelude hiding (Vector)
import Diagrams.TwoD.Size
-- import Diagrams.SVG.Fonts.ReadFont
import Debug.Trace
-- Note: Maybe we could use the Tree from diagrams here but on the other hand this makes diagrams-input
-- more independent of changes of diagrams' internal structures
-------------------------------------------------------------------------------------
-- | A tree structure is needed to handle refences to parts of the tree itself.
-- The \<defs\>-section contains shapes that can be refered to, but the SVG standard allows to refer to
-- every tag in the SVG-file.
--
data Tag b n = Leaf Id (ViewBox n -> Path V2 n) ((HashMaps b n, ViewBox n) -> Diagram b)-- ^
-- A leaf consists of
--
-- * An Id
--
-- * A path so that this leaf can be used to clip some other part of a tree
--
-- * A diagram (Another option would have been to apply a function to the upper path)
| Reference Id Id (ViewBox n -> Path V2 n) ((HashMaps b n, ViewBox n) -> Diagram b -> Diagram b)-- ^
-- A reference (\<use\>-tag) consists of:
--
-- * An Id
--
-- * A reference to an Id
--
-- * A viewbox so that percentages are relative to this viewbox
--
-- * Transformations applied to the reference
| SubTree Bool Id (Double, Double)
(Maybe (ViewBox n))
(Maybe PreserveAR)
(HashMaps b n -> Diagram b -> Diagram b)
[Tag b n]-- ^
-- A subtree consists of:
--
-- * A Bool: Are we in a section that will be rendered directly (not in a \<defs\>-section)
--
-- * An Id of subdiagram
--
-- * A viewbox so that percentages are relative to this viewbox
--
-- * Aspect Ratio
--
-- * A transformation or application of a style to a subdiagram
--
-- * A list of subtrees
| StyleTag [(Text, [(Text, Text)])] -- ^ A tag that contains CSS styles with selectors and attributes
| FontTag (FontData b n)
| Grad Id (Gr n) -- ^ A gradient
| Stop (HashMaps b n -> [GradientStop n]) -- ^
-- We need to make this part of this data structure because Gradient tags can also contain description tags
type Id = Maybe Text
type GradRefId = Maybe Text
type Attrs = [(Text, Text)]
type Nodelist b n = [(Text, Tag b n)]
type CSSlist = [(Text, Attrs)]
data Gr n = Gr GradRefId
GradientAttributes
(Maybe (ViewBox n))
[CSSMap -> [GradientStop n]]
(CSSMap -> GradientAttributes -> ViewBox n -> [CSSMap -> [GradientStop n]] -> Texture n)
type Gradlist n = [(Text, Gr n)]
type Fontlist b n = [(Text, FontData b n)]
type HashMaps b n = (NodesMap b n, CSSMap, GradientsMap n)
type NodesMap b n = H.HashMap Text (Tag b n)
type CSSMap = H.HashMap Text Attrs
type GradientsMap n = H.HashMap Text (Gr n)
type ViewBox n = (n,n,n,n) -- (MinX,MinY,Width,Height)
data PreserveAR = PAR AlignSVG MeetOrSlice -- ^ see <http://www.w3.org/TR/SVG11/coords.html#PreserveAspectRatioAttribute>
data AlignSVG = AlignXY Place Place -- ^ alignment in x and y direction
type Place = Double -- ^ A value between 0 and 1, where 0 is the minimal value and 1 the maximal value
data MeetOrSlice = Meet | Slice
instance Show (Tag b n) where
show (Leaf id1 _ _) = "Leaf " ++ (show id1) ++ "\n"
show (Reference selfid id1 viewbox f) = "Reference " ++ (show id1) ++ "\n"
show (SubTree b id1 wh viewbox ar f tree) = "Sub " ++ (show id1) ++ concat (map show tree) ++ "\n"
show (StyleTag _) = "Style " ++ "\n"
show (Grad id1 gr) = "Grad id:" ++ (show id1) -- ++ (show gr) ++ "\n"
show (Stop _) = "Stop " ++ "\n"
-- instance Show (Gr n) where show (Gr gradRefId gattr vb stops tex) = " ref:" ++ (show gradRefId) ++ "viewbox: " ++ (show vb)
----------------------------------------------------------------------------------
-- | Generate elements that can be referenced by their ID.
-- The tree nodes are splitted into 4 groups of lists of (ID,value)-pairs):
--
-- * Nodes that contain elements that can be transformed to a diagram
--
-- * CSS classes with corresponding (attribute,value)-pairs, from the <defs>-tag
--
-- * Gradients
--
-- * Fonts
nodes :: Maybe (ViewBox n) -> (Nodelist b n, CSSlist, Gradlist n, Fontlist b n) -> Tag b n ->
(Nodelist b n, CSSlist, Gradlist n, Fontlist b n)
nodes viewbox (ns,css,grads,fonts) (Leaf id1 path diagram)
| isJust id1 = (ns ++ [(fromJust id1, Leaf id1 path diagram)],css,grads,fonts)
| otherwise = (ns,css,grads,fonts)
-- A Reference element for the <use>-tag
nodes viewbox (ns,css,grads,fonts) (Reference selfId id1 vb f) = (ns,css,grads,fonts)
nodes viewbox (ns,css,grads,fonts) (SubTree b id1 wh Nothing ar f children)
| isJust id1 = myconcat [ (ns ++ [(fromJust id1, SubTree b id1 wh viewbox ar f children)],css,grads,fonts) ,
(myconcat (map (nodes viewbox (ns,css,grads,fonts)) children)) ]
| otherwise = myconcat (map (nodes viewbox (ns,css,grads,fonts)) children)
nodes viewbox (ns,css,grads,fonts) (SubTree b id1 wh vb ar f children)
| isJust id1 = myconcat [ (ns ++ [(fromJust id1, SubTree b id1 wh vb ar f children)],css,grads,fonts) ,
(myconcat (map (nodes vb (ns,css,grads,fonts)) children)) ]
| otherwise = myconcat (map (nodes vb (ns,css,grads,fonts)) children)
nodes viewbox (ns,css,grads,fonts) (Grad id1 (Gr gradRefId gattr vb stops texture))
| isJust id1 = (ns,css, grads ++ [(fromJust id1, Gr gradRefId gattr vb stops texture)], fonts)
| otherwise = (ns,css,grads,fonts)
-- There is a global style tag in the defs section of some svg files
nodes viewbox (ns,css,grads,fonts) (StyleTag styles) = (ns,css ++ styles,grads,fonts)
-- stops are not extracted here but from the gradient parent node
nodes viewbox lists (Stop _) = lists
nodes viewbox (ns,css,grads,fonts) (FontTag fontData) = (ns,css,grads,fonts ++ [(fromMaybe "" (fontId fontData), fontData)])
myconcat :: [(Nodelist b n, CSSlist, Gradlist n, Fontlist b n)] -> (Nodelist b n, CSSlist, Gradlist n, Fontlist b n)
myconcat list = (concat $ map sel1 list, concat $ map sel2 list, concat $ map sel3 list, concat $ map sel4 list)
where sel1 (a,b,c,d) = a
sel2 (a,b,c,d) = b
sel3 (a,b,c,d) = c
sel4 (a,b,c,d) = d
------------------------------------------------------------------------------------------------------
-- The following code is necessary to handle nested xlink:href in gradients,
-- like in this example (#linearGradient3606 in radialGradient):
--
-- <linearGradient
-- id="linearGradient3606">
-- <stop
-- id="stop3608"
-- style="stop-color:#ff633e;stop-opacity:1"
-- offset="0" />
-- <stop
-- id="stop3610"
-- style="stop-color:#ff8346;stop-opacity:0.78225809"
-- offset="1" />
-- </linearGradient>
-- <radialGradient
-- cx="275.00681"
-- cy="685.96008"
-- r="112.80442"
-- fx="275.00681"
-- fy="685.96008"
-- id="radialGradient3612"
-- xlink:href="#linearGradient3606"
-- gradientUnits="userSpaceOnUse"
-- gradientTransform="matrix(1,0,0,1.049029,-63.38387,-67.864647)" />
-- | Gradients contain references to include attributes/stops from other gradients.
-- expandGradMap expands the gradient with these attributes and stops
expandGradMap :: GradientsMap n -> GradientsMap n -- GradientsMap n = H.HashMap Text (Gr n)
expandGradMap gradMap = H.mapWithKey (newGr gradMap) gradMap
newGr grMap key (Gr gradRefId attrs vb stops f) = (Gr gradRefId newAttributes vb newStops f)
where newStops = stops ++ (gradientStops grMap gradRefId)
newAttributes = overwriteDefaultAttributes $ gradientAttributes grMap (Just key)
-- | Gradients that reference other gradients form a list of attributes
-- The last element of this list are the default attributes (thats why there is "reverse attrs")
-- Then the second last attributes overwrite these defaults (and so on until the root)
-- The whole idea of this nesting is that Nothing values don't overwrite Just values
overwriteDefaultAttributes :: [GradientAttributes] -> GradientAttributes
overwriteDefaultAttributes [attrs] = attrs
overwriteDefaultAttributes attrs = foldl1 updateRec (reverse attrs)
-- | Every reference is looked up in the gradient map and a record of attributes is added to a list
gradientAttributes :: GradientsMap n -> GradRefId -> [GradientAttributes] -- GradientsMap n = H.HashMap Text (Gr n)
gradientAttributes grMap Nothing = []
gradientAttributes grMap (Just refId) | isJust gr = (attrs $ fromJust gr) : (gradientAttributes grMap (grRef $ fromJust gr))
| otherwise = []
where gr = H.lookup refId grMap
grRef (Gr ref _ _ _ _) = ref
attrs (Gr _ att _ _ _) = att
-- | Every reference is looked up in the gradient map and the stops are added to a list
gradientStops :: GradientsMap n -> GradRefId -> [CSSMap -> [GradientStop n]]
gradientStops grMap Nothing = []
gradientStops grMap (Just refId) | isJust gr = (stops $ fromJust gr) ++ (gradientStops grMap (grRef $ fromJust gr))
| otherwise = []
where gr = H.lookup refId grMap
grRef (Gr ref _ _ _ _) = ref
stops (Gr _ _ _ st _) = st
-- | Update the gradient record. The first argument is the leaf record, the second is the record that overwrites the leaf.
-- The upper example references gradients that have only stops (no overwriting of attributes).
-- See <http://www.w3.org/TR/SVG/pservers.html#RadialGradientElementHrefAttribute>
updateRec :: GradientAttributes -> GradientAttributes -> GradientAttributes
updateRec (GA pa class_ style x1 y1 x2 y2 cx cy r fx fy gradientUnits gradientTransform spreadMethod)
(GA paN class1N styleN x1N y1N x2N y2N cxN cyN rN fxN fyN gradientUnitsN gradientTransformN spreadMethodN)
= toGA (paN, (updateList [class_,style,x1,y1,x2,y2,cx,cy,r,fx,fy,gradientUnits,gradientTransform,spreadMethod] -- TODO: update pa
[class1N,styleN,x1N,y1N,x2N,y2N,cxN,cyN,rN,fxN,fyN,gradientUnitsN,gradientTransformN,spreadMethodN]))
where
updateList :: [Maybe Text] -> [Maybe Text] -> [Maybe Text]
updateList (defaultt:xs) ((Just t1):ys) = (Just t1) : (updateList xs ys)
updateList ((Just t0):xs) (Nothing :ys) = (Just t0) : (updateList xs ys)
updateList (Nothing :xs) (Nothing :ys) = Nothing : (updateList xs ys)
updateList _ _ = []
toGA (pa, [class_,style,x1,y1,x2,y2,cx,cy,r,fx,fy,gradientUnits,gradientTransform,spreadMethod]) =
GA pa class_ style x1 y1 x2 y2 cx cy r fx fy gradientUnits gradientTransform spreadMethod
------------------------------------------------------------------------------------------------------------
-- | Lookup a diagram and return an empty diagram in case the SVG-file has a wrong reference
lookUp hmap i | (isJust i) && (isJust l) = fromJust l
| otherwise = Leaf Nothing mempty mempty -- an empty diagram if we can't find the id
where l = H.lookup (fromJust i) hmap
-- | Evaluate the tree into a diagram by inserting xlink:href references from nodes and gradients,
-- applying clipping and passing the viewbox to the leafs
insertRefs :: (V b ~ V2, N b ~ n, RealFloat n, Place ~ n) => (HashMaps b n, ViewBox n) -> Tag b n -> Diagram b
insertRefs (maps,viewbox) (Leaf id1 path f) = (f (maps,viewbox)) # (if isJust id1 then named (T.unpack $ fromJust id1) else id)
insertRefs (maps,viewbox) (Grad _ _) = mempty
insertRefs (maps,viewbox) (Stop f) = mempty
insertRefs (maps,viewbox) (Reference selfId id1 path styles)
| (Diagrams.TwoD.Size.width r) <= 0 || (Diagrams.TwoD.Size.height r) <= 0 = mempty
| otherwise = referencedDiagram # styles (maps,viewbox)
# cutOutViewBox viewboxPAR
-- # stretchViewBox (fromJust w) (fromJust h) viewboxPAR
# (if isJust selfId then named (T.unpack $ fromJust selfId) else id)
where r = path viewbox
viewboxPAR = getViewboxPreserveAR subTree
referencedDiagram = insertRefs (maps,viewbox) (makeSubTreeVisible viewbox subTree)
subTree = lookUp (sel1 maps) id1
getViewboxPreserveAR (SubTree _ id1 wh viewbox ar g children) = (viewbox, ar)
getViewboxPreserveAR _ = (Nothing, Nothing)
sel1 (a,b,c) = a
insertRefs (maps,viewbox) (SubTree False _ _ _ _ _ _) = mempty
insertRefs (maps,viewbox) (SubTree True id1 (w,h) viewb ar styles children) =
subdiagram # styles maps
# cutOutViewBox (viewb, ar)
# (if (w > 0) && (h > 0) then stretchViewBox w h (viewb, ar) else id)
# (if isJust id1 then named (T.unpack $ fromJust id1) else id)
where subdiagram = mconcat (map (insertRefs (maps, fromMaybe viewbox viewb)) children)
insertRefs (maps,viewbox) (StyleTag _) = mempty
-------------------------------------------------------------------------------------------------------------------------------
makeSubTreeVisible viewbox (SubTree _ id1 wh vb ar g children) =
(SubTree True id1 wh (Just viewbox) ar g (map (makeSubTreeVisible viewbox) children))
makeSubTreeVisible _ x = x
stretchViewBox w h ((Just (minX,minY,width,height), Just par)) = preserveAspectRatio w h (width - minX) (height - minY) par
stretchViewBox w h ((Just (minX,minY,width,height), Nothing)) = -- Debug.Trace.trace "nothing" $
preserveAspectRatio w h (width - minX) (height - minY) (PAR (AlignXY 0.5 0.5) Meet)
stretchViewBox w h _ = id
cutOutViewBox (Just (minX,minY,width,height), _) = rectEnvelope (p2 (minX, minY)) (r2 ((width - minX), (height - minY)))
-- (clipBy (rect (width - minX) (height - minY)))
cutOutViewBox _ = id
-------------------------------------------------------------------------------------------------------------------------------
-- | preserveAspectRatio is needed to fit an image into a frame that has a different aspect ratio than the image
-- (e.g. 16:10 against 4:3).
-- SVG embeds images the same way: <http://www.w3.org/TR/SVG11/coords.html#PreserveAspectRatioAttribute>
--
-- > import Graphics.SVGFonts
-- >
-- > portrait preserveAR width height = stroke (readSVGFile preserveAR width height "portrait.svg") # showOrigin
-- > text' t = stroke (textSVG' $ TextOpts t lin INSIDE_H KERN False 1 1 ) # fc back # lc black # fillRule EvenOdd
-- > portraitMeet1 x y = (text' "PAR (AlignXY " ++ show x ++ " " show y ++ ") Meet") ===
-- > (portrait (PAR (AlignXY x y) Meet) 200 100 <> rect 200 100)
-- > portraitMeet2 x y = (text' "PAR (AlignXY " ++ show x ++ " " show y ++ ") Meet") ===
-- > (portrait (PAR (AlignXY x y) Meet) 100 200 <> rect 100 200)
-- > portraitSlice1 x y = (text' "PAR (AlignXY " ++ show x ++ " " show y ++ ") Slice") ===
-- > (portrait (PAR (AlignXY x y) Slice) 100 200 <> rect 100 200)
-- > portraitSlice2 x y = (text' "PAR (AlignXY " ++ show x ++ " " show y ++ ") Slice") ===
-- > (portrait (PAR (AlignXY x y) Slice) 200 100 <> rect 200 100)
-- > meetX = (text' "meet") === (portraitMeet1 0 0 ||| portraitMeet1 0.5 0 ||| portraitMeet1 1 0)
-- > meetY = (text' "meet") === (portraitMeet2 0 0 ||| portraitMeet2 0 0.5 ||| portraitMeet2 0 1)
-- > sliceX = (text' "slice") === (portraitSlice1 0 0 ||| portraitSlice1 0.5 0 ||| portraitSlice1 1 0)
-- > sliceY = (text' "slice") === (portraitSlice2 0 0 ||| portraitSlice2 0 0.5 ||| portraitSlice2 0 1)
-- > im = (text' "Image to fit") === (portrait (PAR (AlignXY 0 0) Meet) 123 456)
-- > viewport1 = (text' "Viewport1") === (rect 200 100)
-- > viewport2 = (text' "Viewport2") === (rect 100 200)
-- > imageAndViewports = im === viewport1 === viewport2
-- >
-- > par = imageAndViewports ||| ( ( meetX ||| meetY) === ( sliceX ||| sliceY) )
--
-- <<diagrams/src_Graphics_SVGFonts_ReadFont_textPic0.svg#diagram=par&width=300>>
-- preserveAspectRatio :: Width -> Height -> Width -> Height -> PreserveAR -> Diagram b -> Diagram b
preserveAspectRatio newWidth newHeight oldWidth oldHeight preserveAR image
| aspectRatio < newAspectRatio = xPlace preserveAR image
| otherwise = yPlace preserveAR image
where aspectRatio = oldWidth / oldHeight
newAspectRatio = newWidth / newHeight
scaX = newHeight / oldHeight
scaY = newWidth / oldWidth
xPlace (PAR (AlignXY x y) Meet) i = i # scale scaX # alignBL # translateX ((newWidth - oldWidth*scaX)*x)
xPlace (PAR (AlignXY x y) Slice) i = i # scale scaY # alignBL # translateX ((newWidth - oldWidth*scaX)*x)
-- # view (p2 (0, 0)) (r2 (newWidth, newHeight))
yPlace (PAR (AlignXY x y) Meet) i = i # scale scaY # alignBL # translateY ((newHeight - oldHeight*scaY)*y)
yPlace (PAR (AlignXY x y) Slice) i = i # scale scaX # alignBL # translateY ((newHeight - oldHeight*scaY)*y)
-- # view (p2 (0, 0)) (r2 (newWidth, newHeight))
-- a combination of linear- and radial-attributes so that referenced gradients can replace Nothing-attributes
data GradientAttributes =
GA { presentationAttributes :: PresentationAttributes
, class_ :: Maybe Text
, style :: Maybe Text
, x1 :: Maybe Text
, y1 :: Maybe Text
, x2 :: Maybe Text
, y2 :: Maybe Text
, cx :: Maybe Text
, cy :: Maybe Text
, r :: Maybe Text
, fx :: Maybe Text
, fy :: Maybe Text
, gradientUnits :: Maybe Text
, gradientTransform :: Maybe Text
, spreadMethod :: Maybe Text
}
-- GA pa class_ style x1 y1 x2 y2 cx cy r fx fy gradientUnits gradientTransform spreadMethod
data PresentationAttributes =
PA { alignmentBaseline :: Maybe Text
, baselineShift :: Maybe Text
, clip :: Maybe Text
, clipPath :: Maybe Text
, clipRule :: Maybe Text
, color :: Maybe Text
, colorInterpolation :: Maybe Text
, colorInterpolationFilters :: Maybe Text
, colorProfile :: Maybe Text
, colorRendering :: Maybe Text
, cursor :: Maybe Text
, direction :: Maybe Text
, display :: Maybe Text
, dominantBaseline :: Maybe Text
, enableBackground :: Maybe Text
, fill :: Maybe Text
, fillOpacity :: Maybe Text
, fillRuleSVG :: Maybe Text
, filter :: Maybe Text
, floodColor :: Maybe Text
, floodOpacity :: Maybe Text
, fontFamily :: Maybe Text
, fntSize :: Maybe Text
, fontSizeAdjust :: Maybe Text
, fontStretch :: Maybe Text
, fontStyle :: Maybe Text
, fontVariant :: Maybe Text
, fontWeight :: Maybe Text
, glyphOrientationHorizontal :: Maybe Text
, glyphOrientationVertical :: Maybe Text
, imageRendering :: Maybe Text
, kerning :: Maybe Text
, letterSpacing :: Maybe Text
, lightingColor :: Maybe Text
, markerEnd :: Maybe Text
, markerMid :: Maybe Text
, markerStart :: Maybe Text
, mask :: Maybe Text
, opacity :: Maybe Text
, overflow :: Maybe Text
, pointerEvents :: Maybe Text
, shapeRendering :: Maybe Text
, stopColor :: Maybe Text
, stopOpacity :: Maybe Text
, strokeSVG :: Maybe Text
, strokeDasharray :: Maybe Text
, strokeDashoffset :: Maybe Text
, strokeLinecap :: Maybe Text
, strokeLinejoin :: Maybe Text
, strokeMiterlimit :: Maybe Text
, strokeOpacity :: Maybe Text
, strokeWidth :: Maybe Text
, textAnchor :: Maybe Text
, textDecoration :: Maybe Text
, textRendering :: Maybe Text
, unicodeBidi :: Maybe Text
, visibility :: Maybe Text
, wordSpacing :: Maybe Text
, writingMode :: Maybe Text
} deriving Show
type SvgGlyphs n = H.HashMap Text (Maybe Text, n, Maybe Text)
-- ^ \[ (unicode, (glyph_name, horiz_advance, ds)) \]
data Kern n = Kern
{ kernDir :: KernDir
, kernU1 :: [Text]
, kernU2 :: [Text]
, kernG1 :: [Text]
, kernG2 :: [Text]
, kernK :: n
}
-- | Data from the subtags
data FontContent b n = FF (FontFace n) | GG (Glyph b n) | KK (Kern n)
-- | All data in the \<font\>-tag
data FontData b n = FontData
{
fontId :: Maybe Text
, fontDataHorizontalOriginX :: Maybe Text
, fontDataHorizontalOriginY :: Maybe Text
, fontDataHorizontalAdvance :: n
, fontDataVerticalOriginX :: Maybe Text
, fontDataVerticalOriginY :: Maybe Text
, fontDataVerticalAdvance :: Maybe Text
-- ^ data gathered from subtags
, fontFace :: FontFace n
, fontMissingGlyph :: Glyph b n
, fontDataGlyphs :: SvgGlyphs n
-- , fontDataRawKernings :: [(Text, [Text], [Text], [Text], [Text])]
, fontDataKerning :: KernMaps n
-- , fontDataFileName :: Text
}
data FontFace n = FontFace
{ fontDataFamily :: Maybe Text
, fontDataStyle :: Maybe Text
, fontDataVariant :: Maybe Text
, fontDataWeight :: Maybe Text
, fontDataStretch :: Maybe Text
, fontDataSize :: Maybe Text
, fontDataUnicodeRange :: Maybe Text
, fontDataUnitsPerEm :: Maybe Text
, fontDataPanose :: Maybe Text
, fontDataVerticalStem :: Maybe Text
, fontDataHorizontalStem :: Maybe Text
, fontDataSlope :: Maybe Text
, fontDataCapHeight :: Maybe Text
, fontDataXHeight :: Maybe Text
, fontDataAccentHeight :: Maybe Text
, fontDataAscent :: Maybe Text
, fontDataDescent :: Maybe Text
, fontDataWidths :: Maybe Text
, fontDataBoundingBox :: [n]
, fontDataIdeographicBaseline :: Maybe Text
, fontDataAlphabeticBaseline :: Maybe Text
, fontDataMathematicalBaseline :: Maybe Text
, fontDataHangingBaseline :: Maybe Text
, fontDataVIdeographicBaseline :: Maybe Text
, fontDataVAlphabeticBaseline :: Maybe Text
, fontDataVMathematicalBaseline :: Maybe Text
, fontDataVHangingBaseline :: Maybe Text
, fontDataUnderlinePos :: Maybe Text
, fontDataUnderlineThickness :: Maybe Text
, fontDataStrikethroughPos :: Maybe Text
, fontDataStrikethroughThickness :: Maybe Text
, fontDataOverlinePos :: Maybe Text
, fontDataOverlineThickness :: Maybe Text
}
data Glyph b n = Glyph
{ glyphId :: Maybe Text
, glyph :: Tag b n
, d :: Maybe Text
, horizAdvX :: n
, vertOriginX :: n
, vertOriginY :: n
, vertAdvY :: n
, unicode :: Maybe Text
, glyphName :: Maybe Text
, orientation :: Maybe Text
, arabicForm :: Maybe Text
, lang :: Maybe Text
}
data KernDir = HKern | VKern
data KernMaps n = KernMaps
{ kernDirs :: [KernDir]
, kernU1S :: H.HashMap Text [Int]
, kernU2S :: H.HashMap Text [Int]
, kernG1S :: H.HashMap Text [Int]
, kernG2S :: H.HashMap Text [Int]
, kernKs :: Vector n
}
| diagrams/diagrams-input | src/Diagrams/SVG/Tree.hs | bsd-3-clause | 24,547 | 0 | 15 | 6,254 | 5,974 | 3,339 | 2,635 | 337 | 6 |
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
data Nil
data Cons x xs
class First list x | list -> x
instance First Nil Nil
instance First (Cons x xs) x
class ListConcat a b c | a b -> c
instance ListConcat Nil x x
instance ListConcat as bs cs => ListConcat (Cons a as) bs (Cons a cs)
class ListConcatAll ls l | ls -> l
instance ListConcatAll Nil Nil
instance (ListConcat chunk acc result, ListConcatAll rest acc) =>
ListConcatAll (Cons chunk rest) result
data False
data True
class AnyTrue list t | list -> t
instance AnyTrue Nil False
instance AnyTrue (Cons True more) True
instance (AnyTrue list t) => AnyTrue (Cons False list) t
class Not b1 b | b1 -> b
instance Not True False
instance Not False True
class Or b1 b2 b | b1 b2 -> b
instance Or True True True
instance Or False True True
instance Or True False True
instance Or False False False
class And b1 b2 b | b1 b2 -> b
instance And True True True
instance And True False False
instance And False True False
instance And False False False
data Z
data S n
type N0 = Z
type N1 = S N0
type N2 = S N1
type N3 = S N2
type N4 = S N3
type N5 = S N4
type N6 = S N5
type N7 = S N6
type N8 = S N7
class PeanoEqual a b t | a b -> t
instance PeanoEqual Z Z True
instance PeanoEqual (S a) Z False
instance PeanoEqual Z (S b) False
instance (PeanoEqual a b t) => PeanoEqual (S a) (S b) t
class PeanoLT a b t | a b -> t
instance PeanoLT Z Z False
instance PeanoLT (S a) Z False
instance PeanoLT Z (S b) True
instance PeanoLT a b t =>
PeanoLT (S a) (S b) t
class PeanoAbsDiff a b c | a b -> c
instance PeanoAbsDiff Z Z Z
instance PeanoAbsDiff (S a) Z (S a)
instance PeanoAbsDiff Z (S b) (S b)
instance PeanoAbsDiff a b c => PeanoAbsDiff (S a) (S b) c
class Range n xs | n -> xs
instance Range Z Nil
instance (Range n xs) => Range (S n) (Cons n xs)
class PeanoAdd x y z | x y -> z
instance PeanoAdd Z y y
instance PeanoAdd x y z => PeanoAdd (S x) y (S z)
class Add2 a b c | a b -> c where
add2 :: a -> b -> c
instance PeanoAdd x y z => Add2 x y z where add2 = undefined
class PeanoSub x y z | x y -> z
instance PeanoSub Z Z Z
instance PeanoSub (S x) Z (S x)
instance ( PeanoLT y x r1,
PeanoEqual y x r2,
Or r1 r2 True,
PeanoAbsDiff x y r4
) => PeanoSub x y r4
class Sub2 x y z | x y -> z where
sub2 :: x -> y -> z
instance (PeanoSub x y z) => Sub2 x y z where sub2 = undefined
class PeanoMul x y z | x y -> z
instance PeanoMul Z b Z
instance PeanoMul a Z Z
instance (PeanoMul a b r1,
PeanoAdd b r1 r
) => PeanoMul (S a) b r
class Mul2 a b c | a b -> c where
mul2 :: a -> b -> c
instance PeanoMul a b c => Mul2 a b c where mul2 = undefined
| wangbj/excises | peano.hs | bsd-3-clause | 2,844 | 0 | 8 | 713 | 1,298 | 658 | 640 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE TypeInType #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Equality
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : Rank2Types
--
----------------------------------------------------------------------------
module Control.Lens.Equality
(
-- * Type Equality
Equality, Equality'
, AnEquality, AnEquality'
, (:~:)(..)
, runEq
, substEq
, mapEq
, fromEq
, simply
-- * The Trivial Equality
, simple
-- * 'Iso'-like functions
, equality
, equality'
, withEquality
, underEquality
, overEquality
, fromLeibniz
, fromLeibniz'
, cloneEquality
-- * Implementation Details
, Identical(..)
) where
import Control.Lens.Type
import Data.Proxy (Proxy)
import Data.Type.Equality ((:~:)(..))
#if __GLASGOW_HASKELL__ >= 800
import GHC.Exts (TYPE)
import Data.Kind (Type)
#endif
#ifdef HLINT
{-# ANN module "HLint: ignore Use id" #-}
{-# ANN module "HLint: ignore Eta reduce" #-}
#endif
-- $setup
-- >>> import Control.Lens
#include "lens-common.h"
-----------------------------------------------------------------------------
-- Equality
-----------------------------------------------------------------------------
-- | Provides witness that @(s ~ a, b ~ t)@ holds.
data Identical a b s t where
Identical :: Identical a b a b
-- | When you see this as an argument to a function, it expects an 'Equality'.
#if __GLASGOW_HASKELL__ >= 706
type AnEquality (s :: k1) (t :: k2) (a :: k1) (b :: k2) = Identical a (Proxy b) a (Proxy b) -> Identical a (Proxy b) s (Proxy t)
#else
type AnEquality s t a b = Identical a (Proxy b) a (Proxy b) -> Identical a (Proxy b) s (Proxy t)
#endif
-- | A 'Simple' 'AnEquality'.
type AnEquality' s a = AnEquality s s a a
-- | Extract a witness of type 'Equality'.
runEq :: AnEquality s t a b -> Identical s t a b
runEq l = case l Identical of Identical -> Identical
{-# INLINE runEq #-}
-- | Substituting types with 'Equality'.
#if __GLASGOW_HASKELL__ >= 800
substEq :: forall s t a b rep (r :: TYPE rep).
AnEquality s t a b -> ((s ~ a, t ~ b) => r) -> r
#else
substEq :: AnEquality s t a b -> ((s ~ a, t ~ b) => r) -> r
#endif
substEq l = case runEq l of
Identical -> \r -> r
{-# INLINE substEq #-}
-- | We can use 'Equality' to do substitution into anything.
#if __GLASGOW_HASKELL__ >= 800
mapEq :: forall k1 k2 (s :: k1) (t :: k2) (a :: k1) (b :: k2) (f :: k1 -> Type) . AnEquality s t a b -> f s -> f a
#elif __GLASGOW_HASKELL__ >= 706
mapEq :: forall (s :: k1) (t :: k2) (a :: k1) (b :: k2) (f :: k1 -> *) . AnEquality s t a b -> f s -> f a
#else
mapEq :: AnEquality s t a b -> f s -> f a
#endif
mapEq l r = substEq l r
{-# INLINE mapEq #-}
-- | 'Equality' is symmetric.
fromEq :: AnEquality s t a b -> Equality b a t s
fromEq l = substEq l id
{-# INLINE fromEq #-}
-- | This is an adverb that can be used to modify many other 'Lens' combinators to make them require
-- simple lenses, simple traversals, simple prisms or simple isos as input.
#if __GLASGOW_HASKELL__ >= 800
simply :: forall p f s a rep (r :: TYPE rep).
(Optic' p f s a -> r) -> Optic' p f s a -> r
#else
simply :: (Optic' p f s a -> r) -> Optic' p f s a -> r
#endif
simply = id
{-# INLINE simply #-}
-- | Composition with this isomorphism is occasionally useful when your 'Lens',
-- 'Control.Lens.Traversal.Traversal' or 'Iso' has a constraint on an unused
-- argument to force that argument to agree with the
-- type of a used argument and avoid @ScopedTypeVariables@ or other ugliness.
simple :: Equality' a a
simple = id
{-# INLINE simple #-}
cloneEquality :: AnEquality s t a b -> Equality s t a b
cloneEquality an = substEq an id
{-# INLINE cloneEquality #-}
-- | Construct an 'Equality' from explicit equality evidence.
equality :: s :~: a -> b :~: t -> Equality s t a b
equality Refl Refl = id
{-# INLINE equality #-}
-- | A 'Simple' version of 'equality'
equality' :: a :~: b -> Equality' a b
equality' Refl = id
{-# INLINE equality' #-}
-- | Recover a "profunctor lens" form of equality. Reverses 'fromLeibniz'.
overEquality :: AnEquality s t a b -> p a b -> p s t
overEquality an = substEq an id
{-# INLINE overEquality #-}
-- | The opposite of working 'overEquality' is working 'underEquality'.
underEquality :: AnEquality s t a b -> p t s -> p b a
underEquality an = substEq an id
{-# INLINE underEquality #-}
-- | Convert a "profunctor lens" form of equality to an equality. Reverses
-- 'overEquality'.
--
-- The type should be understood as
--
-- @fromLeibniz :: (forall p. p a b -> p s t) -> Equality s t a b@
fromLeibniz :: (Identical a b a b -> Identical a b s t) -> Equality s t a b
fromLeibniz f = case f Identical of Identical -> id
{-# INLINE fromLeibniz #-}
-- | Convert Leibniz equality to equality. Reverses 'mapEq' in 'Simple' cases.
--
-- The type should be understood as
--
-- @fromLeibniz' :: (forall f. f s -> f a) -> Equality' s a@
fromLeibniz' :: (s :~: s -> s :~: a) -> Equality' s a
-- Note: even though its type signature mentions (:~:), this function works just
-- fine in base versions before 4.7.0; it just requires a polymorphic argument!
fromLeibniz' f = case f Refl of Refl -> id
{-# INLINE fromLeibniz' #-}
-- | A version of 'substEq' that provides explicit, rather than implicit,
-- equality evidence.
#if __GLASGOW_HASKELL__ >= 800
withEquality :: forall s t a b rep (r :: TYPE rep).
AnEquality s t a b -> (s :~: a -> b :~: t -> r) -> r
#else
withEquality :: forall s t a b r.
AnEquality s t a b -> (s :~: a -> b :~: t -> r) -> r
#endif
withEquality an = substEq an (\f -> f Refl Refl)
{-# INLINE withEquality #-}
| ddssff/lens | src/Control/Lens/Equality.hs | bsd-3-clause | 5,997 | 0 | 11 | 1,212 | 1,087 | 638 | 449 | 76 | 1 |
{-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-name-shadowing #-}
import Prelude hiding (log)
import Control.Concurrent
import Control.Monad (forever, void)
import Criterion.Main
import Network (PortID(..))
import Network.Socket (Family(..), SocketType(..), PortNumber, SockAddr(..),
defaultProtocol, inet_addr)
import System.IO
import Winsock
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Network as N
import qualified Network.Socket as NS
import qualified Network.Socket.ByteString as NSB
portNum :: PortNumber
portNum = 1234
server = do
sock <- N.listenOn $ PortNumber portNum
void $ forkIO $ forever $ do
(h, host, port) <- N.accept sock
forkIO $ do
hSetBuffering h NoBuffering
let log msg = putStrLn $ "server: " ++ host ++ ":" ++ show port ++ ": " ++ msg
log "accepted connection"
let chunk = B.concat $ replicate 16 $ B8.pack ['\0' .. '\255']
forever $ B.hPut h chunk
main = do
mapM_ (`hSetBuffering` LineBuffering) [stdout, stderr]
server
addr <- inet_addr "127.0.0.1"
sock <- socket AF_INET Stream defaultProtocol
connect sock $ SockAddrInet portNum addr
nsbSock <- NS.socket AF_INET Stream defaultProtocol
NS.connect nsbSock $ SockAddrInet portNum addr
threadDelay 1000000
defaultMain
[ bench "Winsock.recv" $
whnfIO $ recv sock 1
, bench "Network.Socket.ByteString.recv" $
whnfIO $ NSB.recv nsbSock 1
]
| joeyadams/haskell-iocp | testing/recv-bench.hs | bsd-3-clause | 1,610 | 0 | 21 | 423 | 457 | 241 | 216 | 41 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module UTxO.Translate (
-- * Monadic context for the translation from the DSL to Cardano
TranslateT(..)
, Translate
, runTranslateT
, runTranslateTNoErrors
, runTranslate
, runTranslateNoErrors
, withConfig
, mapTranslateErrors
, catchTranslateErrors
, catchSomeTranslateErrors
-- * Convenience wrappers
, translateFirstSlot
, translateNextSlot
, translateGenesisHeader
-- * Interface to the verifier
, verify
, verifyBlocksPrefix
-- * Convenience re-exports
, MonadError(..)
, MonadGState(..)
) where
import Control.Exception (throw)
import Control.Monad.Except
import Data.Constraint (Dict (..))
import Data.Validated
import Universum
import Pos.Chain.Block
import qualified Pos.Chain.Block.Slog.LastBlkSlots as LastBlkSlots
import Pos.Chain.Genesis
import Pos.Chain.Txp
import Pos.Chain.Update
import Pos.Core
import Pos.Core.Chrono
import Pos.Core.NetworkMagic (makeNetworkMagic)
import Pos.Core.Slotting (EpochOrSlot)
import Pos.Crypto (ProtocolMagic)
import Pos.DB.Class (MonadGState (..))
import UTxO.Context
import UTxO.Verify (Verify)
import qualified UTxO.Verify as Verify
import Test.Pos.Chain.Genesis.Dummy (dummyBlockVersionData,
dummyEpochSlots)
{-------------------------------------------------------------------------------
Testing infrastructure from cardano-sl-core
The genesis block comes from defaultTestConf, which in turn uses
configuration.yaml. It is specified by a 'GenesisSpec'.
-------------------------------------------------------------------------------}
import Test.Pos.Configuration (withProvidedMagicConfig)
{-------------------------------------------------------------------------------
Translation monad
The translation provides access to the translation context as well as some
dictionaries so that we can lift Cardano operations to the 'Translate' monad.
(Eventually we may wish to do this differently.)
-------------------------------------------------------------------------------}
-- | Translation environment
--
-- NOTE: As we reduce the scope of 'HasConfiguration' and
-- 'HasUpdateConfiguration', those values should be added into the
-- 'CardanoContext' instead.
data TranslateEnv = TranslateEnv {
teContext :: TransCtxt
, teUpdate :: Dict HasUpdateConfiguration
}
newtype TranslateT e m a = TranslateT {
unTranslateT :: ExceptT e (ReaderT TranslateEnv m) a
}
deriving ( Functor
, Applicative
, Monad
, MonadError e
, MonadIO
, MonadFail
)
instance MonadTrans (TranslateT e) where
lift = TranslateT . lift . lift
type Translate e = TranslateT e Identity
instance Monad m => MonadReader TransCtxt (TranslateT e m) where
ask = TranslateT $ asks teContext
local f = TranslateT . local f' . unTranslateT
where
f' env = env { teContext = f (teContext env) }
-- | Right now this always returns the genesis policy
instance Monad m => MonadGState (TranslateT e m) where
gsAdoptedBVData = pure dummyBlockVersionData
-- | Run translation
--
-- NOTE: This uses the default test configuration, and throws any errors as
-- pure exceptions.
runTranslateT :: Monad m => Exception e
=> ProtocolMagic -> TranslateT e m a -> m a
runTranslateT pm (TranslateT ta) =
withProvidedMagicConfig pm $ \genesisConfig _ _ ->
let nm = makeNetworkMagic pm
env :: TranslateEnv
env = TranslateEnv {
teContext = initContext nm (initCardanoContext genesisConfig)
, teUpdate = Dict
}
in do ma <- runReaderT (runExceptT ta) env
case ma of
Left e -> throw e
Right a -> return a
-- | Specialised form of 'runTranslateT' when there can be no errors
runTranslateTNoErrors :: Monad m => ProtocolMagic -> TranslateT Void m a -> m a
runTranslateTNoErrors = runTranslateT
-- | Specialization of 'runTranslateT'
runTranslate :: Exception e => ProtocolMagic -> Translate e a -> a
runTranslate pm = runIdentity . (runTranslateT pm)
-- | Specialised form of 'runTranslate' when there can be no errors
runTranslateNoErrors :: ProtocolMagic -> Translate Void a -> a
runTranslateNoErrors = runTranslate
-- | Lift functions that want the configuration as type class constraints
withConfig :: Monad m
=> (HasUpdateConfiguration => TranslateT e m a)
-> TranslateT e m a
withConfig f = do
Dict <- TranslateT $ asks teUpdate
f
-- | Map errors
mapTranslateErrors :: Functor m
=> (e -> e') -> TranslateT e m a -> TranslateT e' m a
mapTranslateErrors f (TranslateT ma) = TranslateT $ withExceptT f ma
-- | Catch and return errors
catchTranslateErrors :: Functor m
=> TranslateT e m a -> TranslateT e' m (Either e a)
catchTranslateErrors (TranslateT (ExceptT (ReaderT ma))) =
TranslateT $ ExceptT $ ReaderT $ \env -> fmap Right (ma env)
catchSomeTranslateErrors :: Monad m
=> TranslateT (Either e e') m a
-> TranslateT e m (Either e' a)
catchSomeTranslateErrors act = do
ma <- catchTranslateErrors act
case ma of
Left (Left e) -> throwError e
Left (Right e') -> return $ Left e'
Right a -> return $ Right a
{-------------------------------------------------------------------------------
Convenience wrappers
-------------------------------------------------------------------------------}
-- | Slot ID of the first block
translateFirstSlot :: SlotId
translateFirstSlot = SlotId 0 localSlotIndexMinBound
-- | Increment slot ID
--
-- TODO: Surely a function like this must already exist somewhere?
translateNextSlot :: Monad m => SlotId -> TranslateT e m SlotId
translateNextSlot (SlotId epoch lsi) = withConfig $
return $ case addLocalSlotIndex dummyEpochSlots 1 lsi of
Just lsi' -> SlotId epoch lsi'
Nothing -> SlotId (epoch + 1) localSlotIndexMinBound
-- | Genesis block header
translateGenesisHeader :: Monad m => TranslateT e m GenesisBlockHeader
translateGenesisHeader = view gbHeader <$> asks (ccBlock0 . tcCardano)
{-------------------------------------------------------------------------------
Interface to the verifier
-------------------------------------------------------------------------------}
-- | Run the verifier
verify :: Monad m
=> Verify e a
-> TranslateT e' m (Validated e (a, Utxo))
verify ma = withConfig $ do
utxo <- asks (ccUtxo . tcCardano)
return $ validatedFromEither (Verify.verify utxo ma)
-- | Wrapper around 'UTxO.Verify.verifyBlocksPrefix'
--
-- NOTE: This assumes right now that we verify starting from the genesis block.
-- If that assumption is not valid, we need to pass in the slot leaders here.
-- Probably easier is to always start from an epoch boundary block; in such a
-- case in principle we don't need to pass in the set of leaders all, since the
-- the core of the block verification code ('verifyBlocks' from module
-- "Pos.Chain.Block") will then take the set of leaders from the
-- genesis/epoch boundary block itself. In practice, however, the passed in set
-- of leaders is verified 'slogVerifyBlocks', so we'd have to modify the
-- verification code a bit.
-- It is not required that all blocks are from the same epoch. This will
-- split the chain into epochs and validate each epoch individually
verifyBlocksPrefix
:: forall e' m. Monad m
=> ConsensusEra
-> OldestFirst NE Block
-> TxValidationRules
-> TranslateT e' m (Validated VerifyBlocksException (OldestFirst NE Undo, Utxo))
verifyBlocksPrefix era blocks txValRules =
case splitEpochs blocks of
ESREmptyEpoch _ ->
validatedFromExceptT . throwError $ VerifyBlocksError "Whoa! Empty epoch!"
ESRStartsOnBoundary _ ->
validatedFromExceptT . throwError $ VerifyBlocksError "No genesis epoch!"
ESRValid genEpoch (OldestFirst succEpochs) -> case era of
OBFT _ -> validatedFromExceptT . throwError $ VerifyBlocksError "No support for OBFT validation in UTxO package."
Original -> do
CardanoContext{..} <- asks tcCardano
let pm = ccMagic
let leaders = OriginalLeaders ccInitLeaders
verify $ validateGenEpoch pm txValRules ccHash0 leaders genEpoch >>= \genUndos -> do
epochUndos <- sequence $ validateSuccEpoch pm txValRules <$> succEpochs
return $ foldl' (\a b -> a <> b) genUndos epochUndos
where
validateGenEpoch :: ProtocolMagic
-> TxValidationRules
-> HeaderHash
-> ConsensusEraLeaders
-> OldestFirst NE MainBlock
-> Verify VerifyBlocksException (OldestFirst NE Undo)
validateGenEpoch pm txValRules ccHash0 ccInitLeaders geb = do
Verify.verifyBlocksPrefix
pm
txValRules
ccHash0
era
Nothing
ccInitLeaders
(LastBlkSlots.create 0) -- WTF? This is be because copy-paste.
(Right <$> geb :: OldestFirst NE Block)
validateSuccEpoch :: ProtocolMagic
-> TxValidationRules
-> EpochBlocks NE
-> Verify VerifyBlocksException (OldestFirst NE Undo)
validateSuccEpoch pm txValRules (SuccEpochBlocks ebb emb) = do
Verify.verifyBlocksPrefix
pm
txValRules
(ebb ^. headerHashG)
era
Nothing
-- FIXME: Hardcoded `Original`
(OriginalLeaders (ebb ^. gbBody . gbLeaders))
(LastBlkSlots.create 0) -- WTF? This is be because copy-paste.
(Right <$> emb)
-- | Blocks inside an epoch
data EpochBlocks a = SuccEpochBlocks !GenesisBlock !(OldestFirst a MainBlock)
-- | Try to convert the epoch into a non-empty epoch
neEpoch :: EpochBlocks [] -> Maybe (EpochBlocks NE)
neEpoch (SuccEpochBlocks ebb (OldestFirst mbs)) = case nonEmpty mbs of
Nothing -> Nothing
Just mbs' -> Just $ SuccEpochBlocks ebb (OldestFirst mbs')
-- | Epoch splitting result. This validates that the chain follow the pattern
-- `m(m*)(b(m+))*`, where `m` denotes a main block, and `b` a boundary block.
--
-- Either we have a valid splitting of the chain into epochs, or at some point
-- we have an empty epoch, in which case we return the successive boundary
-- blocks, or we have that the chain starts on a boundary block.
--
-- This does not catch the case where blocks are in the wrong epoch, which
-- will be detected by slot leaders being incorrect.
data EpochSplitResult
= ESRValid !(OldestFirst NE MainBlock) !(OldestFirst [] (EpochBlocks NE))
| ESREmptyEpoch !GenesisBlock
| ESRStartsOnBoundary !GenesisBlock
-- | Split a non-empty set of blocks into the genesis epoch (which does not start with
-- an epoch boundary block) and a set of successive epochs, starting with an EBB.
splitEpochs :: OldestFirst NE Block
-> EpochSplitResult
splitEpochs blocks = case spanEpoch blocks of
(Left (SuccEpochBlocks ebb _), _) -> ESRStartsOnBoundary ebb
(Right genEpoch, OldestFirst rem') -> go [] (OldestFirst <$> nonEmpty rem') where
go !acc Nothing = ESRValid genEpoch (OldestFirst $ reverse acc)
go !acc (Just neRem) = case spanEpoch neRem of
(Right _, _) -> error "Impossible!"
(Left ebs@(SuccEpochBlocks ebb _), OldestFirst newRem) -> case neEpoch ebs of
Nothing -> if null newRem
then ESRValid genEpoch (OldestFirst $ reverse acc)
else ESREmptyEpoch ebb
Just ebs' -> go (ebs' : acc) (OldestFirst <$> nonEmpty newRem)
-- | Span the epoch until the next epoch boundary block.
--
-- - If the list of blocks starts with an EBB, this will return 'Left
-- EpochBlocks' containing the EBB and the successive blocks.
-- - If the list of blocks does not start with an EBB, this will return
-- `Right (OldestFirst NE Block)` containg all blocks before the next
-- EBB.
--
-- In either case, it will also return any remainng blocks, which will either be
-- empty or start with an EBB.
spanEpoch :: OldestFirst NE Block
-> (Either (EpochBlocks []) (OldestFirst NE MainBlock), OldestFirst [] Block)
spanEpoch (OldestFirst (x:|xs)) = case x of
Left ebb -> over _1 (Left . SuccEpochBlocks ebb . OldestFirst)
. over _2 OldestFirst
$ spanMaybe rightToMaybe xs
-- Take until we find an EBB
Right mb -> over _1 (Right . OldestFirst . (mb :|))
. over _2 OldestFirst
$ spanMaybe rightToMaybe xs
-- | Returns the maximal prefix of the input list mapped to `Just`, along with
-- the remainder.
spanMaybe :: (a -> Maybe b) -> [a] -> ([b], [a])
spanMaybe = go [] where
go !acc _ [] = (reverse acc, [])
go !acc f (x:xs) = case f x of
Just x' -> go (x':acc) f xs
Nothing -> (reverse acc, x:xs)
| input-output-hk/pos-haskell-prototype | utxo/src/UTxO/Translate.hs | mit | 13,154 | 22 | 23 | 3,210 | 2,590 | 1,358 | 1,232 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.ReplaceRoute
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Replaces an existing route within a route table in a VPC. You must
-- provide only one of the following: Internet gateway or virtual private
-- gateway, NAT instance, VPC peering connection, or network interface.
--
-- For more information about route tables, see
-- <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html Route Tables>
-- in the /Amazon Virtual Private Cloud User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRoute.html AWS API Reference> for ReplaceRoute.
module Network.AWS.EC2.ReplaceRoute
(
-- * Creating a Request
replaceRoute
, ReplaceRoute
-- * Request Lenses
, rrVPCPeeringConnectionId
, rrInstanceId
, rrNetworkInterfaceId
, rrGatewayId
, rrDryRun
, rrRouteTableId
, rrDestinationCIdRBlock
-- * Destructuring the Response
, replaceRouteResponse
, ReplaceRouteResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'replaceRoute' smart constructor.
data ReplaceRoute = ReplaceRoute'
{ _rrVPCPeeringConnectionId :: !(Maybe Text)
, _rrInstanceId :: !(Maybe Text)
, _rrNetworkInterfaceId :: !(Maybe Text)
, _rrGatewayId :: !(Maybe Text)
, _rrDryRun :: !(Maybe Bool)
, _rrRouteTableId :: !Text
, _rrDestinationCIdRBlock :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReplaceRoute' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rrVPCPeeringConnectionId'
--
-- * 'rrInstanceId'
--
-- * 'rrNetworkInterfaceId'
--
-- * 'rrGatewayId'
--
-- * 'rrDryRun'
--
-- * 'rrRouteTableId'
--
-- * 'rrDestinationCIdRBlock'
replaceRoute
:: Text -- ^ 'rrRouteTableId'
-> Text -- ^ 'rrDestinationCIdRBlock'
-> ReplaceRoute
replaceRoute pRouteTableId_ pDestinationCIdRBlock_ =
ReplaceRoute'
{ _rrVPCPeeringConnectionId = Nothing
, _rrInstanceId = Nothing
, _rrNetworkInterfaceId = Nothing
, _rrGatewayId = Nothing
, _rrDryRun = Nothing
, _rrRouteTableId = pRouteTableId_
, _rrDestinationCIdRBlock = pDestinationCIdRBlock_
}
-- | The ID of a VPC peering connection.
rrVPCPeeringConnectionId :: Lens' ReplaceRoute (Maybe Text)
rrVPCPeeringConnectionId = lens _rrVPCPeeringConnectionId (\ s a -> s{_rrVPCPeeringConnectionId = a});
-- | The ID of a NAT instance in your VPC.
rrInstanceId :: Lens' ReplaceRoute (Maybe Text)
rrInstanceId = lens _rrInstanceId (\ s a -> s{_rrInstanceId = a});
-- | The ID of a network interface.
rrNetworkInterfaceId :: Lens' ReplaceRoute (Maybe Text)
rrNetworkInterfaceId = lens _rrNetworkInterfaceId (\ s a -> s{_rrNetworkInterfaceId = a});
-- | The ID of an Internet gateway or virtual private gateway.
rrGatewayId :: Lens' ReplaceRoute (Maybe Text)
rrGatewayId = lens _rrGatewayId (\ s a -> s{_rrGatewayId = a});
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
rrDryRun :: Lens' ReplaceRoute (Maybe Bool)
rrDryRun = lens _rrDryRun (\ s a -> s{_rrDryRun = a});
-- | The ID of the route table.
rrRouteTableId :: Lens' ReplaceRoute Text
rrRouteTableId = lens _rrRouteTableId (\ s a -> s{_rrRouteTableId = a});
-- | The CIDR address block used for the destination match. The value you
-- provide must match the CIDR of an existing route in the table.
rrDestinationCIdRBlock :: Lens' ReplaceRoute Text
rrDestinationCIdRBlock = lens _rrDestinationCIdRBlock (\ s a -> s{_rrDestinationCIdRBlock = a});
instance AWSRequest ReplaceRoute where
type Rs ReplaceRoute = ReplaceRouteResponse
request = postQuery eC2
response = receiveNull ReplaceRouteResponse'
instance ToHeaders ReplaceRoute where
toHeaders = const mempty
instance ToPath ReplaceRoute where
toPath = const "/"
instance ToQuery ReplaceRoute where
toQuery ReplaceRoute'{..}
= mconcat
["Action" =: ("ReplaceRoute" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"VpcPeeringConnectionId" =:
_rrVPCPeeringConnectionId,
"InstanceId" =: _rrInstanceId,
"NetworkInterfaceId" =: _rrNetworkInterfaceId,
"GatewayId" =: _rrGatewayId, "DryRun" =: _rrDryRun,
"RouteTableId" =: _rrRouteTableId,
"DestinationCidrBlock" =: _rrDestinationCIdRBlock]
-- | /See:/ 'replaceRouteResponse' smart constructor.
data ReplaceRouteResponse =
ReplaceRouteResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReplaceRouteResponse' with the minimum fields required to make a request.
--
replaceRouteResponse
:: ReplaceRouteResponse
replaceRouteResponse = ReplaceRouteResponse'
| fmapfmapfmap/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ReplaceRoute.hs | mpl-2.0 | 5,857 | 0 | 11 | 1,197 | 833 | 500 | 333 | 102 | 1 |
{-
- Copyright 2014 - 2015 Per Magnus Therning
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
{-# LANGUAGE FlexibleContexts #-}
module Extract
where
import Util.HackageIndex
import Util.Misc
import Util.Cfg
import Control.Monad.Trans.Except
import Control.Monad.Reader
import qualified Data.ByteString.Lazy as BSL
import Data.Version
import Distribution.Text (display)
import System.FilePath
extract :: Command ()
extract = do
aD <- asks $ appDir . fst
pkgsNVersions <- asks $ cmdExtractPkgs . optsCmd . fst
cfg <- asks snd
--
idx <- liftIO $ readIndexFile aD (getIndexFileName cfg)
_ <- mapM (runExceptT . extractAndSave idx) pkgsNVersions >>= exitOnAnyLefts
return ()
extractAndSave :: MonadIO m => BSL.ByteString -> (String, Version) -> ExceptT String m ()
extractAndSave idx (pkg, ver) = maybe (throwE errorMsg) (liftIO . BSL.writeFile destFn) (extractCabal idx pkg ver)
where
destFn = pkg <.> "cabal"
errorMsg = "Failed to extract Cabal for " ++ pkg ++ " " ++ display ver
| mmhat/cblrepo | src/Extract.hs | apache-2.0 | 1,550 | 0 | 12 | 304 | 298 | 157 | 141 | 23 | 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="ar-SA">
<title>تخصيص تقرير HTML</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>محتوى</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>الفهرس</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>بحث</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>المفضلة</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 986 | 89 | 62 | 158 | 400 | 203 | 197 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP #-}
module GHC.Constants where
import Prelude
#include "../../../include/HaskellConstants.hs"
| joelburget/haste-compiler | libraries/base-ghc-7.8/GHC/Constants.hs | bsd-3-clause | 144 | 0 | 3 | 19 | 12 | 9 | 3 | 4 | 0 |
{-|
Module : Data.STM.Bag.Internal.TListBag
Description : STM-based Concurrent Bag data structure implementation
Copyright : (c) Alex Semin, 2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Implementation of the 'Data.STM.Bag.Class' using fine-grained list.
It is efficient only if there are not many threads.
-}
module Data.STM.Bag.Internal.TListBag(
TListBag
) where
import Control.Concurrent.STM
import Data.STM.Bag.Class
-- | Fine-grained list upon 'Control.Concurrent.STM.TVar's
data TList v = Nil | TNode v (TVar (TList v))
data TListBag v = B
{ _getHead :: TVar (TList v)
, _getTail :: TVar (TVar (TList v))
}
bNew :: STM (TListBag v)
bNew = do
h <- newTVar Nil
t <- newTVar h
return $ B h t
bAdd :: TListBag v -> v -> STM ()
bAdd (B _ t'') v = do
nt' <- newTVar Nil
t' <- readTVar t''
writeTVar t' (TNode v nt')
writeTVar t'' nt'
bTake :: TListBag v -> STM v
bTake (B h' t'') = do
h <- readTVar h'
case h of
Nil -> retry
TNode v i' -> do
i <- readTVar i'
case i of
Nil -> writeTVar h' i >> writeTVar t'' h'
_ -> writeTVar h' i
return v
bIsEmpty :: TListBag v -> STM Bool
bIsEmpty (B h' _) = do
h <- readTVar h'
case h of
Nil -> return True
_ -> return False
instance Bag TListBag where
new = bNew
add = bAdd
take = bTake
isEmpty = bIsEmpty
| Alllex/stm-data-collection | src/Data/STM/Bag/Internal/TListBag.hs | bsd-3-clause | 1,507 | 0 | 16 | 445 | 449 | 220 | 229 | 41 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings #-}
module Tests.Tokenize where
import Control.Applicative
import Data.Char ( isPrint )
import Test.QuickCheck
import Tests.Util
import Text.Trans.Tokenize
import Graphics.Vty.Widgets.Util
import qualified Data.Text as T
lineGen :: Gen [Token ()]
lineGen = listOf1 $ oneof [wsgen, strgen]
where
strgen = do
s <- stringGen
return $ S (T.pack s) ()
wsgen = do
s <- listOf1 $ elements " \t"
return $ WS (T.pack s) ()
stringGen :: Gen String
stringGen = listOf1 charGen
textGen :: Gen T.Text
textGen = T.pack <$> stringGen
charGen :: Gen Char
charGen = oneof [ arbitrary `suchThat` (\c -> isPrint c)
, pure '台'
]
tests :: [Property]
tests = [ label "tokenize and serialize work" $
property $ forAll textGen $
\s -> (serialize $ tokenize s ()) == s
, label "truncateLine leaves short lines unchanged" $
property $ forAll lineGen $
\ts -> ts == truncateLine (lineLength ts) ts
-- Bound the truncation width at twice the size of the input
-- since huge cases are silly.
, label "truncateLine truncates long lines" $
property $ forAll lineGen $
\ts -> forAll (choose (0, 2 * (lineLength ts))) $
\width -> (lineLength $ truncateLine width ts) <= width
, label "wrapStream does the right thing with whitespace" $ property $
and [ wrapStream 5 (TS [T (S "foo" ()), T (WS " " ()), T (S "bar" ())]) ==
(TS [ T (S "foo" ())
, T (WS " " ())
, NL
, T (S "bar" ())
])
, wrapStream 5 (TS [ T (S "foo" ()), T (WS " " ()), T (S "bar" ())
, T (WS " " ()), T (S "baz" ())]) ==
(TS [ T (S "foo" ())
, T (WS " " ())
, NL
, T (S "bar" ())
, T (WS " " ())
, NL
, T (S "baz" ())
])
, wrapStream 3 (TS [ T (S "foo" ()), T (WS " " ()), T (S "bar" ())]) ==
(TS [ T (S "foo" ())
, NL
, T (S "bar" ())
])
, wrapStream 6 (TS [ T (S "foo" ()), T (WS " " ()), T (S "bar" ())]) ==
(TS [ T (S "foo" ())
, T (WS " " ())
, NL
, T (S "bar" ())
])
, wrapStream 7 (TS [ T (S "foo" ()), T (WS " " ()), T (S "bar" ())]) ==
(TS [ T (S "foo" ()), T (WS " " ()), T (S "bar" ())])
, wrapStream 3 (TS [T (WS " " ())]) == TS [T (WS " " ())]
]
, label "wrapStream preserves newlines" $ property $
let ts = TS [T (S "foo" ()), NL, T (S "bar" ())]
in wrapStream 3 ts == ts
, label "wrapStream does the right thing if unable to wrap" $
property $ and [ wrapStream 2 (TS [T (S "FOO" ())]) == TS [T (S "FOO" ())]
, wrapStream 2 (TS [T (S "FOO" ()), (T (S "BAR" ()))]) ==
(TS [T (S "FOO" ()), NL, (T (S "BAR" ()))])
]
-- Each line must be wrapped and be no longer than the
-- wrapping width OR it must be one token in length, assuming
-- that token was longer than the wrapping width and couldn't
-- be broken up.
, label "wrapLine wraps long lines when possible" $
property $ forAll lineGen $
\ts -> forAll (choose ((textWidth $ tokenStr $ ts !! 0), (lineLength ts - Phys 1))) $
\width -> let TS new = wrapStream width $ TS $ T <$> ts
ls = findLines new
check l = (lineLength $ entityToken <$> l) <= width || (length l == 1)
in all check ls
]
| KommuSoft/vty-ui | test/src/Tests/Tokenize.hs | bsd-3-clause | 4,733 | 0 | 18 | 2,402 | 1,554 | 792 | 762 | 77 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -cpp #-}
{-# OPTIONS_NHC98 -cpp #-}
{-# OPTIONS_JHC -fcpp #-}
-- #hide
module Distribution.Compat.Exception (
SomeException,
onException,
catchIO,
handleIO,
catchExit,
throwIOIO
) where
import System.Exit
import qualified Control.Exception as Exception
#if MIN_VERSION_base(4,0,0)
import Control.Exception (SomeException)
#else
import Control.Exception (Exception)
type SomeException = Exception
#endif
onException :: IO a -> IO b -> IO a
#if MIN_VERSION_base(4,0,0)
onException = Exception.onException
#else
onException io what = io `Exception.catch` \e -> do what
Exception.throw e
#endif
throwIOIO :: Exception.IOException -> IO a
#if MIN_VERSION_base(4,0,0)
throwIOIO = Exception.throwIO
#else
throwIOIO = Exception.throwIO . Exception.IOException
#endif
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#if MIN_VERSION_base(4,0,0)
catchIO = Exception.catch
#else
catchIO = Exception.catchJust Exception.ioErrors
#endif
handleIO :: (Exception.IOException -> IO a) -> IO a -> IO a
handleIO = flip catchIO
catchExit :: IO a -> (ExitCode -> IO a) -> IO a
#if MIN_VERSION_base(4,0,0)
catchExit = Exception.catch
#else
catchExit = Exception.catchJust exitExceptions
where exitExceptions (Exception.ExitException ee) = Just ee
exitExceptions _ = Nothing
#endif
| IreneKnapp/Faction | faction/Distribution/Compat/Exception.hs | bsd-3-clause | 1,419 | 0 | 9 | 283 | 233 | 134 | 99 | 28 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.CleanParser where
import Options.Applicative
import Stack.Clean (CleanOpts (..))
import Stack.Prelude
import Stack.Types.PackageName
-- | Command-line parser for the clean command.
cleanOptsParser :: Parser CleanOpts
cleanOptsParser = CleanShallow <$> packages <|> doFullClean
where
packages =
many
(packageNameArgument
(metavar "PACKAGE" <>
help "If none specified, clean all local packages"))
doFullClean =
flag'
CleanFull
(long "full" <>
help "Delete all work directories (.stack-work by default) in the project")
| MichielDerhaeg/stack | src/Stack/Options/CleanParser.hs | bsd-3-clause | 747 | 0 | 12 | 244 | 112 | 62 | 50 | 18 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.AfterDrag
-- Copyright : (c) 2014 Anders Engstrom <[email protected]>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Anders Engstrom <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Perform an action after the current mouse drag is completed.
-----------------------------------------------------------------------------
module XMonad.Actions.AfterDrag (
-- * Usage
-- $usage
afterDrag,
ifClick,
ifClick') where
import XMonad
import System.Time
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.AfterDrag
--
-- Then add appropriate mouse bindings, for example:
--
-- > , ((modm, button3), (\w -> focus w >> mouseResizeWindow w >> ifClick (windows $ W.float w $ W.RationalRect 0 0 1 1)))
--
-- This will allow you to resize windows as usual, but if you instead of
-- draging click the mouse button the window will be automatically resized to
-- fill the whole screen.
--
-- For detailed instructions on editing your mouse bindings, see
-- "XMonad.Doc.Extending#Editing_mouse_bindings".
--
-- More practical examples are available in "XMonad.Actions.FloatSnap".
-- | Schedule a task to take place after the current dragging is completed.
afterDrag
:: X () -- ^ The task to schedule.
-> X ()
afterDrag task = do drag <- gets dragging
case drag of
Nothing -> return () -- Not dragging
Just (motion, cleanup) -> modify $ \s -> s { dragging = Just(motion, cleanup >> task) }
-- | Take an action if the current dragging can be considered a click,
-- supposing the drag just started before this function is called.
-- A drag is considered a click if it is completed within 300 ms.
ifClick
:: X () -- ^ The action to take if the dragging turned out to be a click.
-> X ()
ifClick action = ifClick' 300 action (return ())
-- | Take an action if the current dragging is completed within a certain time (in milliseconds.)
ifClick'
:: Int -- ^ Maximum time of dragging for it to be considered a click (in milliseconds.)
-> X () -- ^ The action to take if the dragging turned out to be a click.
-> X () -- ^ The action to take if the dragging turned out to not be a click.
-> X ()
ifClick' ms click drag = do
start <- io $ getClockTime
afterDrag $ do
stop <- io $ getClockTime
if diffClockTimes stop start <= noTimeDiff { tdPicosec = fromIntegral ms * 10^(9 :: Integer) }
then click
else drag
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Actions/AfterDrag.hs | bsd-2-clause | 2,739 | 0 | 16 | 663 | 328 | 187 | 141 | 29 | 2 |
module GenTerm () where
import Prelude hiding (reverse)
foo :: Int -> Int -> Int
{-@ foo :: n:Nat -> m:Nat -> Nat /[n+m] @-}
foo n m
| cond 1 = 0
| cond 2 && n > 1 = foo (n-1) m
| cond 3 && m > 2 = foo (n+1) (m-2)
{-@ cond :: Int -> Bool @-}
cond :: Int -> Bool
cond _ = undefined
data L a = N | C a (L a)
{-@ data L [llen] @-}
{-@ measure llen :: (L a) -> Int
llen(N) = 0
llen(C x xs) = 1 + (llen xs)
@-}
{-@ invariant {v: L a | (llen v) >= 0} @-}
{-@ reverse :: xs: L a -> ys : L a -> L a / [(llen ys)] @-}
reverse :: L a -> L a -> L a
reverse xs N = xs
reverse xs (C y ys) = reverse (C y xs) ys
merge :: Ord a => L a -> L a -> L a
{-@ merge :: Ord a => xs:L a -> ys:L a -> L a /[(llen xs) + (llen ys)]@-}
merge (C x xs) (C y ys) | x > y = C x $ merge xs (C y ys)
| otherwise = C y $ merge (C x xs) ys
| mightymoose/liquidhaskell | tests/pos/GeneralizedTermination.hs | bsd-3-clause | 868 | 0 | 10 | 288 | 341 | 170 | 171 | 16 | 1 |
-- | Utilities related to Monad and Applicative classes
-- Mostly for backwards compatability.
module MonadUtils
( Applicative(..)
, (<$>)
, MonadFix(..)
, MonadIO(..)
, liftIO1, liftIO2, liftIO3, liftIO4
, zipWith3M
, mapAndUnzipM, mapAndUnzip3M, mapAndUnzip4M
, mapAccumLM
, mapSndM
, concatMapM
, mapMaybeM
, fmapMaybeM, fmapEitherM
, anyM, allM
, foldlM, foldlM_, foldrM
, maybeMapM
) where
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
import Maybes
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
-------------------------------------------------------------------------------
-- Lift combinators
-- These are used throughout the compiler
-------------------------------------------------------------------------------
-- | Lift an 'IO' operation with 1 argument into another monad
liftIO1 :: MonadIO m => (a -> IO b) -> a -> m b
liftIO1 = (.) liftIO
-- | Lift an 'IO' operation with 2 arguments into another monad
liftIO2 :: MonadIO m => (a -> b -> IO c) -> a -> b -> m c
liftIO2 = ((.).(.)) liftIO
-- | Lift an 'IO' operation with 3 arguments into another monad
liftIO3 :: MonadIO m => (a -> b -> c -> IO d) -> a -> b -> c -> m d
liftIO3 = ((.).((.).(.))) liftIO
-- | Lift an 'IO' operation with 4 arguments into another monad
liftIO4 :: MonadIO m => (a -> b -> c -> d -> IO e) -> a -> b -> c -> d -> m e
liftIO4 = (((.).(.)).((.).(.))) liftIO
-------------------------------------------------------------------------------
-- Common functions
-- These are used throughout the compiler
-------------------------------------------------------------------------------
zipWith3M :: Monad m => (a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d]
zipWith3M _ [] _ _ = return []
zipWith3M _ _ [] _ = return []
zipWith3M _ _ _ [] = return []
zipWith3M f (x:xs) (y:ys) (z:zs)
= do { r <- f x y z
; rs <- zipWith3M f xs ys zs
; return $ r:rs
}
-- | mapAndUnzipM for triples
mapAndUnzip3M :: Monad m => (a -> m (b,c,d)) -> [a] -> m ([b],[c],[d])
mapAndUnzip3M _ [] = return ([],[],[])
mapAndUnzip3M f (x:xs) = do
(r1, r2, r3) <- f x
(rs1, rs2, rs3) <- mapAndUnzip3M f xs
return (r1:rs1, r2:rs2, r3:rs3)
mapAndUnzip4M :: Monad m => (a -> m (b,c,d,e)) -> [a] -> m ([b],[c],[d],[e])
mapAndUnzip4M _ [] = return ([],[],[],[])
mapAndUnzip4M f (x:xs) = do
(r1, r2, r3, r4) <- f x
(rs1, rs2, rs3, rs4) <- mapAndUnzip4M f xs
return (r1:rs1, r2:rs2, r3:rs3, r4:rs4)
-- | Monadic version of mapAccumL
mapAccumLM :: Monad m
=> (acc -> x -> m (acc, y)) -- ^ combining funcction
-> acc -- ^ initial state
-> [x] -- ^ inputs
-> m (acc, [y]) -- ^ final state, outputs
mapAccumLM _ s [] = return (s, [])
mapAccumLM f s (x:xs) = do
(s1, x') <- f s x
(s2, xs') <- mapAccumLM f s1 xs
return (s2, x' : xs')
-- | Monadic version of mapSnd
mapSndM :: Monad m => (b -> m c) -> [(a,b)] -> m [(a,c)]
mapSndM _ [] = return []
mapSndM f ((a,b):xs) = do { c <- f b; rs <- mapSndM f xs; return ((a,c):rs) }
-- | Monadic version of concatMap
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f xs = liftM concat (mapM f xs)
-- | Monadic version of mapMaybe
mapMaybeM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f = liftM catMaybes . mapM f
-- | Monadic version of fmap
fmapMaybeM :: (Monad m) => (a -> m b) -> Maybe a -> m (Maybe b)
fmapMaybeM _ Nothing = return Nothing
fmapMaybeM f (Just x) = f x >>= (return . Just)
-- | Monadic version of fmap
fmapEitherM :: Monad m => (a -> m b) -> (c -> m d) -> Either a c -> m (Either b d)
fmapEitherM fl _ (Left a) = fl a >>= (return . Left)
fmapEitherM _ fr (Right b) = fr b >>= (return . Right)
-- | Monadic version of 'any', aborts the computation at the first @True@ value
anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool
anyM _ [] = return False
anyM f (x:xs) = do b <- f x
if b then return True
else anyM f xs
-- | Monad version of 'all', aborts the computation at the first @False@ value
allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
allM _ [] = return True
allM f (b:bs) = (f b) >>= (\bv -> if bv then allM f bs else return False)
-- | Monadic version of foldl
foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM = foldM
-- | Monadic version of foldl that discards its result
foldlM_ :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m ()
foldlM_ = foldM_
-- | Monadic version of foldr
foldrM :: (Monad m) => (b -> a -> m a) -> a -> [b] -> m a
foldrM _ z [] = return z
foldrM k z (x:xs) = do { r <- foldrM k z xs; k x r }
-- | Monadic version of fmap specialised for Maybe
maybeMapM :: Monad m => (a -> m b) -> (Maybe a -> m (Maybe b))
maybeMapM _ Nothing = return Nothing
maybeMapM m (Just x) = liftM Just $ m x
| frantisekfarka/ghc-dsi | compiler/utils/MonadUtils.hs | bsd-3-clause | 5,218 | 6 | 12 | 1,383 | 2,139 | 1,146 | 993 | 90 | 2 |
-- |
--
-- Since 3.0.4
module Network.Wai.Middleware.StreamFile
(streamFile) where
import Network.Wai (responseStream)
import Network.Wai.Internal
import Network.Wai (Middleware, responseToStream)
import qualified Data.ByteString.Char8 as S8
import System.PosixCompat (getFileStatus, fileSize, FileOffset)
import Network.HTTP.Types (hContentLength)
-- |Convert ResponseFile type responses into ResponseStream type
--
-- Checks the response type, and if it's a ResponseFile, converts it
-- into a ResponseStream. Other response types are passed through
-- unchanged.
--
-- Converted responses get a Content-Length header.
--
-- Streaming a file will bypass a sendfile system call, and may be
-- useful to work around systems without working sendfile
-- implementations.
--
-- Since 3.0.4
streamFile :: Middleware
streamFile app env sendResponse = app env $ \res ->
case res of
ResponseFile _ _ fp _ -> withBody sendBody
where
(s, hs, withBody) = responseToStream res
sendBody :: StreamingBody -> IO ResponseReceived
sendBody body = do
len <- getFileSize fp
let hs' = (hContentLength, (S8.pack (show len))) : hs
sendResponse $ responseStream s hs' body
_ -> sendResponse res
getFileSize :: FilePath -> IO FileOffset
getFileSize path = do
stat <- getFileStatus path
return (fileSize stat)
| AndrewRademacher/wai | wai-extra/Network/Wai/Middleware/StreamFile.hs | mit | 1,408 | 0 | 22 | 305 | 293 | 163 | 130 | 23 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module A where
class Matrix a fa | a -> fa where
row :: [a] -> fa
| urbanslug/ghc | testsuite/tests/typecheck/prog001/A.hs | bsd-3-clause | 134 | 0 | 8 | 27 | 34 | 20 | 14 | 4 | 0 |
{-# LANGUAGE ViewPatterns #-}
{-|
Module : Language.C.Preprocessor.Remover.Internal.AddPadding
Description : Padding of the Cpp output
Copyright : (c) Carlo Nucera, 2016
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
After cpp preprocessing, the file is left by the compilation pipeline in the
output format of the @cpp@ program, described in
<https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html this section> of
the C Preprocessor manual.
By default, the @cpp@ program inserts blank lines to preserve line numbering,
but only if the number of blank lines to be created is not too high (<6 or so).
Otherwise a linemarker is created, to reduce the size of the generated file, of
the form:
@
# linenum filename flags
@
As cpp doesn't have an option to output only blank lines and keeping the line
numbering, the following functions parse a file with linemarkers separating it
in `CppOutputComponents` (the source chunks between the linemarkers), and pad
them with the appropriate amount of blank lines.
-}
module Language.C.Preprocessor.Remover.Internal.AddPadding
(
-- * Entry point for padding
addPadding
-- * Data Types
, LineMarker (..)
, isLineMarker
, parseLineMarker
, CppOutputComponent (..)
-- * Stages of padding
, parseCppOutputComponents
, discardUnusefulComponents
, reconstructSource
) where
import Data.Char (isDigit)
import Data.List (isPrefixOf, isSuffixOf)
import Data.List.Extra (repeatedly)
--------------------------------------------------------------------------------
-- Entry point for padding
--------------------------------------------------------------------------------
-- | Substitutes the lineMarker in the content of a file with the appropriate
-- blank line padding.
addPadding :: FilePath -> String -> String
addPadding fp = unlines
. reconstructSource
. discardUnusefulComponents fp
. parseCppOutputComponents
. lines
--------------------------------------------------------------------------------
-- Data Types
--------------------------------------------------------------------------------
-- | A 'LineMarker' follows the structure described
-- <https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html here>. We only
-- retain the linenumber and the file the line is referring to. Note that the
-- filename is surrounded by quotation marks in the cpp output, but not in this
-- representation.
data LineMarker = LineMarker { beginsAtLine :: Int
, filePath :: FilePath
} deriving (Show)
-- |
-- >>> isLineMarker "# 42 \"/path/to/file\""
-- True
isLineMarker :: String -> Bool
isLineMarker (words -> hash:number:fp:_) = hash == "#"
&& all isDigit number
&& isPrefixOf "\"" fp
&& isSuffixOf "\"" fp
isLineMarker _ = False
-- |
-- >>> parseLineMarker "# 42 \"/path/to/file\""
-- LineMarker {beginsAtLine = 42, filePath = "/path/to/file"}
parseLineMarker :: String -> LineMarker
parseLineMarker s = LineMarker (read $ words s !! 1) (unquote $ words s !! 2)
where
unquote = tail . init
-- | A 'CppOutputComponent' is constituted by a 'LineMarker' and the block of
-- code till the next 'LineMarker'.
data CppOutputComponent = CppOutputComponent { lineMarker :: LineMarker
, sourceBlock :: [String]
} deriving (Show)
--------------------------------------------------------------------------------
-- Stages of padding
--------------------------------------------------------------------------------
-- | Given the lines of a file, parses the CppOutputComponents. Note that a file
-- that doesn't need cpp preprocessing doesn't have any 'LineMarker'. In that
-- case a dummy component is created, with an empty path.
parseCppOutputComponents :: [String] -> [CppOutputComponent]
parseCppOutputComponents ss
| any isLineMarker ss =
flip repeatedly ss $
\ls ->
let (content, rest) = span (not . isLineMarker) (tail ls)
cppComponent = CppOutputComponent (parseLineMarker $ head ls) content
in (cppComponent, rest)
| otherwise = [CppOutputComponent (LineMarker 1 "") ss]
-- | Discard the parts of cpp output which correspond to cpp include files. If
-- there's a unique component then we return that one, otherwise we return all
-- the components relative to our file other than the first (which has no real
-- meaning).
discardUnusefulComponents :: FilePath -> [CppOutputComponent] -> [CppOutputComponent]
discardUnusefulComponents _ [] =
error
"The function discardUnusefulComponents expects a non-empty list of components"
discardUnusefulComponents _ [c] = [c]
discardUnusefulComponents fp cs = filter ((== fp) . filePath . lineMarker) cs
-- | Adds padding to the source blocks to mantain the correct line numbers of
-- the source code.
reconstructSource :: [CppOutputComponent] -> [String]
reconstructSource = sourceBlock . foldr1 combine
where
combine (CppOutputComponent lm1 c1) (CppOutputComponent lm2 c2) =
let padding = (beginsAtLine lm2 - beginsAtLine lm1 - length c1)
in CppOutputComponent lm1 (c1 ++ replicate padding "" ++ c2)
| meditans/preprocessor | src/Language/C/Preprocessor/Remover/Internal/AddPadding.hs | mit | 5,418 | 0 | 15 | 1,162 | 673 | 378 | 295 | 55 | 1 |
module ErrorHandling.EitherSpec where
import Prelude hiding (Either(..), map, sequence, traverse)
import Test.Hspec
import ErrorHandling.Either
spec :: Spec
spec = do
describe "map" $ do
context "Left" $ do
it "does nothing" $ do
map (+1) (Left "Foo" :: Either String Int) `shouldBe` Left "Foo"
context "Right" $ do
it "applies a function to the Right value" $ do
map (+1) (Right 1 :: Either String Int) `shouldBe` Right 2
describe "flatMap" $ do
context "Left" $ do
it "does nothing" $ do
map (+1) (Left "Foo" :: Either String Int) `shouldBe` Left "Foo"
context "Right" $ do
it "applies a function that returns an Either value and flattens the result" $ do
let f x = if x == 1 then Right "One" else Left "Error"
flatMap f (Right 1 :: Either String Int) `shouldBe` Right "One"
flatMap f (Left "" :: Either String Int) `shouldBe` Left ""
describe "orElse" $ do
context "Left" $ do
it "returns the second Either" $ do
orElse (Left "" :: Either String Int) (Right 0 :: Either String Int) `shouldBe` Right 0
context "Right" $ do
it "returns the first Either" $ do
orElse (Right 0 :: Either String Int) (Left "" :: Either String Int) `shouldBe` Right 0
describe "map2" $ do
it "lifts a function of two parameters into the Either context" $ do
let e1 = (Right 1 :: Either String Int)
let e2 = (Right 2 :: Either String Int)
map2 (+) e1 e2 `shouldBe` Right 3
map2 (+) (Left "" :: Either String Int) e1 `shouldBe` Left ""
map2 (+) e1 (Left "" :: Either String Int) `shouldBe` Left ""
describe "sequence" $ do
context "list contains one or more Left values" $ do
it "returns the first Left" $ do
let list = [Right 1, Right 2, Left "Foo", Right 3, Left "Bar"] :: [Either String Int]
sequence list `shouldBe` Left "Foo"
context "list contains all Right values" $ do
it "combines a list of Rights into a Right containing a list of all the Right values" $ do
let list = [Right 1, Right 2, Right 3, Right 4, Right 5] :: [Either String Int]
sequence list `shouldBe` Right [1..5]
describe "traverse" $ do
it "maps a (potentially failing) function over a list and sequences the result" $ do
let f = (\x -> if x == 5 then (Left "Foo") else (Right x))
traverse f [1..5] `shouldBe` Left "Foo"
traverse f [1..4] `shouldBe` Right [1..4]
| tomwadeson/fpinhaskell | test/ErrorHandling/EitherSpec.hs | mit | 2,464 | 0 | 20 | 659 | 937 | 452 | 485 | 50 | 3 |
module BattleNet.Plumbing where
import BattleNet.ApiKey
import Control.Applicative
import Control.Monad
import Data.Monoid
import Data.Maybe
import Data.List
import Data.Text hiding (intersperse)
import Data.Aeson
import qualified Data.Aeson as Aeson
import Network.HTTP.Conduit hiding (path, queryString)
apiEndpointUrl' :: Text -> BattleNetConnectionInfo -> [Text] -> [(Text, Text)] -> Text
apiEndpointUrl' baseDomain settings parts queryString = Data.Text.concat $ mconcat
[ ["https://"
, bnetRegion settings
, "."
, baseDomain
, "/"]
, renderedParts parts
, "?" : renderedQueryStringParams queryString
]
where renderedParts = Data.List.intersperse "/"
renderedQueryStringParam (k, v) = [k, "=", v]
renderedQueryStringParams = mconcat . intersperse ["&"] . fmap renderedQueryStringParam
apiEndpointUrl :: [Text] -> [(Text, Text)] -> BattleNetConnectionInfo -> Text
apiEndpointUrl parts queryString settings = apiEndpointUrl' "api.battle.net" settings parts (("apikey", bnetApiKeyText $ bnetApiKey settings) : queryString)
apiEndpoint :: FromJSON a => [Text] -> [(Text, Text)] -> Manager -> BattleNetConnectionInfo -> IO a
apiEndpoint parts queryString manager settings = do
path <- parseUrl $ unpack $ apiEndpointUrl parts queryString settings
response <- responseBody <$> httpLbs path manager
let decoded = Aeson.decode response
return $ fromMaybe (error $ mconcat ["Invalid response from ", show path, ": ", show response]) decoded
| teozkr/hs-battlenet | BattleNet/Plumbing.hs | mit | 1,555 | 0 | 13 | 299 | 446 | 243 | 203 | 31 | 1 |
{-|
Module: Y2015.D13
Description: Advent of Code Day 13 Solutions.
License: MIT
Maintainer: @tylerjl
Solutions to the day 13 set of problems for <adventofcode.com>.
-}
module Y2015.D13 (solveSeating) where
import Data.List (nub, permutations)
import Data.Map (Map, findWithDefault, fromList, keys)
type Guest = String
type Happiness = Int
type Edge = (Guest, Guest)
type Preferences = Map Edge Happiness
-- |Find optimal seating happiness!
solveSeating :: String -- ^ Input of seating happiness stats
-> Int -- ^ Optimal possible happiness
solveSeating i = maximum $ map sum guestMoods
where prefs = toSeating i
guests = nub . uncurry (++) . unzip $ keys prefs
pairs = map (zip <*> tail . cycle) $ permutations guests
arrangements = map rePair pairs
guestMoods = map (map (flip (findWithDefault 0) prefs)) arrangements
rePair :: [(a, a)] -> [(a, a)]
rePair [] = []
rePair ((x,y):xs) = [(x,y),(y,x)] ++ rePair xs
toSeating :: String -> Preferences
toSeating = fromList . map (parseSeating . words . init) . lines
parseSeating :: [String] -> (Edge, Happiness)
parseSeating [a,_,s,h,_,_,_,_,_,_,b] = ((a, b), hap s)
where change = read h
hap "lose" = negate change
hap _ = change
parseSeating _ = (("", ""), 0)
| tylerjl/adventofcode | src/Y2015/D13.hs | mit | 1,381 | 0 | 13 | 369 | 453 | 258 | 195 | 26 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid ((<>))
import Data.Time.Clock (getCurrentTime, utctDay)
import Data.Time.Calendar (addDays)
import Network.HTTP.Client hiding (port)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Types.Status (status200)
import Network.HTTP.Types.Header (hContentType)
import Network.Wai.Handler.Warp (run)
import Network.Wai.Middleware.RequestLogger (logStdout)
import Network.Wai (Application, responseLBS)
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import System.Environment
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as LBS
baseHost :: String
baseHost = "www.campus.rwth-aachen.de"
baseUrl :: String
baseUrl = "https://" <> baseHost <> "/office"
fromUrl :: String -> Request
fromUrl = fromJust . parseUrl
getCalendar :: IO LBS.ByteString
getCalendar = do
user <- BS.pack <$> getEnv "CAMPUS_USER"
password <- BS.pack <$> getEnv "CAMPUS_PASS"
curTime <- getCurrentTime
let startDay = show $ addDays (-60) $ utctDay curTime
endDay = show $ addDays 400 $ utctDay curTime
iCalReq = fromUrl $ baseUrl <> "/views/calendar/iCalExport.asp?startdt=" <> startDay <> "&enddt=" <> endDay <> "%2023:59:59"
authReq = (fromUrl (baseUrl <> "/views/campus/redirect.asp")) {
method = "POST",
queryString = "?u=" <> user <> "&p=" <> password <> "&login=>%20Login"
}
initialReq = fromUrl $ baseUrl <> "/"
mgr <- newManager tlsManagerSettings
initialResp <- httpLbs initialReq mgr
let cookie = responseCookieJar initialResp
_ <- httpLbs (authReq { cookieJar = Just cookie}) mgr
icalResp <- httpLbs (iCalReq { cookieJar = Just cookie}) mgr
return $ responseBody icalResp
serveCal :: Application
serveCal _ resp = do
cal <- getCalendar
resp $ responseLBS status200
[ (hContentType, "text/calendar; charset=utf-8")
, ("Content-Disposition", "attachment; filename=calendar.ics")] cal
app :: Application
app = logStdout serveCal
main :: IO ()
main = do
port <- read <$> getEnv "PORT"
run port app
| jhedev/campus | Main.hs | mit | 2,110 | 0 | 15 | 363 | 606 | 331 | 275 | 52 | 1 |
module GUBS.Term (
Term (..)
, fun
, variable
, constant
, funs
, funsDL
, vars
, varsDL
, args
, argsDL
, definedSymbol
, substitute
, interpret
, interpretM
) where
import Data.List (nub)
import Data.String (IsString (..))
import Data.Functor.Identity (runIdentity)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import GUBS.Algebra
import GUBS.Utils
data Term f v = Var v
| Const Integer
| Fun f [Term f v]
| Mult (Term f v) (Term f v)
| Plus (Term f v) (Term f v)
| Max (Term f v) (Term f v)
deriving (Eq, Ord, Show)
pattern ZERO = Const 0
pattern ONE = Const 1
fun :: f -> [Term f v] -> Term f v
fun = Fun
variable :: v -> Term f v
variable = Var
constant :: (IsNat n, Integral n) => n -> Term f v
constant = Const . fromNatural
instance IsString (Term f String) where
fromString = Var
instance IsNat (Term f v) where
fromNatural_ = Const
instance Additive (Term f v) where
zero = ZERO
ZERO .+ t2 = t2
t1 .+ ZERO = t1
Const i .+ Const j = Const (i + j)
t1 .+ t2 = Plus t1 t2
instance Max (Term f v) where
maxA ZERO t2 = t2
maxA t1 ZERO = t1
maxA (Const i) (Const j) = Const (max i j)
maxA t1 t2 = Max t1 t2
instance Multiplicative (Term f v) where
one = ONE
ZERO .* _ = ZERO
_ .* ZERO = ZERO
ONE .* t2 = t2
t1 .* ONE = t1
Const i .* Const j = Const (i * j)
t1 .* t2 = Mult t1 t2
instance Num (Term f v) where
(+) = (.+)
(*) = (.*)
fromInteger = fromNatural
signum _ = error "signums not defined on terms"
abs _ = error "abs not defined on terms"
negate _ = error "negate not defined on terms"
-- ops
argsDL :: Term f v -> [Term f v] -> [Term f v]
argsDL Var{} = id
argsDL Const{} = id
argsDL (Fun f ts) = (++) ts . foldr ((.) . argsDL) id ts
argsDL (Mult t1 t2) = (++) [t1,t2] . argsDL t1 . argsDL t2
argsDL (Plus t1 t2) = (++) [t1,t2] . argsDL t1 . argsDL t2
argsDL (Max t1 t2) = (++) [t1,t2] . argsDL t1 . argsDL t2
args :: Term f v -> [Term f v]
args = flip argsDL []
varsDL :: Term f v -> [v] -> [v]
varsDL (Var v) = (v:)
varsDL Const {} = id
varsDL (Fun f ts) = foldr ((.) . varsDL) id ts
varsDL (Mult t1 t2) = varsDL t1 . varsDL t2
varsDL (Plus t1 t2) = varsDL t1 . varsDL t2
varsDL (Max t1 t2) = varsDL t1 . varsDL t2
vars :: Term f v -> [v]
vars = flip varsDL []
funsDL :: Term f v -> [(f,Int)] -> [(f,Int)]
funsDL Var {} = id
funsDL Const {} = id
funsDL (Fun f ts) = ((f,length ts):) . foldr ((.) . funsDL) id ts
funsDL (Mult t1 t2) = funsDL t1 . funsDL t2
funsDL (Plus t1 t2) = funsDL t1 . funsDL t2
funsDL (Max t1 t2) = funsDL t1 . funsDL t2
funs :: Eq f => Term f v -> [(f,Int)]
funs = nub . flip funsDL []
definedSymbol :: Term f v -> Maybe f
definedSymbol (Fun f _) = Just f
definedSymbol _ = Nothing
-- pretty printing
instance (PP.Pretty f, PP.Pretty v) => PP.Pretty (Term f v) where
pretty = pp id where
pp _ (Var v) = PP.pretty v
pp _ (Const i) = PP.integer i
pp _ (Fun f ts) = PP.pretty f PP.<> PP.tupled [PP.pretty ti | ti <- ts]
pp par (Mult t1 t2) = ppBin par "*" (pp PP.parens t1) (pp PP.parens t2)
pp par (Plus t1 t2) = ppBin par "+" (pp PP.parens t1) (pp PP.parens t2)
pp _ (Max t1 t2) = PP.text "max" PP.<> PP.tupled [PP.pretty t1, PP.pretty t2]
instance (PP.Pretty f, PP.Pretty v) => PrettySexp (Term f v) where
prettySexp (Var v) = ppCall "var" [PP.pretty v]
prettySexp (Const i) = PP.integer i
prettySexp (Fun f ts) = ppSexp (PP.pretty f : [prettySexp ti | ti <- ts])
prettySexp (Mult t1 t2) = ppCall "*" [prettySexp t1, prettySexp t2]
prettySexp (Plus t1 t2) = ppCall "+" [prettySexp t1, prettySexp t2]
prettySexp (Max t1 t2) = ppCall "max" [prettySexp t1, prettySexp t2]
interpretM :: (Max a, SemiRing a, IsNat a, Monad m) => (v -> m a) -> (f -> [a] -> m a) -> Term f v -> m a
interpretM s _ (Var v) = s v
interpretM _ _ (Const c) = pure (fromNatural c)
interpretM s i (Fun f ts) = i f =<< interpretM s i `mapM` ts
interpretM s i (Plus t1 t2) = (.+) <$> interpretM s i t1 <*> interpretM s i t2
interpretM s i (Max t1 t2) = maxA <$> interpretM s i t1 <*> interpretM s i t2
interpretM s i (Mult t1 t2) = (.*) <$> interpretM s i t1 <*> interpretM s i t2
interpret :: (Max a, SemiRing a, IsNat a) => (v -> a) -> (f -> [a] -> a) -> Term f v -> a
interpret s i = runIdentity . interpretM (pure . s) (\ f as -> pure (i f as))
substitute :: (v -> Term f v') -> Term f v -> Term f v'
substitute s = interpret s Fun
| mzini/gubs | src/GUBS/Term.hs | mit | 4,782 | 0 | 12 | 1,462 | 2,416 | 1,229 | 1,187 | 122 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Network.Wai.Test
( -- * Session
Session
, runSession
-- * Client Cookies
, ClientCookies
, getClientCookies
, modifyClientCookies
, setClientCookie
, deleteClientCookie
-- * Requests
, request
, srequest
, SRequest (..)
, SResponse (..)
, defaultRequest
, setPath
, setRawPathInfo
-- * Assertions
, assertStatus
, assertContentType
, assertBody
, assertBodyContains
, assertHeader
, assertNoHeader
, assertClientCookieExists
, assertNoClientCookieExists
, assertClientCookieValue
, WaiTestFailure (..)
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
import Data.Monoid (mempty, mappend)
#endif
import Network.Wai
import Network.Wai.Internal (ResponseReceived (ResponseReceived))
import Network.Wai.Test.Internal
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.State as ST
import Control.Monad.Trans.Reader (runReaderT, ask)
import Control.Monad (unless)
import Control.DeepSeq (deepseq)
import Control.Exception (throwIO, Exception)
import Data.Typeable (Typeable)
import qualified Data.Map as Map
import qualified Web.Cookie as Cookie
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.ByteString.Builder (toLazyByteString)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Network.HTTP.Types as H
import Data.CaseInsensitive (CI)
import qualified Data.ByteString as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.IORef
import Data.Time.Clock (getCurrentTime)
-- |
--
-- Since 3.0.6
getClientCookies :: Session ClientCookies
getClientCookies = clientCookies <$> lift ST.get
-- |
--
-- Since 3.0.6
modifyClientCookies :: (ClientCookies -> ClientCookies) -> Session ()
modifyClientCookies f =
lift (ST.modify (\cs -> cs { clientCookies = f $ clientCookies cs }))
-- |
--
-- Since 3.0.6
setClientCookie :: Cookie.SetCookie -> Session ()
setClientCookie c =
modifyClientCookies
(Map.insert (Cookie.setCookieName c) c)
-- |
--
-- Since 3.0.6
deleteClientCookie :: ByteString -> Session ()
deleteClientCookie cookieName =
modifyClientCookies
(Map.delete cookieName)
-- | See also: 'runSessionWith'.
runSession :: Session a -> Application -> IO a
runSession session app = ST.evalStateT (runReaderT session app) initState
data SRequest = SRequest
{ simpleRequest :: Request
, simpleRequestBody :: L.ByteString
}
data SResponse = SResponse
{ simpleStatus :: H.Status
, simpleHeaders :: H.ResponseHeaders
, simpleBody :: L.ByteString
}
deriving (Show, Eq)
request :: Request -> Session SResponse
request = srequest . flip SRequest L.empty
-- | Set whole path (request path + query string).
setPath :: Request -> S8.ByteString -> Request
setPath req path = req {
pathInfo = segments
, rawPathInfo = (L8.toStrict . toLazyByteString) (H.encodePathSegments segments)
, queryString = query
, rawQueryString = (H.renderQuery True query)
}
where
(segments, query) = H.decodePath path
setRawPathInfo :: Request -> S8.ByteString -> Request
setRawPathInfo r rawPinfo =
let pInfo = dropFrontSlash $ T.split (== '/') $ TE.decodeUtf8 rawPinfo
in r { rawPathInfo = rawPinfo, pathInfo = pInfo }
where
dropFrontSlash ("":"":[]) = [] -- homepage, a single slash
dropFrontSlash ("":path) = path
dropFrontSlash path = path
addCookiesToRequest :: Request -> Session Request
addCookiesToRequest req = do
oldClientCookies <- getClientCookies
let requestPath = "/" `T.append` T.intercalate "/" (pathInfo req)
currentUTCTime <- liftIO getCurrentTime
let cookiesForRequest =
Map.filter
(\c -> checkCookieTime currentUTCTime c
&& checkCookiePath requestPath c)
oldClientCookies
let cookiePairs = [ (Cookie.setCookieName c, Cookie.setCookieValue c)
| c <- map snd $ Map.toList cookiesForRequest
]
let cookieValue = L8.toStrict . toLazyByteString $ Cookie.renderCookies cookiePairs
addCookieHeader rest
| null cookiePairs = rest
| otherwise = ("Cookie", cookieValue) : rest
return $ req { requestHeaders = addCookieHeader $ requestHeaders req }
where checkCookieTime t c =
case Cookie.setCookieExpires c of
Nothing -> True
Just t' -> t < t'
checkCookiePath p c =
case Cookie.setCookiePath c of
Nothing -> True
Just p' -> p' `S8.isPrefixOf` TE.encodeUtf8 p
extractSetCookieFromSResponse :: SResponse -> Session SResponse
extractSetCookieFromSResponse response = do
let setCookieHeaders =
filter (("Set-Cookie"==) . fst) $ simpleHeaders response
let newClientCookies = map (Cookie.parseSetCookie . snd) setCookieHeaders
modifyClientCookies
(Map.union
(Map.fromList [(Cookie.setCookieName c, c) | c <- newClientCookies ]))
return response
srequest :: SRequest -> Session SResponse
srequest (SRequest req bod) = do
app <- ask
refChunks <- liftIO $ newIORef $ L.toChunks bod
let req' = req
{ requestBody = atomicModifyIORef refChunks $ \bss ->
case bss of
[] -> ([], S.empty)
x:y -> (y, x)
}
req'' <- addCookiesToRequest req'
response <- liftIO $ do
ref <- newIORef $ error "runResponse gave no result"
ResponseReceived <- app req'' (runResponse ref)
readIORef ref
extractSetCookieFromSResponse response
runResponse :: IORef SResponse -> Response -> IO ResponseReceived
runResponse ref res = do
refBuilder <- newIORef mempty
let add y = atomicModifyIORef refBuilder $ \x -> (x `mappend` y, ())
withBody $ \body -> body add (return ())
builder <- readIORef refBuilder
let lbs = toLazyByteString builder
len = L.length lbs
-- Force evaluation of the body to have exceptions thrown at the right
-- time.
seq len $ writeIORef ref $ SResponse s h $ toLazyByteString builder
return ResponseReceived
where
(s, h, withBody) = responseToStream res
assertBool :: String -> Bool -> Session ()
assertBool s b = unless b $ assertFailure s
assertString :: String -> Session ()
assertString s = unless (null s) $ assertFailure s
assertFailure :: String -> Session ()
assertFailure msg = msg `deepseq` liftIO (throwIO (WaiTestFailure msg))
data WaiTestFailure = WaiTestFailure String
deriving (Show, Eq, Typeable)
instance Exception WaiTestFailure
assertContentType :: ByteString -> SResponse -> Session ()
assertContentType ct SResponse{simpleHeaders = h} =
case lookup "content-type" h of
Nothing -> assertString $ concat
[ "Expected content type "
, show ct
, ", but no content type provided"
]
Just ct' -> assertBool (concat
[ "Expected content type "
, show ct
, ", but received "
, show ct'
]) (go ct == go ct')
where
go = S8.takeWhile (/= ';')
assertStatus :: Int -> SResponse -> Session ()
assertStatus i SResponse{simpleStatus = s} = assertBool (concat
[ "Expected status code "
, show i
, ", but received "
, show sc
]) $ i == sc
where
sc = H.statusCode s
assertBody :: L.ByteString -> SResponse -> Session ()
assertBody lbs SResponse{simpleBody = lbs'} = assertBool (concat
[ "Expected response body "
, show $ L8.unpack lbs
, ", but received "
, show $ L8.unpack lbs'
]) $ lbs == lbs'
assertBodyContains :: L.ByteString -> SResponse -> Session ()
assertBodyContains lbs SResponse{simpleBody = lbs'} = assertBool (concat
[ "Expected response body to contain "
, show $ L8.unpack lbs
, ", but received "
, show $ L8.unpack lbs'
]) $ strict lbs `S.isInfixOf` strict lbs'
where
strict = S.concat . L.toChunks
assertHeader :: CI ByteString -> ByteString -> SResponse -> Session ()
assertHeader header value SResponse{simpleHeaders = h} =
case lookup header h of
Nothing -> assertString $ concat
[ "Expected header "
, show header
, " to be "
, show value
, ", but it was not present"
]
Just value' -> assertBool (concat
[ "Expected header "
, show header
, " to be "
, show value
, ", but received "
, show value'
]) (value == value')
assertNoHeader :: CI ByteString -> SResponse -> Session ()
assertNoHeader header SResponse{simpleHeaders = h} =
case lookup header h of
Nothing -> return ()
Just s -> assertString $ concat
[ "Unexpected header "
, show header
, " containing "
, show s
]
-- |
--
-- Since 3.0.6
assertClientCookieExists :: String -> ByteString -> Session ()
assertClientCookieExists s cookieName = do
cookies <- getClientCookies
assertBool s $ Map.member cookieName cookies
-- |
--
-- Since 3.0.6
assertNoClientCookieExists :: String -> ByteString -> Session ()
assertNoClientCookieExists s cookieName = do
cookies <- getClientCookies
assertBool s $ not $ Map.member cookieName cookies
-- |
--
-- Since 3.0.6
assertClientCookieValue :: String -> ByteString -> ByteString -> Session ()
assertClientCookieValue s cookieName cookieValue = do
cookies <- getClientCookies
case Map.lookup cookieName cookies of
Nothing ->
assertFailure (s ++ " (cookie does not exist)")
Just c ->
assertBool
(concat
[ s
, " (actual value "
, show $ Cookie.setCookieValue c
, " expected value "
, show cookieValue
, ")"
]
)
(Cookie.setCookieValue c == cookieValue)
| creichert/wai | wai-extra/Network/Wai/Test.hs | mit | 10,090 | 0 | 18 | 2,545 | 2,787 | 1,471 | 1,316 | 251 | 3 |
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
module Main where
import qualified Data.Text as T
import Data.Monoid
import Data.CSS.Syntax.Tokens
import Test.Hspec
import Test.Hspec.QuickCheck
import Prelude
import Test.QuickCheck
import Data.Scientific
testTokenize :: HasCallStack => T.Text -> [Token] -> Expectation
testTokenize s t = do
tokenize s `shouldBe` t
tokenize (serialize (tokenize s)) `shouldBe` t
testSerialize :: HasCallStack => [Token] -> T.Text -> Expectation
testSerialize t s = do
serialize t `shouldBe` s
serialize (tokenize (serialize t)) `shouldBe` s
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "Data.CSS.Syntax.Tokens" $ do
it "Single Character" $ do
testTokenize "(" [LeftParen]
testTokenize ")" [RightParen]
testTokenize "[" [LeftSquareBracket]
testTokenize "]" [RightSquareBracket]
testTokenize ",," [Comma, Comma]
it "Multiple Character" $ do
testTokenize "~=" [IncludeMatch]
testTokenize "||" [Column]
testTokenize "|||" [Column, Delim '|']
testTokenize "<!--" [CDO]
testTokenize "<!---" [CDO, Delim '-']
testTokenize "<!---->" [CDO, CDC]
testTokenize "<!-- -->" [CDO, Whitespace, CDC]
it "Delimiter" $ do
testTokenize "^" [Delim '^']
testTokenize "|" [Delim '|']
testTokenize "\x7f" [Delim '\x7f']
testTokenize "\1" [Delim '\x1']
testTokenize "~-" [Delim '~', Delim '-']
testTokenize "*^" [Delim '*', Delim '^']
it "Whitespace" $ do
testTokenize " " [Whitespace]
testTokenize "\n\rS" [Whitespace, Ident "S"]
testTokenize " *" [Whitespace, Delim '*']
testTokenize "\n\r\f2" [Whitespace, Number "2" (NVInteger 2)]
it "Escapes" $ do
testTokenize "hel\\6Co" [Ident "hello"]
testTokenize "\\26 B" [Ident "&B"]
testTokenize "'hel\\6c o'" [String "hello"]
testTokenize "'spac\\65\r\ns'" [String "spaces"]
testTokenize "spac\\65\r\ns" [Ident "spaces"]
testTokenize "spac\\65\n\rs" [Ident "space", Whitespace, Ident "s"]
testTokenize "sp\\61\tc\\65\fs" [Ident "spaces"]
testTokenize "hel\\6c o" [Ident "hell", Whitespace, Ident "o"]
testTokenize "test\\\n" [Ident "test", Delim '\\', Whitespace]
testTokenize "test\\D799" [Ident "test\xD799"]
testTokenize "\\E000" [Ident "\xe000"]
testTokenize "te\\s\\t" [Ident "test"]
testTokenize "spaces\\ in\\\tident" [Ident "spaces in\tident"]
testTokenize "\\.\\,\\:\\!" [Ident ".,:!"]
testTokenize "\\\r" [Delim '\\', Whitespace]
testTokenize "\\\f" [Delim '\\', Whitespace]
testTokenize "\\\r\n" [Delim '\\', Whitespace]
-- let replacement = "\xFFFD"
testTokenize "null\\\0" [Ident "null\xfffd"]
testTokenize "null\\\0\0" [Ident $ "null" <> "\xfffd" <> "\xfffd"]
testTokenize "null\\0" [Ident $ "null" <> "\xfffd"]
testTokenize "null\\0000" [Ident $ "null" <> "\xfffd"]
testTokenize "large\\110000" [Ident $ "large" <> "\xfffd"]
testTokenize "large\\23456a" [Ident $ "large" <> "\xfffd"]
testTokenize "surrogate\\D800" [Ident $ "surrogate" <> "\xfffd"]
testTokenize "surrogate\\0DABC" [Ident $ "surrogate" <> "\xfffd"]
testTokenize "\\00DFFFsurrogate" [Ident $ "\xfffd" <> "surrogate"]
testTokenize "\\10fFfF" [Ident "\x10ffff"]
testTokenize "\\10fFfF0" [Ident $ "\x10ffff" <> "0"]
testTokenize "\\10000000" [Ident $ "\x100000" <> "00"]
testTokenize "eof\\" [Ident "eof", Delim '\\']
it "Ident" $ do
testTokenize "simple-ident" [Ident "simple-ident"]
testTokenize "testing123" [Ident "testing123"]
testTokenize "hello!" [Ident "hello", Delim '!']
testTokenize "world\5" [Ident "world", Delim '\5']
testTokenize "_under score" [Ident "_under", Whitespace, Ident "score"]
testTokenize "-_underscore" [Ident "-_underscore"]
testTokenize "-text" [Ident "-text"]
testTokenize "-\\6d" [Ident "-m"]
testTokenize "--abc" [Ident "--abc"]
testTokenize "--" [Ident "--"]
testTokenize "--11" [Ident "--11"]
testTokenize "---" [Ident "---"]
testTokenize "\x2003" [Ident "\x2003"] -- em-space
testTokenize "\xA0" [Ident "\xA0"] -- non-breaking space
testTokenize "\x1234" [Ident "\x1234"]
testTokenize "\x12345" [Ident "\x12345"]
testTokenize "\0" [Ident "\xfffd"]
testTokenize "ab\0c" [Ident $ "ab\xfffd" <> "c"]
it "Function" $ do
testTokenize "scale(2)" [Function "scale", Number "2" (NVInteger 2), RightParen]
testTokenize "foo-bar\\ baz(" [Function "foo-bar baz"]
testTokenize "fun\\(ction(" [Function "fun(ction"]
testTokenize "-foo(" [Function "-foo"]
testTokenize "url(\"foo.gif\"" [Function "url", String "foo.gif"]
testTokenize "foo( \'bar.gif\'" [Function "foo", Whitespace, String "bar.gif"]
-- // To simplify implementation we drop the whitespace in function(url),whitespace,string()
testTokenize "url( \'bar.gif\'" [Function "url", String "bar.gif"]
it "AtKeyword" $ do
testTokenize "@at-keyword" [AtKeyword "at-keyword"]
testTokenize "@hello!" [AtKeyword "hello", Delim '!']
testTokenize "@-text" [AtKeyword "-text"]
testTokenize "@--abc" [AtKeyword "--abc"]
testTokenize "@--" [AtKeyword "--"]
testTokenize "@--11" [AtKeyword "--11"]
testTokenize "@---" [AtKeyword "---"]
testTokenize "@\\ " [AtKeyword " "]
testTokenize "@-\\ " [AtKeyword "- "]
testTokenize "@@" [Delim '@', Delim '@']
testTokenize "@2" [Delim '@', Number "2" (NVInteger 2)]
testTokenize "@-1" [Delim '@', Number "-1" (NVInteger (-1))]
it "Url" $ do
testTokenize "url(foo.gif)" [Url "foo.gif"]
testTokenize "urL(https://example.com/cats.png)" [Url "https://example.com/cats.png"]
testTokenize "uRl(what-a.crazy^URL~this\\ is!)" [Url "what-a.crazy^URL~this is!"]
testTokenize "uRL(123#test)" [Url "123#test"]
testTokenize "Url(escapes\\ \\\"\\'\\)\\()" [Url "escapes \"')("]
testTokenize "UrL( whitespace )" [Url "whitespace"]
testTokenize "URl( whitespace-eof " [Url "whitespace-eof"]
testTokenize "URL(eof" [Url "eof"]
testTokenize "url(not/*a*/comment)" [Url "not/*a*/comment"]
testTokenize "urL()" [Url ""]
testTokenize "uRl(white space)," [BadUrl, Comma]
testTokenize "Url(b(ad)," [BadUrl, Comma]
testTokenize "uRl(ba'd):" [BadUrl, Colon]
testTokenize "urL(b\"ad):" [BadUrl, Colon]
testTokenize "uRl(b\"ad):" [BadUrl, Colon]
testTokenize "Url(b\\\rad):" [BadUrl, Colon]
testTokenize "url(b\\\nad):" [BadUrl, Colon]
testTokenize "url(/*'bad')*/" [BadUrl, Delim '*', Delim '/']
testTokenize "url(ba'd\\\\))" [BadUrl, RightParen]
it "String" $ do
testTokenize "'text'" [String "text"]
testTokenize "\"text\"" [String "text"]
testTokenize "'testing, 123!'" [String "testing, 123!"]
testTokenize "'es\\'ca\\\"pe'" [String "es'ca\"pe"]
testTokenize "'\"quotes\"'" [String "\"quotes\""]
testTokenize "\"'quotes'\"" [String "'quotes'"]
testTokenize "\"mismatch'" [String "mismatch'"]
testTokenize "'text\5\t\xb'" [String "text\5\t\xb"]
testTokenize "\"end on eof" [String "end on eof"]
testTokenize "'esca\\\nped'" [String "escaped"]
testTokenize "\"esc\\\faped\"" [String "escaped"]
testTokenize "'new\\\rline'" [String "newline"]
testTokenize "\"new\\\r\nline\"" [String "newline"]
testTokenize "'bad\nstring" [BadString, Whitespace, Ident "string"]
testTokenize "'bad\rstring" [BadString, Whitespace, Ident "string"]
testTokenize "'bad\r\nstring" [BadString, Whitespace, Ident "string"]
testTokenize "'bad\fstring" [BadString, Whitespace, Ident "string"]
testTokenize "'\0'" [String "\xFFFD"]
testTokenize "'hel\0lo'" [String "hel\xfffdlo"]
testTokenize "'h\\65l\0lo'" [String "hel\xfffdlo"]
testTokenize "'ignore backslash at eof\\" [String "ignore backslash at eof"]
it "Hash" $ do
testTokenize "#id-selector" [Hash HId "id-selector"]
testTokenize "#FF7700" [Hash HId "FF7700"]
testTokenize "#3377FF" [Hash HUnrestricted "3377FF"]
testTokenize "#\\ " [Hash HId " "]
testTokenize "# " [Delim '#', Whitespace]
testTokenize "#\\\n" [Delim '#', Delim '\\', Whitespace]
testTokenize "#\\\r\n" [Delim '#', Delim '\\', Whitespace]
testTokenize "#!" [Delim '#', Delim '!']
it "Number" $ do
testTokenize "10" [Number "10" (NVInteger 10)]
testTokenize "12.0" [Number "12.0" (NVNumber 12)]
testTokenize "+45.6" [Number "+45.6" (NVNumber 45.6)]
testTokenize "-7" [Number "-7" (NVInteger (-7))]
testTokenize "010" [Number "010" (NVInteger 10)]
testTokenize "10e0" [Number "10e0" (NVNumber 10)]
testTokenize "12e3" [Number "12e3" (NVNumber 12000)]
testTokenize "3e+1" [Number "3e+1" (NVNumber 30)]
testTokenize "12E-1" [Number "12E-1" (NVNumber 1.2)]
testTokenize ".7" [Number ".7" (NVNumber 0.7)]
testTokenize "-.3" [Number "-.3" (NVNumber (-0.3))]
testTokenize "+637.54e-2" [Number "+637.54e-2" (NVNumber 6.3754)]
testTokenize "-12.34E+2" [Number "-12.34E+2" (NVNumber (-1234))]
testTokenize "+ 5" [Delim '+', Whitespace, Number "5" (NVInteger 5)]
testTokenize "-+12" [Delim '-', Number "+12" (NVInteger 12)]
testTokenize "+-21" [Delim '+', Number "-21" (NVInteger (-21))]
testTokenize "++22" [Delim '+', Number "+22" (NVInteger 22)]
testTokenize "13." [Number "13" (NVInteger 13), Delim ('.')]
testTokenize "1.e2" [Number "1" (NVInteger 1), Delim '.', Ident "e2"]
testTokenize "2e3.5" [Number "2e3" (NVNumber 2e3), Number ".5" (NVNumber 0.5)]
testTokenize "2e3." [Number "2e3" (NVNumber 2e3), Delim '.']
testTokenize "1000000000000000000000000" [Number "1000000000000000000000000" (NVInteger 1000000000000000000000000)]
testTokenize "123456789223456789323456789423456789523456789623456789723456789823456789923456789" [Number "123456789223456789323456789423456789523456789623456789723456789823456789923456789" (NVInteger 123456789223456789323456789423456789523456789623456789723456789823456789923456789)]
testTokenize "1.797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668781715404589535143824642e308" [Number "1.797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668781715404589535143824642e308" (NVNumber 1.797693134862315708145274237317043567980705675258449965989174768031572607800285387605895586327668781715404589535143824642e308)]
it "Dimension" $ do
testTokenize "10px" [Dimension "10" (NVInteger 10) "px"]
testTokenize "12.0em" [Dimension "12.0" (NVNumber 12) "em"]
testTokenize "-12.0em" [Dimension "-12.0" (NVNumber (-12)) "em"]
testTokenize "+45.6__qem" [Dimension "+45.6" (NVNumber 45.6) "__qem"]
testTokenize "5e" [Dimension "5" (NVInteger 5) "e"]
testTokenize "5px-2px" [Dimension "5" (NVInteger 5) "px-2px"]
testTokenize "5e-" [Dimension "5" (NVInteger 5) "e-"]
testTokenize "5\\ " [Dimension "5" (NVInteger 5) " "]
testTokenize "40\\70\\78" [Dimension "40" (NVInteger 40) "px"]
testTokenize "4e3e2" [Dimension "4e3" (NVNumber 4e3) "e2"]
testTokenize "0x10px" [Dimension "0" (NVInteger 0) "x10px"]
testTokenize "4unit " [Dimension "4" (NVInteger 4) "unit", Whitespace]
testTokenize "5e+" [Dimension "5" (NVInteger 5) "e", Delim '+']
testTokenize "2e.5" [Dimension "2" (NVInteger 2) "e", Number ".5" (NVNumber 0.5)]
testTokenize "2e+.5" [Dimension "2" (NVInteger 2) "e", Number "+.5" (NVNumber 0.5)]
testTokenize "1-2" [Number "1" (NVInteger 1), Number "-2" (NVInteger (-2))]
testTokenize "1\\65 1" [Dimension "1" (NVInteger 1) "e1"]
testTokenize "1\\31 em" [Dimension "1" (NVInteger 1) "1em"]
testTokenize "1e\\31 em" [Dimension "1" (NVInteger 1) "e1em"]
it "Percentage" $ do
testTokenize "10%" [Percentage "10" $ NVInteger 10]
testTokenize "+12.0%" [Percentage "+12.0" $ NVNumber 12.0]
testTokenize "-48.99%" [Percentage "-48.99" $ NVNumber (-48.99)]
testTokenize "6e-1%" [Percentage "6e-1" $ NVNumber 6e-1]
testTokenize "5%%" [Percentage "5" (NVInteger 5), Delim '%']
-- 402 TEST(CSSTokenizerTest, UnicodeRangeToken)
-- 403 {
-- 404 TEST_TOKENS("u+012345-123456", unicodeRange(0x012345, 0x123456));
-- 405 TEST_TOKENS("U+1234-2345", unicodeRange(0x1234, 0x2345));
-- 406 TEST_TOKENS("u+222-111", unicodeRange(0x222, 0x111));
-- 407 TEST_TOKENS("U+CafE-d00D", unicodeRange(0xcafe, 0xd00d));
-- 408 TEST_TOKENS("U+2??", unicodeRange(0x200, 0x2ff));
-- 409 TEST_TOKENS("U+ab12??", unicodeRange(0xab1200, 0xab12ff));
-- 410 TEST_TOKENS("u+??????", unicodeRange(0x000000, 0xffffff));
-- 411 TEST_TOKENS("u+??", unicodeRange(0x00, 0xff));
-- 412
-- 413 TEST_TOKENS("u+222+111", unicodeRange(0x222, 0x222), number(IntegerValueType, 111, PlusSign));
-- 414 TEST_TOKENS("u+12345678", unicodeRange(0x123456, 0x123456), number(IntegerValueType, 78, NoSign));
-- 415 TEST_TOKENS("u+123-12345678", unicodeRange(0x123, 0x123456), number(IntegerValueType, 78, NoSign));
-- 416 TEST_TOKENS("u+cake", unicodeRange(0xca, 0xca), ident("ke"));
-- 417 TEST_TOKENS("u+1234-gggg", unicodeRange(0x1234, 0x1234), ident("-gggg"));
-- 418 TEST_TOKENS("U+ab12???", unicodeRange(0xab1200, 0xab12ff), delim('?'));
-- 419 TEST_TOKENS("u+a1?-123", unicodeRange(0xa10, 0xa1f), number(IntegerValueType, -123, MinusSign));
-- 420 TEST_TOKENS("u+1??4", unicodeRange(0x100, 0x1ff), number(IntegerValueType, 4, NoSign));
-- 421 TEST_TOKENS("u+z", ident("u"), delim('+'), ident("z"));
-- 422 TEST_TOKENS("u+", ident("u"), delim('+'));
-- 423 TEST_TOKENS("u+-543", ident("u"), delim('+'), number(IntegerValueType, -543, MinusSign));
it "Comment" $ do
testTokenize "/*comment*/a" [Ident "a"]
testTokenize "/**\\2f**//" [Delim '/']
testTokenize "/**y*a*y**/ " [Whitespace]
testTokenize ",/* \n :) \n */)" [Comma, RightParen]
testTokenize ":/*/*/" [Colon]
testTokenize "/**/*" [Delim '*']
testTokenize ";/******" [Semicolon]
it "Serialization" $ do
testSerialize [String "hello,\x0world"] "\"hello,\xFFFDworld\""
testSerialize [String "\x10\x7f\""] "\"\\10 \\7f \\\"\""
testSerialize [String "\xABCDE"] "\"\xABCDE\""
testSerialize [Ident "-"] "\\-"
testSerialize [Ident "5"] "\\35 "
testSerialize [Ident "-5"] "-\\35 "
testSerialize [Ident "-9f\\oo()"] "-\\39 f\\\\oo\\(\\)"
testSerialize [Ident "\xABCDE"] "\xABCDE"
testSerialize [Ident "a", Ident "b"] "a/**/b"
testSerialize [Dimension "1" (NVInteger 1) "em", Ident "b"] "1em/**/b"
modifyMaxSize (const 500) $ modifyMaxSuccess (const 100000) $
prop "Tokeninze=>serialize=>tokenize roundtrip"
prop_tstRoundTrip
modifyMaxSize (const 50) $ modifyMaxSuccess (const 100000) $
prop "Serialize=>tokenize roundtrip"
prop_stRoundTrip
prop_tstRoundTrip :: String -> Bool
prop_tstRoundTrip s = tokenize (serialize t) == t
where t = tokenize $ T.pack s
prop_stRoundTrip :: TestTokens -> Bool
prop_stRoundTrip (TestTokens t) = tokenize (serialize t) == t
newtype TestTokens = TestTokens [Token]
deriving (Show, Eq)
instance Arbitrary TestTokens where
arbitrary = TestTokens . go <$> arbitrary
where go [] = []
go (x : xs@(Whitespace : _)) | needWhitespace x = x : go xs
-- we can only have [BadString, Whitespace]
-- or [Delim '\\', Whitespace] sequences
go (x : xs) | needWhitespace x = x : Whitespace : go xs
go (x@(Function (T.toLower -> "url")) : xs) =
x : String "argument" : go xs
go (x : xs) = x : go xs
needWhitespace x = case x of
BadString -> True
Delim '\\' -> True
_ -> False
instance Arbitrary Token where
arbitrary = oneof $
map return
[ Whitespace
, CDO
, CDC
, Comma
, Colon
, Semicolon
, LeftParen
, RightParen
, LeftSquareBracket
, RightSquareBracket
, LeftCurlyBracket
, RightCurlyBracket
, SuffixMatch
, SubstringMatch
, PrefixMatch
, DashMatch
, IncludeMatch
, Column
, BadString
, BadUrl
]
++
[ String <$> text
, num Number
, num Percentage
, num Dimension <*> ident
, Url <$> text
, Ident <$> ident
, AtKeyword <$> ident
, Function <$> ident
, return $ Function "url"
, Hash HId <$> ident
, Delim <$> elements possibleDelimiters
]
where ident = notEmpty text
notEmpty x = do
r <- x
if r /= "" then return r else notEmpty x
text = T.replace "\NUL" "\xFFFD" . T.pack <$> arbitrary
num token = do
c <- arbitrary
e <- arbitrary
let (t, n)
| e /= 0 = nv NVNumber (scientific c e)
| otherwise = nv NVInteger c
nv f x = (T.pack $ show x, f x)
return $ token t n
possibleDelimiters =
[d | c <- ['\0'..'\xff']
, [Delim d] <- [tokenize (T.pack [c])]]
++ ['\\']
| wereHamster/haskell-css-syntax | test/Test.hs | mit | 19,177 | 0 | 20 | 5,443 | 4,919 | 2,311 | 2,608 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Error where
import ClassyPrelude.Yesod
import Data.Aeson
import Data.Aeson.TH
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Encoding.Error as TEE
data ErrorResponseBody = ErrorResponseBody
{ title :: T.Text
, detail :: T.Text
}
instance ToContent ErrorResponseBody where
toContent = toContent . encode
instance ToTypedContent ErrorResponseBody where
toTypedContent = TypedContent "application/json" . toContent
$(deriveJSON defaultOptions 'ErrorResponseBody)
defaultErrorHandlerJson :: Yesod site => ErrorResponse -> HandlerFor site TypedContent
-- 400
defaultErrorHandlerJson (InvalidArgs ia) = fmap toTypedContent $ returnJson $
ErrorResponseBody "Bad Request" $ T.intercalate " " ia
-- 401
defaultErrorHandlerJson NotAuthenticated = fmap toTypedContent $ returnJson $
ErrorResponseBody "Unauthorized" "authentication required"
-- 403
defaultErrorHandlerJson (PermissionDenied _) = fmap toTypedContent $ returnJson $
ErrorResponseBody "Forbidden" "unauthorized"
-- 404
defaultErrorHandlerJson NotFound = fmap toTypedContent $ returnJson $
ErrorResponseBody "Not Found" "resource not found"
-- 405
defaultErrorHandlerJson (BadMethod m) = fmap toTypedContent $ returnJson $
ErrorResponseBody "Method Not Allowed" $ "method " <> TE.decodeUtf8With TEE.lenientDecode m <> " not supported"
-- 500
defaultErrorHandlerJson (InternalError e) = fmap toTypedContent $ returnJson $
ErrorResponseBody "Internal Server Error" e
-- 501
notImplemented :: HandlerFor site res
notImplemented = sendResponseStatus notImplemented501 $
ErrorResponseBody "Not Implemented" "operation not implemented"
| cliffano/swaggy-jenkins | clients/haskell-yesod/generated/src/Error.hs | mit | 1,856 | 0 | 10 | 314 | 376 | 198 | 178 | 34 | 1 |
{-# LANGUAGE RankNTypes #-}
module ConcSplit.Safe (
makeImpl
) where
import System.IO
import Control.Monad
import Control.Applicative ((<$>),pure)
import Control.Arrow (first,second) -- only to map over tuples with first and second
import Control.Exception
import Data.Iteratee.IO.Handle (enumHandle)
import Util.Parser
import Util.Iteratee
import Util.Allocator
import ConcSplit
makeImpl :: Int -> Impl
makeImpl chunkSize =
let
prettySize = prettyPrintSize chunkSize
name = "safe" ++ prettySize
desc = "iteratee-based, should work in all cases (preferred chunk size of " ++ prettySize ++ ")"
in Impl name (concsplit_impl chunkSize) desc
concsplit_impl:: Int -> [Allocator Handle] -> Int -> [Allocator Handle] -> IO ()
concsplit_impl chunkSize files2join partSize parts =
let mkIter :: Allocator Handle -> Allocator ByteIter
mkIter = fmap (first (cappedIterHandle partSize))
-- We need this to ensure that leftover input in the last iteratee doesn't overflow the last file.
chunkSize' = min chunkSize partSize
-- Prepends a ByteIter (possibly containing leftover input) to
-- the head of a list of as-yet unallocated ByteIters.
fuse::ByteIter -> [Allocator ByteIter] -> [Allocator ByteIter]
fuse iter iterAllocs = (first ((>>) iter) <$> head iterAllocs) : tail iterAllocs
gomasked:: (forall a. IO a -> IO a) -> -- restore function to run computations unmasked
[Allocator ByteIter] -> -- this list of destinations is assumed to be infinite
[Allocator Handle] ->
IO ()
gomasked restore destinations sources =
let writeToIter handle iter = do
iter' <- restore $ enumHandle chunkSize' handle iter
atEOF <- hIsEOF handle
if atEOF then return (Right iter',\hRelease iRelease -> (hRelease,iRelease))
else return (Left (handle,iter'),\hRelease iRelease -> (iRelease,hRelease))
go _ destinations [] = head destinations >>= snd -- we release the handle underneath the iteratee
go allocStrategy destinations (source:sources) = do
(result,cleanup) <- allocStrategy writeToIter source (head destinations)
case result of
-- We are creating a "fake" allocator from an already-allocated iteratee,
-- and we use combine-flipped to avoid the danger that an exception
-- while opening the source file leaves the destination handle unclosed.
-- With combine_flipped, the cleanup handler for the destination file
-- is set up before the cleanup handler for the source file.
Right iter' -> go combine_flipped (pure (iter',cleanup):tail destinations) sources
-- We prepend the iteratee containing leftover input to the list of destinations,
-- and we prepend a "fake" allocator with the already-opened file to the list
-- of sources.
Left (handle,iter') -> go combine (fuse iter' . tail $ destinations) (pure (handle,cleanup):sources)
in go combine destinations sources
in mask $ \restore -> gomasked restore (map mkIter parts) files2join
| danidiaz/concsplit | src/ConcSplit/Safe.hs | mit | 3,481 | 0 | 22 | 1,074 | 698 | 368 | 330 | 45 | 4 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module SDL.Geometry where
import qualified Graphics.UI.SDL.Types as SDL.T
import Foreign.C.Types
import Utils.Utils
import GHC.Int
instance Num a => Num (Point a) where
(ax, ay) + (bx, by) = (ax + bx, ay + by)
(ax, ay) - (bx, by) = (ax - bx, ay - by)
(ax, ay) * (bx, by) = (ax * bx, ay * by)
abs (x, y) = (abs x, abs y)
signum (x, y) = (signum x, signum y)
fromInteger a = (fromInteger a, 0)
cross :: Num a => Point a -> Point a -> a
cross (ax, ay) (bx, by) = (ax * by) - (bx * ay)
dot :: Num a => Point a -> Point a -> a
dot (ax, ay) (bx, by) = (ax * bx) + (ay * by)
type Point a = (a, a)
type GeomPoint = Point CInt
toGeomPoint :: RealFrac a => Point a -> GeomPoint
toGeomPoint = pairMap floor
toGeomPointInt :: Integral a => Point a -> GeomPoint
toGeomPointInt = pairMap (CInt . fromIntegral)
zero :: Num a => Point a
zero = (0, 0)
unitRight :: Num a => Point a
unitRight = (1, 0)
unitLeft :: Num a => Point a
unitLeft = (-1, 0)
unitDown :: Num a => Point a
unitDown = (0, 1)
unitUp :: Num a => Point a
unitUp = (0, -1)
toRect :: (Integral a) => a -> a -> a -> a -> SDL.T.Rect
toRect x y w h = SDL.T.Rect { SDL.T.rectX = fromIntegral x, SDL.T.rectY = fromIntegral y, SDL.T.rectW = fromIntegral w, SDL.T.rectH = fromIntegral h }
moveTo :: (Integral a1, Integral a2) => SDL.T.Rect -> (a1, a2) -> SDL.T.Rect
moveTo rect (x, y) = rect { SDL.T.rectX = fromIntegral x, SDL.T.rectY = fromIntegral y }
moveBy :: (Integral a1, Integral a2) => SDL.T.Rect -> (a1, a2) -> SDL.T.Rect
moveBy shape (x, y) = shape { SDL.T.rectX = SDL.T.rectX shape + fromIntegral x, SDL.T.rectY = SDL.T.rectY shape + fromIntegral y }
centredOn :: SDL.T.Rect -> SDL.T.Rect -> SDL.T.Rect
centredOn inner outer = inner `moveBy` (centreOf outer - centreOf inner)
centreOf :: SDL.T.Rect -> GeomPoint
centreOf shape = (x, y)
where x = SDL.T.rectX shape + SDL.T.rectW shape `div` 2
y = SDL.T.rectY shape + SDL.T.rectH shape `div` 2
toSDLPoint :: GeomPoint -> SDL.T.Point
toSDLPoint (x, y) = SDL.T.Point { SDL.T.pointX = x, SDL.T.pointY = y }
| ublubu/tile-rider | src/SDL/Geometry.hs | mit | 2,131 | 0 | 10 | 452 | 1,052 | 585 | 467 | 48 | 1 |
module Data.Bitcoin.TypesSpec where
import Test.Hspec
spec :: Spec
spec = return ()
| solatis/haskell-bitcoin-types | test/Data/Bitcoin/TypesSpec.hs | mit | 96 | 0 | 6 | 24 | 27 | 16 | 11 | 4 | 1 |
{-# htermination (blockIO :: ((a -> IOResult) -> IO Tup0) -> IO a) #-}
import qualified Prelude
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Tup0 = Tup0 ;
data Maybe a = Nothing | Just a ;
data IOErrorKind = Junk ;
data Char = Char MyInt ;
data IO a = IO ((IOError -> IOResult) -> (a -> IOResult) -> IOResult) ;
data IOError = IOError IOErrorKind (List Char) (List Char) (Maybe (List Char)) ;
data HugsException = HugsException ;
data IOResult = Hugs_ExitWith MyInt | Hugs_Error IOError | Hugs_Catch IOResult (HugsException -> IOResult) (IOError -> IOResult) (Obj -> IOResult) | Hugs_ForkThread IOResult IOResult | Hugs_DeadThread | Hugs_YieldThread IOResult | Hugs_Return Obj | Hugs_BlockThread (Obj -> IOResult) ((Obj -> IOResult) -> IOResult) ;
data Obj = Obj ;
pt :: (a -> c) -> (b -> a) -> b -> c;
pt f g x = f (g x);
const :: a -> b -> a;
const k vv = k;
threadToIOResult :: IO a -> IOResult;
threadToIOResult (IO m) = m Hugs_Error (const Hugs_DeadThread);
toObj :: a -> Obj;
toObj = toObj;
blockIOM' vw k = threadToIOResult (vw (pt k toObj));
fromObj :: Obj -> a;
fromObj = fromObj;
blockIOBlockIO0 vw f s = Hugs_BlockThread (pt s fromObj) (blockIOM' vw);
blockIO :: ((a -> IOResult) -> IO Tup0) -> IO a;
blockIO m = IO (blockIOBlockIO0 m);
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/blockIO_1.hs | mit | 1,418 | 0 | 11 | 337 | 550 | 309 | 241 | 28 | 1 |
module HeartsSpec (spec) where
import Prelude hiding (foldr)
import qualified Data.Foldable as F
import Data.List (sort, group)
import qualified Data.Set as S
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck (arbitrary)
import Hearts
import Hearts.Hand
import Hearts.Instances()
{-# ANN module "HLint: ignore Redundant do" #-}
spec :: Spec
spec = parallel $ do
describe "Card" $ do
it "can be ordered by rank" $ do
Card Ace Hearts `shouldSatisfy` (> Card King Hearts)
Card Five Spades `shouldSatisfy` (< Card Jack Spades)
context "when counting points" $ do
context "when is not a Heart or the Queen of Spades" $ do
prop "is worth zero points" $ do
\c -> case c of
Card _ Clubs -> cardScore c == 0
Card _ Diamonds -> cardScore c == 0
_ -> otherwise
context "when is a Heart" $ do
prop "is worth one point" $ do
\c -> case c of
Card _ Hearts -> cardScore c == 1
_ -> otherwise
context "when is the Queen of Spades" $ do
prop "is worth 13 points" $ do
\c -> case c of
Card Queen Spades -> cardScore c == 13
_ -> otherwise
describe "Deck" $ do
it "contains no duplicates" $ do
let deck = makeDeck
let isUnique [_] = True
isUnique _ = False
keepDuplicates = filter (not . isUnique)
(keepDuplicates . group . sort . deckToList) deck `shouldBe` []
it "can be reduced to its card count" $
F.foldr (const succ) 0 makeDeck `shouldBe` (52 :: Int)
describe "deckScore" $ do
it "counts how many points a deck is worth" $ do
let deck = deckFromList [Card Queen Spades, Card Three Clubs, Card King Hearts, Card Seven Hearts, Card Ace Spades, Card Ten Diamonds]
deckScore deck `shouldBe` 15
let deck' = deckFromList [Card Three Hearts, Card Queen Clubs, Card Four Hearts, Card Ace Diamonds, Card Ten Hearts]
deckScore deck' `shouldBe` 3
let deck'' = deckFromList [Card Three Clubs, Card Ace Spades, Card Ten Diamonds]
deckScore deck'' `shouldBe` 0
let deck''' = deckFromList [Card rank Hearts | rank <- [Two ..]]
deckScore deck''' `shouldBe` 13
context "any amount of Hearts less than all, with/without Queen of Spades in Deck" $ do
prop "score is more than zero" $ do
let allScoreCards = S.fromList $ Card Queen Spades : [Card rank Hearts | rank <- [Two ..]]
containsSomeScoreCards (Deck cards) = case S.toList onlyScoreCards of
[] -> False
_ -> onlyScoreCards `S.isProperSubsetOf` allScoreCards
where onlyScoreCards = cards `S.intersection` allScoreCards
\deck -> if containsSomeScoreCards deck
then deckScore deck > 0
else otherwise
context "when all Hearts and the Queen of Spades are in Deck" $ do
it "a full deck sums up to zero" $ do
deckScore makeDeck `shouldBe` 0
prop "sums up to zero" $ do
let allScoreCards = S.fromList $ Card Queen Spades : [Card rank Hearts | rank <- [Two ..]]
\deck -> if allScoreCards == (allScoreCards `S.intersection` unDeck deck)
then deckScore deck == 0
else otherwise
describe "emptyHand" $ do
it "contains no cards" $ do
handToList emptyHand `shouldBe` []
describe "validatePlayOnHand" $ do
prop "can add a card to the Hand" $ do
let h = emptyHand
\p c -> validatePlayOnHand (p, c) h == PlayHand (p, c) h
prop "can not add a card if player has already played" $ do
let h = emptyHand
\p c -> let h' = insert (p, c) h in do
c' <- arbitrary
return $ validatePlayOnHand (p, c') h' == ForbiddenPlay h'
| nadirs/hearts-hs | tests/HeartsSpec.hs | mit | 4,365 | 0 | 25 | 1,696 | 1,201 | 589 | 612 | 84 | 9 |
module Math.Ray
( Ray(..)
, throughPoint
) where
import Math.Vector
data Ray = Ray Vector3 Unit3
throughPoint :: Vector3 -> Vector3 -> Ray
throughPoint s p = let d = unit $ p - s in Ray s d
| burz/Rayzer | Math/Ray.hs | mit | 194 | 0 | 10 | 43 | 81 | 44 | 37 | 7 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module Test.Control.TimeWarp.Timed.ExceptionSpec
( spec
) where
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (TVar, modifyTVar, newTVarIO, readTVarIO)
import Control.Exception.Base (ArithException (Overflow),
AsyncException (ThreadKilled),
SomeException (..))
import Control.Monad.Catch (catch, catchAll, throwM)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans (MonadIO)
import System.Wlog (LoggerConfig (..), Severity (Error),
setupLogging)
import Test.Hspec (Spec, before, describe)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (NonNegative (..), Property)
import Test.QuickCheck.Monadic (monadicIO)
import Test.QuickCheck.Property (Result (reason), failed, ioProperty,
succeeded)
import Control.TimeWarp.Timed (Microsecond, TimedT, after, for, fork,
fork_, invoke, runTimedT, sec, throwTo,
wait)
import Test.Control.TimeWarp.Common ()
spec :: Spec
spec =
before initLogging $
describe "WorkMode" $ do
describe "error" $ do
prop "should abort the execution"
exceptionShouldAbortExecution
prop "caught nicely"
excCaught
prop "exception from main thread caught outside of monad"
excCaughtOutside
prop "exception from main thread caught outside of monad (+ wait)"
excCaughtOutsideWithWait
prop "proper catch order (catch inside catch)"
excCatchOrder
prop "(wait + throw) - exception doesn't get lost"
excWaitThrow
prop "(wait + throw) in forked thread - exception doesn't get lost"
excWaitThrowForked
prop "catch doesn't handle future exceptions"
excCatchScope
prop "catch doesn't handle future exceptions (with wait inside)"
excCatchScopeWithWait
prop "different exceptions, catch inner"
excDiffCatchInner
prop "different exceptions, catch outer"
excDiffCatchOuter
describe "handler error" $
prop "throws"
handlerThrow
describe "async error" $ do
prop "shouldn't abort the execution"
asyncExceptionShouldntAbortExecution
prop "throwTo throws correct exception"
throwToThrowsCorrectException
prop "throwTo can kell thread"
throwToCanKillThread
where
initLogging = setupLogging Nothing mempty{ _lcTermSeverity = Just Error }
-- FIXME
exceptionShouldAbortExecution
:: NonNegative Microsecond
-> Property
exceptionShouldAbortExecution (getNonNegative -> t) = (const (monadicIO $ pure ())) t
-- monadicIO $
-- do var <- liftIO $ newTVarIO (0 :: Int)
-- runTimedT $
-- fork_ $
-- do liftIO $ atomically $ writeTVar var 1
-- wait $ for t mcs
-- void $ throwM $ TextException "Error"
-- liftIO $ atomically $ writeTVar var 2
-- res <- liftIO $ readTVarIO var
-- assert $ res == 1
-- FIXME
asyncExceptionShouldntAbortExecution
:: NonNegative Microsecond
-> NonNegative Microsecond
-> Property
asyncExceptionShouldntAbortExecution (getNonNegative -> t1) (getNonNegative -> t2) = (const (const (monadicIO $ pure ()))) t1 t2
-- monadicIO $
-- do var <- liftIO $ newTVarIO (0 :: Int)
-- runTimedT $
-- do liftIO $ atomically $ writeTVar var 1
-- fork_ $
-- do wait $ for t2 mcs
-- throwM $ TextException "Error"
-- wait $ for t1 mcs
-- liftIO $ atomically $ writeTVar var 2
-- res <- liftIO $ readTVarIO var
-- assert $ res == 2
excCaught
:: Property
excCaught =
ioProperty . withCheckPoints $
\checkPoint -> runEmu $
let act = throwM ThreadKilled >> checkPoint (-1)
hnd _ = checkPoint 1
in act `catchAll` hnd
excCaughtOutside
:: Property
excCaughtOutside =
ioProperty . withCheckPoints $
\checkPoint ->
let act = do
runEmu $ wait (for 1 sec) >> throwM ThreadKilled
checkPoint (-1)
hnd _ = checkPoint 1
in do act `catchAll` hnd
checkPoint 2
excCaughtOutsideWithWait
:: Property
excCaughtOutsideWithWait =
ioProperty . withCheckPoints $
\checkPoint ->
let act = do
runEmu $ throwM ThreadKilled
checkPoint (-1)
hnd _ = checkPoint 1
in do act `catchAll` hnd
checkPoint 2
excWaitThrow
:: Property
excWaitThrow =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = do
wait (for 1 sec)
throwM ThreadKilled
hnd _ = checkPoint 1
in do act `catchAll` hnd
checkPoint 2
excWaitThrowForked
:: Property
excWaitThrowForked =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = do
wait (for 1 sec)
throwM ThreadKilled
hnd _ = checkPoint 1
in do fork_ $ act `catchAll` hnd
invoke (after 1 sec) $ checkPoint 2
excCatchOrder
:: Property
excCatchOrder =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = throwM ThreadKilled
hnd1 _ = checkPoint 1
hnd2 _ = checkPoint (-1)
in do act `catchAll` hnd1 `catchAll` hnd2
checkPoint 2
excCatchScope
:: Property
excCatchScope =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act1 = checkPoint 1 `catchAll` const (checkPoint $ -1)
act2 = act1 >> throwM ThreadKilled
in do act2 `catchAll` const (checkPoint 2)
checkPoint 3
excCatchScopeWithWait :: Property
excCatchScopeWithWait =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act1 = checkPoint 1 >> wait (for 1 sec)
act2 = act1 `catchAll` const (checkPoint $ -1)
act3 = act2 >> wait (for 1 sec) >> throwM ThreadKilled
in do act3 `catchAll` const (checkPoint 2)
checkPoint 3
excDiffCatchInner
:: Property
excDiffCatchInner =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = throwM ThreadKilled
hnd1 (_ :: AsyncException) = checkPoint 1
hnd2 (_ :: ArithException) = checkPoint (-1)
in do act `catch` hnd1 `catch` hnd2
checkPoint 2
excDiffCatchOuter
:: Property
excDiffCatchOuter =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = throwM Overflow
hnd1 (_ :: AsyncException) = checkPoint (-1)
hnd2 (_ :: ArithException) = checkPoint 1
in do act `catch` hnd1 `catch` hnd2
checkPoint 2
handlerThrow
:: Property
handlerThrow =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $
let act = throwM ThreadKilled
hnd1 (_ :: SomeException) = throwM Overflow
hnd2 (_ :: ArithException) = checkPoint 1
in do act `catch` hnd1 `catch` hnd2
checkPoint 2
throwToThrowsCorrectException
:: Property
throwToThrowsCorrectException =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $ do
tid <- fork $ catch (wait $ for 1 sec) $
\(_ :: ArithException) -> checkPoint 1
throwTo tid $ SomeException Overflow -- should be unwrapped
-- automatically
wait $ for 2 sec
checkPoint 2
throwToCanKillThread
:: Property
throwToCanKillThread =
ioProperty . withCheckPoints $
\checkPoint ->
runEmu $ do
tid <- fork $ wait (for 1 sec) >> checkPoint (-1)
throwTo tid Overflow
runEmu :: TimedT IO () -> IO ()
runEmu = runTimedT
-- Principle of checkpoints: every checkpoint has it's id
-- Checkpoints should be visited in according order: 1, 2, 3 ...
newtype CheckPoints = CP { getCP :: TVar (Either String Int) }
initCheckPoints :: MonadIO m => m CheckPoints
initCheckPoints = fmap CP $ liftIO $ newTVarIO $ Right 0
visitCheckPoint :: MonadIO m => CheckPoints -> Int -> m ()
visitCheckPoint cp curId = liftIO $ atomically $ modifyTVar (getCP cp) $
\wasId ->
if wasId == Right (curId - 1)
then Right curId
else Left $ either id (showError curId) wasId
where
showError cur was = mconcat
["Wrong chechpoint. Expected "
, show (was + 1)
, ", but visited "
, show cur
]
assertCheckPoints :: MonadIO m => CheckPoints -> m Result
assertCheckPoints = fmap mkRes . liftIO . readTVarIO . getCP
where
mkRes (Left msg) = failed { reason = msg }
mkRes (Right _) = succeeded
withCheckPoints :: MonadIO m => ((Int -> m ()) -> IO a) -> IO Result
withCheckPoints act = do
cp <- initCheckPoints
_ <- act $ liftIO . visitCheckPoint cp
assertCheckPoints cp
| serokell/time-warp | test/Test/Control/TimeWarp/Timed/ExceptionSpec.hs | mit | 9,889 | 0 | 17 | 3,609 | 2,224 | 1,147 | 1,077 | 233 | 2 |
{- Да се напише функция extractEvens string, която връща списък от всички
- четни числа в низа string.
-}
extractEvens :: String -> [String]
extractEvens [] = []
extractEvens s@(c:cs)
| isDigit c && isNumberEven s =
extractNumber s : extractEvens (dropWhile isDigit s)
| otherwise = extractEvens cs
where extractNumber s = (takeWhile isDigit s)
lastDigit s = last s
isNumberEven s = last (extractNumber s) `elem` ['0', '2'..'9']
isDigit :: Char -> Bool
isDigit c = c `elem` ['0'..'9']
| fmi-lab/fp-elective-2017 | exams/preparation/extractEvens.hs | mit | 583 | 0 | 10 | 123 | 178 | 90 | 88 | 11 | 1 |
#!/usr/bin/env runghc
import Data.List
import System.Cmd
main :: IO ()
main = do
system $ "rm -rf *.tix hpc_out"
system $ "cabal clean"
system $ "cabal configure --enable-tests --enable-library-coverage"
system $ "cabal build"
system $ "dist/build/specs/specs"
system $ hpc "markup" ["--destdir=hpc_out"]
system $ hpc "report" []
return ()
hpc :: String -> [String] -> String
hpc cmd args = unwords [ "hpc", cmd, hpcdir, exclusions
, unwords args, "specs" ]
hpcdir :: String
hpcdir = "--hpcdir=dist/hpc/mix/noise-0.0.0.0"
exclusions :: String
exclusions = concat . intersperse " " $ map ("--exclude="++)
[ "Main" ]
| thoughtpolice/hs-noise | scripts/coverage.hs | mit | 691 | 0 | 9 | 168 | 192 | 98 | 94 | 20 | 1 |
module Data.Expenses.Parse.Megaparsec.UsingDirective
( using
)
where
import Control.Monad ( void )
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as Set
import Text.Megaparsec ( ErrorItem(Tokens)
, choice
, count
, failure
, hidden
, lookAhead
, many
, skipMany
)
import Text.Megaparsec.Char ( char
, letterChar
, string
, tab
, upperChar
)
import qualified Text.Megaparsec.Char.Lexer as L
import Data.Expenses.Parse.Megaparsec.Types
( Configuration(..)
, Parser
)
sc :: Parser ()
sc = hidden . skipMany . void $ choice [char ' ', tab]
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
currency :: Parser String
currency = lexeme $ count 3 upperChar
keyword :: String -> Parser ()
keyword keyw = do
word <- lookAhead $ many letterChar :: Parser String
case word of
x | x == keyw -> string keyw *> sc
_ -> failure (Just $ Tokens $ NE.fromList word)
(Set.fromList [Tokens (NE.fromList keyw)])
using :: Parser Configuration
using = do
_ <- keyword "Using"
cur <- currency
_ <- lexeme $ string "as"
_ <- lexeme $ string "the"
_ <- lexeme $ string "default"
_ <- lexeme $ string "currency"
return $ Configuration { configDefaultCurrency = cur }
| rgoulter/expenses-csv-utils | src/Data/Expenses/Parse/Megaparsec/UsingDirective.hs | mit | 2,147 | 0 | 17 | 1,179 | 437 | 235 | 202 | 44 | 2 |
{-# LANGUAGE QuasiQuotes, ScopedTypeVariables, OverloadedStrings #-}
import qualified Hasql as H
import qualified Hasql.Postgres as H
import qualified Data.Int as I
psqlConf :: H.Postgres
psqlConf = H.Postgres "haruko.gonyeo.com" 5432 "psql-user" "s3kr1t" "my-database"
main :: IO ()
main = do s <- maybe (fail "Improper session settings") return $
H.sessionSettings 6 30
H.session psqlConf s $ do
initDb
saveData 1.1
saveData 1.1
initDb :: H.Session H.Postgres IO ()
initDb = H.tx Nothing $ do
H.unit [H.q|DROP TABLE IF EXISTS data|]
H.unit [H.q|CREATE TABLE data (
field1 DECIMAL NOT NULL,
field2 BIGINT NOT NULL,
PRIMARY KEY (field1)
)|]
saveData :: Double -> H.Session H.Postgres IO ()
saveData num =
H.tx (Just (H.Serializable, True)) $ do
(mrow :: Maybe (Double,I.Int64))
<- H.single $ [H.q|SELECT *
FROM data
WHERE field1=?|] num
case mrow of
Just (field1,field2) ->
let newfield2 = field2 * 2 + 1
in H.unit $ [H.q|UPDATE data
SET field2=?
WHERE field1=?|] newfield2 field1
Nothing -> H.unit $ [H.q|INSERT INTO data
( field1
, field2
) VALUES (?,?)|] num (1 :: I.Int64)
| dgonyeo/blog-hasql-example | Main.hs | mit | 1,805 | 0 | 16 | 898 | 364 | 192 | 172 | 30 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Char
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Handler.Warp
import System.Directory
import System.Environment
import System.FilePath
import qualified Control.Concurrent.Lock as L
import qualified Data.ByteString.Lazy as BS
import qualified Data.Text as T
main = do
args <- getArgs
lock <- L.new
case args of
[port, docRoot] | all isDigit port -> run (read port) $ waiApp lock docRoot
_ -> putStrLn "Usage: mrag <PORT> <DOCROOT>"
waiApp lock docRoot request respond =
case requestMethod request of
"POST" -> respond =<< doWrite lock path =<< strictRequestBody request
"GET" -> respond $ responseFile status200 [] path Nothing
_ -> respond $ responseLBS status405 [] "Method not Allowed"
where path = joinPath $ docRoot : map T.unpack (pathInfo request)
doWrite lock path content =
L.with lock appendLine >> return (responseLBS status200 [] "")
where appendLine = do
createDirectoryIfMissing True $ takeDirectory path
BS.appendFile path $ BS.append content "\n"
| dvaergiller/mrag | Mrag.hs | mit | 1,086 | 0 | 14 | 202 | 332 | 169 | 163 | 28 | 3 |
module Git.Result where
import Foreign.C.Types
type Result a = IO (Either ErrorCode a)
newtype ErrorCode = ErrorCode Int
handle_git_return::IO CInt -> IO a -> Result a
handle_git_return action wrapper = do
return_value <- action
if return_value /= 0 then return $ Left $ ErrorCode $ fromIntegral return_value
else fmap Right wrapper
| sakari/hgit | src/Git/Result.hs | gpl-2.0 | 344 | 0 | 10 | 62 | 112 | 58 | 54 | 9 | 2 |
import Control.Monad ( guard )
import System.Directory ( doesDirectoryExist, setCurrentDirectory )
import System.IO.Temp ( withSystemTempDirectory )
-- internal modules
import Command.Init ( gtInit )
import Command.Log ( gtLog )
main :: IO ()
main =
withSystemTempDirectory "" $ \tmp -> do
setCurrentDirectory tmp
gtInit
guard =<< doesDirectoryExist ".git"
commits <- gtLog
guard $ null commits
| cblp/gt | Tests/Command/InitLog.hs | gpl-2.0 | 496 | 0 | 10 | 156 | 119 | 62 | 57 | 13 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Robots.Solver where
-- $Id$
import Robots.Config
import Robots.Data
import Robots.Move
import Robots.Final
import Robots.Hull
import Robots.Nice
import Robots.Final
import Robots.Examples
import Autolib.Schichten
import Data.Maybe
import Autolib.Set
import Autolib.ToDoc
import Autolib.Reporter ( export )
import Control.Monad ( guard )
nachfolger_without_loss :: Config -> [ Config ]
nachfolger_without_loss k = do
n <- nachfolger k
guard $ length ( robots n ) == length ( robots k )
return n
nachfolger :: Config -> [ Config ]
nachfolger k = do
( z, k' ) <- znachfolger k
return k'
znachfolger :: Config -> [ ( Zug, Config ) ]
znachfolger k = do
let ( t, _ :: Doc ) = export $ valid k
guard $ isJust t
r <- robots k
d <- richtungen
let z = (name r, d)
k' <- maybeToList $ execute k z
guard $ covered k'
guard $ each_goal_in_right_cluster k'
-- guard $ not $ empty_quads k' -- ??
return ( z, k' )
znachfolger_all_onboard k = do
let ( t, _ :: Doc ) = export $ valid k
guard $ isJust t
r <- robots k
d <- richtungen
let z = (name r, d)
k' <- maybeToList $ execute k z
guard $ covered k'
-- guard $ not $ empty_quads k' -- ??
guard $ each_goal_in_right_cluster k'
guard $ length ( robots k ) == length ( robots k' )
return ( z, k' )
each_goal_in_right_cluster k = and $ do
r @ Robot { ziel = Just z } <- robots k
return $ cluster_of k ( position r ) == cluster_of k z
empty_quads k =
case ( do r <- robots k ; maybeToList $ ziel r ) of
[ (x0,y0) ] -> or $ do
let comps = [ (<=), (>=) ]
gx <- comps
gy <- comps
return $ null $ do
r <- robots k
let (x,y) = position r
guard $ gx x x0 && gy y y0
return ()
_ -> False -- DON'T KNOW
reachables :: Config -> [[ Config ]]
reachables k = map setToList $ schichten ( mkSet . nachfolger ) k
solutions :: Config -> [ ((Int, Int), [[Zug]]) ]
solutions k = do
(d, ps) <- zip [0 :: Int ..] $ schichten ( mkSet . nachfolger ) k
let out = do p <- setToList ps
let ( t, _ :: Doc ) = export $ final p
guard $ isJust t
return $ reverse $ geschichte p
return $ (( d, length out), filter (not . null) out)
solutions' :: Int -> Config -> [ ((Int, Int), [[Zug]]) ]
solutions' sw k = do
(d, ps) <- zip [0 :: Int ..]
$ takeWhile ( \ zss -> cardinality zss < sw )
$ schichten ( mkSet . nachfolger ) k
let out = do p <- setToList ps
let ( t, _ :: Doc ) = export $ final p
guard $ isJust t
return $ reverse $ geschichte p
return $ (( d, length out), filter (not . null) out)
solve :: Config -> IO ()
solve k = sequence_ $ map ( print . toDoc ) $ solutions k
shortest :: Config -> [[Zug]]
shortest k = take 1 $ do
( _ , zss ) <- solutions k
zss
shortest' :: Int -> Config -> [[Zug]]
shortest' sw k = take 1 $ do
( _ , zss ) <- solutions' sw k
zss
vorganger :: Config -> [ Config ]
vorganger c = do
r <- robots c
d <- richtungen
let z = (name r, d)
reverse_executes c z
ancestors :: Config -> [[Config]]
ancestors c = map setToList
$ schichten ( mkSet . vorganger ) c
----------------------------------------------------
ex :: Config
ex = Robots.Config.make
[ Robot { name = "A", position = ( -2, -2 ) , ziel = Nothing }
, Robot { name = "B", position = ( 2, 3 ), ziel = Just ( 0, 0 ) }
, Robot { name = "C", position = ( -2, 1 ), ziel = Nothing }
, Robot { name = "D", position = ( 2, 0 ), ziel = Nothing }
, Robot { name = "E", position = ( -3, 1 ), ziel = Nothing }
] | Erdwolf/autotool-bonn | src/Robots/Solver.hs | gpl-2.0 | 3,788 | 71 | 20 | 1,171 | 1,561 | 808 | 753 | 108 | 2 |
----
-- Factorial.hs
-- by Daniel Brice
-- Invoke as `Factorial <num>`
-- Prints <num> factorial
----
import System.Environment (getArgs)
import Data.List (foldl')
factorial :: Integer -> Integer
factorial n = foldl' (*) 1 [1..n]
main = print . factorial . read . head =<< getArgs
| friedbrice/hemingway | Factorial/Factorial.hs | gpl-2.0 | 283 | 1 | 8 | 48 | 82 | 46 | 36 | 5 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : Database/Hedsql/CRUD.hs
Description : CRUD pre-built queries.
Copyright : (c) Leonard Monnier, 2016
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Pre-built generic CRUD SQL statements which can then be parsed to specific
backends.
==Note
Nothing prevents you from using one of these statements as a basis to build a
more complex one. For example if you wish to add a LIMIT clause to 'selectAll'
you could do the following:
@
selectAllLimit table columns maxResults = do
selectAll table columns
limit maxResults
@
-}
module Database.Hedsql.CRUD
( selectAll
, selectOne
, insertOne
, updateOne
, deleteOne
) where
--------------------------------------------------------------------------------
-- IMPORTS
--------------------------------------------------------------------------------
import Database.Hedsql
import Database.Hedsql.Ext
--------------------------------------------------------------------------------
-- PRIVATE
--------------------------------------------------------------------------------
-- | Assign a placeholder linked to each column.
assignPlaceholders ::
(ToCol k (Column colType dbVendor))
=> [k] -- ^ Name of the columns.
-> [Assignment dbVendor]
assignPlaceholders = map (\k -> assign k (/?))
--------------------------------------------------------------------------------
-- PUBLIC
--------------------------------------------------------------------------------
{-|
Select query returning all the rows of the provided table(s).
The generated SQL code will be of kind:
> SELECT "Column1", "Column2"
> FROM "Table"
-}
selectAll ::
( ToList table [tables], ToTableRef tables (TableRef dbVendor)
, SelectConstr columns (Query [[Undefined]] dbVendor)
)
=> table -- ^ Table(s) or name of the table(s).
-> columns -- ^ Column(s) or name of the column(s).
-> Query [[Undefined]] dbVendor
selectAll tb columns = do
select columns
from tb
{-|
Select query with a placedholder for the expected matching key.
The generated SQL code will be of kind:
> SELECT "Column1", "Column2"
> FROM "Table"
> WHERE "key" = ?
-}
selectOne ::
( ToList table [tables], ToTableRef tables (TableRef dbVendor)
, SelectConstr columns (Query [[Undefined]] dbVendor)
, ToColRef key (ColRef keyType dbVendor)
)
=> table -- ^ Table(s) or names of the table(s).
-> columns -- ^ Columns or names of the columns.
-> key -- ^ Primary key which has to be matched by the placeholder.
-> Query [[Undefined]] dbVendor
selectOne tb columns key = do
selectAll tb columns
where_ $ key /== (/?)
{-|
Generic insert statement using placeholders.
The generated SQL code will be of kind:
> INSERT INTO "Table"
> ("Column1", "Column2")
> VALUES (?, ?)
-}
insertOne ::
( ToTable table (Table dbVendor)
, ToCol column (Column colType dbVendor)
)
=> table -- ^ Table or name of the table.
-> [column] -- ^ Columns or names of the columns.
-> InsertStmt Void dbVendor
insertOne tb values =
insert tb $ assignPlaceholders values
{-|
Generic update statement using placeholders.
The generated SQL code will be of kind:
> UPDATE "Table"
> SET "Column1" = ?, "Column2" = ?
> WHERE "key" = ?
-}
updateOne ::
( ToTable table (Table dbVendor)
, ToCol column (Column colType dbVendor)
, ToColRef key (ColRef keyType dbVendor)
)
=> table -- ^ Table or name of the table.
-> [column] -- ^ Columns or names of the columns.
-> key
-> UpdateStmt Void dbVendor
updateOne tb values key = do
update tb $ assignPlaceholders values
where_ $ key /== (/?)
{-|
Generic delete statement using a placeholder.
The generated SQL code will be of kind:
> DELETE FROM "Table"
> WHERE "id" = ?
-}
deleteOne ::
( ToTable table (Table dbVendor)
, ToColRef key (ColRef keyType dbVendor)
)
=> table -- ^ Table or name of the table.
-> key -- ^ Primary key which has to be matched by the placeholder.
-> DeleteStmt Void dbVendor
deleteOne tb key = do
deleteFrom tb
where_ $ key /== (/?)
| momomimachli/Hedsql | src/Database/Hedsql/CRUD.hs | gpl-3.0 | 4,245 | 0 | 11 | 903 | 613 | 333 | 280 | 62 | 1 |
module MakeContents(
handleMakefileDescr
) where
import qualified Data.List as Lists
import System.Directory
import Split
import System.FilePath
import Parser
import qualified Scaner as SC
data Info1=Info1{proj_name :: String,
main_f :: String,
compiler_name:: String,
compiler_flgs:: String,
linker_flgs :: String,
linker_name :: String,
src_dir :: String,
src_exts :: [String],
build_d :: String,
incl_dirs :: [String],
makefile_n :: String }
deriving (Eq,Ord,Show)
convertInfo::Info->Either String Info1
convertInfo i = Right i1
where
i1=Info1{proj_name = name . project $ i,
main_f = main_file . project $ i,
compiler_name = compiler i,
compiler_flgs = compiler_flags i,
linker_name = linker i,
src_dir = source_dir i,
src_exts = Lists.words . source_exts $ i,
linker_flgs = linker_flags i,
build_d = build_dir i,
incl_dirs = filter (not . null) . splitBy ';' $ include_dirs i,
makefile_n = makefile_name i }
correctInfo1::Info1->Either String Info1
correctInfo1 =
Right . correctMakefileName . correctSourceExts .
correctLinkerFlags . correctLinkerName . correctCompilerFlags .
correctCompilerName . correctPNandMainfile
correctPNandMainfile::Info1->Info1
correctPNandMainfile i
|(null pn) && (null mf) = i{proj_name = "main", main_f="main.cpp"}
|(null pn) && (not . null $ mf) = i{proj_name = dropExtension mf}
|(not . null $ pn) && (null mf) = i{main_f = pn ++ ".cpp"}
|otherwise = i
where
pn = proj_name i
mf = main_f i
correctCompilerName::Info1->Info1
correctCompilerName i =
if null cn then i{compiler_name = "g++"} else i
where
cn = compiler_name i
correctCompilerFlags::Info1->Info1
correctCompilerFlags i =
if null cf then i{compiler_flgs = "-O3 -Wall -std=c++14"} else i
where
cf=compiler_flgs i
correctLinkerName::Info1->Info1
correctLinkerName i =
if null ln then i{linker_name = compiler_name i} else i
where
ln=linker_name i
correctLinkerFlags::Info1->Info1
correctLinkerFlags i =
if null lf then i{linker_flgs = "-s"} else i
where
lf=linker_flgs i
correctSourceExts::Info1->Info1
correctSourceExts i =
if null se then i{src_exts=["cpp"]} else i
where
se=src_exts i
correctMakefileName::Info1->Info1
correctMakefileName i =
if null . makefile_n $ i then i{makefile_n = "Makefile"} else i
txt2Info1::String->Either String Info1
txt2Info1 t = do
lexStream <- SC.scaner t
i <- parser lexStream
i1 <- convertInfo i
correctInfo1 i1
usualContents::FilePath->IO [FilePath]
usualContents p = do
contents<-getDirectoryContents p
return $ filter (\n -> (n/=".") && (n/="..")) contents
sourceFiles::FilePath->[String]->IO [FilePath]
sourceFiles p exts = do
files <- usualContents p
return $ filter (\n -> admissibleName n exts) files
admissibleExt :: String -> [String] -> Bool
admissibleExt [] _ = False
admissibleExt e exts = (tail e) `elem` exts
admissibleName :: FilePath -> [String] -> Bool
admissibleName n exts = admissibleExt (takeExtension n) exts
makefileText :: Info1 -> IO String
makefileText i = do
o <- obj i
lo <- linkobj i
return $ Lists.intercalate "\n\n" [
cppLinkerCompilerBin i ++ vpath i ++ o ++ lo,
phony,
target_all,
clean i,
rules_for_srcs i,
bin_sec i]
cppLinkerCompilerBin::Info1->String
cppLinkerCompilerBin i =
"LINKER = " ++ linker_name i ++ "\n" ++
"LINKERFLAGS = " ++ linker_flgs i ++ "\n" ++
"CXX = " ++ compiler_name i ++ "\n" ++
"CXXFLAGS = " ++ compiler_flgs i ++ "\n" ++
"BIN = " ++ proj_name i
phony::String
phony=".PHONY: all all-before all-after clean clean-custom"
target_all::String
target_all = "all: all-before $(BIN) all-after"
clean::Info1->String
clean i =
"clean: clean-custom \n\t" ++
"rm -f " ++ prefix ++ "*.o\n\t" ++
"rm -f " ++ prefix ++ "$(BIN)"
where
b = build_d i
prefix = if not . null $ b then "./" ++ b ++ "/" else "./"
includes::Info1->String
includes i =
Lists.intercalate " " . map (\x-> "-I\""++x++ "\"") $ incl
where
incl = incl_dirs i
src_vpath::Info1->String
src_vpath i =
if null srcs then
""
else
Lists.intercalate "\n" . map (\e-> "vpath %." ++ e ++ " " ++ srcs ) $ exts
where
srcs = src_dir i
exts = src_exts i
objects_vpath::Info1->String
objects_vpath i =
if null b then
""
else
"vpath %.o " ++ b
where
b = build_d i
vpath::Info1->String
vpath i = if null v then "" else "\n" ++ v
where
v = Lists.intercalate "\n" . filter (\s -> not . null $ s) $ [
src_vpath i, objects_vpath i]
rules_for_srcs::Info1->String
rules_for_srcs i =
Lists.intercalate "\n\n" . map (
\e-> "." ++ e ++ ".o:\n\t" ++ "$(CXX) -c $< -o $@ $(CXXFLAGS) " ++ incl ++
(if not . null $ b then "\n\t" ++ "mv $@ ./" ++ b else "")
) $ exts
where
exts = src_exts i
incl = includes i
b = build_d i
bin_sec::Info1->String
bin_sec i =
"$(BIN):$(OBJ)\n\t"++
"$(LINKER) -o $(BIN) $(LINKOBJ) $(LINKERFLAGS)\n\t"++
if null b then "" else ("mv $(BIN) ./"++ b)
where
b=build_d i
obj'' :: Info1 -> IO [String]
obj'' i = do
sdir <- srcdir i
fnames <- sourceFiles sdir . src_exts $ i
return . map (\f->replaceExtension f "o") $ mf:(Lists.delete mf fnames)
where
mf = main_f i
obj' :: Info1 -> IO String
obj' i = do
o'' <- obj'' i
return . Lists.intercalate " " $ o''
obj :: Info1 -> IO String
obj i = do
o' <- obj' i
return $ "\nOBJ = " ++ o'
linkobj' :: Info1 -> IO String
linkobj' i = do
o'' <- obj'' i
return . Lists.intercalate " " . map (prefix ++) $ o''
where
b = build_d i
prefix = if not . null $ b then b ++ "/" else ""
linkobj :: Info1 -> IO String
linkobj i = do
lo' <- linkobj' i
return $ "\nLINKOBJ = " ++ lo'
srcdir :: Info1-> IO String
srcdir i =
if null sd then getCurrentDirectory else return sd
where
sd = src_dir i
writeMakefile :: Info1->IO()
writeMakefile i = do
mft <- makefileText i
writeFile mkf mft
where
mkf = makefile_n i
handleMakefileDescr :: FilePath -> IO ()
handleMakefileDescr n = do
mkfDescr <- readFile n
either putStrLn writeMakefile . txt2Info1 $ mkfDescr | geva995/murlyka | src/Utils/MakeContents.hs | gpl-3.0 | 6,704 | 0 | 18 | 1,911 | 2,258 | 1,166 | 1,092 | 190 | 2 |
{- |
A self-contained audio playback machine.
* Load from any number of audio files
* Combine them in an arbitrary mix configuration
* Play/pause audio at any time, with precise knowledge of audio timing
Currently assumes all audio files are stereo, 44.1 kHz.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
module Jelly.AudioPipe
( AudioPipe, withPipe, seekTo, playPause, setVolumes
) where
import Jelly.Prelude
import Control.Arrow ((***))
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, isEmptyMVar,
newEmptyMVar, newMVar,
readMVar, tryPutMVar)
import Control.Exception (bracket, bracket_)
import Control.Monad.Fix (fix)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Conduit (($$), (=$=))
import qualified Data.Conduit as C
import qualified Data.Conduit.List as CL
import Data.Int (Int16)
import Data.IORef (IORef, newIORef, readIORef,
writeIORef)
import Data.List (elemIndex, foldl1', nub)
import qualified Data.Set as Set
import qualified Data.Vector.Storable as V
import Foreign (sizeOf)
import qualified Sound.File.Sndfile as Snd
import qualified Sound.File.Sndfile.Buffer.Vector as SndV
import Sound.OpenAL (($=))
import qualified Sound.OpenAL as AL
import qualified Sound.RubberBand as RB
type Stoppable = (MVar (), MVar ())
newStoppable :: IO Stoppable
newStoppable = liftA2 (,) newEmptyMVar newEmptyMVar
newStopped :: IO Stoppable
newStopped = liftA2 (,) (newMVar ()) (newMVar ())
stop :: Stoppable -> IO ()
stop s = do
requestStop s
waitTillStopped s
requestStop :: Stoppable -> IO ()
requestStop (v1, _) = do
_ <- tryPutMVar v1 ()
pure ()
waitTillStopped :: Stoppable -> IO ()
waitTillStopped (_, v2) = readMVar v2
stopRequested :: Stoppable -> IO Bool
stopRequested (v1, _ ) = fmap not $ isEmptyMVar v1
markStopped :: Stoppable -> IO ()
markStopped (_, v2) = do
_ <- tryPutMVar v2 ()
pure ()
data AudioPipe = AudioPipe
{ handles_ :: [Snd.Handle]
, sources_ :: [(AL.Source, AL.Source)]
, filler_ :: IORef Stoppable
, playing_ :: IORef Bool
, rewire_ :: forall a. (Num a, V.Storable a) =>
[(V.Vector a, V.Vector a)] -> [(V.Vector a, V.Vector a)]
, lenmax_ :: Double
, lenmin_ :: Double
, full_ :: IORef Bool
}
type Input = ([FilePath], [FilePath])
-- | Makes a new pipe, and starts loading data from position zero at 100% speed.
makePipe
:: Double -- ^ In seconds, max length of audio data loaded into the queues
-> Double -- ^ In seconds, min length of audio data before playing sources
-> [Input]
-> IO AudioPipe
makePipe lenmax lenmin ins = do
srcsL <- AL.genObjectNames $ length ins
srcsR <- AL.genObjectNames $ length ins
forM_ srcsL $ \src -> AL.sourcePosition src $= AL.Vertex3 (-1) 0 0
forM_ srcsR $ \src -> AL.sourcePosition src $= AL.Vertex3 1 0 0
let allFiles = nub $ ins >>= uncurry (++)
hnds <- forM allFiles $ \f -> Snd.openFile f Snd.ReadMode Snd.defaultInfo
let fileIndex :: FilePath -> Int
fileIndex f = case elemIndex f allFiles of
Nothing -> error "makePipe: impossible! file not found in list"
Just i -> i
let insNumbered :: [([Int], [Int])]
insNumbered = map (map fileIndex *** map fileIndex) ins
let rewire :: (Num a, V.Storable a) =>
[(V.Vector a, V.Vector a)] -> [(V.Vector a, V.Vector a)]
rewire loaded = do
(pos, neg) <- insNumbered
let pos' = map (loaded !!) pos
neg' = map (V.map negate *** V.map negate) $ map (loaded !!) neg
pure $ foldl1'
(\(l1, r1) (l2, r2) -> (V.zipWith (+) l1 l2, V.zipWith (+) r1 r2))
$ pos' ++ neg'
filler <- newStopped >>= newIORef
playing <- newIORef False
full <- newIORef False
let pipe = AudioPipe
{ handles_ = hnds
, sources_ = zip srcsL srcsR
, filler_ = filler
, playing_ = playing
, rewire_ = rewire
, lenmax_ = lenmax
, lenmin_ = lenmin
, full_ = full
}
seekTo 0 1 pipe
pure pipe
closePipe :: AudioPipe -> IO ()
closePipe pipe = do
readIORef (filler_ pipe) >>= stop
writeIORef (playing_ pipe) False
forM_ (handles_ pipe) Snd.hClose
forM_ (sources_ pipe) $ \(srcL, srcR) -> AL.deleteObjectNames [srcL, srcR]
withPipe :: Double -> Double -> [Input] -> (AudioPipe -> IO a) -> IO a
withPipe lenmax lenmin ins = withALContext
. bracket (makePipe lenmax lenmin ins) closePipe
withALContext :: IO a -> IO a
withALContext act = bracket
— AL.openDevice Nothing
>>= maybe (error "couldn't open audio device") pure
— AL.closeDevice
— \dev -> bracket
— AL.createContext dev []
>>= maybe (error "couldn't create audio context") pure
— AL.destroyContext
— \ctxt -> bracket_
— AL.currentContext $= Just ctxt
— AL.currentContext $= Nothing
— act
-- | If paused, seeks to the new position and begins queueing data.
-- If playing, pauses, seeks to the new position, and plays once data is queued.
seekTo
:: Double -- ^ Position in seconds
-> Double -- ^ Playing speed: ratio of heard seconds to file seconds
-> AudioPipe
-> IO ()
seekTo pos speed pipe = readIORef (playing_ pipe) >>= \case
True -> playPause pipe >> seekTo pos speed pipe >> playPause pipe
False -> do
readIORef (filler_ pipe) >>= stop
forM_ (handles_ pipe) $ \h -> let
len = Snd.frames $ Snd.hInfo h
newPos = min len $ floor $ pos * 44100
in Snd.hSeek h Snd.AbsoluteSeek newPos
s <- newStoppable
let source :: C.Source IO [V.Vector Int16]
source = case speed of
1 -> load (handles_ pipe) =$= rewire
_ -> load (handles_ pipe) =$= rewire =$= stretch 44100 numOut speed 1 =$= convert
rewire :: (V.Storable e, Num e) => C.Conduit [V.Vector e] IO [V.Vector e]
rewire = CL.map $ breakPairs . rewire_ pipe . joinPairs
numOut = length sourcesFlat
sourcesFlat = breakPairs $ sources_ pipe
_ <- forkIO $ source $$ do
let loop :: Int -> Set.Set AL.Buffer -> C.Sink [V.Vector Int16] IO ()
loop q bufs = liftIO (stopRequested s) >>= \case
True -> liftIO $ do
AL.stop sourcesFlat
forM_ sourcesFlat $ \src ->
AL.buffer src $= Nothing
AL.rewind sourcesFlat
writeIORef (full_ pipe) True
fix $ \loopCleanup -> do
_ <- AL.get AL.alErrors
AL.deleteObjectNames $ Set.toList bufs
AL.get AL.alErrors >>= \case
[] -> markStopped s
_ -> shortWait >> loopCleanup
False -> do
canRemove <- liftIO $ fmap minimum $
mapM (AL.get . AL.buffersProcessed) sourcesFlat
bufsRemoved <- liftIO $ forM sourcesFlat $ \src ->
AL.unqueueBuffers src canRemove
p <- liftIO $ fmap sum $ forM (head bufsRemoved) $ \buf -> do
AL.BufferData (AL.MemoryRegion _ size) _ _
<- AL.get $ AL.bufferData buf
pure $ fromIntegral size `quot` 2
let q' = q - p
bufs' = Set.difference bufs $ Set.fromList $ concat bufsRemoved
liftIO $ AL.deleteObjectNames $ concat bufsRemoved
if q' >= floor (44100 * lenmax_ pipe)
then shortWait >> loop q' bufs'
else C.await >>= \case
Nothing -> do -- shouldn't happen
liftIO $ requestStop s
loop q' bufs'
Just vs -> do
bufsNew <- liftIO $ mapM makeBuffer vs
let q'' = q' + V.length (head vs)
bufs'' = Set.union bufs' $ Set.fromList bufsNew
liftIO $ forM_ (zip sourcesFlat bufsNew) $ \(src, buf) ->
AL.queueBuffers src [buf]
liftIO $ when (q'' >= floor (44100 * lenmin_ pipe))
$ writeIORef (full_ pipe) True
loop q'' bufs''
loop 0 Set.empty
writeIORef (filler_ pipe) s
-- | Converts a vector of samples to an OpenAL buffer.
makeBuffer :: V.Vector Int16 -> IO AL.Buffer
makeBuffer v = do
buf <- liftIO AL.genObjectName
V.unsafeWith v $ \p -> do
let mem = AL.MemoryRegion p $ fromIntegral vsize
vsize = V.length v * sizeOf (v V.! 0)
AL.bufferData buf $= AL.BufferData mem AL.Mono16 44100
pure buf
-- | Translates samples from floats (Rubber Band) to 16-bit ints (OpenAL).
convert :: (Monad m) => C.Conduit [V.Vector Float] m [V.Vector Int16]
convert =
CL.map $ map $ V.map $ \f -> round $ f * fromIntegral (maxBound :: Int16)
loadBlockSize :: Int
loadBlockSize = 5000
load
:: (MonadIO m, Snd.Sample e, V.Storable e, Snd.Buffer SndV.Buffer e, Num e)
=> [Snd.Handle] -> C.Source m [V.Vector e]
load = C.mapOutput concat . C.sequenceSources . map loadOne
loadOne
:: (MonadIO m, Snd.Sample e, V.Storable e, Snd.Buffer SndV.Buffer e, Num e)
=> Snd.Handle -> C.Source m [V.Vector e]
loadOne h = let
chans = Snd.channels $ Snd.hInfo h
fullBlock b = if V.length b == loadBlockSize
then b
else V.take loadBlockSize $ b V.++ V.replicate loadBlockSize 0
in fix $ \loop -> liftIO (Snd.hGetBuffer h loadBlockSize) >>= \case
Nothing -> do
C.yield $ replicate chans $ V.replicate loadBlockSize 0
loop
Just buf -> do
C.yield $ map fullBlock $ deinterleave chans $ SndV.fromBuffer buf
loop
breakBlock
:: Int -- ^ Maximum size of the output blocks
-> [V.Vector Float] -- ^ One vector per channel
-> [[V.Vector Float]]
breakBlock maxSize chans = if V.length (head chans) <= maxSize
then [chans]
else let
pairs = map (V.splitAt maxSize) chans
in map fst pairs : breakBlock maxSize (map snd pairs)
-- | An arbitrary \"this thread has nothing to do immediately\" wait.
shortWait :: (MonadIO m) => m ()
shortWait = liftIO $ threadDelay 1000
stretch :: (MonadIO m)
=> RB.SampleRate -> RB.NumChannels -> RB.TimeRatio -> RB.PitchScale
-> C.Conduit [V.Vector Float] m [V.Vector Float]
stretch a b c d = do
let opts = RB.defaultOptions { RB.oProcess = RB.RealTime }
s <- liftIO $ RB.new a b opts c d
liftIO $ RB.setMaxProcessSize s loadBlockSize
fix $ \loop -> liftIO (RB.available s) >>= \case
Nothing -> pure () -- shouldn't happen?
Just 0 -> liftIO (RB.getSamplesRequired s) >>= \case
0 -> shortWait >> loop
_ -> C.await >>= \case
Nothing -> pure ()
Just block -> do
forM_ (breakBlock loadBlockSize block) $ \blk ->
liftIO $ RB.process s blk False
loop
Just n -> liftIO (RB.retrieve s $ min n loadBlockSize) >>= C.yield >> loop
-- | If paused, waits till data is queued, then starts playing.
-- If playing, pauses. Data will already be queued.
playPause :: AudioPipe -> IO ()
playPause pipe = readIORef (playing_ pipe) >>= \case
True -> do
writeIORef (playing_ pipe) False
AL.pause sourcesFlat
False -> fix $ \loop -> readIORef (full_ pipe) >>= \case
False -> shortWait >> loop
True -> do
writeIORef (playing_ pipe) True
AL.play sourcesFlat
where sourcesFlat = breakPairs $ sources_ pipe
breakPairs :: [(a, a)] -> [a]
breakPairs xs = xs >>= \(x, y) -> [x, y]
joinPairs :: [a] -> [(a, a)]
joinPairs (x : y : xs) = (x, y) : joinPairs xs
joinPairs [] = []
joinPairs [_] = error "joinPairs: odd number of elements"
-- | Sets volumes of the audio sources. Doesn't care whether playing/paused.
setVolumes :: [Double] -> AudioPipe -> IO ()
setVolumes vols pipe = forM_ (zip vols $ sources_ pipe) $ \(vol, (srcL, srcR)) -> do
AL.sourceGain srcL $= realToFrac vol
AL.sourceGain srcR $= realToFrac vol
-- | Given a vector with interleaved samples, like @[L0, R0, L1, R1, ...]@,
-- converts it into @[[L0, L1, ...], [R0, R1, ...]]@.
deinterleave :: (V.Storable a)
=> Int -- ^ The number of channels to split into.
-> V.Vector a
-> [V.Vector a]
deinterleave n v = do
let len = V.length v `div` n
i <- [0 .. n - 1]
pure $ V.generate len $ \j -> v V.! (n * j + i)
| mtolly/jelly | src/Jelly/AudioPipe.hs | gpl-3.0 | 12,775 | 8 | 30 | 3,830 | 4,223 | 2,148 | 2,075 | 281 | 7 |
-- otsu algorithm for binarization
module Otsu (threshold, binarize) where
import qualified Data.Array.Repa as R
import qualified Data.Map as Map
import Data.Array.Repa (U, D, Z (..), (:.)(..))
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as Vm
import qualified Data.List as L
import qualified PixelMaps as PMaps
import Pixel
import qualified YCbCr
histogram :: R.Array U sh Double -> Int -> IO [Int]
histogram arr buckets = do
hist <- Vm.replicate buckets 0
V.mapM_ (updateHist hist) vec
frozen <- V.unsafeFreeze hist
return $ V.toList frozen
where vec = R.toUnboxed arr
max = V.maximum vec
min = V.minimum vec
d = max - min + 1.0
updateHist vec val = do
let bucket = floor ((val - min) / d * fromIntegral buckets)
Vm.modify vec (+1) bucket
threshold :: R.Array U sh Double -> Int -> IO Double
threshold arr buckets = do
hist <- histogram arr buckets
return $ histThreshold hist
binarize :: R.Array U R.DIM2 RGB8 -> IO (R.Array D R.DIM2 RGB8)
binarize arr = do
yArr <- R.computeUnboxedP $ R.map YCbCr.y arr
th <- threshold yArr 256
return $ R.map (PMaps.binarizeY' 0 th) yArr
histThreshold :: [Int] -> Double
histThreshold hist = (th1 + th2) / 2.0
where hist' = map fromIntegral hist
(wB, wF, th1, th2, sumB, max, break) =
foldl f (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, False) (zip [0.0..] hist')
total = fromIntegral $ L.sum hist
sum = foldl (\acc (i, v) -> acc + i*v ) 0.0 (zip [1.0..] (L.tail hist'))
f (wB, wF, th1, th2, sumB, max, break) (index, bucketValue) =
if break then (wB, wF, th1, th2, sumB, max, True)
else
let wB' = wB + bucketValue
wF' = total - wB' in
if wB' == 0.0 then (wB', wF, th1, th2, sumB, max, False)
else
if wF' == 0.0 then (wB', wF', th1, th2, sumB, max, True)
else
let sumB' = sumB + index * bucketValue in
fInter (wB', wF', th1, th2, sumB', max) (index, bucketValue)
fInter (wB, wF, th1, th2, sumB, max) (index, bucketValue) =
let mB = sumB / wB
mF = (sum - sumB) / wF
between = wB * wF * (mB - mF) * (mB - mF) in
if between >= max then
if between > max then (wB, wF, index, index, sumB, between, False)
else (wB, wF, index, th2, sumB, between, False)
else (wB, wF, th1, th2, sumB, max, False)
| mikolajsacha/HaskellPics | otsu.hs | gpl-3.0 | 2,555 | 1 | 24 | 792 | 1,022 | 575 | 447 | 55 | 6 |
{-# 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.ImportExport.ListJobs
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation returns the jobs associated with the requester. AWS
-- Import\/Export lists the jobs in reverse chronological order based on
-- the date of creation. For example if Job Test1 was created 2009Dec30 and
-- Test2 was created 2010Feb05, the ListJobs operation would return Test2
-- followed by Test1.
--
-- /See:/ <http://docs.aws.amazon.com/AWSImportExport/latest/DG/WebListJobs.html AWS API Reference> for ListJobs.
--
-- This operation returns paginated results.
module Network.AWS.ImportExport.ListJobs
(
-- * Creating a Request
listJobs
, ListJobs
-- * Request Lenses
, ljAPIVersion
, ljMarker
, ljMaxJobs
-- * Destructuring the Response
, listJobsResponse
, ListJobsResponse
-- * Response Lenses
, ljrsJobs
, ljrsIsTruncated
, ljrsResponseStatus
) where
import Network.AWS.ImportExport.Types
import Network.AWS.ImportExport.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Input structure for the ListJobs operation.
--
-- /See:/ 'listJobs' smart constructor.
data ListJobs = ListJobs'
{ _ljAPIVersion :: !(Maybe Text)
, _ljMarker :: !(Maybe Text)
, _ljMaxJobs :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobs' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljAPIVersion'
--
-- * 'ljMarker'
--
-- * 'ljMaxJobs'
listJobs
:: ListJobs
listJobs =
ListJobs'
{ _ljAPIVersion = Nothing
, _ljMarker = Nothing
, _ljMaxJobs = Nothing
}
-- | Undocumented member.
ljAPIVersion :: Lens' ListJobs (Maybe Text)
ljAPIVersion = lens _ljAPIVersion (\ s a -> s{_ljAPIVersion = a});
-- | Undocumented member.
ljMarker :: Lens' ListJobs (Maybe Text)
ljMarker = lens _ljMarker (\ s a -> s{_ljMarker = a});
-- | Undocumented member.
ljMaxJobs :: Lens' ListJobs (Maybe Int)
ljMaxJobs = lens _ljMaxJobs (\ s a -> s{_ljMaxJobs = a});
instance AWSPager ListJobs where
page rq rs
| stop (rs ^? ljrsJobs . _last . jobJobId) = Nothing
| stop (rs ^. ljrsJobs) = Nothing
| otherwise =
Just $ rq &
ljMarker .~ rs ^? ljrsJobs . _last . jobJobId
instance AWSRequest ListJobs where
type Rs ListJobs = ListJobsResponse
request = postQuery importExport
response
= receiveXMLWrapper "ListJobsResult"
(\ s h x ->
ListJobsResponse' <$>
(x .@? "Jobs" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "IsTruncated")
<*> (pure (fromEnum s)))
instance ToHeaders ListJobs where
toHeaders = const mempty
instance ToPath ListJobs where
toPath = const "/"
instance ToQuery ListJobs where
toQuery ListJobs'{..}
= mconcat
["Operation=ListJobs",
"Action" =: ("ListJobs" :: ByteString),
"Version" =: ("2010-06-01" :: ByteString),
"APIVersion" =: _ljAPIVersion, "Marker" =: _ljMarker,
"MaxJobs" =: _ljMaxJobs]
-- | Output structure for the ListJobs operation.
--
-- /See:/ 'listJobsResponse' smart constructor.
data ListJobsResponse = ListJobsResponse'
{ _ljrsJobs :: !(Maybe [Job])
, _ljrsIsTruncated :: !(Maybe Bool)
, _ljrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListJobsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ljrsJobs'
--
-- * 'ljrsIsTruncated'
--
-- * 'ljrsResponseStatus'
listJobsResponse
:: Int -- ^ 'ljrsResponseStatus'
-> ListJobsResponse
listJobsResponse pResponseStatus_ =
ListJobsResponse'
{ _ljrsJobs = Nothing
, _ljrsIsTruncated = Nothing
, _ljrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
ljrsJobs :: Lens' ListJobsResponse [Job]
ljrsJobs = lens _ljrsJobs (\ s a -> s{_ljrsJobs = a}) . _Default . _Coerce;
-- | Undocumented member.
ljrsIsTruncated :: Lens' ListJobsResponse (Maybe Bool)
ljrsIsTruncated = lens _ljrsIsTruncated (\ s a -> s{_ljrsIsTruncated = a});
-- | The response status code.
ljrsResponseStatus :: Lens' ListJobsResponse Int
ljrsResponseStatus = lens _ljrsResponseStatus (\ s a -> s{_ljrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-importexport/gen/Network/AWS/ImportExport/ListJobs.hs | mpl-2.0 | 5,246 | 0 | 16 | 1,257 | 926 | 541 | 385 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.SearchForSeries
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- SearchForSeries returns a list of matching series. See [Search
-- Transaction]
-- (http:\/\/dicom.nema.org\/medical\/dicom\/current\/output\/html\/part18.html#sect_10.6).
-- For details on the implementation of SearchForSeries, see [Search
-- transaction](https:\/\/cloud.google.com\/healthcare\/docs\/dicom#search_transaction)
-- in the Cloud Healthcare API conformance statement. For samples that show
-- how to call SearchForSeries, see [Searching for studies, series,
-- instances, and
-- frames](https:\/\/cloud.google.com\/healthcare\/docs\/how-tos\/dicomweb#searching_for_studies_series_instances_and_frames).
--
-- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.dicomStores.searchForSeries@.
module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.DicomStores.SearchForSeries
(
-- * REST Resource
ProjectsLocationsDataSetsDicomStoresSearchForSeriesResource
-- * Creating a Request
, projectsLocationsDataSetsDicomStoresSearchForSeries
, ProjectsLocationsDataSetsDicomStoresSearchForSeries
-- * Request Lenses
, pldsdssfsParent
, pldsdssfsXgafv
, pldsdssfsUploadProtocol
, pldsdssfsAccessToken
, pldsdssfsUploadType
, pldsdssfsCallback
, pldsdssfsDicomWebPath
) where
import Network.Google.Healthcare.Types
import Network.Google.Prelude
-- | A resource alias for @healthcare.projects.locations.datasets.dicomStores.searchForSeries@ method which the
-- 'ProjectsLocationsDataSetsDicomStoresSearchForSeries' request conforms to.
type ProjectsLocationsDataSetsDicomStoresSearchForSeriesResource
=
"v1" :>
Capture "parent" Text :>
"dicomWeb" :>
Capture "dicomWebPath" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] HTTPBody
-- | SearchForSeries returns a list of matching series. See [Search
-- Transaction]
-- (http:\/\/dicom.nema.org\/medical\/dicom\/current\/output\/html\/part18.html#sect_10.6).
-- For details on the implementation of SearchForSeries, see [Search
-- transaction](https:\/\/cloud.google.com\/healthcare\/docs\/dicom#search_transaction)
-- in the Cloud Healthcare API conformance statement. For samples that show
-- how to call SearchForSeries, see [Searching for studies, series,
-- instances, and
-- frames](https:\/\/cloud.google.com\/healthcare\/docs\/how-tos\/dicomweb#searching_for_studies_series_instances_and_frames).
--
-- /See:/ 'projectsLocationsDataSetsDicomStoresSearchForSeries' smart constructor.
data ProjectsLocationsDataSetsDicomStoresSearchForSeries =
ProjectsLocationsDataSetsDicomStoresSearchForSeries'
{ _pldsdssfsParent :: !Text
, _pldsdssfsXgafv :: !(Maybe Xgafv)
, _pldsdssfsUploadProtocol :: !(Maybe Text)
, _pldsdssfsAccessToken :: !(Maybe Text)
, _pldsdssfsUploadType :: !(Maybe Text)
, _pldsdssfsCallback :: !(Maybe Text)
, _pldsdssfsDicomWebPath :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsDataSetsDicomStoresSearchForSeries' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pldsdssfsParent'
--
-- * 'pldsdssfsXgafv'
--
-- * 'pldsdssfsUploadProtocol'
--
-- * 'pldsdssfsAccessToken'
--
-- * 'pldsdssfsUploadType'
--
-- * 'pldsdssfsCallback'
--
-- * 'pldsdssfsDicomWebPath'
projectsLocationsDataSetsDicomStoresSearchForSeries
:: Text -- ^ 'pldsdssfsParent'
-> Text -- ^ 'pldsdssfsDicomWebPath'
-> ProjectsLocationsDataSetsDicomStoresSearchForSeries
projectsLocationsDataSetsDicomStoresSearchForSeries pPldsdssfsParent_ pPldsdssfsDicomWebPath_ =
ProjectsLocationsDataSetsDicomStoresSearchForSeries'
{ _pldsdssfsParent = pPldsdssfsParent_
, _pldsdssfsXgafv = Nothing
, _pldsdssfsUploadProtocol = Nothing
, _pldsdssfsAccessToken = Nothing
, _pldsdssfsUploadType = Nothing
, _pldsdssfsCallback = Nothing
, _pldsdssfsDicomWebPath = pPldsdssfsDicomWebPath_
}
-- | The name of the DICOM store that is being accessed. For example,
-- \`projects\/{project_id}\/locations\/{location_id}\/datasets\/{dataset_id}\/dicomStores\/{dicom_store_id}\`.
pldsdssfsParent :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries Text
pldsdssfsParent
= lens _pldsdssfsParent
(\ s a -> s{_pldsdssfsParent = a})
-- | V1 error format.
pldsdssfsXgafv :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries (Maybe Xgafv)
pldsdssfsXgafv
= lens _pldsdssfsXgafv
(\ s a -> s{_pldsdssfsXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pldsdssfsUploadProtocol :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries (Maybe Text)
pldsdssfsUploadProtocol
= lens _pldsdssfsUploadProtocol
(\ s a -> s{_pldsdssfsUploadProtocol = a})
-- | OAuth access token.
pldsdssfsAccessToken :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries (Maybe Text)
pldsdssfsAccessToken
= lens _pldsdssfsAccessToken
(\ s a -> s{_pldsdssfsAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pldsdssfsUploadType :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries (Maybe Text)
pldsdssfsUploadType
= lens _pldsdssfsUploadType
(\ s a -> s{_pldsdssfsUploadType = a})
-- | JSONP
pldsdssfsCallback :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries (Maybe Text)
pldsdssfsCallback
= lens _pldsdssfsCallback
(\ s a -> s{_pldsdssfsCallback = a})
-- | The path of the SearchForSeries DICOMweb request. For example,
-- \`series\` or \`studies\/{study_uid}\/series\`.
pldsdssfsDicomWebPath :: Lens' ProjectsLocationsDataSetsDicomStoresSearchForSeries Text
pldsdssfsDicomWebPath
= lens _pldsdssfsDicomWebPath
(\ s a -> s{_pldsdssfsDicomWebPath = a})
instance GoogleRequest
ProjectsLocationsDataSetsDicomStoresSearchForSeries
where
type Rs
ProjectsLocationsDataSetsDicomStoresSearchForSeries
= HTTPBody
type Scopes
ProjectsLocationsDataSetsDicomStoresSearchForSeries
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsDataSetsDicomStoresSearchForSeries'{..}
= go _pldsdssfsParent _pldsdssfsDicomWebPath
_pldsdssfsXgafv
_pldsdssfsUploadProtocol
_pldsdssfsAccessToken
_pldsdssfsUploadType
_pldsdssfsCallback
(Just AltJSON)
healthcareService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsDataSetsDicomStoresSearchForSeriesResource)
mempty
| brendanhay/gogol | gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/DicomStores/SearchForSeries.hs | mpl-2.0 | 7,869 | 0 | 17 | 1,431 | 794 | 471 | 323 | 126 | 1 |
module Network.HighHock.Controller (
Controller,
newController,
stop,
trigger,
wait,
isStopped,
ticker) where
import Control.Monad (void, when)
import qualified Control.Concurrent.STM.TMVar as STM
import Control.Monad.STM (atomically)
import Control.Concurrent (threadDelay)
import Data.Maybe (fromMaybe)
data Controller = Controller (STM.TMVar Bool)
newController :: IO Controller
newController = atomically $ fmap Controller STM.newEmptyTMVar
stop :: Controller -> IO ()
stop (Controller c) = void $ atomically $ do
void $ STM.tryTakeTMVar c
STM.putTMVar c False
-- | Returns False if the controller has been stopped
trigger :: Controller -> IO Bool
trigger (Controller c) = atomically $ do
v <- STM.tryTakeTMVar c
let v' = fromMaybe True v
STM.putTMVar c v'
return v'
-- | Returns False if the controller has been 'stopped'
wait :: Controller -> IO Bool
wait (Controller c) = atomically $ do
v <- STM.takeTMVar c
when (not v) $ STM.putTMVar c v
return v
-- | Doesn't block
isStopped :: Controller -> IO Bool
isStopped (Controller c) = atomically $ do
v <- STM.tryTakeTMVar c
case v of
Just v' -> STM.putTMVar c v'
_ -> return ()
return $ v == Just False
ticker :: Controller -> Int -> IO ()
ticker c i =
trigger c >>= \s ->
when s $ threadDelay i >> ticker c i
| bluepeppers/highhockwho | src/Network/HighHock/Controller.hs | agpl-3.0 | 1,320 | 0 | 12 | 264 | 478 | 239 | 239 | 42 | 2 |
{-# LANGUAGE TemplateHaskell #-}
--------------------------------------------------
-- |
-- Module : Crypto.Noise.Internal.CipherState
-- Maintainer : John Galt <[email protected]>
-- Stability : experimental
-- Portability : POSIX
module Crypto.Noise.Internal.CipherState where
import Control.Exception.Safe
import Control.Lens
import Crypto.Noise.Cipher
import Crypto.Noise.Exception
data CipherState c =
CipherState { _csk :: Maybe (SymmetricKey c)
, _csn :: Nonce c
} deriving Show
$(makeLenses ''CipherState)
-- | Creates a new CipherState with an optional symmetric key and a zero nonce.
cipherState :: Cipher c
=> Maybe (SymmetricKey c)
-> CipherState c
cipherState sk = CipherState sk cipherZeroNonce
-- | Encrypts the provided plaintext and increments the nonce. If this
-- CipherState does not have a key associated with it, the plaintext
-- will be returned.
encryptWithAd :: (MonadThrow m, Cipher c)
=> AssocData
-> Plaintext
-> CipherState c
-> m (Ciphertext c, CipherState c)
encryptWithAd ad plaintext cs
| validNonce cs = return (result, newState)
| otherwise = throwM MessageLimitReached
where
result = maybe (cipherBytesToText plaintext)
(\k -> cipherEncrypt k (cs ^. csn) ad plaintext)
$ cs ^. csk
newState = cs & csn %~ cipherIncNonce
-- | Decrypts the provided ciphertext and increments the nonce. If this
-- CipherState does not have a key associated with it, the ciphertext
-- will be returned. If the CipherState does have a key and decryption
-- fails, a @DecryptionError@ will be returned.
decryptWithAd :: (MonadThrow m, Cipher c)
=> AssocData
-> Ciphertext c
-> CipherState c
-> m (Plaintext, CipherState c)
decryptWithAd ad ct cs
| validNonce cs =
maybe (throwM DecryptionError)
(\x -> return (x, newState))
result
| otherwise = throwM MessageLimitReached
where
result = maybe (Just . cipherTextToBytes $ ct)
(\k -> cipherDecrypt k (cs ^. csn) ad ct)
$ cs ^. csk
newState = cs & csn %~ cipherIncNonce
-- | Rekeys the CipherState. If a key has not been established yet, the
-- CipherState is returned unmodified.
rekey :: Cipher c
=> CipherState c
-> CipherState c
rekey cs = cs & csk %~ (<*>) (pure cipherRekey)
-- | Tests whether the Nonce contained within a CipherState is valid (less
-- than the maximum allowed).
validNonce :: Cipher c
=> CipherState c
-> Bool
validNonce cs = cs ^. csn < cipherMaxNonce
| centromere/cacophony | src/Crypto/Noise/Internal/CipherState.hs | unlicense | 2,721 | 0 | 14 | 747 | 560 | 294 | 266 | 50 | 1 |
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Internal.Picture where
import qualified "codeworld-api" CodeWorld as CW
import GHC.Stack
import Internal.Color
import Internal.Num
import Internal.Text
import "base" Prelude ((.), ($), map)
type Point = (Number, Number)
toCWPoint :: Point -> CW.Point
toCWPoint (x, y) = (toDouble x, toDouble y)
fromCWPoint :: CW.Point -> Point
fromCWPoint (x, y) = (fromDouble x, fromDouble y)
translatedPoint :: (Point, Number, Number) -> Point
translatedPoint (p, x, y) =
fromCWPoint (CW.translatedPoint (toDouble x) (toDouble y) (toCWPoint p))
rotatedPoint :: (Point, Number) -> Point
rotatedPoint (p, a) =
fromCWPoint (CW.rotatedPoint (toDouble (pi * a / 180)) (toCWPoint p))
scaledPoint :: (Point, Number, Number) -> Point
scaledPoint (p, x, y) =
fromCWPoint (CW.scaledPoint (toDouble x) (toDouble y) (toCWPoint p))
dilatedPoint :: (Point, Number) -> Point
dilatedPoint (p, k) =
fromCWPoint (CW.dilatedPoint (toDouble k) (toCWPoint p))
type Vector = (Number, Number)
toCWVect :: Vector -> CW.Vector
toCWVect = toCWPoint
fromCWVect :: CW.Vector -> Vector
fromCWVect = fromCWPoint
vectorLength :: Vector -> Number
vectorLength v = fromDouble (CW.vectorLength (toCWVect v))
vectorDirection :: Vector -> Number
vectorDirection v = 180 / pi * fromDouble (CW.vectorDirection (toCWVect v))
vectorSum :: (Vector, Vector) -> Vector
vectorSum (v, w) = fromCWVect (CW.vectorSum (toCWVect v) (toCWVect w))
vectorDifference :: (Vector, Vector) -> Vector
vectorDifference (v, w) =
fromCWVect (CW.vectorDifference (toCWVect v) (toCWVect w))
scaledVector :: (Vector, Number) -> Vector
scaledVector (v, k) = fromCWVect (CW.scaledVector (toDouble k) (toCWVect v))
rotatedVector :: (Vector, Number) -> Vector
rotatedVector (v, k) =
fromCWVect (CW.rotatedVector (toDouble (pi * k / 180)) (toCWVect v))
dotProduct :: (Vector, Vector) -> Number
dotProduct (v, w) = fromDouble (CW.dotProduct (toCWVect v) (toCWVect w))
newtype Picture = CWPic
{ toCWPic :: CW.Picture
}
data Font
= Serif
| SansSerif
| Monospace
| Handwriting
| Fancy
| NamedFont !Text
data TextStyle
= Plain
| Italic
| Bold
-- | A blank picture
blank :: HasCallStack => Picture
blank = withFrozenCallStack $ CWPic CW.blank
-- | A thin sequence of line segments with these endpoints
polyline :: HasCallStack => [Point] -> Picture
polyline ps = withFrozenCallStack $ CWPic (CW.polyline (map toCWVect ps))
-- | A thin sequence of line segments with these endpoints
path :: HasCallStack => [Point] -> Picture
path ps = withFrozenCallStack $ CWPic (CW.path (map toCWVect ps))
{-# WARNING path ["Please use polyline(...) instead of path(...).",
"path may be removed July 2019."] #-}
-- | A thin sequence of line segments, with these endpoints and line width
thickPolyline :: HasCallStack => ([Point], Number) -> Picture
thickPolyline (ps, n) = withFrozenCallStack $ CWPic (CW.thickPolyline (toDouble n) (map toCWVect ps))
-- | A thin sequence of line segments, with these endpoints and line width
thickPath :: HasCallStack => ([Point], Number) -> Picture
thickPath (ps, n) = withFrozenCallStack $ CWPic (CW.thickPath (toDouble n) (map toCWVect ps))
{-# WARNING thickPath ["Please use thickPolyline(...) instead of thickPath(...).",
"thickPath may be removed July 2019."] #-}
-- | A thin polygon with these points as vertices
polygon :: HasCallStack => [Point] -> Picture
polygon ps = withFrozenCallStack $ CWPic (CW.polygon (map toCWVect ps))
-- | A thin polygon with these points as vertices
thickPolygon :: HasCallStack => ([Point], Number) -> Picture
thickPolygon (ps, n) = withFrozenCallStack $ CWPic (CW.thickPolygon (toDouble n) (map toCWVect ps))
-- | A solid polygon with these points as vertices
solidPolygon :: HasCallStack => [Point] -> Picture
solidPolygon ps = withFrozenCallStack $ CWPic (CW.solidPolygon (map toCWVect ps))
-- | A thin curve passing through these points.
curve :: HasCallStack => [Point] -> Picture
curve ps = withFrozenCallStack $ CWPic (CW.curve (map toCWVect ps))
-- | A thick curve passing through these points, with this line width
thickCurve :: HasCallStack => ([Point], Number) -> Picture
thickCurve (ps, n) = withFrozenCallStack $ CWPic (CW.thickCurve (toDouble n) (map toCWVect ps))
-- | A thin closed curve passing through these points.
closedCurve :: HasCallStack => [Point] -> Picture
closedCurve ps = withFrozenCallStack $ CWPic (CW.closedCurve (map toCWVect ps))
-- | A thick closed curve passing through these points, with this line width.
thickClosedCurve :: HasCallStack => ([Point], Number) -> Picture
thickClosedCurve (ps, n) = withFrozenCallStack $ CWPic (CW.thickClosedCurve (toDouble n) (map toCWVect ps))
-- | A solid closed curve passing through these points.
solidClosedCurve :: HasCallStack => [Point] -> Picture
solidClosedCurve ps = CWPic (CW.solidClosedCurve (map toCWVect ps))
-- | A thin rectangle, with this width and height
rectangle :: HasCallStack => (Number, Number) -> Picture
rectangle (w, h) = withFrozenCallStack $ CWPic (CW.rectangle (toDouble w) (toDouble h))
-- | A solid rectangle, with this width and height
solidRectangle :: HasCallStack => (Number, Number) -> Picture
solidRectangle (w, h) = withFrozenCallStack $ CWPic (CW.solidRectangle (toDouble w) (toDouble h))
-- | A thick rectangle, with this width and height and line width
thickRectangle :: HasCallStack => (Number, Number, Number) -> Picture
thickRectangle (w, h, lw) =
withFrozenCallStack $ CWPic (CW.thickRectangle (toDouble lw) (toDouble w) (toDouble h))
-- | A thin circle, with this radius
circle :: HasCallStack => Number -> Picture
circle r = withFrozenCallStack $ CWPic (CW.circle (toDouble r))
-- | A solid circle, with this radius
solidCircle :: HasCallStack => Number -> Picture
solidCircle r = withFrozenCallStack $ CWPic (CW.solidCircle (toDouble r))
-- | A thick circle, with this radius and line width
thickCircle :: HasCallStack => (Number, Number) -> Picture
thickCircle (r, w) = withFrozenCallStack $ CWPic (CW.thickCircle (toDouble w) (toDouble r))
-- | A thin arc, starting and ending at these angles, with this radius
arc :: HasCallStack => (Number, Number, Number) -> Picture
arc (b, e, r) = withFrozenCallStack $ CWPic
(CW.arc (toDouble (pi * b / 180)) (toDouble (pi * e / 180)) (toDouble r))
-- | A solid sector of a circle (i.e., a pie slice) starting and ending at these
-- angles, with this radius
sector :: HasCallStack => (Number, Number, Number) -> Picture
sector (b, e, r) = withFrozenCallStack $ CWPic
(CW.sector
(toDouble (pi * b / 180))
(toDouble (pi * e / 180))
(toDouble r))
-- | A thick arc, starting and ending at these angles, with this radius and
-- line width
thickArc :: HasCallStack => (Number, Number, Number, Number) -> Picture
thickArc (b, e, r, w) = withFrozenCallStack $ CWPic
(CW.thickArc
(toDouble w)
(toDouble (pi * b / 180))
(toDouble (pi * e / 180))
(toDouble r))
-- | A rendering of text characters.
lettering :: HasCallStack => Text -> Picture
lettering t = withFrozenCallStack $ CWPic (CW.lettering (fromCWText t))
-- | A rendering of text characters.
text :: HasCallStack => Text -> Picture
text t = withFrozenCallStack $ CWPic (CW.lettering (fromCWText t))
{-# WARNING text ["Please use lettering(...) instead of text(...).",
"text may be removed July 2019."] #-}
-- | A rendering of text characters, with a specific choice of font and style.
styledLettering :: HasCallStack => (Text, Font, TextStyle) -> Picture
styledLettering (t, f, s) =
withFrozenCallStack $ CWPic (CW.styledLettering (fromCWStyle s) (fromCWFont f) (fromCWText t))
where
fromCWStyle Plain = CW.Plain
fromCWStyle Bold = CW.Bold
fromCWStyle Italic = CW.Italic
fromCWFont Serif = CW.Serif
fromCWFont SansSerif = CW.SansSerif
fromCWFont Monospace = CW.Monospace
fromCWFont Handwriting = CW.Handwriting
fromCWFont Fancy = CW.Fancy
fromCWFont (NamedFont fnt) = CW.NamedFont (fromCWText fnt)
-- | A rendering of text characters, with a specific choice of font and style.
styledText :: HasCallStack => (Text, Font, TextStyle) -> Picture
styledText args = withFrozenCallStack $ styledLettering args
{-# WARNING styledText ["Please use styledLettering(...) instead of styledText(...).",
"styledText may be removed July 2019."] #-}
-- | A picture drawn entirely in this color.
colored :: HasCallStack => (Picture, Color) -> Picture
colored (p, c) = withFrozenCallStack $ CWPic (CW.colored (toCWColor c) (toCWPic p))
-- | A picture drawn entirely in this color.
coloured :: HasCallStack => (Picture, Color) -> Picture
coloured args = withFrozenCallStack $ colored args
-- | A picture drawn translated in these directions.
translated :: HasCallStack => (Picture, Number, Number) -> Picture
translated (p, x, y) =
withFrozenCallStack $ CWPic (CW.translated (toDouble x) (toDouble y) (toCWPic p))
-- | A picture scaled by these factors.
scaled :: HasCallStack => (Picture, Number, Number) -> Picture
scaled (p, x, y) = withFrozenCallStack $ CWPic (CW.scaled (toDouble x) (toDouble y) (toCWPic p))
-- | A picture scaled by these factors.
dilated :: HasCallStack => (Picture, Number) -> Picture
dilated (p, k) = withFrozenCallStack $ CWPic (CW.dilated (toDouble k) (toCWPic p))
-- | A picture rotated by this angle.
rotated :: HasCallStack => (Picture, Number) -> Picture
rotated (p, th) = withFrozenCallStack $ CWPic (CW.rotated (toDouble (pi * th / 180)) (toCWPic p))
-- A picture made by drawing these pictures, ordered from top to bottom.
pictures :: HasCallStack => [Picture] -> Picture
pictures ps = withFrozenCallStack $ CWPic (CW.pictures (map toCWPic ps))
-- Binary composition of pictures.
(&) :: HasCallStack => Picture -> Picture -> Picture
infixr 0 &
a & b = withFrozenCallStack $ CWPic (toCWPic a CW.& toCWPic b)
-- | A coordinate plane. Adding this to your pictures can help you measure distances
-- more accurately.
--
-- Example:
--
-- program = drawingOf(myPicture & coordinatePlane)
-- myPicture = ...
coordinatePlane :: HasCallStack => Picture
coordinatePlane = withFrozenCallStack $ CWPic CW.coordinatePlane
-- | The CodeWorld logo.
codeWorldLogo :: HasCallStack => Picture
codeWorldLogo = withFrozenCallStack $ CWPic CW.codeWorldLogo
| pranjaltale16/codeworld | codeworld-base/src/Internal/Picture.hs | apache-2.0 | 11,092 | 0 | 13 | 1,984 | 3,109 | 1,667 | 1,442 | -1 | -1 |
module Clear ( ClearTag(..)
, parseClear
) where
import Text.Parsec.Combinator (choice)
import Data.Maybe (fromJust)
import ClassyPrelude
import Common
data ClearTag = Clear String
| ClearAll String
deriving (Show, Eq)
parseClear :: PParser ClearTag
parseClear = ClearAll <$> parseClearAll
<|> Clear <$> parseClearOnly
parseClearOnly :: PParser String
parseClearOnly = do
-- intentionally very limited (for now).
what <- choice $ tryPrefixes [ "RANGE"
, "TYPE"
, "PRE"
, "DESC"
, "CSKILL"
, "AUTO"
, "LANG"
, "TARGETAREA"
, "SCHOOL"
, "SAB"]
return $ stripClear what where
tryPrefixes = tryStrings . map (++ ":.CLEAR")
stripClear = fromJust . stripSuffix ":.CLEAR"
parseClearAll :: PParser String
parseClearAll = do
-- intentionally very limited (for now).
what <- choice $ tryPrefixes [ "CLASSES"
, "DESC" ]
return $ stripClear what where
tryPrefixes = tryStrings . map (++ ":.CLEARALL")
stripClear = fromJust . stripSuffix ":.CLEARALL"
| gamelost/pcgen-rules | src/Clear.hs | apache-2.0 | 1,345 | 0 | 10 | 546 | 265 | 147 | 118 | 34 | 1 |
#!/usr/local/bin/perl
##########################################################
##Check for referer, if not user is jumped to Home Page #
##########################################################
@referers = ('www.coastlinemicro.com','coastlinemicro.com');
&check_url;
sub check_url {
# Localize the check_referer flag which determines if user is valid. #
local($check_referer) = 0;
# If a referring URL was specified, for each valid referer, make sure #
# that a valid referring URL was passed to FormMail. #
if ($ENV{'HTTP_REFERER'}) {
foreach $referer (@referers) {
if ($ENV{'HTTP_REFERER'} =~ m|https?://([^/]*)$referer|i) {
$check_referer = 1;
last;
}
}
}
else {
$check_referer = 1;
}
# If the HTTP_REFERER was invalid, send back an error. #
if ($check_referer != 1) { &bad_referer; }
}
sub bad_referer {
print "Location: index.html\n\n";
exit;
}
####################
##End Check Referer#
####################
##return =true
1; | drlouie/public-views | _client-workareas/COASTLINE/backup/03022001/referer.hs | apache-2.0 | 1,110 | 40 | 9 | 297 | 235 | 153 | 82 | -1 | -1 |
import P10
data ListItem a = Single a | Multiple Int a
deriving (Show)
encodeModified :: (Eq a) => [a] -> [ListItem a]
encodeModified xs = map (\s -> if fst s == 1 then Single (snd s) else Multiple (fst s) (snd s)) (encode xs)
| plilja/h99 | p11.hs | apache-2.0 | 234 | 0 | 11 | 53 | 123 | 65 | 58 | 5 | 2 |
module Laborantin (
prepare
, load
, remove
, runAnalyze
, missingParameterSets
, expandParameterSets
) where
import Laborantin.Types
import Laborantin.Query
import Laborantin.Implementation
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Error
import Control.Applicative
import qualified Data.Set as S
import qualified Data.Map as M
-- | Prepare a list of execution actions for a given
-- (scenario, parameter-query, existing) ancestors.
--
-- This function returns one action per ParameterSet which is required by the
-- parameter-query and not yet present in the existing list of executions.
--
-- For instance, if the scenario has one parameter 'foo'; the query wants 'foo'
-- in [1,2,3,4]; and there is one execution with 'foo' == 2; then this function
-- returns 3 actions (for parameters 1, 3, and 4).
--
-- A user can then run these actions in sequence (or concurrently if it makes
-- sense).
prepare :: (MonadIO m) => Backend m
-> TExpr Bool
-> [Execution m]
-> ScenarioDescription m
-> [m (Execution m)]
prepare b expr execs sc = map toAction neededParamSets
where toAction = execute b sc
neededParamSets = missingParameterSets sc expr existing
where existing = map eParamSet execs
-- | Like matchingParameterSets but also remove existing ParameterSet given as
-- third parameter.
missingParameterSets :: ScenarioDescription m -> TExpr Bool -> [ParameterSet] -> [ParameterSet]
missingParameterSets sc expr sets = listDiff target sets
where target = matchingParameterSets sc expr
-- | Like expandParameterSets but also filter ParameterSet to only those that
-- actually match the TExpr query.
matchingParameterSets :: ScenarioDescription m -> TExpr Bool -> [ParameterSet]
matchingParameterSets sc expr = filter matching allSets
where matching = matchTExpr' expr sc
allSets = expandParameterSets sc expr
-- | Expands parameters given a TExpr and a ScenarioDescription into a list of
-- parameter spaces (sort of cartesian product of all possible params)
expandParameterSets :: ScenarioDescription m -> TExpr Bool -> [ParameterSet]
expandParameterSets sc expr = paramSets $ expandParamSpace (sParams sc) expr
-- | Shortcut to remove from l1 the items in l2.
-- Implementation transposes objects to sets thus needs the Ord capability.
--
-- e.g. listDiff "abcd" "bcde" = "a"
listDiff :: Ord a => [a] -> [a] -> [a]
listDiff l1 l2 = S.toList (S.fromList l1 `S.difference` S.fromList l2)
-- | Executes a given scenario for a given set of parameters using a given backend.
execute :: (MonadIO m) => Backend m -> ScenarioDescription m -> ParameterSet -> m (Execution m)
execute b sc prm = execution
where execution = do
(exec,final) <- bPrepareExecution b sc prm
status <- liftM fst $ runReaderT (runStateT (runErrorT (go exec `catchError` recover exec)) emptyEnv) (b, exec)
let exec' = either (\_ -> exec {eStatus = Failure}) (\_ -> exec {eStatus = Success}) status
bFinalizeExecution b exec' final
return exec'
where go exec = do
bSetup b exec
bRun b exec
bTeardown b exec
bAnalyze b exec
recover exec err = bRecover b err exec >> throwError err
-- | Loads executions of given ScenarioDescription and matching a given query
-- using a specific backend.
load :: (MonadIO m) => Backend m -> [ScenarioDescription m] -> TExpr Bool -> m [Execution m]
load = bLoad
-- | Remove an execution using a specific backend.
remove :: (MonadIO m) => Backend m -> Execution m -> m ()
remove = bRemove
-- | Runs the analysis hooks.
runAnalyze :: (MonadIO m, Functor m) => Backend m -> Execution m -> m (Either AnalysisError ())
runAnalyze b exec = do
let status = runReaderT (runStateT (runErrorT (go exec)) emptyEnv) (b, exec)
(either rebrandError Right) . fst <$> status
where go exec = bAnalyze b exec
rebrandError (ExecutionError str) = Left $ AnalysisError str
| lucasdicioccio/laborantin-hs | Laborantin.hs | apache-2.0 | 4,262 | 0 | 18 | 1,057 | 959 | 501 | 458 | 61 | 1 |
{-# language TypeSynonymInstances #-}
{-# language LiberalTypeSynonyms #-}
module FrequencyResponse
(Analyzer (..),
AnalyzerAcyclic (..),
Spectrum (..),
SpecLin (..),
SpecWide ,
getResponse,
getResponseLin,
getResponseAcyclic)
where
import CLaSH.Prelude (Default(..))
import Prelude
import CLaSH.Signal.MultiSignal
import Data.Complex as C
import Data.Maybe
import Control.Applicative
import Data.Map.Strict as Map
-- | Type representing input and output signal in circuitry
-- p of kind (* -> *) represents underlaying Signal of type Prependable (ZipList for example)
-- s is type of Spectrum
data Analyzer p s = Analyzer {unAnalyzer :: ([Maybe (s -> s)] , p s)}
instance (Functor p, Prependable p) => Prependable (Analyzer p) where
prepend a da = Analyzer (Nothing : f , (prepend a $ fmap fx d))
where
(f,d) = unAnalyzer da
fx = fromMaybe id $ foldr1 (<|>) f
instance (Applicative p,Num n) => Num (Analyzer p n) where
(+) = liftA2FA (+)
(-) = liftA2FA (-)
(*) = liftA2FA (*)
fromInteger = makeAnalyzer . fromInteger
negate = liftA1FA negate
abs = liftA1FA abs
signum = liftA1FA signum
instance (Applicative p,Fractional n) => Fractional (Analyzer p n) where
(/) = liftA2FA (/)
fromRational = makeAnalyzer . fromRational
liftA2FA op da db = Analyzer (zipWith (<|>) fa fb, liftA2 op a b) where
(fa,a) = unAnalyzer da
(fb,b) = unAnalyzer db
liftA1FA op f = Analyzer (repeat Nothing , fmap op s) where
(_,s) = unAnalyzer f
makeAnalyzer s = Analyzer ( repeat Nothing , pure s )
{- inline liftA2FA, liftA1FA-}
-- | spectrum is result of frequency mixing two spectrums
-- n represents type represented as harmonics (Int or better, Rational)
-- and a is type of complex number (frequently Double)
data Spectrum n a = Spectrum {getSpectrum :: Map.Map n (Complex a)}
instance (Ord n,Num n,Default a,RealFloat a) => Default (Spectrum n a) where
def = dcSpectrum def
instance (Ord n,Num n,RealFloat a) => Num (Spectrum n a) where
(+) = dotMergeSpec (+)
(-) = dotMergeSpec (-)
(*) = mixSpectrum
negate = fmapSpec negate
abs = error "no abs function for spectrum available"
signum = error "no sig num function for spectrum available"
fromInteger = dcSpectrum . fromInteger
instance (Show n, Show a, Ord n,Num n,Fractional a,RealFloat a) => Fractional (Spectrum n a) where
(/) = spectrumDiv
fromRational = dcSpectrum . fromRational
dotMergeSpec op (Spectrum sa) (Spectrum sb) = Spectrum $ (Map.unionWith op) sa sb
fmapSpec f = Spectrum . fmap f . getSpectrum
constSpectrum freq a = Spectrum $ Map.singleton freq (a :+ 0 )
dcSpectrum a = constSpectrum 0 a
mixSpectrum (Spectrum sa) (Spectrum sb) = Spectrum
$ Map.fromListWith (+)
$ concat [mixFeq a b | a <- Map.toList sa , b <- Map.toList sb]
mixFeq (fa,pa) (fb,pb)
| fa > fb = mixFeqSorted (fb,pb) (fa,pa)
| True = mixFeqSorted (fa,pa) (fb,pb)
mixFeqSorted (0,pa) (fb,pb) = [(fb,pa*pb)]
mixFeqSorted (fa,pa) (fb,pb) = [(fb - fa,r1),(fb+fa,r2)] where
(ma,pha) = polar pa
(mb,phb) = polar pb
k = ma * mb / 2
r1
| fa == fb = mkPolar (k * sin (phb - pha + pi/2)) 0
| otherwise = mkPolar k (phb - pha + pi/2)
r2 = mkPolar ((-1)*k) (phb + pha + pi/2)
delaySpec ph (Spectrum s) = Spectrum $ Map.mapWithKey f s where
f 0 a = a
f k a = a * mkPolar 1 (fromRational k * ph)
spectrumDiv (Spectrum a) sb = Spectrum (fmap (/ dc) a) where
dc = getDcOrError sb
getDcOrError (Spectrum a) =
case toList a of
((0,dc):[]) -> dc
s -> error ("spectrum is not dc, but" ++ show s )
makeDcSig :: (Applicative p, Num n, Num a) => a -> Analyzer p (Spectrum n a)
makeDcSig = makeAnalyzer . dcSpectrum
-- | spectrum for linear system, faster version of Spectrum
-- underlaying type is tuple insted of Map
newtype SpecLin = SpecLin {getSpecLin :: (Double,Complex Double)}
instance Default SpecLin where
def = SpecLin (def,def :+ def)
instance Num SpecLin where
(+) = dotMergeSpecLin (+)
(-) = dotMergeSpecLin (-)
(*) = mixSpecLin
negate = fmapSpecLin negate
abs = error "no abs function for spectrum available"
signum = error "no signum function for spectrum available"
fromInteger = dcSpecLin . fromInteger
instance Fractional SpecLin where
(/) = undefined -- dcSpecLin
fromRational = dcSpecLin . fromRational
dotMergeSpecLin op (SpecLin (dcA,acA)) (SpecLin (dcB,acB)) = SpecLin (op dcA dcB , acr) where
acr = op (realPart acA) (realPart acB) :+ op (imagPart acA) (imagPart acB)
mixSpecLin (SpecLin (dcA,acA)) (SpecLin (dcB,acB))
| (acA /= 0 ) && (acB /= 0) = error "can not mix two linear spectrum"
| otherwise = SpecLin (dcr , acr) where
dcr = dcA * dcB
acr = fmap (* dcA) acB + fmap (* dcB) acA
dcSpecLin dc = SpecLin (dc,0)
fmapSpecLin f (SpecLin (dc,ac)) = SpecLin (f dc,fmap f ac)
delayLinSpec ph (SpecLin (dc,ac)) = SpecLin (dc,ac * mkPolar 1 ph)
-- end of SpecLin
-- for acyclic circuits we can implement faster version of Prependable
-- It has nice property that first value of output is correct.
data AnalyzerAcyclic s = AnalyzerAcyclic {unAnalyzerAcyclic :: (Maybe (s -> s), s)}
-- Prependable instance has funny laws (no laws?)
-- it does not follow list isomorphism, because it is single value
instance Prependable AnalyzerAcyclic where
prepend _ da = AnalyzerAcyclic (f , fx d)
where
(f,d) = unAnalyzerAcyclic da
fx = fromMaybe id f
instance (Num n) => Num (AnalyzerAcyclic n) where
(+) = opAcyclic (+)
(-) = opAcyclic (-)
(*) = opAcyclic (*)
fromInteger = pureAcyclic . fromInteger
negate = liftAcyclic negate
abs = liftAcyclic abs
signum = liftAcyclic signum
instance (Fractional n) => Fractional (AnalyzerAcyclic n) where
(/) = opAcyclic (/)
fromRational = pureAcyclic . fromRational
pureAcyclic n = AnalyzerAcyclic (Nothing,n)
opAcyclic op (AnalyzerAcyclic (fa,a)) (AnalyzerAcyclic (fb,b)) = (AnalyzerAcyclic (fa <|> fb ,op a b))
liftAcyclic f (AnalyzerAcyclic (fa,a)) = (AnalyzerAcyclic (fa,f a))
-- end of AnalyzerAcyclic
type SpecWide = Spectrum Rational Double
-- | run analysis for both acyclic\/cyclic and both linear\/nonlinear circuits
-- It is required to skip first N resulting values
-- where N represent delay of circuitry (approx total number of registers)
getResponse :: (Analyzer ZipList SpecWide -> Analyzer ZipList SpecWide) -- ^ circuitry
-> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)
-> [Spectrum Rational Double] -- ^ response as stream
getResponse f ph = getZipList $ snd $ unAnalyzer $ f $ Analyzer ([ Just (delaySpec ph)] , pure (constSpectrum 1 1))
-- | run analysis for both acyclic\/cyclic and only linear circuits
-- faster version of getResponse for acyclic linear ciruits
getResponseLin :: (Analyzer ZipList SpecLin -> Analyzer ZipList SpecLin) -- ^ circuitry
-> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)
-> [SpecLin] -- ^ response as stream
getResponseLin f ph = getZipList $ snd $ unAnalyzer $ f $ Analyzer ([Just (delayLinSpec ph)] , pure (SpecLin (0,1 :+ 0)))
-- | run analysis both linear\/nonlinear and only acyclic circuit
-- calculate response of acyclic circuit
getResponseAcyclic :: (AnalyzerAcyclic SpecWide -> AnalyzerAcyclic SpecWide) -- ^ circuitry
-> Double -- ^ phase in radians that represents Nyquist frequency. (phase pi ≡ 1.0 of sampling frequency)
-> Spectrum Rational Double -- ^ response as stream
getResponseAcyclic f ph = snd $ unAnalyzerAcyclic $ f $ AnalyzerAcyclic (Just (delaySpec ph) ,constSpectrum 1 1)
| ra1u/frequency-response | src/FrequencyResponse.hs | bsd-3-clause | 7,832 | 0 | 15 | 1,727 | 2,592 | 1,408 | 1,184 | 140 | 2 |
{-# LANGUAGE CPP #-}
module Servant.EDE.Internal.Validate where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
import Data.Foldable
import Data.Traversable
#endif
import Data.Functor.Compose
import Data.Semigroup
data Validated e a = OK a | NotOK e
deriving (Eq, Show)
instance Functor (Validated e) where
fmap f (OK x) = OK (f x)
fmap _ (NotOK e) = NotOK e
instance Semigroup e => Applicative (Validated e) where
pure x = OK x
OK f <*> OK x = OK (f x)
OK _ <*> NotOK e = NotOK e
NotOK e <*> OK _ = NotOK e
NotOK e <*> NotOK e' = NotOK (e <> e')
instance Foldable (Validated e) where
foldMap f (OK x) = f x
foldMap _ (NotOK _) = mempty
instance Traversable (Validated e) where
traverse f (OK x) = fmap OK (f x)
traverse _ (NotOK x) = pure (NotOK x)
instance (Semigroup e, Semigroup a) => Semigroup (Validated e a) where
NotOK e <> NotOK e' = NotOK (e <> e')
NotOK e <> OK _ = NotOK e
OK a <> OK b = OK (a <> b)
OK _ <> NotOK e = NotOK e
validateEither :: Either e a -> Validated e a
validateEither (Left e) = NotOK e
validateEither (Right x) = OK x
eitherValidate :: Validated e a -> Either e a
eitherValidate (OK x) = Right x
eitherValidate (NotOK e) = Left e
ok :: Applicative m => a -> ValidateT e m a
ok = VT . pure . OK
no :: Applicative m => e -> ValidateT e m a
no = VT . pure . NotOK
validated :: (e -> r) -> (a -> r) -> Validated e a -> r
validated f _ (NotOK e) = f e
validated _ f (OK x) = f x
newtype ValidateT e m a = VT
{ runValidateT :: m (Validated e a) }
validate :: m (Validated e a) -> ValidateT e m a
validate = VT
instance Functor m => Functor (ValidateT e m) where
fmap f (VT m) = VT $ fmap (fmap f) m
instance (Applicative m, Semigroup e) => Applicative (ValidateT e m) where
pure = VT . pure . pure
VT f <*> VT x = VT . getCompose $ Compose f <*> Compose x
instance (Applicative m, Semigroup e, Semigroup a) => Semigroup (ValidateT e m a) where
VT a <> VT b = VT $ (<>) <$> a <*> b
| alpmestan/servant-ede | src/Servant/EDE/Internal/Validate.hs | bsd-3-clause | 2,024 | 0 | 9 | 516 | 1,005 | 492 | 513 | 53 | 1 |
module Test.QuickCheck.Instances.Eq (notEqualTo, notOneof) where
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Control.Monad.Extensions
notEqualTo :: (Eq a,Arbitrary a) => a -> Gen a -> Gen a
notEqualTo v = satisfiesM (/= v)
notOneof :: (Eq a,Arbitrary a) => [a] -> Gen a
notOneof es = arbitrarySatisfying (not . (`elem` es))
| bitemyapp/checkers | src/Test/QuickCheck/Instances/Eq.hs | bsd-3-clause | 346 | 0 | 8 | 52 | 136 | 77 | 59 | 8 | 1 |
module Rfc6979Ex where
import Functions
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Crypto.Hash.SHA256 as SHA256
q1 = 0x996f967f6c8e388d9e28d01e205fba957a5698b1
x1 = 0x411602cb19a6ccc34494d79d98ef1e7ed5af25f7
q2 = 0xf2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde9998c1f
x2 = 0x69c7548c21d0dfea6b9a51c9ead4e27c33d3b3f180316e5bcab92c933f0e4dbc
q3 = 0xffffffffffffffffffffffff99def836146bc9b1b4d22831
x3 = 0x6fab034934e4c0fc9ae67f5b5659a9d7d1fefd187ee09fd4
| YoshikuniJujo/forest | subprojects/tls-analysis/rfc6979/examples2.hs | bsd-3-clause | 485 | 0 | 4 | 38 | 55 | 37 | 18 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module JKF.TypeSpec where
import Data.Aeson
import Data.HashMap.Strict (fromList)
import JKF.Type
import Test.Hspec
spec :: Spec
spec = do
let h1 = Header "habu" "moriuchi" "2015-10-28 07:43" "2015-10-28 20:40" "hirate"
h2 = Header "" "" "" "" ""
mmf1 = MoveMoveFormat Black (Just (PlaceFormat 1 2)) (Just (PlaceFormat 1 3)) "FU" Nothing Nothing Nothing Nothing
describe "JKF.Type" $ do
describe "Header toJSON" $ do
it "toJSON (Header \"habu\" \"moriuchi\" \"2015-10-28 07:43\" \"2015-10-28 20:40\" \"hirate\")" $
toJSON h1
`shouldBe`
Object (fromList [
("後手",String "moriuchi")
,("終了日時",String "2015-10-28 20:40")
,("手合割",String "hirate")
,("先手",String "habu")
,("開始日時",String "2015-10-28 07:43")
])
it "toJSON (Header \"\" \"\" \"\" \"\" \"\")" $
toJSON h2
`shouldBe`
Object (fromList [
("後手",String "")
,("終了日時",String "")
,("手合割",String "")
,("先手",String "")
,("開始日時",String "")
])
describe "MoveMoveFormat toJSON" $ do
it "toJSON (MoveMoveFormat Black (Just (PlaceFormat 1 2)) (Just (PlaceFormat 1 3)) \"FU\" Nothing Nothing Nothing Nothing)" $
toJSON mmf1
`shouldBe`
Object (fromList [
("moveMoveFormatColor",String "Black")
,("moveMoveFormatFrom",Object (fromList [("placeFormatX",Number 1.0),("placeFormatY",Number 2.0)]))
,("moveMoveFormatTo",Object (fromList [("placeFormatX",Number 1.0),("placeFormatY",Number 3.0)]))
,("moveMoveFormatPiece",String "FU")
,("moveMoveFormatSame",Null)
,("moveMoveFormatRelative",Null)
,("moveMoveFormatCapture",Null)
,("moveMoveFormatPromote",Null)
])
| suzuki-shin/jkf-hs | test/JKF/TypeSpec.hs | bsd-3-clause | 2,150 | 0 | 24 | 730 | 507 | 276 | 231 | 44 | 1 |
module Problems.Problem3 where
import qualified Lib.Math as Math
getSolution :: Int
getSolution = head $ filter f valsDesc
where
num = 600851475143
maxVal = Math.maxPossiblePrimeFactor num
valsDesc = [maxVal, maxVal - 1 .. 2]
f :: Int -> Bool
f n = num `mod` n == 0 && Math.isPrime n
| sarangj/eulerhs | src/Problems/Problem3.hs | bsd-3-clause | 309 | 0 | 9 | 75 | 104 | 59 | 45 | 9 | 1 |
{-# OPTIONS_GHC -Wall -Werror #-}
module Main(main) where
import System.IO
import Text.PrettyPrint.Pp(
render,
above,
pp)
import qualified Lobster.SELinux.SELinux as SELinux
import Lobster.Common
main :: IO ()
main = do
(options,fns) <- processOptions
domain <- parseAndInterpretPolicyFiles_ options fns
let output = outputFile options
let selinux = SELinux.compileDomain output domain
System.IO.writeFile (output ++ ".te")
(render (pp (SELinux.typeEnforcement selinux))++"\n")
System.IO.writeFile (output ++ ".fc")
(render (above (map pp (SELinux.fileContext selinux)))++"\n")
| GaloisInc/sk-dev-platform | libs/lobster-selinux/src/Lobster/SELinux/Main.hs | bsd-3-clause | 607 | 0 | 17 | 95 | 206 | 109 | 97 | 19 | 1 |
module Test (main) where
import FFI
import HtmlCanvas
import Prelude
main :: Fay ()
main = do
addEventListener "load" start False
start :: Fay ()
start = do
canvas <- getElementById "can"
context <- getContext "2d" canvas
setFillStyle "rgb(200,0,0)" context
fillRect 0 0 10 10 context
| svaiter/fay-canvas | test.hs | bsd-3-clause | 328 | 0 | 8 | 89 | 102 | 50 | 52 | 13 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
module System.Win32.DHCP.DhcpStructure where
import Control.Monad (when)
import Import
-- |Function dictionary for objects used with the DHCP api.
-- * Ability to peek from a pointer to that object.
-- * Ability to properly free an object using Win32's rpcFreeMemory
-- created by the DHCP api.
-- * Ability to use the with* metaphor to temporarily poke an
-- object into C memory, call a continuation on it, and then
-- free the memory from Haskell's heap.
--
-- Extra features made possible by the typeclass
-- * Ability to turn any Storable instance into a DhpcStructure instance
-- by wrapping it into a 'storableDhcpStructure'.
-- * Ability to peek an array of DHCP structures into a list.
-- * Ability to poke a list of objects into contiguous memory, then
-- call a continuation on that block of memory.
data DhcpStructure a = DhcpStructure
{ peekDhcp :: Ptr a -> IO a
-- |Cleaning up memory is the responsibility of the client of this
-- library. Most out parameters return compound structures which need to
-- be recursively navigated, freeing all children, before freeing the main
-- pointer.
--
-- This function only frees child objects without freeing the pointer
-- itself. It's necessary because some structures contained inline
-- structures instead of the usual pointer. A separate 'freeDhcp' function
-- will call this one before freeing its supplied pointer.
, freeDhcpChildren :: (forall x. Ptr x -> IO ()) -> Ptr a -> IO ()
-- |Like `withDhcp`, but without any allocation or cleanup of memory.
-- The continuation is not automatically given a pointer because
-- the caller should already have it.
, withDhcp' :: forall r. a -> Ptr a -> IO r -> IO r
, sizeDhcp :: Int
}
freeDhcp :: DhcpStructure a -> (forall x. Ptr x -> IO ()) -> Ptr a -> IO ()
freeDhcp dict free ptr = do
freeDhcpChildren dict free ptr
free ptr
-- |Allocate memory for a structure, poke it into memory, apply
-- a function, and then clean up the memory.
withDhcp :: DhcpStructure a -> a -> (Ptr a -> IO r) -> IO r
withDhcp dict a f = allocaBytes (sizeDhcp dict) $ \ptr ->
withDhcp' dict a ptr $ f ptr
-- |Convert a DhcpStructure so that it can be used with a newtype
-- wrapper.
newtypeDhcpStructure :: (a -> nt) -> (nt -> a)
-> DhcpStructure a -> DhcpStructure nt
newtypeDhcpStructure wrap unwrap dict =
DhcpStructure peekNt freeNt withNt' (sizeDhcp dict)
where
peekNt ptr = wrap <$> peekDhcp dict (castPtr ptr)
freeNt :: (forall x. Ptr x -> IO ()) -> Ptr a -> IO ()
freeNt f ptr = freeDhcpChildren dict f (castPtr ptr)
withNt' a ptr f = withDhcp' dict (unwrap a) (castPtr ptr) f
-- |This is used in cases like 'CLIENT_UID' where we want to treat it like
-- a 'LengthArray' but individual elements of the array are simple values that
-- do not need to be freed individually. An example of this (and the only
-- place where it is used) is 'CLIENT_UID'. We reuse the 'Storable' instances
-- peek and poke functions.
storableDhcpStructure :: forall a. (Storable a) => DhcpStructure a
storableDhcpStructure = DhcpStructure
{ peekDhcp = peek
, freeDhcpChildren = \freeFunc ptr -> freeFunc ptr
, withDhcp' = withStorable'
, sizeDhcp = sizeOf (undefined :: a)
}
where
withStorable' x ptr f = poke ptr x >> f
data DhcpArray a = DhcpArray
{ peekDhcpArray :: Int -> Ptr a -> IO [a]
, freeDhcpArray :: (forall x. Ptr x -> IO ()) -> Int -> Ptr a -> IO ()
, withDhcpArray' :: forall r. [a] -> Ptr a -> IO r -> IO r
, dhcpStructure :: DhcpStructure a
}
-- |Allocate enough contiguous memory for each element. Recursively
-- free all memory once the supplied function returns.
-- The continuation receives a length argument. This is because
-- the length must be calculated in the course of execution, and will
-- likely be needed again by the caller.
withDhcpArray :: DhcpArray a -> [a] -> (Int -> Ptr a -> IO r) -> IO r
withDhcpArray dict elems f =
allocaBytes (stride * size) $ \ptr ->
-- `f` is meant to be called on the array as a whole; not individual elements.
-- It's supplied its pointer here because we want it called on position 0.
withDhcpArray' dict elems ptr $ f size ptr
where
size = length elems
stride = sizeDhcp . dhcpStructure $ dict
-- |This dictionary is a default set to "base" other versions on.
-- Scanning through the buffer happens dhcpSize bytes at a time. Memory
-- is freed by calling the freeing function on every element in the buffer.
baseDhcpArray :: DhcpStructure a -> DhcpArray a
baseDhcpArray s = DhcpArray
{ peekDhcpArray = basePeekArray s
, freeDhcpArray = baseFreeArray s
, withDhcpArray' = baseWithArray' s
, dhcpStructure = s
}
-- |This differs from `baseDhcpArray` in that the entire buffer
-- is freed with a single call to the freeing function.
basicDhcpArray :: DhcpStructure a -> DhcpArray a
basicDhcpArray dict = (baseDhcpArray dict)
{ freeDhcpArray = basicFreeArray dict
}
ptrDhcpArray :: DhcpStructure a -> DhcpArray a
ptrDhcpArray dict = (baseDhcpArray dict)
{ peekDhcpArray = ptrPeekArray dict
, freeDhcpArray = ptrFreeArray dict
, withDhcpArray' = ptrWithArray' dict
}
basePeekArray :: DhcpStructure a -> Int -> Ptr a -> IO [a]
basePeekArray dict len ptr0 = mapM (peekDhcp dict) ptrs
where
ptrs = take len . iterate (`plusPtr` sizeDhcp dict) $ ptr0
-- |Elements are arranged end to end in a buffer. The buffer is freed
-- at once after each element's children are freed.
baseFreeArray :: DhcpStructure a
-> (forall x. Ptr x -> IO ()) -> Int -> Ptr a -> IO ()
baseFreeArray dict freefunc len ptr
| len <= 0 = return ()
| otherwise = do
f (len - 1)
freefunc ptr
where
f 0 = freeDhcpChildren dict freefunc ptr
f n = do
freeDhcpChildren dict freefunc $ ptr `plusPtr` (n * sizeDhcp dict)
f (n - 1)
baseWithArray' :: DhcpStructure a -> [a] -> Ptr a -> IO r -> IO r
baseWithArray' _ [] _ f = f
baseWithArray' dict (e:es) ptr f =
-- We're not concerned with the individual element.
withDhcp' dict e ptr
$ baseWithArray' dict es (ptr `plusPtr` sizeDhcp dict) f
basicFreeArray :: DhcpStructure a -> (forall x. Ptr x -> IO ())
-> Int -> Ptr a -> IO ()
basicFreeArray dict freefunc _ ptr = freeDhcp dict freefunc ptr
ptrPeekArray :: DhcpStructure a -> Int -> Ptr a -> IO [a]
ptrPeekArray dict len ptr = mapM peekElement pptrs
where
--Each element is a pointer to the real data
pptrs = take len . iterate (`plusPtr` sizeOf nullPtr) $ castPtr ptr
peekElement pptr = peek pptr >>= peekDhcp dict
ptrFreeArray :: DhcpStructure a
-> (forall x. Ptr x -> IO ()) -> Int -> Ptr a -> IO ()
ptrFreeArray dict freefunc len ptr = do
mapM (freeDhcp dict freefunc `scrubbing_`) pptrs
-- Len may very well be 0 in which case there's really nothing to free.
when (len > 0) $ freefunc ptr
where
--Each element is a pointer to the real data
pptrs = take len . iterate (`plusPtr` sizeOf nullPtr) $ castPtr ptr
ptrWithArray' :: DhcpStructure a -> [a] -> Ptr a -> IO r -> IO r
ptrWithArray' _ [] _ f = f
ptrWithArray' dict (e:es) ptr f =
-- We're not concerned with the individual element.
withDhcp dict e $ \pe -> do
poke pptr pe
ptrWithArray' dict es (ptr `plusPtr` sizeOf nullPtr) f
where
--Each element is a pointer to the real data
pptr = castPtr ptr
| mikesteele81/Win32-dhcp-server | src/System/Win32/DHCP/DhcpStructure.hs | bsd-3-clause | 7,533 | 0 | 14 | 1,718 | 1,812 | 932 | 880 | 96 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Client.ClientStaticT where
import Control.Lens (makeLenses)
import qualified Data.ByteString as B
import QCommon.NetChanT
import Types
makeLenses ''ClientStaticT
newClientStaticT :: ClientStaticT
newClientStaticT = ClientStaticT
{ _csState = 0
, _csKeyDest = 0
, _csFrameCount = 0
, _csRealTime = 0
, _csFrameTime = 0
, _csDisableScreen = 0
, _csDisableServerCount = 0
, _csServerName = ""
, _csConnectTime = 0
, _csQuakePort = 0
, _csNetChan = newNetChanT
, _csServerProtocol = 0
, _csChallenge = 0
, _csDownload = Nothing
, _csDownloadTempName = ""
, _csDownloadName = ""
, _csDownloadNumber = 0
, _csDownloadType = 0
, _csDownloadPercent = 0
, _csDemoRecording = False
, _csDemoWaiting = False
, _csDemoFile = Nothing
}
| ksaveljev/hake-2 | src/Client/ClientStaticT.hs | bsd-3-clause | 1,051 | 0 | 6 | 404 | 185 | 120 | 65 | 31 | 1 |
-- | Detailed audio sample description.
module Data.ByteString.IsoBaseFileFormat.Boxes.AudioSampleEntry where
import Data.ByteString.IsoBaseFileFormat.Box
import Data.ByteString.IsoBaseFileFormat.Boxes.Handler
import Data.ByteString.IsoBaseFileFormat.ReExports
import Data.ByteString.IsoBaseFileFormat.Util.BoxContent
import Data.ByteString.IsoBaseFileFormat.Util.BoxFields
-- | Fields of audio sample entries
newtype AudioSampleEntry b where
AudioSampleEntry ::
Constant (U32Arr "reserved" 2) '[0, 0]
:+ Template (U16 "channelcount") 2
:+ Template (U16 "samplesize") 16
:+ U16 "pre_defined"
:+ Constant (U16 "reserved") 0
:+ Template
(U32 "samplerate")
(DefaultSoundSamplerate * 65536) -- TODO implement fix point integer
:+ b ->
AudioSampleEntry b
deriving (Default, IsBoxContent)
instance Functor AudioSampleEntry where
fmap fun (AudioSampleEntry (a :+ b :+ c :+ d :+ e :+ f :+ x)) =
AudioSampleEntry (a :+ b :+ c :+ d :+ e :+ f :+ fun x)
type DefaultSoundSamplerate = 48000
type instance GetHandlerType (AudioSampleEntry b) = 'AudioTrack
type instance BoxTypeSymbol (AudioSampleEntry b) = BoxTypeSymbol b
| sheyll/isobmff-builder | src/Data/ByteString/IsoBaseFileFormat/Boxes/AudioSampleEntry.hs | bsd-3-clause | 1,191 | 0 | 15 | 214 | 305 | 168 | 137 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Configure
-- Copyright : (c) David Himmelstrup 2005,
-- Duncan Coutts 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- High level interface to configuring a package.
-----------------------------------------------------------------------------
module Distribution.Client.Configure (
configure,
configureSetupScript,
chooseCabalVersion,
checkConfigExFlags
) where
import Distribution.Client.Dependency
import Distribution.Client.Dependency.Types
( AllowNewer(..), isAllowNewer, ConstraintSource(..)
, LabeledPackageConstraint(..), showConstraintSource )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackages, getInstalledPackages )
import Distribution.Client.PackageIndex ( PackageIndex, elemByPackageName )
import Distribution.Client.Setup
( ConfigExFlags(..), configureCommand, filterConfigureFlags
, RepoContext(..) )
import Distribution.Client.Types as Source
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Targets
( userToPackageConstraint, userConstraintPackageName )
import qualified Distribution.Client.ComponentDeps as CD
import Distribution.Package (PackageId)
import Distribution.Client.JobControl (Lock)
import Distribution.Simple.Compiler
( Compiler, CompilerInfo, compilerInfo, PackageDB(..), PackageDBStack )
import Distribution.Simple.Program (ProgramConfiguration )
import Distribution.Simple.Setup
( ConfigFlags(..), fromFlag, toFlag, flagToMaybe, fromFlagOrDefault )
import Distribution.Simple.PackageIndex
( InstalledPackageIndex, lookupPackageName )
import Distribution.Simple.Utils
( defaultPackageDesc )
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Package
( Package(..), UnitId, packageName
, Dependency(..), thisPackageVersion
)
import qualified Distribution.PackageDescription as PkgDesc
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.PackageDescription.Configuration
( finalizePackageDescription )
import Distribution.Version
( anyVersion, thisVersion )
import Distribution.Simple.Utils as Utils
( warn, notice, info, debug, die )
import Distribution.System
( Platform )
import Distribution.Text ( display )
import Distribution.Verbosity as Verbosity
( Verbosity )
import Distribution.Version
( Version(..), VersionRange, orLaterVersion )
import Control.Monad (unless)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
#endif
import Data.Maybe (isJust, fromMaybe)
-- | Choose the Cabal version such that the setup scripts compiled against this
-- version will support the given command-line flags.
chooseCabalVersion :: ConfigExFlags -> Maybe Version -> VersionRange
chooseCabalVersion configExFlags maybeVersion =
maybe defaultVersionRange thisVersion maybeVersion
where
-- Cabal < 1.19.2 doesn't support '--exact-configuration' which is needed
-- for '--allow-newer' to work.
allowNewer = fromFlagOrDefault False $
fmap isAllowNewer (configAllowNewer configExFlags)
defaultVersionRange = if allowNewer
then orLaterVersion (Version [1,19,2] [])
else anyVersion
-- | Configure the package found in the local directory
configure :: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> Platform
-> ProgramConfiguration
-> ConfigFlags
-> ConfigExFlags
-> [String]
-> IO ()
configure verbosity packageDBs repoCtxt comp platform conf
configFlags configExFlags extraArgs = do
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
sourcePkgDb <- getSourcePackages verbosity repoCtxt
checkConfigExFlags verbosity installedPkgIndex
(packageIndex sourcePkgDb) configExFlags
progress <- planLocalPackage verbosity comp platform configFlags configExFlags
installedPkgIndex sourcePkgDb
notice verbosity "Resolving dependencies..."
maybePlan <- foldProgress logMsg (return . Left) (return . Right)
progress
case maybePlan of
Left message -> do
info verbosity $
"Warning: solver failed to find a solution:\n"
++ message
++ "Trying configure anyway."
setupWrapper verbosity (setupScriptOptions installedPkgIndex Nothing)
Nothing configureCommand (const configFlags) extraArgs
Right installPlan -> case InstallPlan.ready installPlan of
[pkg@(ReadyPackage
(ConfiguredPackage (SourcePackage _ _ (LocalUnpackedPackage _) _)
_ _ _)
_)] -> do
configurePackage verbosity
platform (compilerInfo comp)
(setupScriptOptions installedPkgIndex (Just pkg))
configFlags pkg extraArgs
_ -> die $ "internal error: configure install plan should have exactly "
++ "one local ready package."
where
setupScriptOptions :: InstalledPackageIndex
-> Maybe ReadyPackage
-> SetupScriptOptions
setupScriptOptions =
configureSetupScript
packageDBs
comp
platform
conf
(fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(configDistPref configFlags))
(chooseCabalVersion
configExFlags
(flagToMaybe (configCabalVersion configExFlags)))
Nothing
False
logMsg message rest = debug verbosity message >> rest
configureSetupScript :: PackageDBStack
-> Compiler
-> Platform
-> ProgramConfiguration
-> FilePath
-> VersionRange
-> Maybe Lock
-> Bool
-> InstalledPackageIndex
-> Maybe ReadyPackage
-> SetupScriptOptions
configureSetupScript packageDBs
comp
platform
conf
distPref
cabalVersion
lock
forceExternal
index
mpkg
= SetupScriptOptions {
useCabalVersion = cabalVersion
, useCabalSpecVersion = Nothing
, useCompiler = Just comp
, usePlatform = Just platform
, usePackageDB = packageDBs'
, usePackageIndex = index'
, useProgramConfig = conf
, useDistPref = distPref
, useLoggingHandle = Nothing
, useWorkingDir = Nothing
, setupCacheLock = lock
, useWin32CleanHack = False
, forceExternalSetupMethod = forceExternal
-- If we have explicit setup dependencies, list them; otherwise, we give
-- the empty list of dependencies; ideally, we would fix the version of
-- Cabal here, so that we no longer need the special case for that in
-- `compileSetupExecutable` in `externalSetupMethod`, but we don't yet
-- know the version of Cabal at this point, but only find this there.
-- Therefore, for now, we just leave this blank.
, useDependencies = fromMaybe [] explicitSetupDeps
, useDependenciesExclusive = isJust explicitSetupDeps
, useVersionMacros = isJust explicitSetupDeps
}
where
-- When we are compiling a legacy setup script without an explicit
-- setup stanza, we typically want to allow the UserPackageDB for
-- finding the Cabal lib when compiling any Setup.hs even if we're doing
-- a global install. However we also allow looking in a specific package
-- db.
packageDBs' :: PackageDBStack
index' :: Maybe InstalledPackageIndex
(packageDBs', index') =
case packageDBs of
(GlobalPackageDB:dbs) | UserPackageDB `notElem` dbs
, Nothing <- explicitSetupDeps
-> (GlobalPackageDB:UserPackageDB:dbs, Nothing)
-- but if the user is using an odd db stack, don't touch it
_otherwise -> (packageDBs, Just index)
explicitSetupDeps :: Maybe [(UnitId, PackageId)]
explicitSetupDeps = do
ReadyPackage (ConfiguredPackage (SourcePackage _ gpkg _ _) _ _ _) deps
<- mpkg
-- Check if there is an explicit setup stanza
_buildInfo <- PkgDesc.setupBuildInfo (PkgDesc.packageDescription gpkg)
-- Return the setup dependencies computed by the solver
return [ ( Installed.installedUnitId deppkg
, Installed.sourcePackageId deppkg
)
| deppkg <- CD.setupDeps deps
]
-- | Warn if any constraints or preferences name packages that are not in the
-- source package index or installed package index.
checkConfigExFlags :: Package pkg
=> Verbosity
-> InstalledPackageIndex
-> PackageIndex pkg
-> ConfigExFlags
-> IO ()
checkConfigExFlags verbosity installedPkgIndex sourcePkgIndex flags = do
unless (null unknownConstraints) $ warn verbosity $
"Constraint refers to an unknown package: "
++ showConstraint (head unknownConstraints)
unless (null unknownPreferences) $ warn verbosity $
"Preference refers to an unknown package: "
++ display (head unknownPreferences)
where
unknownConstraints = filter (unknown . userConstraintPackageName . fst) $
configExConstraints flags
unknownPreferences = filter (unknown . \(Dependency name _) -> name) $
configPreferences flags
unknown pkg = null (lookupPackageName installedPkgIndex pkg)
&& not (elemByPackageName sourcePkgIndex pkg)
showConstraint (uc, src) =
display uc ++ " (" ++ showConstraintSource src ++ ")"
-- | Make an 'InstallPlan' for the unpacked package in the current directory,
-- and all its dependencies.
--
planLocalPackage :: Verbosity -> Compiler
-> Platform
-> ConfigFlags -> ConfigExFlags
-> InstalledPackageIndex
-> SourcePackageDb
-> IO (Progress String String InstallPlan)
planLocalPackage verbosity comp platform configFlags configExFlags
installedPkgIndex
(SourcePackageDb _ packagePrefs) = do
pkg <- readPackageDescription verbosity =<< defaultPackageDesc verbosity
solver <- chooseSolver verbosity (fromFlag $ configSolver configExFlags)
(compilerInfo comp)
let -- We create a local package and ask to resolve a dependency on it
localPkg = SourcePackage {
packageInfoId = packageId pkg,
Source.packageDescription = pkg,
packageSource = LocalUnpackedPackage ".",
packageDescrOverride = Nothing
}
testsEnabled = fromFlagOrDefault False $ configTests configFlags
benchmarksEnabled =
fromFlagOrDefault False $ configBenchmarks configFlags
resolverParams =
removeUpperBounds (fromFlagOrDefault AllowNewerNone $
configAllowNewer configExFlags)
. addPreferences
-- preferences from the config file or command line
[ PackageVersionPreference name ver
| Dependency name ver <- configPreferences configExFlags ]
. addConstraints
-- version constraints from the config file or command line
-- TODO: should warn or error on constraints that are not on direct
-- deps or flag constraints not on the package in question.
[ LabeledPackageConstraint (userToPackageConstraint uc) src
| (uc, src) <- configExConstraints configExFlags ]
. addConstraints
-- package flags from the config file or command line
[ let pc = PackageConstraintFlags (packageName pkg)
(configConfigurationsFlags configFlags)
in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
]
. addConstraints
-- '--enable-tests' and '--enable-benchmarks' constraints from
-- the config file or command line
[ let pc = PackageConstraintStanzas (packageName pkg) $
[ TestStanzas | testsEnabled ] ++
[ BenchStanzas | benchmarksEnabled ]
in LabeledPackageConstraint pc ConstraintSourceConfigFlagOrTarget
]
$ standardInstallPolicy
installedPkgIndex
(SourcePackageDb mempty packagePrefs)
[SpecificSourcePackage localPkg]
return (resolveDependencies platform (compilerInfo comp) solver resolverParams)
-- | Call an installer for an 'SourcePackage' but override the configure
-- flags with the ones given by the 'ReadyPackage'. In particular the
-- 'ReadyPackage' specifies an exact 'FlagAssignment' and exactly
-- versioned package dependencies. So we ignore any previous partial flag
-- assignment or dependency constraints and use the new ones.
--
-- NB: when updating this function, don't forget to also update
-- 'installReadyPackage' in D.C.Install.
configurePackage :: Verbosity
-> Platform -> CompilerInfo
-> SetupScriptOptions
-> ConfigFlags
-> ReadyPackage
-> [String]
-> IO ()
configurePackage verbosity platform comp scriptOptions configFlags
(ReadyPackage (ConfiguredPackage (SourcePackage _ gpkg _ _)
flags stanzas _)
deps)
extraArgs =
setupWrapper verbosity
scriptOptions (Just pkg) configureCommand configureFlags extraArgs
where
configureFlags = filterConfigureFlags configFlags {
configConfigurationsFlags = flags,
-- We generate the legacy constraints as well as the new style precise
-- deps. In the end only one set gets passed to Setup.hs configure,
-- depending on the Cabal version we are talking to.
configConstraints = [ thisPackageVersion (packageId deppkg)
| deppkg <- CD.nonSetupDeps deps ],
configDependencies = [ (packageName (Installed.sourcePackageId deppkg),
Installed.installedUnitId deppkg)
| deppkg <- CD.nonSetupDeps deps ],
-- Use '--exact-configuration' if supported.
configExactConfiguration = toFlag True,
configVerbosity = toFlag verbosity,
configBenchmarks = toFlag (BenchStanzas `elem` stanzas),
configTests = toFlag (TestStanzas `elem` stanzas)
}
pkg = case finalizePackageDescription flags
(const True)
platform comp [] (enableStanzas stanzas gpkg) of
Left _ -> error "finalizePackageDescription ReadyPackage failed"
Right (desc, _) -> desc
| lukexi/cabal | cabal-install/Distribution/Client/Configure.hs | bsd-3-clause | 15,577 | 9 | 22 | 4,492 | 2,524 | 1,376 | 1,148 | 273 | 3 |
{-# LANGUAGE CPP, ForeignFunctionInterface, BangPatterns #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable #-}
#endif
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Module : Data.ByteString.Lazy.Internal
-- Copyright : (c) Don Stewart 2006-2008
-- (c) Duncan Coutts 2006-2011
-- License : BSD-style
-- Maintainer : [email protected], [email protected]
-- Stability : unstable
-- Portability : non-portable
--
-- A module containing semi-public 'ByteString' internals. This exposes
-- the 'ByteString' representation and low level construction functions.
-- Modules which extend the 'ByteString' system will need to use this module
-- while ideally most users will be able to make do with the public interface
-- modules.
--
module Data.ByteString.Lazy.Internal (
-- * The lazy @ByteString@ type and representation
ByteString(..), -- instances: Eq, Ord, Show, Read, Data, Typeable
chunk,
foldrChunks,
foldlChunks,
-- * Data type invariant and abstraction function
invariant,
checkInvariant,
-- * Chunk allocation sizes
defaultChunkSize,
smallChunkSize,
chunkOverhead,
-- * Conversion with lists: packing and unpacking
packBytes, packChars,
unpackBytes, unpackChars,
) where
import Prelude hiding (concat)
import qualified Data.ByteString.Internal as S
import qualified Data.ByteString as S (length, take, drop)
import Data.Word (Word8)
import Foreign.Storable (Storable(sizeOf))
import Data.Monoid (Monoid(..))
import Control.DeepSeq (NFData, rnf)
#if MIN_VERSION_base(3,0,0)
import Data.String (IsString(..))
#endif
import Data.Typeable (Typeable)
#if MIN_VERSION_base(4,1,0)
import Data.Data (Data(..))
#if MIN_VERSION_base(4,2,0)
import Data.Data (mkNoRepType)
#else
import Data.Data (mkNorepType)
#endif
#else
import Data.Generics (Data(..), mkNorepType)
#endif
-- | A space-efficient representation of a Word8 vector, supporting many
-- efficient operations. A 'ByteString' contains 8-bit characters only.
--
-- Instances of Eq, Ord, Read, Show, Data, Typeable
--
data ByteString = Empty | Chunk {-# UNPACK #-} !S.ByteString ByteString
#if defined(__GLASGOW_HASKELL__)
deriving (Typeable)
#endif
instance Eq ByteString where
(==) = eq
instance Ord ByteString where
compare = cmp
instance Monoid ByteString where
mempty = Empty
mappend = append
mconcat = concat
instance NFData ByteString where
rnf Empty = ()
rnf (Chunk _ b) = rnf b
instance Show ByteString where
showsPrec p ps r = showsPrec p (unpackChars ps) r
instance Read ByteString where
readsPrec p str = [ (packChars x, y) | (x, y) <- readsPrec p str ]
#if MIN_VERSION_base(3,0,0)
instance IsString ByteString where
fromString = packChars
#endif
instance Data ByteString where
gfoldl f z txt = z packBytes `f` unpackBytes txt
toConstr _ = error "Data.ByteString.Lazy.ByteString.toConstr"
gunfold _ _ = error "Data.ByteString.Lazy.ByteString.gunfold"
#if MIN_VERSION_base(4,2,0)
dataTypeOf _ = mkNoRepType "Data.ByteString.Lazy.ByteString"
#else
dataTypeOf _ = mkNorepType "Data.ByteString.Lazy.ByteString"
#endif
------------------------------------------------------------------------
-- Packing and unpacking from lists
packBytes :: [Word8] -> ByteString
packBytes cs0 =
packChunks 32 cs0
where
packChunks n cs = case S.packUptoLenBytes n cs of
(bs, []) -> chunk bs Empty
(bs, cs') -> Chunk bs (packChunks (min (n * 2) smallChunkSize) cs')
packChars :: [Char] -> ByteString
packChars cs0 =
packChunks 32 cs0
where
packChunks n cs = case S.packUptoLenChars n cs of
(bs, []) -> chunk bs Empty
(bs, cs') -> Chunk bs (packChunks (min (n * 2) smallChunkSize) cs')
unpackBytes :: ByteString -> [Word8]
unpackBytes Empty = []
unpackBytes (Chunk c cs) = S.unpackAppendBytesLazy c (unpackBytes cs)
unpackChars :: ByteString -> [Char]
unpackChars Empty = []
unpackChars (Chunk c cs) = S.unpackAppendCharsLazy c (unpackChars cs)
------------------------------------------------------------------------
-- | The data type invariant:
-- Every ByteString is either 'Empty' or consists of non-null 'S.ByteString's.
-- All functions must preserve this, and the QC properties must check this.
--
invariant :: ByteString -> Bool
invariant Empty = True
invariant (Chunk (S.PS _ _ len) cs) = len > 0 && invariant cs
-- | In a form that checks the invariant lazily.
checkInvariant :: ByteString -> ByteString
checkInvariant Empty = Empty
checkInvariant (Chunk c@(S.PS _ _ len) cs)
| len > 0 = Chunk c (checkInvariant cs)
| otherwise = error $ "Data.ByteString.Lazy: invariant violation:"
++ show (Chunk c cs)
------------------------------------------------------------------------
-- | Smart constructor for 'Chunk'. Guarantees the data type invariant.
chunk :: S.ByteString -> ByteString -> ByteString
chunk c@(S.PS _ _ len) cs | len == 0 = cs
| otherwise = Chunk c cs
{-# INLINE chunk #-}
-- | Consume the chunks of a lazy ByteString with a natural right fold.
foldrChunks :: (S.ByteString -> a -> a) -> a -> ByteString -> a
foldrChunks f z = go
where go Empty = z
go (Chunk c cs) = f c (go cs)
{-# INLINE foldrChunks #-}
-- | Consume the chunks of a lazy ByteString with a strict, tail-recursive,
-- accumulating left fold.
foldlChunks :: (a -> S.ByteString -> a) -> a -> ByteString -> a
foldlChunks f z = go z
where go a _ | a `seq` False = undefined
go a Empty = a
go a (Chunk c cs) = go (f a c) cs
{-# INLINE foldlChunks #-}
------------------------------------------------------------------------
-- The representation uses lists of packed chunks. When we have to convert from
-- a lazy list to the chunked representation, then by default we use this
-- chunk size. Some functions give you more control over the chunk size.
--
-- Measurements here:
-- http://www.cse.unsw.edu.au/~dons/tmp/chunksize_v_cache.png
--
-- indicate that a value around 0.5 to 1 x your L2 cache is best.
-- The following value assumes people have something greater than 128k,
-- and need to share the cache with other programs.
-- | The chunk size used for I\/O. Currently set to 32k, less the memory management overhead
defaultChunkSize :: Int
defaultChunkSize = 32 * k - chunkOverhead
where k = 1024
-- | The recommended chunk size. Currently set to 4k, less the memory management overhead
smallChunkSize :: Int
smallChunkSize = 4 * k - chunkOverhead
where k = 1024
-- | The memory management overhead. Currently this is tuned for GHC only.
chunkOverhead :: Int
chunkOverhead = 2 * sizeOf (undefined :: Int)
------------------------------------------------------------------------
-- Implementations for Eq, Ord and Monoid instances
eq :: ByteString -> ByteString -> Bool
eq Empty Empty = True
eq Empty _ = False
eq _ Empty = False
eq (Chunk a as) (Chunk b bs) =
case compare (S.length a) (S.length b) of
LT -> a == (S.take (S.length a) b) && eq as (Chunk (S.drop (S.length a) b) bs)
EQ -> a == b && eq as bs
GT -> (S.take (S.length b) a) == b && eq (Chunk (S.drop (S.length b) a) as) bs
cmp :: ByteString -> ByteString -> Ordering
cmp Empty Empty = EQ
cmp Empty _ = LT
cmp _ Empty = GT
cmp (Chunk a as) (Chunk b bs) =
case compare (S.length a) (S.length b) of
LT -> case compare a (S.take (S.length a) b) of
EQ -> cmp as (Chunk (S.drop (S.length a) b) bs)
result -> result
EQ -> case compare a b of
EQ -> cmp as bs
result -> result
GT -> case compare (S.take (S.length b) a) b of
EQ -> cmp (Chunk (S.drop (S.length b) a) as) bs
result -> result
append :: ByteString -> ByteString -> ByteString
append xs ys = foldrChunks Chunk ys xs
concat :: [ByteString] -> ByteString
concat css0 = to css0
where
go Empty css = to css
go (Chunk c cs) css = Chunk c (go cs css)
to [] = Empty
to (cs:css) = go cs css
| markflorisson/hpack | testrepo/bytestring-0.10.2.0/Data/ByteString/Lazy/Internal.hs | bsd-3-clause | 8,289 | 0 | 18 | 1,927 | 1,979 | 1,064 | 915 | 126 | 6 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Build the project.
module Stack.Build
(build
,loadPackage
,mkBaseConfigOpts
,queryBuildInfo
,splitObjsWarning
,CabalVersionException(..))
where
import Stack.Prelude hiding (loadPackage)
import Data.Aeson (Value (Object, Array), (.=), object)
import qualified Data.HashMap.Strict as HM
import Data.List ((\\), isPrefixOf)
import Data.List.Extra (groupSort)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as TIO
import Data.Text.Read (decimal)
import qualified Data.Vector as V
import qualified Data.Yaml as Yaml
import qualified Distribution.PackageDescription as C
import Distribution.Types.Dependency (depLibraries)
import Distribution.Version (mkVersion)
import Path (parent)
import Stack.Build.ConstructPlan
import Stack.Build.Execute
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Package
import Stack.Types.Build
import Stack.Types.Config
import Stack.Types.NamedComponent
import Stack.Types.Package
import Stack.Types.SourceMap
import Stack.Types.Compiler (compilerVersionText, getGhcVersion)
import System.Terminal (fixCodePage)
-- | Build.
--
-- If a buildLock is passed there is an important contract here. That lock must
-- protect the snapshot, and it must be safe to unlock it if there are no further
-- modifications to the snapshot to be performed by this build.
build :: HasEnvConfig env
=> Maybe (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files
-> RIO env ()
build msetLocalFiles = do
mcp <- view $ configL.to configModifyCodePage
ghcVersion <- view $ actualCompilerVersionL.to getGhcVersion
fixCodePage mcp ghcVersion $ do
bopts <- view buildOptsL
sourceMap <- view $ envConfigL.to envConfigSourceMap
locals <- projectLocalPackages
depsLocals <- localDependencies
let allLocals = locals <> depsLocals
checkSubLibraryDependencies (Map.elems $ smProject sourceMap)
boptsCli <- view $ envConfigL.to envConfigBuildOptsCLI
-- Set local files, necessary for file watching
stackYaml <- view stackYamlL
for_ msetLocalFiles $ \setLocalFiles -> do
files <-
if boptsCLIWatchAll boptsCli
then sequence [lpFiles lp | lp <- allLocals]
else forM allLocals $ \lp -> do
let pn = packageName (lpPackage lp)
case Map.lookup pn (smtTargets $ smTargets sourceMap) of
Nothing ->
pure Set.empty
Just (TargetAll _) ->
lpFiles lp
Just (TargetComps components) ->
lpFilesForComponents components lp
liftIO $ setLocalFiles $ Set.insert stackYaml $ Set.unions files
checkComponentsBuildable allLocals
installMap <- toInstallMap sourceMap
(installedMap, globalDumpPkgs, snapshotDumpPkgs, localDumpPkgs) <-
getInstalled installMap
baseConfigOpts <- mkBaseConfigOpts boptsCli
plan <- constructPlan baseConfigOpts localDumpPkgs loadPackage sourceMap installedMap (boptsCLIInitialBuildSteps boptsCli)
allowLocals <- view $ configL.to configAllowLocals
unless allowLocals $ case justLocals plan of
[] -> return ()
localsIdents -> throwM $ LocalPackagesPresent localsIdents
checkCabalVersion
warnAboutSplitObjs bopts
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan
when (boptsPreFetch bopts) $
preFetch plan
if boptsCLIDryrun boptsCli
then printPlan plan
else executePlan boptsCli baseConfigOpts locals
globalDumpPkgs
snapshotDumpPkgs
localDumpPkgs
installedMap
(smtTargets $ smTargets sourceMap)
plan
justLocals :: Plan -> [PackageIdentifier]
justLocals =
map taskProvides .
filter ((== Local) . taskLocation) .
Map.elems .
planTasks
checkCabalVersion :: HasEnvConfig env => RIO env ()
checkCabalVersion = do
allowNewer <- view $ configL.to configAllowNewer
cabalVer <- view cabalVersionL
-- https://github.com/haskell/cabal/issues/2023
when (allowNewer && cabalVer < mkVersion [1, 22]) $ throwM $
CabalVersionException $
"Error: --allow-newer requires at least Cabal version 1.22, but version " ++
versionString cabalVer ++
" was found."
-- Since --exact-configuration is always passed, some old cabal
-- versions can no longer be used. See the following link for why
-- it's 1.19.2:
-- https://github.com/haskell/cabal/blob/580fe6b6bf4e1648b2f66c1cb9da9f1f1378492c/cabal-install/Distribution/Client/Setup.hs#L592
when (cabalVer < mkVersion [1, 19, 2]) $ throwM $
CabalVersionException $
"Stack no longer supports Cabal versions older than 1.19.2, but version " ++
versionString cabalVer ++
" was found. To fix this, consider updating the resolver to lts-3.0 or later / nightly-2015-05-05 or later."
newtype CabalVersionException = CabalVersionException { unCabalVersionException :: String }
deriving (Typeable)
instance Show CabalVersionException where show = unCabalVersionException
instance Exception CabalVersionException
-- | See https://github.com/commercialhaskell/stack/issues/1198.
warnIfExecutablesWithSameNameCouldBeOverwritten
:: HasLogFunc env => [LocalPackage] -> Plan -> RIO env ()
warnIfExecutablesWithSameNameCouldBeOverwritten locals plan = do
logDebug "Checking if we are going to build multiple executables with the same name"
forM_ (Map.toList warnings) $ \(exe,(toBuild,otherLocals)) -> do
let exe_s
| length toBuild > 1 = "several executables with the same name:"
| otherwise = "executable"
exesText pkgs =
T.intercalate
", "
["'" <> T.pack (packageNameString p) <> ":" <> exe <> "'" | p <- pkgs]
(logWarn . display . T.unlines . concat)
[ [ "Building " <> exe_s <> " " <> exesText toBuild <> "." ]
, [ "Only one of them will be available via 'stack exec' or locally installed."
| length toBuild > 1
]
, [ "Other executables with the same name might be overwritten: " <>
exesText otherLocals <> "."
| not (null otherLocals)
]
]
where
-- Cases of several local packages having executables with the same name.
-- The Map entries have the following form:
--
-- executable name: ( package names for executables that are being built
-- , package names for other local packages that have an
-- executable with the same name
-- )
warnings :: Map Text ([PackageName],[PackageName])
warnings =
Map.mapMaybe
(\(pkgsToBuild,localPkgs) ->
case (pkgsToBuild,NE.toList localPkgs \\ NE.toList pkgsToBuild) of
(_ :| [],[]) ->
-- We want to build the executable of single local package
-- and there are no other local packages with an executable of
-- the same name. Nothing to warn about, ignore.
Nothing
(_,otherLocals) ->
-- We could be here for two reasons (or their combination):
-- 1) We are building two or more executables with the same
-- name that will end up overwriting each other.
-- 2) In addition to the executable(s) that we want to build
-- there are other local packages with an executable of the
-- same name that might get overwritten.
-- Both cases warrant a warning.
Just (NE.toList pkgsToBuild,otherLocals))
(Map.intersectionWith (,) exesToBuild localExes)
exesToBuild :: Map Text (NonEmpty PackageName)
exesToBuild =
collect
[ (exe,pkgName')
| (pkgName',task) <- Map.toList (planTasks plan)
, TTLocalMutable lp <- [taskType task]
, exe <- (Set.toList . exeComponents . lpComponents) lp
]
localExes :: Map Text (NonEmpty PackageName)
localExes =
collect
[ (exe,packageName pkg)
| pkg <- map lpPackage locals
, exe <- Set.toList (packageExes pkg)
]
collect :: Ord k => [(k,v)] -> Map k (NonEmpty v)
collect = Map.map NE.fromList . Map.fromDistinctAscList . groupSort
warnAboutSplitObjs :: HasLogFunc env => BuildOpts -> RIO env ()
warnAboutSplitObjs bopts | boptsSplitObjs bopts = do
logWarn $ "Building with --split-objs is enabled. " <> fromString splitObjsWarning
warnAboutSplitObjs _ = return ()
splitObjsWarning :: String
splitObjsWarning = unwords
[ "Note that this feature is EXPERIMENTAL, and its behavior may be changed and improved."
, "You will need to clean your workdirs before use. If you want to compile all dependencies"
, "with split-objs, you will need to delete the snapshot (and all snapshots that could"
, "reference that snapshot)."
]
-- | Get the @BaseConfigOpts@ necessary for constructing configure options
mkBaseConfigOpts :: (HasEnvConfig env)
=> BuildOptsCLI -> RIO env BaseConfigOpts
mkBaseConfigOpts boptsCli = do
bopts <- view buildOptsL
snapDBPath <- packageDatabaseDeps
localDBPath <- packageDatabaseLocal
snapInstallRoot <- installationRootDeps
localInstallRoot <- installationRootLocal
packageExtraDBs <- packageDatabaseExtra
return BaseConfigOpts
{ bcoSnapDB = snapDBPath
, bcoLocalDB = localDBPath
, bcoSnapInstallRoot = snapInstallRoot
, bcoLocalInstallRoot = localInstallRoot
, bcoBuildOpts = bopts
, bcoBuildOptsCLI = boptsCli
, bcoExtraDBs = packageExtraDBs
}
-- | Provide a function for loading package information from the package index
loadPackage
:: (HasBuildConfig env, HasSourceMap env)
=> PackageLocationImmutable
-> Map FlagName Bool
-> [Text] -- ^ GHC options
-> [Text] -- ^ Cabal configure options
-> RIO env Package
loadPackage loc flags ghcOptions cabalConfigOpts = do
compiler <- view actualCompilerVersionL
platform <- view platformL
let pkgConfig = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = flags
, packageConfigGhcOptions = ghcOptions
, packageConfigCabalConfigOpts = cabalConfigOpts
, packageConfigCompilerVersion = compiler
, packageConfigPlatform = platform
}
resolvePackage pkgConfig <$> loadCabalFileImmutable loc
-- | Query information about the build and print the result to stdout in YAML format.
queryBuildInfo :: HasEnvConfig env
=> [Text] -- ^ selectors
-> RIO env ()
queryBuildInfo selectors0 =
rawBuildInfo
>>= select id selectors0
>>= liftIO . TIO.putStrLn . addGlobalHintsComment . decodeUtf8 . Yaml.encode
where
select _ [] value = return value
select front (sel:sels) value =
case value of
Object o ->
case HM.lookup sel o of
Nothing -> err "Selector not found"
Just value' -> cont value'
Array v ->
case decimal sel of
Right (i, "")
| i >= 0 && i < V.length v -> cont $ v V.! i
| otherwise -> err "Index out of range"
_ -> err "Encountered array and needed numeric selector"
_ -> err $ "Cannot apply selector to " ++ show value
where
cont = select (front . (sel:)) sels
err msg = throwString $ msg ++ ": " ++ show (front [sel])
-- Include comments to indicate that this portion of the "stack
-- query" API is not necessarily stable.
addGlobalHintsComment
| null selectors0 = T.replace globalHintsLine ("\n" <> globalHintsComment <> globalHintsLine)
-- Append comment instead of pre-pending. The reasoning here is
-- that something *could* expect that the result of 'stack query
-- global-hints ghc-boot' is just a string literal. Seems easier
-- for to expect the first line of the output to be the literal.
| ["global-hints"] `isPrefixOf` selectors0 = (<> ("\n" <> globalHintsComment))
| otherwise = id
globalHintsLine = "\nglobal-hints:\n"
globalHintsComment = T.concat
[ "# Note: global-hints is experimental and may be renamed / removed in the future.\n"
, "# See https://github.com/commercialhaskell/stack/issues/3796"
]
-- | Get the raw build information object
rawBuildInfo :: HasEnvConfig env => RIO env Value
rawBuildInfo = do
locals <- projectLocalPackages
wantedCompiler <- view $ wantedCompilerVersionL.to (utf8BuilderToText . display)
actualCompiler <- view $ actualCompilerVersionL.to compilerVersionText
return $ object
[ "locals" .= Object (HM.fromList $ map localToPair locals)
, "compiler" .= object
[ "wanted" .= wantedCompiler
, "actual" .= actualCompiler
]
]
where
localToPair lp =
(T.pack $ packageNameString $ packageName p, value)
where
p = lpPackage lp
value = object
[ "version" .= CabalString (packageVersion p)
, "path" .= toFilePath (parent $ lpCabalFile lp)
]
checkComponentsBuildable :: MonadThrow m => [LocalPackage] -> m ()
checkComponentsBuildable lps =
unless (null unbuildable) $ throwM $ SomeTargetsNotBuildable unbuildable
where
unbuildable =
[ (packageName (lpPackage lp), c)
| lp <- lps
, c <- Set.toList (lpUnbuildable lp)
]
-- | Find if sublibrary dependency exist in each project
checkSubLibraryDependencies :: HasLogFunc env => [ProjectPackage] -> RIO env ()
checkSubLibraryDependencies proj = do
forM_ proj $ \p -> do
C.GenericPackageDescription _ _ lib subLibs foreignLibs exes tests benches <- liftIO $ cpGPD . ppCommon $ p
let dependencies = concatMap getDeps subLibs <>
concatMap getDeps foreignLibs <>
concatMap getDeps exes <>
concatMap getDeps tests <>
concatMap getDeps benches <>
maybe [] C.condTreeConstraints lib
libraries = concatMap (toList . depLibraries) dependencies
when (subLibDepExist libraries)
(logWarn "SubLibrary dependency is not supported, this will almost certainly fail")
where
getDeps (_, C.CondNode _ dep _) = dep
subLibDepExist lib =
any (\x ->
case x of
C.LSubLibName _ -> True
C.LMainLibName -> False
) lib
| juhp/stack | src/Stack/Build.hs | bsd-3-clause | 15,564 | 0 | 25 | 4,475 | 3,136 | 1,624 | 1,512 | 284 | 6 |
{-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-}
{-# LANGUAGE MagicHash, UndecidableInstances, OverlappingInstances #-}
module Idris.RunIO where
-- import SimplDSL
import Ivor.TT
import Ivor.Shell
import Ivor.Construction
import Data.Typeable
import Data.IORef
import System.IO.Unsafe
import System.IO
import Control.Monad.Error
import Control.Concurrent
import Debug.Trace
newtype Lock = Lock QSem
instance Typeable Lock where
typeOf a = mkTyConApp (mkTyCon "Lock") []
instance Show Lock where
show x = "<<Lock>>"
instance Eq Lock where
(==) x y = False -- Hmm
instance ViewConst Handle where
typeof x = (name "Handle")
instance ViewConst Lock where
typeof x = (name "Lock")
exec :: Context -> Term -> IO ()
exec ctxt wurzel = do res <- runIO ctxt (view (whnf ctxt wurzel))
putStrLn $ show res
runIO :: Context -> ViewTerm -> IO ViewTerm
runIO ctxt (App (App (App (Name _ d) _) act) k)
| d == name "IODo" = runAction ctxt (parseAction act) k
runIO ctxt (App (App (Name _ l) _) res)
| l == name "IOReturn" = return res
runIO _ x = fail $ "Not an IO action: " ++ show x
data Action = ReadStr
| WriteStr String
| Fork ViewTerm
| NewLock Int
| DoLock Lock
| DoUnlock Lock
| NewRef
| ReadRef Int
| WriteRef Int ViewTerm
| CantReduce ViewTerm
parseAction x = parseAction' x [] where
parseAction' (App f a) args = parseAction' f (a:args)
parseAction' (Name _ n) args = (getAction n args)
getAction n []
| n == name "GetStr" = ReadStr
getAction n [Constant str]
| n == name "PutStr"
= case cast str of
Just str' -> WriteStr str'
getAction n [_,t]
| n == name "Fork"
= Fork t
getAction n [Constant i]
| n == name "NewLock"
= case cast i of
Just i' -> NewLock i'
getAction n [lock]
| n == name "DoLock"
= DoLock (getLock lock)
| n == name "DoUnlock"
= DoUnlock (getLock lock)
getAction n []
| n == name "NewRef" = NewRef
getAction n [_,Constant i]
| n == name "ReadRef"
= case cast i of
Just i' -> ReadRef i'
getAction n [_,Constant i,val]
| n == name "WriteRef"
= case cast i of
Just i' -> WriteRef i' val
getAction n args = CantReduce (apply (Name Unknown n) args)
getHandle (App _ (Constant h)) = case cast h of
Just h' -> h'
getLock (Constant h) = case cast h of
Just h' -> h'
Nothing -> error ("Lock error in constant " ++ show h)
getLock x = error ("Lock error " ++ show x)
continue ctxt k arg = case fastCheck ctxt (App k arg) of
t -> let next = whnf ctxt t in
runIO ctxt (view next)
{- Right t -> let next = whnf ctxt t in
runIO ctxt (view next)
Left err -> fail $ "Can't happen - continue " ++ err ++ "\n" ++ show k ++ "\n" ++ show arg
-}
unit = Name Unknown (name "II")
runAction ctxt (WriteStr str) k
-- Print the string, then run the continuation with the argument 'II'
= do putStr str
hFlush stdout
continue ctxt k unit
runAction ctxt ReadStr k
-- Read a string then run the continuation with the constant str
= do str <- getLine
continue ctxt k (Constant str)
runAction ctxt (Fork t) k
= do forkIO (do x <- runIO ctxt t
return ())
continue ctxt k unit
runAction ctxt (NewLock n) k
= do mv <- newQSem n
continue ctxt k (Constant (Lock mv))
runAction ctxt (DoLock l) k
= do primLock l
continue ctxt k unit
runAction ctxt (DoUnlock l) k
= do primUnlock l
continue ctxt k unit
runAction ctxt NewRef k
= do i <- newRef
continue ctxt k (Constant i)
runAction ctxt (ReadRef i) k
= do v <- getMem i
continue ctxt k v
runAction ctxt (WriteRef i val) k
= do putMem i val
continue ctxt k unit
runAction ctxt (CantReduce t) k
= do fail $ "Stuck at: " ++ show t
-- hFlush stdout
primLock :: Lock -> IO ()
primLock (Lock lock) = do waitQSem lock
primUnlock :: Lock -> IO ()
primUnlock (Lock lock) = signalQSem lock
-- Some mutable memory, for implementing IORefs idris side.
type Value = ViewTerm
defaultVal = (Constant (0xDEADBEEF::Int))
data MemState = MemState (IORef (Int, [Value]))
memory :: MemState
memory = unsafePerformIO
(do mem <- newIORef (0, (take 100 (repeat defaultVal)))
return (MemState mem))
newRef :: IO Int
newRef = do let (MemState mem) = memory
(p,ref) <- readIORef mem
writeIORef mem (p+1, ref)
return p
putMem :: Int -> Value -> IO ()
putMem loc val = do let (MemState mem) = memory
(p,content) <- readIORef mem
writeIORef mem (p, update content loc val)
getMem :: Int -> IO Value
getMem loc = do let (MemState mem) = memory
(p, content) <- readIORef mem
return (content!!loc)
update :: [a] -> Int -> a -> [a]
update [] _ _ = []
update (x:xs) 0 v = (v:xs)
update (x:xs) n v = x:(update xs (n-1) v)
| avsm/Idris | Idris/RunIO.hs | bsd-3-clause | 5,393 | 0 | 15 | 1,770 | 1,971 | 955 | 1,016 | 144 | 2 |
module Widgets where
import Graphics.UI.Threepenny.Core
import qualified Graphics.UI.Threepenny as UI
import Control.Applicative
import Control.Monad (void, mapM, zipWithM_)
collapsiblePanel :: String -> UI Element -> String -> [UI Element] -> UI Element
collapsiblePanel ident titleLevel title contents = do
toggle <- string "+" #. "toggleCollapse"
collapsingSection <- UI.div #. "collapsible" # set style [("display","none")]
flipFlop <- UI.accumE True (not <$ UI.click toggle)
onEvent flipFlop $ \showing -> do
stateToggle <- toggle # get text
case showing of
False -> do
element collapsingSection # set style [("display", "block")]
element toggle # set text "-"
True -> do
element collapsingSection # set style [("display", "none")]
element toggle # set text "+"
UI.div #+ [
titleLevel #+ [element toggle, string title]
,element collapsingSection ## ident #+ contents
]
tabbedPanel :: Int -> String -> [(UI Element,[UI Element])] -> UI Element
tabbedPanel width ident tabs = do
let (titles, contents) = unzip tabs
tabCount = length tabs
-- 6px for paddings, 2px for margins, 2px for borders, 2 more for spaces ?
tabWidth = ((width `div` tabCount) - 12)
container <- UI.div #. "tabbedContainer" ## ident
activeTitles <-
mapM (\t -> UI.li #. "tab" # set UI.style [("width",show tabWidth ++ "px")] #+ [t]) titles
activeContents <-
mapM (\c -> UI.div #. "tabContent" #+ c) contents
let changingTab i = do
element (activeTitles !! i) # set UI.class_ "tab activeTab"
mapM (set UI.class_ "tab inactiveTab" . element) $ deleteIndex i activeTitles
element (activeContents !! i) # set style [("display", "block")]
mapM (set style [("display", "none")] . element) $ deleteIndex i activeContents
return ()
zipWithM_ (\i t -> on UI.click t $ \_ -> changingTab i) [0..] activeTitles
changingTab 0
element container #+ (
(UI.olist #. "tabs" #+ map element activeTitles)
: map element activeContents
)
deleteIndex _ [] = []
deleteIndex 0 (x:xs) = xs
deleteIndex n xs'@(x:xs)
| n < 0 = xs'
| otherwise = x : deleteIndex (n-1) xs
infixl 8 ##
e ## ident = e # set UI.id_ ident
| ocramz/CurveProject | src/Widgets.hs | bsd-3-clause | 2,249 | 0 | 19 | 515 | 874 | 435 | 439 | 50 | 2 |
import qualified Database.Concelo.Ignis as Ignis
main = Ignis.main
| Concelo/concelo | src/Main.hs | bsd-3-clause | 68 | 0 | 5 | 9 | 17 | 11 | 6 | 2 | 1 |
-- Problem 6: Sum square difference
--
-- https://projecteuler.net/problem=6
--
-- The sum of the squares of the first ten natural numbers is,
-- 1^2 + 2^2 + ... + 10^2 = 385
--
-- The square of the sum of the first ten natural numbers is,
-- (1 + 2 + ... + 10)^2 = 55^2 = 3025
--
-- Hence the difference between the sum of the squares of the first ten natural numbers
-- and the square of the sum is 3025 − 385 = 2640.
--
-- Find the difference between the sum of the squares of the first one hundred natural
-- numbers and the square of the sum.
squareOfSumDiff n = ((^2) $ sum [1..n]) - (sum $ map (^2) [1..n])
main = putStrLn $ show $ squareOfSumDiff 100
| moddyz/euler | p6/p6.hs | mit | 666 | 0 | 9 | 140 | 84 | 52 | 32 | 2 | 1 |
module ValidateTheWord where
import Data.List (elemIndex)
-- Use the Maybe type to write a function that
-- counts the number of vowels in a string and the
-- number of consonants. If the number of vowels
-- exceeds the number of consonants return Nothing.
-- In many human languages, vowels rarely exceed
-- the number of consonants so when they do, it
-- *may* indicate the input isn't a word.
newtype Word' =
Word' String
deriving (Eq, Show)
countVowels :: String -> Int
countVowels s =
foldr (\c acc -> if isVowel c then 1 + acc else acc) 0 s
where
isVowel c =
case elemIndex c "aeoiu" of
Just _ -> True
_ -> False
mkWord :: String -> Maybe Word'
mkWord w =
if vowelCount > consonantCount
then Nothing
else Just (Word' w)
where
vowelCount = countVowels w
consonantCount = length w - vowelCount
-- Next: ItsOnlyNaturalChapter12.hs | brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/ValidateTheWordChapter12.hs | mit | 908 | 0 | 10 | 224 | 187 | 102 | 85 | 19 | 3 |
module Graph.TreeWidth where
-- $Id$
import Graph.Util
import Autolib.Graph
import Autolib.Dot ( peng )
import Autolib.Graph.Basic
import Autolib.Graph.Ops
import Inter.Types
import Autolib.ToDoc
import Autolib.Size
import Autolib.Set
import Autolib.FiniteMap
import qualified Challenger as C
import Data.Typeable
import Data.List ( inits, tails )
data TreeWidth = TreeWidth deriving ( Eq, Ord, Show, Read, Typeable )
instance OrderScore TreeWidth where
scoringOrder _ = Increasing
instance C.Measure TreeWidth ( Graph Int, Int )
( FiniteMap Int (Set Int) , Graph Int ) where
measure p ( g, w ) ( fm, t ) = fromIntegral $
maximum $ do ( i, s ) <- fmToList fm ; return $ cardinality s
instance C.Partial TreeWidth ( Graph Int, Int )
( FiniteMap Int (Set Int) , Graph Int ) where
report p (g, w) = do
inform $ vcat
[ text "Gesucht ist eine Baum-Überdeckung"
, text "mit Weite <=" <+> toDoc w
, text "für diesen Graphen:"
, nest 4 $ toDoc g
]
peng g
initial p (g, w) =
let c = do
vs <- tails $ lknoten g
let s = mkSet $ take (succ w) vs
guard $ w < cardinality s
return s
v = [ 1 .. length c ]
in ( listToFM $ zip v c , Autolib.Graph.Basic.path v )
partial p (g, w) ( fm, t ) = do
inform $ text "Die Struktur Ihrer Überdeckung ist:"
-- setToList, damit die Beschriftung kleiner wird (sonst mkSet)
peng $ gmap ( \ i -> setToList $ lookupset fm i ) t
assert ( is_connected t
&& cardinality (kanten t) < cardinality (knoten g) )
( text "Ist das ein Baum?" )
inform $ text "Ist keine Menge zu groß?"
let large = do
(i, s) <- fmToList fm
guard $ cardinality s - 1 > w
return (i, s)
when ( not $ null large ) $ reject $ vcat
[ text "doch, diese:"
, nest 4 $ toDoc large
]
total p (g, w) ( fm, t ) = do
inform $ text "Ist jeder Knoten überdeckt?"
let nein = knoten g `minusSet` unionManySets ( eltsFM fm )
when ( not $ isEmptySet nein ) $ reject $ vcat
[ text "nein, diese nicht:"
, nest 4 $ toDoc nein
]
inform $ text "Ist jede Kante überdeckt?"
-- welcher Knoten in welchen Mengen?
let wh = addListToFM_C Autolib.Set.union emptyFM $ do
(i, s) <- fmToList fm
x <- setToList s
return ( x, unitSet i )
let nein = do
k <- lkanten g
let xs = lookupset wh $ von k
ys = lookupset wh $ nach k
guard $ isEmptySet $ intersect xs ys
return (k, xs, ys)
when ( not $ null nein ) $ reject $ vcat
[ text "nein, diese Kanten nicht:"
, nest 4 $ vcat $ do
(k, xs, ys) <- nein
return $ vcat
[ toDoc k
, nest 4 $ vcat
[ text "die Knoten sind in den Mengen:"
, nest 4 $ toDoc xs
, nest 4 $ toDoc ys
]
]
]
inform $ text "Gilt die Helly-Eigenschaft?"
let nein = do
( x, is ) <- fmToList wh
guard $ not $ is_connected $ restrict is t
return (x, is)
when ( not $ null nein ) $ reject $ vcat
[ text "nein:"
, nest 4 $ vcat $ take 5 $ do
( x, is ) <- nein
return $ vcat
[ text "Der Knoten" <+> toDoc x
, text "ist enthalten in den Mengen" <+> toDoc is
, text "aber diese bilden keinen zusammenhängenden Teilgraphen."
]
]
make :: Make
make =
let p = Autolib.Graph.Basic.path [ 1 .. 4 :: Int ]
in direct TreeWidth ( normalize $ grid p p, 3 :: Int )
| florianpilz/autotool | src/Graph/TreeWidth.hs | gpl-2.0 | 3,621 | 53 | 18 | 1,228 | 1,302 | 664 | 638 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
module HplAssets.Hephaestus.Types where
import Language.Haskell.Syntax
import Data.Generics
data HephaestusTransformation
= SelectBaseProduct
| SelectAsset String
| SelectExport String
| BindProductName String
| RemoveProductMainFunction
| SelectCKParser
deriving (Show)
data HephaestusModel = HephaestusModel [HsModule] deriving (Show, Data, Typeable)
data ExportHephaestusDoc = ExportDoc
| rbonifacio/hephaestus-pl | src/meta-hephaestus/HplAssets/Hephaestus/Types.hs | lgpl-3.0 | 454 | 0 | 7 | 71 | 88 | 53 | 35 | 14 | 0 |
{-# LANGUAGE MagicHash #-}
module Foundation.Foreign.Alloc
( allocaBytes
) where
import qualified Foreign.Marshal.Alloc as A (allocaBytes)
import Basement.Imports
import Basement.Types.OffsetSize
allocaBytes :: CountOf Word8 -> (Ptr a -> IO b) -> IO b
allocaBytes (CountOf i) f = A.allocaBytes i f
| vincenthz/hs-foundation | foundation/Foundation/Foreign/Alloc.hs | bsd-3-clause | 328 | 0 | 9 | 71 | 93 | 52 | 41 | 8 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: TODO
-- Copyright: (c) 2016 Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- TODO
module Data.DHT.DKS.Type.EVar
where
import Control.Applicative (pure)
import Control.Exception (Exception(toException), SomeException)
import Data.Either (Either(Left, Right))
import Data.Function ((.))
import System.IO (IO)
type EVar a = Either SomeException a
type EVarIO a = IO (EVar a)
failure :: Exception e => e -> EVar a
failure = Left . toException
success :: a -> EVar a
success = Right
success_ :: EVar ()
success_ = success ()
successIO :: a -> EVarIO a
successIO = pure . success
successIO_ :: EVarIO ()
successIO_ = successIO ()
| FPBrno/dht-dks | src/Data/DHT/DKS/Type/EVar.hs | bsd-3-clause | 797 | 0 | 7 | 148 | 219 | 130 | 89 | 19 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Stack.Config.Urls (urlsFromMonoid) where
import Stack.Types.Urls
import Stack.Prelude
urlsFromMonoid :: UrlsMonoid -> Urls
urlsFromMonoid monoid =
Urls
(fromFirst defaultLatestSnapshot $ urlsMonoidLatestSnapshot monoid)
(fromFirst defaultLtsBuildPlans $ urlsMonoidLtsBuildPlans monoid)
(fromFirst defaultNightlyBuildPlans $ urlsMonoidNightlyBuildPlans monoid)
where
defaultLatestSnapshot =
"https://s3.amazonaws.com/haddock.stackage.org/snapshots.json"
defaultLtsBuildPlans =
"https://raw.githubusercontent.com/fpco/lts-haskell/master/"
defaultNightlyBuildPlans =
"https://raw.githubusercontent.com/fpco/stackage-nightly/master/"
| MichielDerhaeg/stack | src/Stack/Config/Urls.hs | bsd-3-clause | 812 | 0 | 8 | 155 | 105 | 57 | 48 | 17 | 1 |
module Tst1 where
data Bool = False | True
data Nat = Zero | Succ Nat
-- length :: [a] -> Nat
length [] = Zero
length (x:xs) = Succ (length xs)
-- map :: (a->b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x:map f xs
mapLengthProp f xs = length (map f xs) == length xs
---
Zero == Zero = True
Succ _ == Zero = False
Zero == Succ _ = False
Succ n == Succ m = n==m
| forste/haReFork | tools/hs2alfa/tst1.hs | bsd-3-clause | 386 | 0 | 8 | 112 | 194 | 96 | 98 | 12 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.